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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
apple/swift
|
test/SILGen/writeback.swift
|
4
|
5800
|
// RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle %s | %FileCheck %s
struct Foo {
mutating // used to test writeback.
func foo() {}
subscript(x: Int) -> Foo {
get {
return Foo()
}
set {}
}
}
var x: Foo {
get {
return Foo()
}
set {}
}
var y: Foo {
get {
return Foo()
}
set {}
}
var z: Foo {
get {
return Foo()
}
set {}
}
var readonly: Foo {
get {
return Foo()
}
}
func bar(x x: inout Foo) {}
// Writeback to value type 'self' argument
x.foo()
// CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo
// CHECK: [[GET_X:%.*]] = function_ref @$s9writeback1xAA3FooVvg : $@convention(thin) () -> Foo
// CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: store [[X]] to [trivial] [[X_TEMP]]
// CHECK: [[FOO:%.*]] = function_ref @$s9writeback3FooV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout Foo) -> ()
// CHECK: apply [[FOO]]([[X_TEMP]]) : $@convention(method) (@inout Foo) -> ()
// CHECK: [[X1:%.*]] = load [trivial] [[X_TEMP]] : $*Foo
// CHECK: [[SET_X:%.*]] = function_ref @$s9writeback1xAA3FooVvs : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> ()
// CHECK: dealloc_stack [[X_TEMP]] : $*Foo
// Writeback to inout argument
bar(x: &x)
// CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo
// CHECK: [[GET_X:%.*]] = function_ref @$s9writeback1xAA3FooVvg : $@convention(thin) () -> Foo
// CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: store [[X]] to [trivial] [[X_TEMP]] : $*Foo
// CHECK: [[BAR:%.*]] = function_ref @$s9writeback3bar1xyAA3FooVz_tF : $@convention(thin) (@inout Foo) -> ()
// CHECK: apply [[BAR]]([[X_TEMP]]) : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[X1:%.*]] = load [trivial] [[X_TEMP]] : $*Foo
// CHECK: [[SET_X:%.*]] = function_ref @$s9writeback1xAA3FooVvs : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> ()
// CHECK: dealloc_stack [[X_TEMP]] : $*Foo
func zang(x x: Foo) {}
// No writeback for pass-by-value argument
zang(x: x)
// CHECK: function_ref @$s9writeback4zang1xyAA3FooV_tF : $@convention(thin) (Foo) -> ()
// CHECK-NOT: @$s9writeback1xAA3FooVvs
zang(x: readonly)
// CHECK: function_ref @$s9writeback4zang1xyAA3FooV_tF : $@convention(thin) (Foo) -> ()
// CHECK-NOT: @$s9writeback8readonlyAA3FooVvs
func zung() -> Int { return 0 }
// Ensure that subscripts are only evaluated once.
bar(x: &x[zung()])
// CHECK: [[ZUNG:%.*]] = function_ref @$s9writeback4zungSiyF : $@convention(thin) () -> Int
// CHECK: [[INDEX:%.*]] = apply [[ZUNG]]() : $@convention(thin) () -> Int
// CHECK: [[GET_X:%.*]] = function_ref @$s9writeback1xAA3FooVvg : $@convention(thin) () -> Foo
// CHECK: [[GET_SUBSCRIPT:%.*]] = function_ref @$s9writeback3FooV{{[_0-9a-zA-Z]*}}ig : $@convention(method) (Int, Foo) -> Foo
// CHECK: apply [[GET_SUBSCRIPT]]([[INDEX]], {{%.*}}) : $@convention(method) (Int, Foo) -> Foo
// CHECK: [[BAR:%.*]] = function_ref @$s9writeback3bar1xyAA3FooVz_tF : $@convention(thin) (@inout Foo) -> ()
// CHECK: apply [[BAR]]({{%.*}}) : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[SET_SUBSCRIPT:%.*]] = function_ref @$s9writeback3FooV{{[_0-9a-zA-Z]*}}is : $@convention(method) (Foo, Int, @inout Foo) -> ()
// CHECK: apply [[SET_SUBSCRIPT]]({{%.*}}, [[INDEX]], {{%.*}}) : $@convention(method) (Foo, Int, @inout Foo) -> ()
// CHECK: function_ref @$s9writeback1xAA3FooVvs : $@convention(thin) (Foo) -> ()
protocol Fungible {}
extension Foo : Fungible {}
var addressOnly: Fungible {
get {
return Foo()
}
set {}
}
func funge(x x: inout Fungible) {}
funge(x: &addressOnly)
// CHECK: [[TEMP:%.*]] = alloc_stack $any Fungible
// CHECK: [[GET:%.*]] = function_ref @$s9writeback11addressOnlyAA8Fungible_pvg : $@convention(thin) () -> @out any Fungible
// CHECK: apply [[GET]]([[TEMP]]) : $@convention(thin) () -> @out any Fungible
// CHECK: [[FUNGE:%.*]] = function_ref @$s9writeback5funge1xyAA8Fungible_pz_tF : $@convention(thin) (@inout any Fungible) -> ()
// CHECK: apply [[FUNGE]]([[TEMP]]) : $@convention(thin) (@inout any Fungible) -> ()
// CHECK: [[SET:%.*]] = function_ref @$s9writeback11addressOnlyAA8Fungible_pvs : $@convention(thin) (@in any Fungible) -> ()
// CHECK: apply [[SET]]([[TEMP]]) : $@convention(thin) (@in any Fungible) -> ()
// CHECK: dealloc_stack [[TEMP]] : $*any Fungible
// Test that writeback occurs with generic properties.
// <rdar://problem/16525257>
protocol Runcible {
associatedtype Frob: Frobable
var frob: Frob { get set }
}
protocol Frobable {
associatedtype Anse
var anse: Anse { get set }
}
// CHECK-LABEL: sil hidden [ossa] @$s9writeback12test_generic{{[_0-9a-zA-Z]*}}F
// CHECK: witness_method $Runce, #Runcible.frob!modify
// CHECK: witness_method $Runce.Frob, #Frobable.anse!setter
func test_generic<Runce: Runcible>(runce runce: inout Runce, anse: Runce.Frob.Anse) {
runce.frob.anse = anse
}
// We should *not* write back when referencing decls or members as rvalues.
// <rdar://problem/16530235>
// CHECK-LABEL: sil hidden [ossa] @$s9writeback15loadAddressOnlyAA8Fungible_pyF : $@convention(thin) () -> @out any Fungible {
func loadAddressOnly() -> Fungible {
// CHECK: function_ref writeback.addressOnly.getter
// CHECK-NOT: function_ref writeback.addressOnly.setter
return addressOnly
}
// CHECK-LABEL: sil hidden [ossa] @$s9writeback10loadMember{{[_0-9a-zA-Z]*}}F
// CHECK: witness_method $Runce, #Runcible.frob!getter
// CHECK: witness_method $Runce.Frob, #Frobable.anse!getter
// CHECK-NOT: witness_method $Runce.Frob, #Frobable.anse!setter
// CHECK-NOT: witness_method $Runce, #Runcible.frob!setter
func loadMember<Runce: Runcible>(runce runce: Runce) -> Runce.Frob.Anse {
return runce.frob.anse
}
|
apache-2.0
|
3e7c09daaaebbcc2e873b54de75fdd17
| 36.179487 | 136 | 0.613966 | 3.186813 | false | false | false | false |
hooman/swift
|
stdlib/public/core/Codable.swift
|
3
|
232456
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Codable
//===----------------------------------------------------------------------===//
/// A type that can encode itself to an external representation.
public protocol Encodable {
/// Encodes this value into the given encoder.
///
/// If the value fails to encode anything, `encoder` will encode an empty
/// keyed container in its place.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
func encode(to encoder: Encoder) throws
}
/// A type that can decode itself from an external representation.
public protocol Decodable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
init(from decoder: Decoder) throws
}
/// A type that can convert itself into and out of an external representation.
///
/// `Codable` is a type alias for the `Encodable` and `Decodable` protocols.
/// When you use `Codable` as a type or a generic constraint, it matches
/// any type that conforms to both protocols.
public typealias Codable = Encodable & Decodable
//===----------------------------------------------------------------------===//
// CodingKey
//===----------------------------------------------------------------------===//
/// A type that can be used as a key for encoding and decoding.
public protocol CodingKey: Sendable,
CustomStringConvertible,
CustomDebugStringConvertible {
/// The string to use in a named collection (e.g. a string-keyed dictionary).
var stringValue: String { get }
/// Creates a new instance from the given string.
///
/// If the string passed as `stringValue` does not correspond to any instance
/// of this type, the result is `nil`.
///
/// - parameter stringValue: The string value of the desired key.
init?(stringValue: String)
/// The value to use in an integer-indexed collection (e.g. an int-keyed
/// dictionary).
var intValue: Int? { get }
/// Creates a new instance from the specified integer.
///
/// If the value passed as `intValue` does not correspond to any instance of
/// this type, the result is `nil`.
///
/// - parameter intValue: The integer value of the desired key.
init?(intValue: Int)
}
extension CodingKey {
/// A textual representation of this key.
public var description: String {
let intValue = self.intValue?.description ?? "nil"
return "\(type(of: self))(stringValue: \"\(stringValue)\", intValue: \(intValue))"
}
/// A textual representation of this key, suitable for debugging.
public var debugDescription: String {
return description
}
}
//===----------------------------------------------------------------------===//
// Encoder & Decoder
//===----------------------------------------------------------------------===//
/// A type that can encode values into a native format for external
/// representation.
public protocol Encoder {
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// Any contextual information set by the user for encoding.
var userInfo: [CodingUserInfoKey: Any] { get }
/// Returns an encoding container appropriate for holding multiple values
/// keyed by the given key type.
///
/// You must use only one kind of top-level encoding container. This method
/// must not be called after a call to `unkeyedContainer()` or after
/// encoding a value through a call to `singleValueContainer()`
///
/// - parameter type: The key type to use for the container.
/// - returns: A new keyed encoding container.
func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key>
/// Returns an encoding container appropriate for holding multiple unkeyed
/// values.
///
/// You must use only one kind of top-level encoding container. This method
/// must not be called after a call to `container(keyedBy:)` or after
/// encoding a value through a call to `singleValueContainer()`
///
/// - returns: A new empty unkeyed container.
func unkeyedContainer() -> UnkeyedEncodingContainer
/// Returns an encoding container appropriate for holding a single primitive
/// value.
///
/// You must use only one kind of top-level encoding container. This method
/// must not be called after a call to `unkeyedContainer()` or
/// `container(keyedBy:)`, or after encoding a value through a call to
/// `singleValueContainer()`
///
/// - returns: A new empty single value container.
func singleValueContainer() -> SingleValueEncodingContainer
}
/// A type that can decode values from a native format into in-memory
/// representations.
public protocol Decoder {
/// The path of coding keys taken to get to this point in decoding.
var codingPath: [CodingKey] { get }
/// Any contextual information set by the user for decoding.
var userInfo: [CodingUserInfoKey: Any] { get }
/// Returns the data stored in this decoder as represented in a container
/// keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A keyed decoding container view into this decoder.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a keyed container.
func container<Key>(
keyedBy type: Key.Type
) throws -> KeyedDecodingContainer<Key>
/// Returns the data stored in this decoder as represented in a container
/// appropriate for holding values with no keys.
///
/// - returns: An unkeyed container view into this decoder.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not an unkeyed container.
func unkeyedContainer() throws -> UnkeyedDecodingContainer
/// Returns the data stored in this decoder as represented in a container
/// appropriate for holding a single primitive value.
///
/// - returns: A single value container view into this decoder.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a single value container.
func singleValueContainer() throws -> SingleValueDecodingContainer
}
//===----------------------------------------------------------------------===//
// Keyed Encoding Containers
//===----------------------------------------------------------------------===//
/// A type that provides a view into an encoder's storage and is used to hold
/// the encoded properties of an encodable type in a keyed manner.
///
/// Encoders should provide types conforming to
/// `KeyedEncodingContainerProtocol` for their format.
public protocol KeyedEncodingContainerProtocol {
associatedtype Key: CodingKey
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// Encodes a null value for the given key.
///
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the
/// current context for this format.
mutating func encodeNil(forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Bool, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: String, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Double, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Float, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int8, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int16, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int32, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int64, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt8, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt16, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt32, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt64, forKey key: Key) throws
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode<T: Encodable>(_ value: T, forKey key: Key) throws
/// Encodes a reference to the given object only if it is encoded
/// unconditionally elsewhere in the payload (previously, or in the future).
///
/// For encoders which don't support this feature, the default implementation
/// encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - parameter key: The key to associate the object with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeConditional<T: AnyObject & Encodable>(
_ object: T,
forKey key: Key
) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Bool?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: String?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Double?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Float?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int8?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int16?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int32?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: Int64?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt8?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt16?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt32?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent(_ value: UInt64?, forKey key: Key) throws
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeIfPresent<T: Encodable>(
_ value: T?,
forKey key: Key
) throws
/// Stores a keyed encoding container for the given key and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - parameter key: The key to encode the container for.
/// - returns: A new keyed encoding container.
mutating func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type,
forKey key: Key
) -> KeyedEncodingContainer<NestedKey>
/// Stores an unkeyed encoding container for the given key and returns it.
///
/// - parameter key: The key to encode the container for.
/// - returns: A new unkeyed encoding container.
mutating func nestedUnkeyedContainer(
forKey key: Key
) -> UnkeyedEncodingContainer
/// Stores a new nested container for the default `super` key and returns a
/// new encoder instance for encoding `super` into that container.
///
/// Equivalent to calling `superEncoder(forKey:)` with
/// `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new encoder to pass to `super.encode(to:)`.
mutating func superEncoder() -> Encoder
/// Stores a new nested container for the given key and returns a new encoder
/// instance for encoding `super` into that container.
///
/// - parameter key: The key to encode `super` for.
/// - returns: A new encoder to pass to `super.encode(to:)`.
mutating func superEncoder(forKey key: Key) -> Encoder
}
// An implementation of _KeyedEncodingContainerBase and
// _KeyedEncodingContainerBox are given at the bottom of this file.
/// A concrete container that provides a view into an encoder's storage, making
/// the encoded properties of an encodable type accessible by keys.
public struct KeyedEncodingContainer<K: CodingKey> :
KeyedEncodingContainerProtocol
{
public typealias Key = K
/// The container for the concrete encoder.
internal var _box: _KeyedEncodingContainerBase
/// Creates a new instance with the given container.
///
/// - parameter container: The container to hold.
public init<Container: KeyedEncodingContainerProtocol>(
_ container: Container
) where Container.Key == Key {
_box = _KeyedEncodingContainerBox(container)
}
/// The path of coding keys taken to get to this point in encoding.
public var codingPath: [CodingKey] {
return _box.codingPath
}
/// Encodes a null value for the given key.
///
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the
/// current context for this format.
public mutating func encodeNil(forKey key: Key) throws {
try _box.encodeNil(forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Bool, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: String, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Double, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Float, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int8, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int16, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int32, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: Int64, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt8, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt16, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt32, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode(_ value: UInt64, forKey key: Key) throws {
try _box.encode(value, forKey: key)
}
/// Encodes the given value for the given key.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encode<T: Encodable>(
_ value: T,
forKey key: Key
) throws {
try _box.encode(value, forKey: key)
}
/// Encodes a reference to the given object only if it is encoded
/// unconditionally elsewhere in the payload (previously, or in the future).
///
/// For encoders which don't support this feature, the default implementation
/// encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - parameter key: The key to associate the object with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeConditional<T: AnyObject & Encodable>(
_ object: T,
forKey key: Key
) throws {
try _box.encodeConditional(object, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Bool?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: String?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Double?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Float?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int8?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int16?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int32?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: Int64?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt8?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt16?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt32?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent(
_ value: UInt64?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Encodes the given value for the given key if it is not `nil`.
///
/// - parameter value: The value to encode.
/// - parameter key: The key to associate the value with.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
public mutating func encodeIfPresent<T: Encodable>(
_ value: T?,
forKey key: Key
) throws {
try _box.encodeIfPresent(value, forKey: key)
}
/// Stores a keyed encoding container for the given key and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - parameter key: The key to encode the container for.
/// - returns: A new keyed encoding container.
public mutating func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type,
forKey key: Key
) -> KeyedEncodingContainer<NestedKey> {
return _box.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
/// Stores an unkeyed encoding container for the given key and returns it.
///
/// - parameter key: The key to encode the container for.
/// - returns: A new unkeyed encoding container.
public mutating func nestedUnkeyedContainer(
forKey key: Key
) -> UnkeyedEncodingContainer {
return _box.nestedUnkeyedContainer(forKey: key)
}
/// Stores a new nested container for the default `super` key and returns a
/// new encoder instance for encoding `super` into that container.
///
/// Equivalent to calling `superEncoder(forKey:)` with
/// `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new encoder to pass to `super.encode(to:)`.
public mutating func superEncoder() -> Encoder {
return _box.superEncoder()
}
/// Stores a new nested container for the given key and returns a new encoder
/// instance for encoding `super` into that container.
///
/// - parameter key: The key to encode `super` for.
/// - returns: A new encoder to pass to `super.encode(to:)`.
public mutating func superEncoder(forKey key: Key) -> Encoder {
return _box.superEncoder(forKey: key)
}
}
/// A type that provides a view into a decoder's storage and is used to hold
/// the encoded properties of a decodable type in a keyed manner.
///
/// Decoders should provide types conforming to `UnkeyedDecodingContainer` for
/// their format.
public protocol KeyedDecodingContainerProtocol {
associatedtype Key: CodingKey
/// The path of coding keys taken to get to this point in decoding.
var codingPath: [CodingKey] { get }
/// All the keys the `Decoder` has for this container.
///
/// Different keyed containers from the same `Decoder` may return different
/// keys here; it is possible to encode with multiple key types which are
/// not convertible to one another. This should report all keys present
/// which are convertible to the requested type.
var allKeys: [Key] { get }
/// Returns a Boolean value indicating whether the decoder contains a value
/// associated with the given key.
///
/// The value associated with `key` may be a null value as appropriate for
/// the data format.
///
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
func contains(_ key: Key) -> Bool
/// Decodes a null value for the given key.
///
/// - parameter key: The key that the decoded value is associated with.
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
func decodeNil(forKey key: Key) throws -> Bool
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: String.Type, forKey key: Key) throws -> String
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Double.Type, forKey key: Key) throws -> Double
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Float.Type, forKey key: Key) throws -> Float
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int.Type, forKey key: Key) throws -> Int
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func decode<T: Decodable>(_ type: T.Type, forKey key: Key) throws -> T
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Bool.Type, forKey key: Key) throws -> Bool?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: String.Type, forKey key: Key) throws -> String?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Double.Type, forKey key: Key) throws -> Double?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Float.Type, forKey key: Key) throws -> Float?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int.Type, forKey key: Key) throws -> Int?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int8.Type, forKey key: Key) throws -> Int8?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int16.Type, forKey key: Key) throws -> Int16?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int32.Type, forKey key: Key) throws -> Int32?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: Int64.Type, forKey key: Key) throws -> Int64?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt.Type, forKey key: Key) throws -> UInt?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt8.Type, forKey key: Key) throws -> UInt8?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt16.Type, forKey key: Key) throws -> UInt16?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt32.Type, forKey key: Key) throws -> UInt32?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent(_ type: UInt64.Type, forKey key: Key) throws -> UInt64?
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
func decodeIfPresent<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T?
/// Returns the data stored for the given key as represented in a container
/// keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - parameter key: The key that the nested container is associated with.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a keyed container.
func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type,
forKey key: Key
) throws -> KeyedDecodingContainer<NestedKey>
/// Returns the data stored for the given key as represented in an unkeyed
/// container.
///
/// - parameter key: The key that the nested container is associated with.
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not an unkeyed container.
func nestedUnkeyedContainer(
forKey key: Key
) throws -> UnkeyedDecodingContainer
/// Returns a `Decoder` instance for decoding `super` from the container
/// associated with the default `super` key.
///
/// Equivalent to calling `superDecoder(forKey:)` with
/// `Key(stringValue: "super", intValue: 0)`.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the default `super` key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the default `super` key.
func superDecoder() throws -> Decoder
/// Returns a `Decoder` instance for decoding `super` from the container
/// associated with the given key.
///
/// - parameter key: The key to decode `super` for.
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
func superDecoder(forKey key: Key) throws -> Decoder
}
// An implementation of _KeyedDecodingContainerBase and
// _KeyedDecodingContainerBox are given at the bottom of this file.
/// A concrete container that provides a view into a decoder's storage, making
/// the encoded properties of a decodable type accessible by keys.
public struct KeyedDecodingContainer<K: CodingKey> :
KeyedDecodingContainerProtocol
{
public typealias Key = K
/// The container for the concrete decoder.
internal var _box: _KeyedDecodingContainerBase
/// Creates a new instance with the given container.
///
/// - parameter container: The container to hold.
public init<Container: KeyedDecodingContainerProtocol>(
_ container: Container
) where Container.Key == Key {
_box = _KeyedDecodingContainerBox(container)
}
/// The path of coding keys taken to get to this point in decoding.
public var codingPath: [CodingKey] {
return _box.codingPath
}
/// All the keys the decoder has for this container.
///
/// Different keyed containers from the same decoder may return different
/// keys here, because it is possible to encode with multiple key types
/// which are not convertible to one another. This should report all keys
/// present which are convertible to the requested type.
public var allKeys: [Key] {
return _box.allKeys as! [Key]
}
/// Returns a Boolean value indicating whether the decoder contains a value
/// associated with the given key.
///
/// The value associated with the given key may be a null value as
/// appropriate for the data format.
///
/// - parameter key: The key to search for.
/// - returns: Whether the `Decoder` has an entry for the given key.
public func contains(_ key: Key) -> Bool {
return _box.contains(key)
}
/// Decodes a null value for the given key.
///
/// - parameter key: The key that the decoded value is associated with.
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
public func decodeNil(forKey key: Key) throws -> Bool {
return try _box.decodeNil(forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool {
return try _box.decode(Bool.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: String.Type, forKey key: Key) throws -> String {
return try _box.decode(String.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Double.Type, forKey key: Key) throws -> Double {
return try _box.decode(Double.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Float.Type, forKey key: Key) throws -> Float {
return try _box.decode(Float.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int.Type, forKey key: Key) throws -> Int {
return try _box.decode(Int.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 {
return try _box.decode(Int8.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 {
return try _box.decode(Int16.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 {
return try _box.decode(Int32.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 {
return try _box.decode(Int64.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt {
return try _box.decode(UInt.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 {
return try _box.decode(UInt8.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 {
return try _box.decode(UInt16.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 {
return try _box.decode(UInt32.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 {
return try _box.decode(UInt64.self, forKey: key)
}
/// Decodes a value of the given type for the given key.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func decode<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T {
return try _box.decode(T.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool? {
return try _box.decodeIfPresent(Bool.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: String.Type,
forKey key: Key
) throws -> String? {
return try _box.decodeIfPresent(String.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Double.Type,
forKey key: Key
) throws -> Double? {
return try _box.decodeIfPresent(Double.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Float.Type,
forKey key: Key
) throws -> Float? {
return try _box.decodeIfPresent(Float.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int.Type,
forKey key: Key
) throws -> Int? {
return try _box.decodeIfPresent(Int.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8? {
return try _box.decodeIfPresent(Int8.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16? {
return try _box.decodeIfPresent(Int16.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32? {
return try _box.decodeIfPresent(Int32.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64? {
return try _box.decodeIfPresent(Int64.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt? {
return try _box.decodeIfPresent(UInt.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8? {
return try _box.decodeIfPresent(UInt8.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16? {
return try _box.decodeIfPresent(UInt16.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32? {
return try _box.decodeIfPresent(UInt32.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64? {
return try _box.decodeIfPresent(UInt64.self, forKey: key)
}
/// Decodes a value of the given type for the given key, if present.
///
/// This method returns `nil` if the container does not have a value
/// associated with `key`, or if the value is null. The difference between
/// these states can be distinguished with a `contains(_:)` call.
///
/// - parameter type: The type of value to decode.
/// - parameter key: The key that the decoded value is associated with.
/// - returns: A decoded value of the requested type, or `nil` if the
/// `Decoder` does not have an entry associated with the given key, or if
/// the value is a null value.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
public func decodeIfPresent<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T? {
return try _box.decodeIfPresent(T.self, forKey: key)
}
/// Returns the data stored for the given key as represented in a container
/// keyed by the given key type.
///
/// - parameter type: The key type to use for the container.
/// - parameter key: The key that the nested container is associated with.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a keyed container.
public func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type,
forKey key: Key
) throws -> KeyedDecodingContainer<NestedKey> {
return try _box.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
/// Returns the data stored for the given key as represented in an unkeyed
/// container.
///
/// - parameter key: The key that the nested container is associated with.
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not an unkeyed container.
public func nestedUnkeyedContainer(
forKey key: Key
) throws -> UnkeyedDecodingContainer {
return try _box.nestedUnkeyedContainer(forKey: key)
}
/// Returns a `Decoder` instance for decoding `super` from the container
/// associated with the default `super` key.
///
/// Equivalent to calling `superDecoder(forKey:)` with
/// `Key(stringValue: "super", intValue: 0)`.
///
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the default `super` key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the default `super` key.
public func superDecoder() throws -> Decoder {
return try _box.superDecoder()
}
/// Returns a `Decoder` instance for decoding `super` from the container
/// associated with the given key.
///
/// - parameter key: The key to decode `super` for.
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.keyNotFound` if `self` does not have an entry
/// for the given key.
/// - throws: `DecodingError.valueNotFound` if `self` has a null entry for
/// the given key.
public func superDecoder(forKey key: Key) throws -> Decoder {
return try _box.superDecoder(forKey: key)
}
}
//===----------------------------------------------------------------------===//
// Unkeyed Encoding Containers
//===----------------------------------------------------------------------===//
/// A type that provides a view into an encoder's storage and is used to hold
/// the encoded properties of an encodable type sequentially, without keys.
///
/// Encoders should provide types conforming to `UnkeyedEncodingContainer` for
/// their format.
public protocol UnkeyedEncodingContainer {
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// The number of elements encoded into the container.
var count: Int { get }
/// Encodes a null value.
///
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the
/// current context for this format.
mutating func encodeNil() throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Bool) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: String) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Double) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Float) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int8) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int16) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int32) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: Int64) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt8) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt16) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt32) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode(_ value: UInt64) throws
/// Encodes the given value.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encode<T: Encodable>(_ value: T) throws
/// Encodes a reference to the given object only if it is encoded
/// unconditionally elsewhere in the payload (previously, or in the future).
///
/// For encoders which don't support this feature, the default implementation
/// encodes the given object unconditionally.
///
/// For formats which don't support this feature, the default implementation
/// encodes the given object unconditionally.
///
/// - parameter object: The object to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
mutating func encodeConditional<T: AnyObject & Encodable>(_ object: T) throws
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Bool
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == String
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Double
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Float
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int8
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int16
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int32
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int64
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt8
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt16
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt32
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt64
/// Encodes the elements of the given sequence.
///
/// - parameter sequence: The sequences whose contents to encode.
/// - throws: An error if any of the contained values throws an error.
mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element: Encodable
/// Encodes a nested container keyed by the given type and returns it.
///
/// - parameter keyType: The key type to use for the container.
/// - returns: A new keyed encoding container.
mutating func nestedContainer<NestedKey>(
keyedBy keyType: NestedKey.Type
) -> KeyedEncodingContainer<NestedKey>
/// Encodes an unkeyed encoding container and returns it.
///
/// - returns: A new unkeyed encoding container.
mutating func nestedUnkeyedContainer() -> UnkeyedEncodingContainer
/// Encodes a nested container and returns an `Encoder` instance for encoding
/// `super` into that container.
///
/// - returns: A new encoder to pass to `super.encode(to:)`.
mutating func superEncoder() -> Encoder
}
/// A type that provides a view into a decoder's storage and is used to hold
/// the encoded properties of a decodable type sequentially, without keys.
///
/// Decoders should provide types conforming to `UnkeyedDecodingContainer` for
/// their format.
public protocol UnkeyedDecodingContainer {
/// The path of coding keys taken to get to this point in decoding.
var codingPath: [CodingKey] { get }
/// The number of elements contained within this container.
///
/// If the number of elements is unknown, the value is `nil`.
var count: Int? { get }
/// A Boolean value indicating whether there are no more elements left to be
/// decoded in the container.
var isAtEnd: Bool { get }
/// The current decoding index of the container (i.e. the index of the next
/// element to be decoded.) Incremented after every successful decode call.
var currentIndex: Int { get }
/// Decodes a null value.
///
/// If the value is not null, does not increment currentIndex.
///
/// - returns: Whether the encountered value was null.
/// - throws: `DecodingError.valueNotFound` if there are no more values to
/// decode.
mutating func decodeNil() throws -> Bool
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Bool.Type) throws -> Bool
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: String.Type) throws -> String
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Double.Type) throws -> Double
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Float.Type) throws -> Float
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int.Type) throws -> Int
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int8.Type) throws -> Int8
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int16.Type) throws -> Int16
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int32.Type) throws -> Int32
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: Int64.Type) throws -> Int64
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt.Type) throws -> UInt
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt8.Type) throws -> UInt8
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt16.Type) throws -> UInt16
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt32.Type) throws -> UInt32
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode(_ type: UInt64.Type) throws -> UInt64
/// Decodes a value of the given type.
///
/// - parameter type: The type of value to decode.
/// - returns: A value of the requested type, if present for the given key
/// and convertible to the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func decode<T: Decodable>(_ type: T.Type) throws -> T
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Bool.Type) throws -> Bool?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: String.Type) throws -> String?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Double.Type) throws -> Double?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Float.Type) throws -> Float?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int.Type) throws -> Int?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int8.Type) throws -> Int8?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int16.Type) throws -> Int16?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int32.Type) throws -> Int32?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: Int64.Type) throws -> Int64?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt.Type) throws -> UInt?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt8.Type) throws -> UInt8?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt16.Type) throws -> UInt16?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt32.Type) throws -> UInt32?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent(_ type: UInt64.Type) throws -> UInt64?
/// Decodes a value of the given type, if present.
///
/// This method returns `nil` if the container has no elements left to
/// decode, or if the value is null. The difference between these states can
/// be distinguished by checking `isAtEnd`.
///
/// - parameter type: The type of value to decode.
/// - returns: A decoded value of the requested type, or `nil` if the value
/// is a null value, or if there are no more elements to decode.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// is not convertible to the requested type.
mutating func decodeIfPresent<T: Decodable>(_ type: T.Type) throws -> T?
/// Decodes a nested container keyed by the given type.
///
/// - parameter type: The key type to use for the container.
/// - returns: A keyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not a keyed container.
mutating func nestedContainer<NestedKey>(
keyedBy type: NestedKey.Type
) throws -> KeyedDecodingContainer<NestedKey>
/// Decodes an unkeyed nested container.
///
/// - returns: An unkeyed decoding container view into `self`.
/// - throws: `DecodingError.typeMismatch` if the encountered stored value is
/// not an unkeyed container.
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer
/// Decodes a nested container and returns a `Decoder` instance for decoding
/// `super` from that container.
///
/// - returns: A new `Decoder` to pass to `super.init(from:)`.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null, or of there are no more values to decode.
mutating func superDecoder() throws -> Decoder
}
//===----------------------------------------------------------------------===//
// Single Value Encoding Containers
//===----------------------------------------------------------------------===//
/// A container that can support the storage and direct encoding of a single
/// non-keyed value.
public protocol SingleValueEncodingContainer {
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// Encodes a null value.
///
/// - throws: `EncodingError.invalidValue` if a null value is invalid in the
/// current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encodeNil() throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Bool) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: String) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Double) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Float) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int8) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int16) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int32) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: Int64) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt8) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt16) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt32) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode(_ value: UInt64) throws
/// Encodes a single value of the given type.
///
/// - parameter value: The value to encode.
/// - throws: `EncodingError.invalidValue` if the given value is invalid in
/// the current context for this format.
/// - precondition: May not be called after a previous `self.encode(_:)`
/// call.
mutating func encode<T: Encodable>(_ value: T) throws
}
/// A container that can support the storage and direct decoding of a single
/// nonkeyed value.
public protocol SingleValueDecodingContainer {
/// The path of coding keys taken to get to this point in encoding.
var codingPath: [CodingKey] { get }
/// Decodes a null value.
///
/// - returns: Whether the encountered value was null.
func decodeNil() -> Bool
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Bool.Type) throws -> Bool
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: String.Type) throws -> String
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Double.Type) throws -> Double
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Float.Type) throws -> Float
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int.Type) throws -> Int
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int8.Type) throws -> Int8
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int16.Type) throws -> Int16
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int32.Type) throws -> Int32
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: Int64.Type) throws -> Int64
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt.Type) throws -> UInt
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt8.Type) throws -> UInt8
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt16.Type) throws -> UInt16
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt32.Type) throws -> UInt32
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode(_ type: UInt64.Type) throws -> UInt64
/// Decodes a single value of the given type.
///
/// - parameter type: The type to decode as.
/// - returns: A value of the requested type.
/// - throws: `DecodingError.typeMismatch` if the encountered encoded value
/// cannot be converted to the requested type.
/// - throws: `DecodingError.valueNotFound` if the encountered encoded value
/// is null.
func decode<T: Decodable>(_ type: T.Type) throws -> T
}
//===----------------------------------------------------------------------===//
// User Info
//===----------------------------------------------------------------------===//
/// A user-defined key for providing context during encoding and decoding.
public struct CodingUserInfoKey: RawRepresentable, Equatable, Hashable, Sendable {
public typealias RawValue = String
/// The key's string value.
public let rawValue: String
/// Creates a new instance with the given raw value.
///
/// - parameter rawValue: The value of the key.
public init?(rawValue: String) {
self.rawValue = rawValue
}
/// Returns a Boolean value indicating whether the given keys are equal.
///
/// - parameter lhs: The key to compare against.
/// - parameter rhs: The key to compare with.
public static func ==(
lhs: CodingUserInfoKey,
rhs: CodingUserInfoKey
) -> Bool {
return lhs.rawValue == rhs.rawValue
}
/// The key's hash value.
public var hashValue: Int {
return self.rawValue.hashValue
}
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
public func hash(into hasher: inout Hasher) {
hasher.combine(self.rawValue)
}
}
//===----------------------------------------------------------------------===//
// Errors
//===----------------------------------------------------------------------===//
/// An error that occurs during the encoding of a value.
public enum EncodingError: Error {
/// The context in which the error occurred.
public struct Context: Sendable {
/// The path of coding keys taken to get to the point of the failing encode
/// call.
public let codingPath: [CodingKey]
/// A description of what went wrong, for debugging purposes.
public let debugDescription: String
/// The underlying error which caused this error, if any.
public let underlyingError: Error?
/// Creates a new context with the given path of coding keys and a
/// description of what went wrong.
///
/// - parameter codingPath: The path of coding keys taken to get to the
/// point of the failing encode call.
/// - parameter debugDescription: A description of what went wrong, for
/// debugging purposes.
/// - parameter underlyingError: The underlying error which caused this
/// error, if any.
public init(
codingPath: [CodingKey],
debugDescription: String,
underlyingError: Error? = nil
) {
self.codingPath = codingPath
self.debugDescription = debugDescription
self.underlyingError = underlyingError
}
}
/// An indication that an encoder or its containers could not encode the
/// given value.
///
/// As associated values, this case contains the attempted value and context
/// for debugging.
case invalidValue(Any, Context)
// MARK: - NSError Bridging
// CustomNSError bridging applies only when the CustomNSError conformance is
// applied in the same module as the declared error type. Since we cannot
// access CustomNSError (which is defined in Foundation) from here, we can
// use the "hidden" entry points.
public var _domain: String {
return "NSCocoaErrorDomain"
}
public var _code: Int {
switch self {
case .invalidValue: return 4866
}
}
public var _userInfo: AnyObject? {
// The error dictionary must be returned as an AnyObject. We can do this
// only on platforms with bridging, unfortunately.
#if _runtime(_ObjC)
let context: Context
switch self {
case .invalidValue(_, let c): context = c
}
var userInfo: [String: Any] = [
"NSCodingPath": context.codingPath,
"NSDebugDescription": context.debugDescription
]
if let underlyingError = context.underlyingError {
userInfo["NSUnderlyingError"] = underlyingError
}
return userInfo as AnyObject
#else
return nil
#endif
}
}
/// An error that occurs during the decoding of a value.
public enum DecodingError: Error {
/// The context in which the error occurred.
public struct Context: Sendable {
/// The path of coding keys taken to get to the point of the failing decode
/// call.
public let codingPath: [CodingKey]
/// A description of what went wrong, for debugging purposes.
public let debugDescription: String
/// The underlying error which caused this error, if any.
public let underlyingError: Error?
/// Creates a new context with the given path of coding keys and a
/// description of what went wrong.
///
/// - parameter codingPath: The path of coding keys taken to get to the
/// point of the failing decode call.
/// - parameter debugDescription: A description of what went wrong, for
/// debugging purposes.
/// - parameter underlyingError: The underlying error which caused this
/// error, if any.
public init(
codingPath: [CodingKey],
debugDescription: String,
underlyingError: Error? = nil
) {
self.codingPath = codingPath
self.debugDescription = debugDescription
self.underlyingError = underlyingError
}
}
/// An indication that a value of the given type could not be decoded because
/// it did not match the type of what was found in the encoded payload.
///
/// As associated values, this case contains the attempted type and context
/// for debugging.
case typeMismatch(Any.Type, Context)
/// An indication that a non-optional value of the given type was expected,
/// but a null value was found.
///
/// As associated values, this case contains the attempted type and context
/// for debugging.
case valueNotFound(Any.Type, Context)
/// An indication that a keyed decoding container was asked for an entry for
/// the given key, but did not contain one.
///
/// As associated values, this case contains the attempted key and context
/// for debugging.
case keyNotFound(CodingKey, Context)
/// An indication that the data is corrupted or otherwise invalid.
///
/// As an associated value, this case contains the context for debugging.
case dataCorrupted(Context)
// MARK: - NSError Bridging
// CustomNSError bridging applies only when the CustomNSError conformance is
// applied in the same module as the declared error type. Since we cannot
// access CustomNSError (which is defined in Foundation) from here, we can
// use the "hidden" entry points.
public var _domain: String {
return "NSCocoaErrorDomain"
}
public var _code: Int {
switch self {
case .keyNotFound, .valueNotFound: return 4865
case .typeMismatch, .dataCorrupted: return 4864
}
}
public var _userInfo: AnyObject? {
// The error dictionary must be returned as an AnyObject. We can do this
// only on platforms with bridging, unfortunately.
#if _runtime(_ObjC)
let context: Context
switch self {
case .keyNotFound(_, let c): context = c
case .valueNotFound(_, let c): context = c
case .typeMismatch(_, let c): context = c
case .dataCorrupted( let c): context = c
}
var userInfo: [String: Any] = [
"NSCodingPath": context.codingPath,
"NSDebugDescription": context.debugDescription
]
if let underlyingError = context.underlyingError {
userInfo["NSUnderlyingError"] = underlyingError
}
return userInfo as AnyObject
#else
return nil
#endif
}
}
// The following extensions allow for easier error construction.
internal struct _GenericIndexKey: CodingKey, Sendable {
internal var stringValue: String
internal var intValue: Int?
internal init?(stringValue: String) {
return nil
}
internal init?(intValue: Int) {
self.stringValue = "Index \(intValue)"
self.intValue = intValue
}
}
extension DecodingError {
/// Returns a new `.dataCorrupted` error using a constructed coding path and
/// the given debug description.
///
/// The coding path for the returned error is constructed by appending the
/// given key to the given container's coding path.
///
/// - param key: The key which caused the failure.
/// - param container: The container in which the corrupted data was
/// accessed.
/// - param debugDescription: A description of the error to aid in debugging.
///
/// - Returns: A new `.dataCorrupted` error with the given information.
public static func dataCorruptedError<C: KeyedDecodingContainerProtocol>(
forKey key: C.Key,
in container: C,
debugDescription: String
) -> DecodingError {
let context = DecodingError.Context(
codingPath: container.codingPath + [key],
debugDescription: debugDescription)
return .dataCorrupted(context)
}
/// Returns a new `.dataCorrupted` error using a constructed coding path and
/// the given debug description.
///
/// The coding path for the returned error is constructed by appending the
/// given container's current index to its coding path.
///
/// - param container: The container in which the corrupted data was
/// accessed.
/// - param debugDescription: A description of the error to aid in debugging.
///
/// - Returns: A new `.dataCorrupted` error with the given information.
public static func dataCorruptedError(
in container: UnkeyedDecodingContainer,
debugDescription: String
) -> DecodingError {
let context = DecodingError.Context(
codingPath: container.codingPath +
[_GenericIndexKey(intValue: container.currentIndex)!],
debugDescription: debugDescription)
return .dataCorrupted(context)
}
/// Returns a new `.dataCorrupted` error using a constructed coding path and
/// the given debug description.
///
/// The coding path for the returned error is the given container's coding
/// path.
///
/// - param container: The container in which the corrupted data was
/// accessed.
/// - param debugDescription: A description of the error to aid in debugging.
///
/// - Returns: A new `.dataCorrupted` error with the given information.
public static func dataCorruptedError(
in container: SingleValueDecodingContainer,
debugDescription: String
) -> DecodingError {
let context = DecodingError.Context(codingPath: container.codingPath,
debugDescription: debugDescription)
return .dataCorrupted(context)
}
}
//===----------------------------------------------------------------------===//
// Keyed Encoding Container Implementations
//===----------------------------------------------------------------------===//
internal class _KeyedEncodingContainerBase {
internal init(){}
deinit {}
// These must all be given a concrete implementation in _*Box.
internal var codingPath: [CodingKey] {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeNil<K: CodingKey>(forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Bool, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: String, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Double, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Float, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Int, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Int8, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Int16, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Int32, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: Int64, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: UInt, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: UInt8, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: UInt16, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: UInt32, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<K: CodingKey>(_ value: UInt64, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encode<T: Encodable, K: CodingKey>(_ value: T, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeConditional<T: AnyObject & Encodable, K: CodingKey>(
_ object: T,
forKey key: K
) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Bool?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: String?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Double?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Float?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Int?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Int8?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Int16?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Int32?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: Int64?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: UInt?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: UInt8?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: UInt16?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: UInt32?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<K: CodingKey>(_ value: UInt64?, forKey key: K) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func encodeIfPresent<T: Encodable, K: CodingKey>(
_ value: T?,
forKey key: K
) throws {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func nestedContainer<NestedKey, K: CodingKey>(
keyedBy keyType: NestedKey.Type,
forKey key: K
) -> KeyedEncodingContainer<NestedKey> {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func nestedUnkeyedContainer<K: CodingKey>(
forKey key: K
) -> UnkeyedEncodingContainer {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func superEncoder() -> Encoder {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
internal func superEncoder<K: CodingKey>(forKey key: K) -> Encoder {
fatalError("_KeyedEncodingContainerBase cannot be used directly.")
}
}
internal final class _KeyedEncodingContainerBox<
Concrete: KeyedEncodingContainerProtocol
>: _KeyedEncodingContainerBase {
typealias Key = Concrete.Key
internal var concrete: Concrete
internal init(_ container: Concrete) {
concrete = container
}
override internal var codingPath: [CodingKey] {
return concrete.codingPath
}
override internal func encodeNil<K: CodingKey>(forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeNil(forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Bool, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: String, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Double, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Float, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Int, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Int8, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Int16, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Int32, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: Int64, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: UInt, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: UInt8, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: UInt16, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: UInt32, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<K: CodingKey>(_ value: UInt64, forKey key: K) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encode<T: Encodable, K: CodingKey>(
_ value: T,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encode(value, forKey: key)
}
override internal func encodeConditional<T: AnyObject & Encodable, K: CodingKey>(
_ object: T,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeConditional(object, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Bool?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: String?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Double?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Float?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Int?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Int8?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Int16?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Int32?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: Int64?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: UInt?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: UInt8?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: UInt16?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: UInt32?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<K: CodingKey>(
_ value: UInt64?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func encodeIfPresent<T: Encodable, K: CodingKey>(
_ value: T?,
forKey key: K
) throws {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
try concrete.encodeIfPresent(value, forKey: key)
}
override internal func nestedContainer<NestedKey, K: CodingKey>(
keyedBy keyType: NestedKey.Type,
forKey key: K
) -> KeyedEncodingContainer<NestedKey> {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return concrete.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
override internal func nestedUnkeyedContainer<K: CodingKey>(
forKey key: K
) -> UnkeyedEncodingContainer {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return concrete.nestedUnkeyedContainer(forKey: key)
}
override internal func superEncoder() -> Encoder {
return concrete.superEncoder()
}
override internal func superEncoder<K: CodingKey>(forKey key: K) -> Encoder {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return concrete.superEncoder(forKey: key)
}
}
internal class _KeyedDecodingContainerBase {
internal init(){}
deinit {}
internal var codingPath: [CodingKey] {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal var allKeys: [CodingKey] {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func contains<K: CodingKey>(_ key: K) -> Bool {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeNil<K: CodingKey>(forKey key: K) throws -> Bool {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Bool.Type,
forKey key: K
) throws -> Bool {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: String.Type,
forKey key: K
) throws -> String {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Double.Type,
forKey key: K
) throws -> Double {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Float.Type,
forKey key: K
) throws -> Float {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Int.Type,
forKey key: K
) throws -> Int {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Int8.Type,
forKey key: K
) throws -> Int8 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Int16.Type,
forKey key: K
) throws -> Int16 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Int32.Type,
forKey key: K
) throws -> Int32 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: Int64.Type,
forKey key: K
) throws -> Int64 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: UInt.Type,
forKey key: K
) throws -> UInt {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: UInt8.Type,
forKey key: K
) throws -> UInt8 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: UInt16.Type,
forKey key: K
) throws -> UInt16 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: UInt32.Type,
forKey key: K
) throws -> UInt32 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<K: CodingKey>(
_ type: UInt64.Type,
forKey key: K
) throws -> UInt64 {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decode<T: Decodable, K: CodingKey>(
_ type: T.Type,
forKey key: K
) throws -> T {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Bool.Type,
forKey key: K
) throws -> Bool? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: String.Type,
forKey key: K
) throws -> String? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Double.Type,
forKey key: K
) throws -> Double? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Float.Type,
forKey key: K
) throws -> Float? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Int.Type,
forKey key: K
) throws -> Int? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Int8.Type,
forKey key: K
) throws -> Int8? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Int16.Type,
forKey key: K
) throws -> Int16? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Int32.Type,
forKey key: K
) throws -> Int32? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: Int64.Type,
forKey key: K
) throws -> Int64? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: UInt.Type,
forKey key: K
) throws -> UInt? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: UInt8.Type,
forKey key: K
) throws -> UInt8? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: UInt16.Type,
forKey key: K
) throws -> UInt16? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: UInt32.Type,
forKey key: K
) throws -> UInt32? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<K: CodingKey>(
_ type: UInt64.Type,
forKey key: K
) throws -> UInt64? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func decodeIfPresent<T: Decodable, K: CodingKey>(
_ type: T.Type,
forKey key: K
) throws -> T? {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func nestedContainer<NestedKey, K: CodingKey>(
keyedBy type: NestedKey.Type,
forKey key: K
) throws -> KeyedDecodingContainer<NestedKey> {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func nestedUnkeyedContainer<K: CodingKey>(
forKey key: K
) throws -> UnkeyedDecodingContainer {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func superDecoder() throws -> Decoder {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
internal func superDecoder<K: CodingKey>(forKey key: K) throws -> Decoder {
fatalError("_KeyedDecodingContainerBase cannot be used directly.")
}
}
internal final class _KeyedDecodingContainerBox<
Concrete: KeyedDecodingContainerProtocol
>: _KeyedDecodingContainerBase {
typealias Key = Concrete.Key
internal var concrete: Concrete
internal init(_ container: Concrete) {
concrete = container
}
override var codingPath: [CodingKey] {
return concrete.codingPath
}
override var allKeys: [CodingKey] {
return concrete.allKeys
}
override internal func contains<K: CodingKey>(_ key: K) -> Bool {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return concrete.contains(key)
}
override internal func decodeNil<K: CodingKey>(forKey key: K) throws -> Bool {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeNil(forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Bool.Type,
forKey key: K
) throws -> Bool {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Bool.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: String.Type,
forKey key: K
) throws -> String {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(String.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Double.Type,
forKey key: K
) throws -> Double {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Double.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Float.Type,
forKey key: K
) throws -> Float {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Float.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Int.Type,
forKey key: K
) throws -> Int {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Int.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Int8.Type,
forKey key: K
) throws -> Int8 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Int8.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Int16.Type,
forKey key: K
) throws -> Int16 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Int16.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Int32.Type,
forKey key: K
) throws -> Int32 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Int32.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: Int64.Type,
forKey key: K
) throws -> Int64 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(Int64.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: UInt.Type,
forKey key: K
) throws -> UInt {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(UInt.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: UInt8.Type,
forKey key: K
) throws -> UInt8 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(UInt8.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: UInt16.Type,
forKey key: K
) throws -> UInt16 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(UInt16.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: UInt32.Type,
forKey key: K
) throws -> UInt32 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(UInt32.self, forKey: key)
}
override internal func decode<K: CodingKey>(
_ type: UInt64.Type,
forKey key: K
) throws -> UInt64 {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(UInt64.self, forKey: key)
}
override internal func decode<T: Decodable, K: CodingKey>(
_ type: T.Type,
forKey key: K
) throws -> T {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decode(T.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Bool.Type,
forKey key: K
) throws -> Bool? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Bool.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: String.Type,
forKey key: K
) throws -> String? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(String.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Double.Type,
forKey key: K
) throws -> Double? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Double.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Float.Type,
forKey key: K
) throws -> Float? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Float.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Int.Type,
forKey key: K
) throws -> Int? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Int.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Int8.Type,
forKey key: K
) throws -> Int8? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Int8.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Int16.Type,
forKey key: K
) throws -> Int16? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Int16.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Int32.Type,
forKey key: K
) throws -> Int32? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Int32.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: Int64.Type,
forKey key: K
) throws -> Int64? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(Int64.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: UInt.Type,
forKey key: K
) throws -> UInt? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(UInt.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: UInt8.Type,
forKey key: K
) throws -> UInt8? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(UInt8.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: UInt16.Type,
forKey key: K
) throws -> UInt16? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(UInt16.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: UInt32.Type,
forKey key: K
) throws -> UInt32? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(UInt32.self, forKey: key)
}
override internal func decodeIfPresent<K: CodingKey>(
_ type: UInt64.Type,
forKey key: K
) throws -> UInt64? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(UInt64.self, forKey: key)
}
override internal func decodeIfPresent<T: Decodable, K: CodingKey>(
_ type: T.Type,
forKey key: K
) throws -> T? {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.decodeIfPresent(T.self, forKey: key)
}
override internal func nestedContainer<NestedKey, K: CodingKey>(
keyedBy type: NestedKey.Type,
forKey key: K
) throws -> KeyedDecodingContainer<NestedKey> {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.nestedContainer(keyedBy: NestedKey.self, forKey: key)
}
override internal func nestedUnkeyedContainer<K: CodingKey>(
forKey key: K
) throws -> UnkeyedDecodingContainer {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.nestedUnkeyedContainer(forKey: key)
}
override internal func superDecoder() throws -> Decoder {
return try concrete.superDecoder()
}
override internal func superDecoder<K: CodingKey>(forKey key: K) throws -> Decoder {
assert(K.self == Key.self)
let key = unsafeBitCast(key, to: Key.self)
return try concrete.superDecoder(forKey: key)
}
}
//===----------------------------------------------------------------------===//
// Primitive and RawRepresentable Extensions
//===----------------------------------------------------------------------===//
extension Bool: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Bool.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Bool, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Bool`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Bool, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Bool`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension String: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(String.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == String, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `String`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == String, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `String`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Double: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Double.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Double, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Double`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Double, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Double`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Float: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Float.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Float, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Float`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Float, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Float`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
#if !((os(macOS) || targetEnvironment(macCatalyst)) && arch(x86_64))
@available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *)
extension Float16: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let floatValue = try Float(from: decoder)
self = Float16(floatValue)
if isInfinite && floatValue.isFinite {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Parsed JSON number \(floatValue) does not fit in Float16."
)
)
}
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
try Float(self).encode(to: encoder)
}
}
#endif
extension Int: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Int8: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int8.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int8, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int8`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int8, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int8`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Int16: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int16.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int16, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int16`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int16, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int16`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Int32: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int32.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int32, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int32`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int32, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int32`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension Int64: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(Int64.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == Int64, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `Int64`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == Int64, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `Int64`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt8: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt8.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt8, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt8`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt8, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt8`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt16: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt16.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt16, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt16`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt16, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt16`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt32: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt32.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt32, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt32`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt32, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt32`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
extension UInt64: Codable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self = try decoder.singleValueContainer().decode(UInt64.self)
}
/// Encodes this value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self)
}
}
extension RawRepresentable where RawValue == UInt64, Self: Encodable {
/// Encodes this value into the given encoder, when the type's `RawValue`
/// is `UInt64`.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.rawValue)
}
}
extension RawRepresentable where RawValue == UInt64, Self: Decodable {
/// Creates a new instance by decoding from the given decoder, when the
/// type's `RawValue` is `UInt64`.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let decoded = try decoder.singleValueContainer().decode(RawValue.self)
guard let value = Self(rawValue: decoded) else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Cannot initialize \(Self.self) from invalid \(RawValue.self) value \(decoded)"
)
)
}
self = value
}
}
//===----------------------------------------------------------------------===//
// Optional/Collection Type Conformances
//===----------------------------------------------------------------------===//
extension Optional: Encodable where Wrapped: Encodable {
/// Encodes this optional value into the given encoder.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .none: try container.encodeNil()
case .some(let wrapped): try container.encode(wrapped)
}
}
}
extension Optional: Decodable where Wrapped: Decodable {
/// Creates a new instance by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
self = .none
} else {
let element = try container.decode(Wrapped.self)
self = .some(element)
}
}
}
extension Array: Encodable where Element: Encodable {
/// Encodes the elements of this array into the given encoder in an unkeyed
/// container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in self {
try container.encode(element)
}
}
}
extension Array: Decodable where Element: Decodable {
/// Creates a new array by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
let element = try container.decode(Element.self)
self.append(element)
}
}
}
extension ContiguousArray: Encodable where Element: Encodable {
/// Encodes the elements of this contiguous array into the given encoder
/// in an unkeyed container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in self {
try container.encode(element)
}
}
}
extension ContiguousArray: Decodable where Element: Decodable {
/// Creates a new contiguous array by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
let element = try container.decode(Element.self)
self.append(element)
}
}
}
extension Set: Encodable where Element: Encodable {
/// Encodes the elements of this set into the given encoder in an unkeyed
/// container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in self {
try container.encode(element)
}
}
}
extension Set: Decodable where Element: Decodable {
/// Creates a new set by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
while !container.isAtEnd {
let element = try container.decode(Element.self)
self.insert(element)
}
}
}
/// A wrapper for dictionary keys which are Strings or Ints.
internal struct _DictionaryCodingKey: CodingKey {
internal let stringValue: String
internal let intValue: Int?
internal init?(stringValue: String) {
self.stringValue = stringValue
self.intValue = Int(stringValue)
}
internal init?(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
}
extension Dictionary: Encodable where Key: Encodable, Value: Encodable {
/// Encodes the contents of this dictionary into the given encoder.
///
/// If the dictionary uses `String` or `Int` keys, the contents are encoded
/// in a keyed container. Otherwise, the contents are encoded as alternating
/// key-value pairs in an unkeyed container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
public func encode(to encoder: Encoder) throws {
if Key.self == String.self {
// Since the keys are already Strings, we can use them as keys directly.
var container = encoder.container(keyedBy: _DictionaryCodingKey.self)
for (key, value) in self {
let codingKey = _DictionaryCodingKey(stringValue: key as! String)!
try container.encode(value, forKey: codingKey)
}
} else if Key.self == Int.self {
// Since the keys are already Ints, we can use them as keys directly.
var container = encoder.container(keyedBy: _DictionaryCodingKey.self)
for (key, value) in self {
let codingKey = _DictionaryCodingKey(intValue: key as! Int)!
try container.encode(value, forKey: codingKey)
}
} else {
// Keys are Encodable but not Strings or Ints, so we cannot arbitrarily
// convert to keys. We can encode as an array of alternating key-value
// pairs, though.
var container = encoder.unkeyedContainer()
for (key, value) in self {
try container.encode(key)
try container.encode(value)
}
}
}
}
extension Dictionary: Decodable where Key: Decodable, Value: Decodable {
/// Creates a new dictionary by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
public init(from decoder: Decoder) throws {
self.init()
if Key.self == String.self {
// The keys are Strings, so we should be able to expect a keyed container.
let container = try decoder.container(keyedBy: _DictionaryCodingKey.self)
for key in container.allKeys {
let value = try container.decode(Value.self, forKey: key)
self[key.stringValue as! Key] = value
}
} else if Key.self == Int.self {
// The keys are Ints, so we should be able to expect a keyed container.
let container = try decoder.container(keyedBy: _DictionaryCodingKey.self)
for key in container.allKeys {
guard key.intValue != nil else {
// We provide stringValues for Int keys; if an encoder chooses not to
// use the actual intValues, we've encoded string keys.
// So on init, _DictionaryCodingKey tries to parse string keys as
// Ints. If that succeeds, then we would have had an intValue here.
// We don't, so this isn't a valid Int key.
var codingPath = decoder.codingPath
codingPath.append(key)
throw DecodingError.typeMismatch(
Int.self,
DecodingError.Context(
codingPath: codingPath,
debugDescription: "Expected Int key but found String key instead."
)
)
}
let value = try container.decode(Value.self, forKey: key)
self[key.intValue! as! Key] = value
}
} else {
// We should have encoded as an array of alternating key-value pairs.
var container = try decoder.unkeyedContainer()
// We're expecting to get pairs. If the container has a known count, it
// had better be even; no point in doing work if not.
if let count = container.count {
guard count % 2 == 0 else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Expected collection of key-value pairs; encountered odd-length array instead."
)
)
}
}
while !container.isAtEnd {
let key = try container.decode(Key.self)
guard !container.isAtEnd else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Unkeyed container reached end before value in key-value pair."
)
)
}
let value = try container.decode(Value.self)
self[key] = value
}
}
}
}
//===----------------------------------------------------------------------===//
// Convenience Default Implementations
//===----------------------------------------------------------------------===//
// Default implementation of encodeConditional(_:forKey:) in terms of
// encode(_:forKey:)
extension KeyedEncodingContainerProtocol {
public mutating func encodeConditional<T: AnyObject & Encodable>(
_ object: T,
forKey key: Key
) throws {
try encode(object, forKey: key)
}
}
// Default implementation of encodeIfPresent(_:forKey:) in terms of
// encode(_:forKey:)
extension KeyedEncodingContainerProtocol {
public mutating func encodeIfPresent(
_ value: Bool?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: String?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Double?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Float?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int8?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int16?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int32?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: Int64?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt8?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt16?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt32?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent(
_ value: UInt64?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
public mutating func encodeIfPresent<T: Encodable>(
_ value: T?,
forKey key: Key
) throws {
guard let value = value else { return }
try encode(value, forKey: key)
}
}
// Default implementation of decodeIfPresent(_:forKey:) in terms of
// decode(_:forKey:) and decodeNil(forKey:)
extension KeyedDecodingContainerProtocol {
public func decodeIfPresent(
_ type: Bool.Type,
forKey key: Key
) throws -> Bool? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Bool.self, forKey: key)
}
public func decodeIfPresent(
_ type: String.Type,
forKey key: Key
) throws -> String? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(String.self, forKey: key)
}
public func decodeIfPresent(
_ type: Double.Type,
forKey key: Key
) throws -> Double? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Double.self, forKey: key)
}
public func decodeIfPresent(
_ type: Float.Type,
forKey key: Key
) throws -> Float? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Float.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int.Type,
forKey key: Key
) throws -> Int? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int8.Type,
forKey key: Key
) throws -> Int8? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int8.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int16.Type,
forKey key: Key
) throws -> Int16? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int16.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int32.Type,
forKey key: Key
) throws -> Int32? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int32.self, forKey: key)
}
public func decodeIfPresent(
_ type: Int64.Type,
forKey key: Key
) throws -> Int64? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(Int64.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt.Type,
forKey key: Key
) throws -> UInt? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt8.Type,
forKey key: Key
) throws -> UInt8? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt8.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt16.Type,
forKey key: Key
) throws -> UInt16? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt16.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt32.Type,
forKey key: Key
) throws -> UInt32? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt32.self, forKey: key)
}
public func decodeIfPresent(
_ type: UInt64.Type,
forKey key: Key
) throws -> UInt64? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(UInt64.self, forKey: key)
}
public func decodeIfPresent<T: Decodable>(
_ type: T.Type,
forKey key: Key
) throws -> T? {
guard try self.contains(key) && !self.decodeNil(forKey: key)
else { return nil }
return try self.decode(T.self, forKey: key)
}
}
// Default implementation of encodeConditional(_:) in terms of encode(_:),
// and encode(contentsOf:) in terms of encode(_:) loop.
extension UnkeyedEncodingContainer {
public mutating func encodeConditional<T: AnyObject & Encodable>(
_ object: T
) throws {
try self.encode(object)
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Bool {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == String {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Double {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Float {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int8 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int16 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int32 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == Int64 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt8 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt16 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt32 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element == UInt64 {
for element in sequence {
try self.encode(element)
}
}
public mutating func encode<T: Sequence>(
contentsOf sequence: T
) throws where T.Element: Encodable {
for element in sequence {
try self.encode(element)
}
}
}
// Default implementation of decodeIfPresent(_:) in terms of decode(_:) and
// decodeNil()
extension UnkeyedDecodingContainer {
public mutating func decodeIfPresent(
_ type: Bool.Type
) throws -> Bool? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Bool.self)
}
public mutating func decodeIfPresent(
_ type: String.Type
) throws -> String? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(String.self)
}
public mutating func decodeIfPresent(
_ type: Double.Type
) throws -> Double? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Double.self)
}
public mutating func decodeIfPresent(
_ type: Float.Type
) throws -> Float? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Float.self)
}
public mutating func decodeIfPresent(
_ type: Int.Type
) throws -> Int? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int.self)
}
public mutating func decodeIfPresent(
_ type: Int8.Type
) throws -> Int8? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int8.self)
}
public mutating func decodeIfPresent(
_ type: Int16.Type
) throws -> Int16? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int16.self)
}
public mutating func decodeIfPresent(
_ type: Int32.Type
) throws -> Int32? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int32.self)
}
public mutating func decodeIfPresent(
_ type: Int64.Type
) throws -> Int64? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(Int64.self)
}
public mutating func decodeIfPresent(
_ type: UInt.Type
) throws -> UInt? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt.self)
}
public mutating func decodeIfPresent(
_ type: UInt8.Type
) throws -> UInt8? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt8.self)
}
public mutating func decodeIfPresent(
_ type: UInt16.Type
) throws -> UInt16? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt16.self)
}
public mutating func decodeIfPresent(
_ type: UInt32.Type
) throws -> UInt32? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt32.self)
}
public mutating func decodeIfPresent(
_ type: UInt64.Type
) throws -> UInt64? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(UInt64.self)
}
public mutating func decodeIfPresent<T: Decodable>(
_ type: T.Type
) throws -> T? {
guard try !self.isAtEnd && !self.decodeNil() else { return nil }
return try self.decode(T.self)
}
}
|
apache-2.0
|
bb0599f3d5785a1dba3831f9fc8411f3
| 36.767019 | 111 | 0.674889 | 4.354413 | false | false | false | false |
alblue/swift-corelibs-foundation
|
Foundation/NSCache.swift
|
6
|
6922
|
// 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
//
private class NSCacheEntry<KeyType : AnyObject, ObjectType : AnyObject> {
var key: KeyType
var value: ObjectType
var cost: Int
var prevByCost: NSCacheEntry?
var nextByCost: NSCacheEntry?
init(key: KeyType, value: ObjectType, cost: Int) {
self.key = key
self.value = value
self.cost = cost
}
}
fileprivate class NSCacheKey: NSObject {
var value: AnyObject
init(_ value: AnyObject) {
self.value = value
super.init()
}
override var hashValue: Int {
switch self.value {
case let nsObject as NSObject:
return nsObject.hashValue
case let hashable as AnyHashable:
return hashable.hashValue
default: return 0
}
}
override func isEqual(_ object: Any?) -> Bool {
guard let other = (object as? NSCacheKey) else { return false }
if self.value === other.value {
return true
} else {
guard let left = self.value as? NSObject,
let right = other.value as? NSObject else { return false }
return left.isEqual(right)
}
}
}
open class NSCache<KeyType : AnyObject, ObjectType : AnyObject> : NSObject {
private var _entries = Dictionary<NSCacheKey, NSCacheEntry<KeyType, ObjectType>>()
private let _lock = NSLock()
private var _totalCost = 0
private var _head: NSCacheEntry<KeyType, ObjectType>?
open var name: String = ""
open var totalCostLimit: Int = 0 // limits are imprecise/not strict
open var countLimit: Int = 0 // limits are imprecise/not strict
open var evictsObjectsWithDiscardedContent: Bool = false
public override init() {}
open weak var delegate: NSCacheDelegate?
open func object(forKey key: KeyType) -> ObjectType? {
var object: ObjectType?
let key = NSCacheKey(key)
_lock.lock()
if let entry = _entries[key] {
object = entry.value
}
_lock.unlock()
return object
}
open func setObject(_ obj: ObjectType, forKey key: KeyType) {
setObject(obj, forKey: key, cost: 0)
}
private func remove(_ entry: NSCacheEntry<KeyType, ObjectType>) {
let oldPrev = entry.prevByCost
let oldNext = entry.nextByCost
oldPrev?.nextByCost = oldNext
oldNext?.prevByCost = oldPrev
if entry === _head {
_head = oldNext
}
}
private func insert(_ entry: NSCacheEntry<KeyType, ObjectType>) {
guard var currentElement = _head else {
// The cache is empty
entry.prevByCost = nil
entry.nextByCost = nil
_head = entry
return
}
guard entry.cost > currentElement.cost else {
// Insert entry at the head
entry.prevByCost = nil
entry.nextByCost = currentElement
currentElement.prevByCost = entry
_head = entry
return
}
while let nextByCost = currentElement.nextByCost, nextByCost.cost < entry.cost {
currentElement = nextByCost
}
// Insert entry between currentElement and nextElement
let nextElement = currentElement.nextByCost
currentElement.nextByCost = entry
entry.prevByCost = currentElement
entry.nextByCost = nextElement
nextElement?.prevByCost = entry
}
open func setObject(_ obj: ObjectType, forKey key: KeyType, cost g: Int) {
let g = max(g, 0)
let keyRef = NSCacheKey(key)
_lock.lock()
let costDiff: Int
if let entry = _entries[keyRef] {
costDiff = g - entry.cost
entry.cost = g
entry.value = obj
if costDiff != 0 {
remove(entry)
insert(entry)
}
} else {
let entry = NSCacheEntry(key: key, value: obj, cost: g)
_entries[keyRef] = entry
insert(entry)
costDiff = g
}
_totalCost += costDiff
var purgeAmount = (totalCostLimit > 0) ? (_totalCost - totalCostLimit) : 0
while purgeAmount > 0 {
if let entry = _head {
delegate?.cache(unsafeDowncast(self, to:NSCache<AnyObject, AnyObject>.self), willEvictObject: entry.value)
_totalCost -= entry.cost
purgeAmount -= entry.cost
remove(entry) // _head will be changed to next entry in remove(_:)
_entries[NSCacheKey(entry.key)] = nil
} else {
break
}
}
var purgeCount = (countLimit > 0) ? (_entries.count - countLimit) : 0
while purgeCount > 0 {
if let entry = _head {
delegate?.cache(unsafeDowncast(self, to:NSCache<AnyObject, AnyObject>.self), willEvictObject: entry.value)
_totalCost -= entry.cost
purgeCount -= 1
remove(entry) // _head will be changed to next entry in remove(_:)
_entries[NSCacheKey(entry.key)] = nil
} else {
break
}
}
_lock.unlock()
}
open func removeObject(forKey key: KeyType) {
let keyRef = NSCacheKey(key)
_lock.lock()
if let entry = _entries.removeValue(forKey: keyRef) {
_totalCost -= entry.cost
remove(entry)
}
_lock.unlock()
}
open func removeAllObjects() {
_lock.lock()
_entries.removeAll()
while let currentElement = _head {
let nextElement = currentElement.nextByCost
currentElement.prevByCost = nil
currentElement.nextByCost = nil
_head = nextElement
}
_totalCost = 0
_lock.unlock()
}
}
public protocol NSCacheDelegate : NSObjectProtocol {
func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: Any)
}
extension NSCacheDelegate {
func cache(_ cache: NSCache<AnyObject, AnyObject>, willEvictObject obj: Any) {
// Default implementation does nothing
}
}
|
apache-2.0
|
05908006a8d6d89ef4cebdf43e938979
| 28.581197 | 122 | 0.545652 | 5.034182 | false | false | false | false |
randallsutton/tablerow
|
tablerow/ViewController.swift
|
1
|
2812
|
import UIKit
class ViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var tableViewRightSideConstraint: NSLayoutConstraint!
// MARK: Variables
var sliderMaxValue: Float = 0.0
var sliderNeedsUpdate = true
// MARK: UIView
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.estimatedRowHeight = 44.0
self.tableView.rowHeight = UITableViewAutomaticDimension
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if self.sliderNeedsUpdate {
// Setup the slider values
self.sliderMaxValue = Float(self.tableView.frame.width)
self.slider.maximumValue = self.sliderMaxValue
self.slider.value = self.sliderMaxValue
// Finish the update
self.sliderNeedsUpdate = false
}
}
override func traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
// Reset the constraint
self.tableViewRightSideConstraint.constant = 0
// Let the slider know it needs to update
self.sliderNeedsUpdate = true
}
// MARK: UISlider
@IBAction func sliderValueChanged(sender: UISlider) {
self.tableViewRightSideConstraint.constant = CGFloat(self.sliderMaxValue) - CGFloat(self.slider.value)
}
}
// MARK: UITableView
extension ViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as! CustomCell
if indexPath.row % 3 == 0 {
cell.leftLabel.text = "Row \(indexPath.row) with some super short text"
}
else if indexPath.row % 3 == 1 {
cell.leftLabel.text = "Row \(indexPath.row) with some super long text that nobody can read because it is so very long"
}
else {
cell.leftLabel.text = "Row \(indexPath.row) with some super long text that nobody can read because it is so very very very very very very very long"
}
if indexPath.row % 2 == 0 {
cell.rightLabel.text = "Right"
}
else {
cell.rightLabel.text = "Right Large"
}
return cell
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
}
|
mit
|
0dc7fde21194d02f07e7aa0a709f985d
| 30.244444 | 160 | 0.633001 | 5.335863 | false | false | false | false |
PaoloCuscela/Cards
|
Demo/Pods/Player/Sources/Player.swift
|
1
|
29519
|
// Player.swift
//
// Created by patrick piemonte on 11/26/14.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-present patrick piemonte (http://patrickpiemonte.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import Foundation
import AVFoundation
import CoreGraphics
// MARK: - types
/// Video fill mode options for `Player.fillMode`.
///
/// - resize: Stretch to fill.
/// - resizeAspectFill: Preserve aspect ratio, filling bounds.
/// - resizeAspectFit: Preserve aspect ratio, fill within bounds.
public typealias PlayerFillMode = AVLayerVideoGravity
/// Asset playback states.
public enum PlaybackState: Int, CustomStringConvertible {
case stopped = 0
case playing
case paused
case failed
public var description: String {
get {
switch self {
case .stopped:
return "Stopped"
case .playing:
return "Playing"
case .failed:
return "Failed"
case .paused:
return "Paused"
}
}
}
}
/// Asset buffering states.
public enum BufferingState: Int, CustomStringConvertible {
case unknown = 0
case ready
case delayed
public var description: String {
get {
switch self {
case .unknown:
return "Unknown"
case .ready:
return "Ready"
case .delayed:
return "Delayed"
}
}
}
}
// MARK: - error types
/// Error domain for all Player errors.
public let PlayerErrorDomain = "PlayerErrorDomain"
/// Error types.
public enum PlayerError: Error, CustomStringConvertible {
case failed
public var description: String {
get {
switch self {
case .failed:
return "failed"
}
}
}
}
// MARK: - PlayerDelegate
/// Player delegate protocol
public protocol PlayerDelegate: AnyObject {
func playerReady(_ player: Player)
func playerPlaybackStateDidChange(_ player: Player)
func playerBufferingStateDidChange(_ player: Player)
// This is the time in seconds that the video has been buffered.
// If implementing a UIProgressView, user this value / player.maximumDuration to set progress.
func playerBufferTimeDidChange(_ bufferTime: Double)
func player(_ player: Player, didFailWithError error: Error?)
}
/// Player playback protocol
public protocol PlayerPlaybackDelegate: AnyObject {
func playerCurrentTimeDidChange(_ player: Player)
func playerPlaybackWillStartFromBeginning(_ player: Player)
func playerPlaybackDidEnd(_ player: Player)
func playerPlaybackWillLoop(_ player: Player)
}
// MARK: - Player
/// ▶️ Player, simple way to play and stream media
open class Player: UIViewController {
/// Player delegate.
open weak var playerDelegate: PlayerDelegate?
/// Playback delegate.
open weak var playbackDelegate: PlayerPlaybackDelegate?
// configuration
/// Local or remote URL for the file asset to be played.
///
/// - Parameter url: URL of the asset.
open var url: URL? {
didSet {
if let url = self.url {
setup(url: url)
}
}
}
/// For setting up with AVAsset instead of URL
/// Note: Resets URL (cannot set both)
open var asset: AVAsset? {
get { return _asset }
set { _ = newValue.map { setupAsset($0) } }
}
/// Specifies how the video is displayed within a player layer’s bounds.
/// The default value is `AVLayerVideoGravityResizeAspect`. See `PlayerFillMode`.
open var fillMode: PlayerFillMode {
get {
return self._playerView.playerFillMode
}
set {
self._playerView.playerFillMode = newValue
}
}
/// Determines if the video should autoplay when a url is set
///
/// - Parameter bool: defaults to true
open var autoplay: Bool = true
/// Mutes audio playback when true.
open var muted: Bool {
get {
return self._avplayer.isMuted
}
set {
self._avplayer.isMuted = newValue
}
}
/// Volume for the player, ranging from 0.0 to 1.0 on a linear scale.
open var volume: Float {
get {
return self._avplayer.volume
}
set {
self._avplayer.volume = newValue
}
}
/// Pauses playback automatically when resigning active.
open var playbackPausesWhenResigningActive: Bool = true
/// Pauses playback automatically when backgrounded.
open var playbackPausesWhenBackgrounded: Bool = true
/// Resumes playback when became active.
open var playbackResumesWhenBecameActive: Bool = true
/// Resumes playback when entering foreground.
open var playbackResumesWhenEnteringForeground: Bool = true
// state
/// Playback automatically loops continuously when true.
open var playbackLoops: Bool {
get {
return self._avplayer.actionAtItemEnd == .none
}
set {
if newValue {
self._avplayer.actionAtItemEnd = .none
} else {
self._avplayer.actionAtItemEnd = .pause
}
}
}
/// Playback freezes on last frame frame at end when true.
open var playbackFreezesAtEnd: Bool = false
/// Current playback state of the Player.
open var playbackState: PlaybackState = .stopped {
didSet {
if playbackState != oldValue || !playbackEdgeTriggered {
self.executeClosureOnMainQueueIfNecessary {
self.playerDelegate?.playerPlaybackStateDidChange(self)
}
}
}
}
/// Current buffering state of the Player.
open var bufferingState: BufferingState = .unknown {
didSet {
if bufferingState != oldValue || !playbackEdgeTriggered {
self.executeClosureOnMainQueueIfNecessary {
self.playerDelegate?.playerBufferingStateDidChange(self)
}
}
}
}
/// Playback buffering size in seconds.
open var bufferSizeInSeconds: Double = 10
/// Playback is not automatically triggered from state changes when true.
open var playbackEdgeTriggered: Bool = true
/// Maximum duration of playback.
open var maximumDuration: TimeInterval {
get {
if let playerItem = self._playerItem {
return CMTimeGetSeconds(playerItem.duration)
} else {
return CMTimeGetSeconds(CMTime.indefinite)
}
}
}
/// Media playback's current time.
open var currentTime: TimeInterval {
get {
if let playerItem = self._playerItem {
return CMTimeGetSeconds(playerItem.currentTime())
} else {
return CMTimeGetSeconds(CMTime.indefinite)
}
}
}
/// The natural dimensions of the media.
open var naturalSize: CGSize {
get {
if let playerItem = self._playerItem,
let track = playerItem.asset.tracks(withMediaType: .video).first {
let size = track.naturalSize.applying(track.preferredTransform)
return CGSize(width: abs(size.width), height: abs(size.height))
} else {
return CGSize.zero
}
}
}
/// self.view as PlayerView type
public var playerView: PlayerView {
get {
return self._playerView
}
}
/// Return the av player layer for consumption by things such as Picture in Picture
open func playerLayer() -> AVPlayerLayer? {
return self._playerView.playerLayer
}
/// Indicates the desired limit of network bandwidth consumption for this item.
open var preferredPeakBitRate: Double = 0 {
didSet {
self._playerItem?.preferredPeakBitRate = self.preferredPeakBitRate
}
}
/// Indicates a preferred upper limit on the resolution of the video to be downloaded.
@available(iOS 11.0, tvOS 11.0, *)
open var preferredMaximumResolution: CGSize {
get {
return self._playerItem?.preferredMaximumResolution ?? CGSize.zero
}
set {
self._playerItem?.preferredMaximumResolution = newValue
self._preferredMaximumResolution = newValue
}
}
// MARK: - private instance vars
internal var _asset: AVAsset? {
didSet {
if let _ = self._asset {
self.setupPlayerItem(nil)
}
}
}
internal var _avplayer: AVPlayer = AVPlayer()
internal var _playerItem: AVPlayerItem?
internal var _playerObservers = [NSKeyValueObservation]()
internal var _playerItemObservers = [NSKeyValueObservation]()
internal var _playerLayerObserver: NSKeyValueObservation?
internal var _playerTimeObserver: Any?
internal var _playerView: PlayerView = PlayerView(frame: .zero)
internal var _seekTimeRequested: CMTime?
internal var _lastBufferTime: Double = 0
internal var _preferredMaximumResolution: CGSize = .zero
// Boolean that determines if the user or calling coded has trigged autoplay manually.
internal var _hasAutoplayActivated: Bool = true
// MARK: - object lifecycle
public convenience init() {
self.init(nibName: nil, bundle: nil)
}
public required init?(coder aDecoder: NSCoder) {
self._avplayer.actionAtItemEnd = .pause
super.init(coder: aDecoder)
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
self._avplayer.actionAtItemEnd = .pause
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
deinit {
self._avplayer.pause()
self.setupPlayerItem(nil)
self.removePlayerObservers()
self.playerDelegate = nil
self.removeApplicationObservers()
self.playbackDelegate = nil
self.removePlayerLayerObservers()
self._playerView.player = nil
}
// MARK: - view lifecycle
open override func loadView() {
super.loadView()
self._playerView.frame = self.view.bounds
self.view = self._playerView
}
open override func viewDidLoad() {
super.viewDidLoad()
if let url = self.url {
setup(url: url)
} else if let asset = self.asset {
setupAsset(asset)
}
self.addPlayerLayerObservers()
self.addPlayerObservers()
self.addApplicationObservers()
}
open override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if self.playbackState == .playing {
self.pause()
}
}
}
// MARK: - action funcs
extension Player {
/// Begins playback of the media from the beginning.
open func playFromBeginning() {
self.playbackDelegate?.playerPlaybackWillStartFromBeginning(self)
self._avplayer.seek(to: CMTime.zero)
self.playFromCurrentTime()
}
/// Begins playback of the media from the current time.
open func playFromCurrentTime() {
if !self.autoplay {
//external call to this method with auto play off. activate it before calling play
self._hasAutoplayActivated = true
}
self.play()
}
fileprivate func play() {
if self.autoplay || self._hasAutoplayActivated {
self.playbackState = .playing
self._avplayer.play()
}
}
/// Pauses playback of the media.
open func pause() {
if self.playbackState != .playing {
return
}
self._avplayer.pause()
self.playbackState = .paused
}
/// Stops playback of the media.
open func stop() {
if self.playbackState == .stopped {
return
}
self._avplayer.pause()
self.playbackState = .stopped
self.playbackDelegate?.playerPlaybackDidEnd(self)
}
/// Updates playback to the specified time.
///
/// - Parameters:
/// - time: The time to switch to move the playback.
/// - completionHandler: Call block handler after seeking/
open func seek(to time: CMTime, completionHandler: ((Bool) -> Swift.Void)? = nil) {
if let playerItem = self._playerItem {
return playerItem.seek(to: time, completionHandler: completionHandler)
} else {
_seekTimeRequested = time
}
}
/// Updates the playback time to the specified time bound.
///
/// - Parameters:
/// - time: The time to switch to move the playback.
/// - toleranceBefore: The tolerance allowed before time.
/// - toleranceAfter: The tolerance allowed after time.
/// - completionHandler: call block handler after seeking
open func seekToTime(to time: CMTime, toleranceBefore: CMTime, toleranceAfter: CMTime, completionHandler: ((Bool) -> Swift.Void)? = nil) {
if let playerItem = self._playerItem {
return playerItem.seek(to: time, toleranceBefore: toleranceBefore, toleranceAfter: toleranceAfter, completionHandler: completionHandler)
}
}
/// Captures a snapshot of the current Player asset.
///
/// - Parameter completionHandler: Returns a UIImage of the requested video frame. (Great for thumbnails!)
open func takeSnapshot(completionHandler: ((_ image: UIImage?, _ error: Error?) -> Void)? ) {
guard let asset = self._playerItem?.asset else {
DispatchQueue.main.async {
completionHandler?(nil, nil)
}
return
}
let imageGenerator = AVAssetImageGenerator(asset: asset)
imageGenerator.appliesPreferredTrackTransform = true
let currentTime = self._playerItem?.currentTime() ?? CMTime.zero
imageGenerator.generateCGImagesAsynchronously(forTimes: [NSValue(time: currentTime)]) { (requestedTime, image, actualTime, result, error) in
if let image = image {
switch result {
case .succeeded:
let uiimage = UIImage(cgImage: image)
DispatchQueue.main.async {
completionHandler?(uiimage, nil)
}
break
case .failed:
fallthrough
case .cancelled:
fallthrough
@unknown default:
DispatchQueue.main.async {
completionHandler?(nil, nil)
}
break
}
} else {
DispatchQueue.main.async {
completionHandler?(nil, error)
}
}
}
}
}
// MARK: - loading funcs
extension Player {
fileprivate func setup(url: URL) {
guard isViewLoaded else { return }
// ensure everything is reset beforehand
if self.playbackState == .playing {
self.pause()
}
//Reset autoplay flag since a new url is set.
self._hasAutoplayActivated = false
if self.autoplay {
self.playbackState = .playing
} else {
self.playbackState = .stopped
}
self.setupPlayerItem(nil)
let asset = AVURLAsset(url: url, options: .none)
self.setupAsset(asset)
}
fileprivate func setupAsset(_ asset: AVAsset, loadableKeys: [String] = ["tracks", "playable", "duration"]) {
guard isViewLoaded else { return }
if self.playbackState == .playing {
self.pause()
}
self.bufferingState = .unknown
self._asset = asset
self._asset?.loadValuesAsynchronously(forKeys: loadableKeys, completionHandler: { () -> Void in
if let asset = self._asset {
for key in loadableKeys {
var error: NSError? = nil
let status = asset.statusOfValue(forKey: key, error: &error)
if status == .failed {
self.playbackState = .failed
self.executeClosureOnMainQueueIfNecessary {
self.playerDelegate?.player(self, didFailWithError: PlayerError.failed)
}
return
}
}
if !asset.isPlayable {
self.playbackState = .failed
self.executeClosureOnMainQueueIfNecessary {
self.playerDelegate?.player(self, didFailWithError: PlayerError.failed)
}
return
}
let playerItem = AVPlayerItem(asset:asset)
self.setupPlayerItem(playerItem)
}
})
}
fileprivate func setupPlayerItem(_ playerItem: AVPlayerItem?) {
self.removePlayerItemObservers()
if let currentPlayerItem = self._playerItem {
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: currentPlayerItem)
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemFailedToPlayToEndTime, object: currentPlayerItem)
}
self._playerItem = playerItem
self._playerItem?.preferredPeakBitRate = self.preferredPeakBitRate
if #available(iOS 11.0, tvOS 11.0, *) {
self._playerItem?.preferredMaximumResolution = self._preferredMaximumResolution
}
if let seek = self._seekTimeRequested, self._playerItem != nil {
self._seekTimeRequested = nil
self.seek(to: seek)
}
if let updatedPlayerItem = self._playerItem {
self.addPlayerItemObservers()
NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidPlayToEndTime(_:)), name: .AVPlayerItemDidPlayToEndTime, object: updatedPlayerItem)
NotificationCenter.default.addObserver(self, selector: #selector(playerItemFailedToPlayToEndTime(_:)), name: .AVPlayerItemFailedToPlayToEndTime, object: updatedPlayerItem)
}
self._avplayer.replaceCurrentItem(with: self._playerItem)
// update new playerItem settings
if self.playbackLoops {
self._avplayer.actionAtItemEnd = .none
} else {
self._avplayer.actionAtItemEnd = .pause
}
}
}
// MARK: - NSNotifications
extension Player {
// MARK: - UIApplication
internal func addApplicationObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(handleApplicationWillResignActive(_:)), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleApplicationDidBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleApplicationDidEnterBackground(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleApplicationWillEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
}
internal func removeApplicationObservers() {
NotificationCenter.default.removeObserver(self)
}
// MARK: - AVPlayerItem handlers
@objc internal func playerItemDidPlayToEndTime(_ aNotification: Notification) {
self.executeClosureOnMainQueueIfNecessary {
if self.playbackLoops {
self.playbackDelegate?.playerPlaybackWillLoop(self)
self._avplayer.pause()
self._avplayer.seek(to: CMTime.zero)
self._avplayer.play()
} else if self.playbackFreezesAtEnd {
self.stop()
} else {
self._avplayer.seek(to: CMTime.zero, completionHandler: { _ in
self.stop()
})
}
}
}
@objc internal func playerItemFailedToPlayToEndTime(_ aNotification: Notification) {
self.playbackState = .failed
}
// MARK: - UIApplication handlers
@objc internal func handleApplicationWillResignActive(_ aNotification: Notification) {
if self.playbackState == .playing && self.playbackPausesWhenResigningActive {
self.pause()
}
}
@objc internal func handleApplicationDidBecomeActive(_ aNotification: Notification) {
if self.playbackState == .paused && self.playbackResumesWhenBecameActive {
self.play()
}
}
@objc internal func handleApplicationDidEnterBackground(_ aNotification: Notification) {
if self.playbackState == .playing && self.playbackPausesWhenBackgrounded {
self.pause()
}
}
@objc internal func handleApplicationWillEnterForeground(_ aNoticiation: Notification) {
if self.playbackState != .playing && self.playbackResumesWhenEnteringForeground {
self.play()
}
}
}
// MARK: - KVO
extension Player {
// MARK: - AVPlayerItemObservers
internal func addPlayerItemObservers() {
guard let playerItem = self._playerItem else {
return
}
self._playerItemObservers.append(playerItem.observe(\.isPlaybackBufferEmpty, options: [.new, .old]) { [weak self] (object, change) in
if object.isPlaybackBufferEmpty {
self?.bufferingState = .delayed
}
switch object.status {
case .readyToPlay:
self?._playerView.player = self?._avplayer
case .failed:
self?.playbackState = PlaybackState.failed
default:
break
}
})
self._playerItemObservers.append(playerItem.observe(\.isPlaybackLikelyToKeepUp, options: [.new, .old]) { [weak self] (object, change) in
if object.isPlaybackLikelyToKeepUp {
self?.bufferingState = .ready
if self?.playbackState == .playing {
self?.playFromCurrentTime()
}
}
switch object.status {
case .failed:
self?.playbackState = PlaybackState.failed
break
case .unknown:
fallthrough
case .readyToPlay:
fallthrough
@unknown default:
self?._playerView.player = self?._avplayer
break
}
})
// self._playerItemObservers.append(playerItem.observe(\.status, options: [.new, .old]) { (object, change) in
// })
self._playerItemObservers.append(playerItem.observe(\.loadedTimeRanges, options: [.new, .old]) { [weak self] (object, change) in
guard let strongSelf = self else {
return
}
strongSelf.bufferingState = .ready
let timeRanges = object.loadedTimeRanges
if let timeRange = timeRanges.first?.timeRangeValue {
let bufferedTime = CMTimeGetSeconds(CMTimeAdd(timeRange.start, timeRange.duration))
if strongSelf._lastBufferTime != bufferedTime {
strongSelf._lastBufferTime = bufferedTime
strongSelf.executeClosureOnMainQueueIfNecessary {
strongSelf.playerDelegate?.playerBufferTimeDidChange(bufferedTime)
}
}
}
let currentTime = CMTimeGetSeconds(object.currentTime())
let passedTime = strongSelf._lastBufferTime <= 0 ? currentTime : (strongSelf._lastBufferTime - currentTime)
if (passedTime >= strongSelf.bufferSizeInSeconds ||
strongSelf._lastBufferTime == strongSelf.maximumDuration ||
timeRanges.first == nil) &&
strongSelf.playbackState == .playing {
strongSelf.play()
}
})
}
internal func removePlayerItemObservers() {
for observer in self._playerItemObservers {
observer.invalidate()
}
self._playerItemObservers.removeAll()
}
// MARK: - AVPlayerLayerObservers
internal func addPlayerLayerObservers() {
self._playerLayerObserver = self._playerView.playerLayer.observe(\.isReadyForDisplay, options: [.new, .old]) { [weak self] (object, change) in
self?.executeClosureOnMainQueueIfNecessary {
if let strongSelf = self {
strongSelf.playerDelegate?.playerReady(strongSelf)
}
}
}
}
internal func removePlayerLayerObservers() {
self._playerLayerObserver?.invalidate()
self._playerLayerObserver = nil
}
// MARK: - AVPlayerObservers
internal func addPlayerObservers() {
self._playerTimeObserver = self._avplayer.addPeriodicTimeObserver(forInterval: CMTimeMake(value: 1, timescale: 100), queue: DispatchQueue.main, using: { [weak self] timeInterval in
guard let strongSelf = self else {
return
}
strongSelf.playbackDelegate?.playerCurrentTimeDidChange(strongSelf)
})
if #available(iOS 10.0, tvOS 10.0, *) {
self._playerObservers.append(self._avplayer.observe(\.timeControlStatus, options: [.new, .old]) { [weak self] (object, change) in
switch object.timeControlStatus {
case .paused:
self?.playbackState = .paused
case .playing:
self?.playbackState = .playing
case .waitingToPlayAtSpecifiedRate:
fallthrough
@unknown default:
break
}
})
}
}
internal func removePlayerObservers() {
if let observer = self._playerTimeObserver {
self._avplayer.removeTimeObserver(observer)
}
for observer in self._playerObservers {
observer.invalidate()
}
self._playerObservers.removeAll()
}
}
// MARK: - queues
extension Player {
internal func executeClosureOnMainQueueIfNecessary(withClosure closure: @escaping () -> Void) {
if Thread.isMainThread {
closure()
} else {
DispatchQueue.main.async(execute: closure)
}
}
}
// MARK: - PlayerView
public class PlayerView: UIView {
// MARK: - overrides
public override class var layerClass: AnyClass {
get {
return AVPlayerLayer.self
}
}
// MARK: - internal properties
internal var playerLayer: AVPlayerLayer {
get {
return self.layer as! AVPlayerLayer
}
}
internal var player: AVPlayer? {
get {
return self.playerLayer.player
}
set {
self.playerLayer.player = newValue
self.playerLayer.isHidden = (self.playerLayer.player == nil)
}
}
// MARK: - public properties
public var playerBackgroundColor: UIColor? {
get {
if let cgColor = self.playerLayer.backgroundColor {
return UIColor(cgColor: cgColor)
}
return nil
}
set {
self.playerLayer.backgroundColor = newValue?.cgColor
}
}
public var playerFillMode: PlayerFillMode {
get {
return self.playerLayer.videoGravity
}
set {
self.playerLayer.videoGravity = newValue
}
}
public var isReadyForDisplay: Bool {
get {
return self.playerLayer.isReadyForDisplay
}
}
// MARK: - object lifecycle
public override init(frame: CGRect) {
super.init(frame: frame)
self.playerLayer.isHidden = true
self.playerFillMode = .resizeAspect
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.playerLayer.isHidden = true
self.playerFillMode = .resizeAspect
}
deinit {
self.player?.pause()
self.player = nil
}
}
|
mit
|
fe63c5910641fc929022b658bf25b78f
| 30.632369 | 188 | 0.603361 | 5.187731 | false | false | false | false |
nameghino/swift-algorithm-club
|
Ring Buffer/RingBuffer.playground/Contents.swift
|
2
|
2218
|
//: Playground - noun: a place where people can play
public struct RingBuffer<T> {
private var array: [T?]
private var readIndex = 0
private var writeIndex = 0
public init(count: Int) {
array = [T?](count: count, repeatedValue: nil)
}
public mutating func write(element: T) -> Bool {
if !isFull {
array[writeIndex % array.count] = element
writeIndex += 1
return true
} else {
return false
}
}
public mutating func read() -> T? {
if !isEmpty {
let element = array[readIndex % array.count]
readIndex += 1
return element
} else {
return nil
}
}
private var availableSpaceForReading: Int {
return writeIndex - readIndex
}
public var isEmpty: Bool {
return availableSpaceForReading == 0
}
private var availableSpaceForWriting: Int {
return array.count - availableSpaceForReading
}
public var isFull: Bool {
return availableSpaceForWriting == 0
}
}
var buffer = RingBuffer<Int>(count: 5)
buffer.array // [nil, nil, nil, nil, nil]
buffer.readIndex // 0
buffer.writeIndex // 0
buffer.availableSpaceForReading // 0
buffer.availableSpaceForWriting // 5
buffer.write(123)
buffer.write(456)
buffer.write(789)
buffer.write(666)
buffer.array // [{Some 123}, {Some 456}, {Some 789}, {Some 666}, nil]
buffer.readIndex // 0
buffer.writeIndex // 4
buffer.availableSpaceForReading // 4
buffer.availableSpaceForWriting // 1
buffer.read() // 123
buffer.readIndex // 1
buffer.availableSpaceForReading // 3
buffer.availableSpaceForWriting // 2
buffer.read() // 456
buffer.read() // 789
buffer.readIndex // 3
buffer.availableSpaceForReading // 1
buffer.availableSpaceForWriting // 4
buffer.write(333)
buffer.write(555)
buffer.array // [{Some 555}, {Some 456}, {Some 789}, {Some 666}, {Some 333}]
buffer.availableSpaceForReading // 3
buffer.availableSpaceForWriting // 2
buffer.writeIndex // 6
buffer.read() // 666
buffer.read() // 333
buffer.read() // 555
buffer.read() // nil
buffer.availableSpaceForReading // 0
buffer.availableSpaceForWriting // 5
buffer.readIndex // 6
|
mit
|
be9442ba6d33dd8e80b744475784794d
| 23.373626 | 85 | 0.649684 | 3.884413 | false | false | false | false |
zapdroid/RXWeather
|
Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift
|
1
|
5420
|
//
// CompositeDisposable.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/20/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents a group of disposable resources that are disposed together.
public final class CompositeDisposable: DisposeBase, Disposable, Cancelable {
/// Key used to remove disposable from composite disposable
public struct DisposeKey {
fileprivate let key: BagKey
fileprivate init(key: BagKey) {
self.key = key
}
}
private var _lock = SpinLock()
// state
private var _disposables: Bag<Disposable>? = Bag()
public var isDisposed: Bool {
_lock.lock(); defer { _lock.unlock() }
return _disposables == nil
}
public override init() {
}
/// Initializes a new instance of composite disposable with the specified number of disposables.
public init(_ disposable1: Disposable, _ disposable2: Disposable) {
// This overload is here to make sure we are using optimized version up to 4 arguments.
_ = _disposables!.insert(disposable1)
_ = _disposables!.insert(disposable2)
}
/// Initializes a new instance of composite disposable with the specified number of disposables.
public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) {
// This overload is here to make sure we are using optimized version up to 4 arguments.
_ = _disposables!.insert(disposable1)
_ = _disposables!.insert(disposable2)
_ = _disposables!.insert(disposable3)
}
/// Initializes a new instance of composite disposable with the specified number of disposables.
public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposable4: Disposable, _ disposables: Disposable...) {
// This overload is here to make sure we are using optimized version up to 4 arguments.
_ = _disposables!.insert(disposable1)
_ = _disposables!.insert(disposable2)
_ = _disposables!.insert(disposable3)
_ = _disposables!.insert(disposable4)
for disposable in disposables {
_ = _disposables!.insert(disposable)
}
}
/// Initializes a new instance of composite disposable with the specified number of disposables.
public init(disposables: [Disposable]) {
for disposable in disposables {
_ = _disposables!.insert(disposable)
}
}
/**
Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
- parameter disposable: Disposable to add.
- returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already
disposed `nil` will be returned.
*/
public func insert(_ disposable: Disposable) -> DisposeKey? {
let key = _insert(disposable)
if key == nil {
disposable.dispose()
}
return key
}
private func _insert(_ disposable: Disposable) -> DisposeKey? {
_lock.lock(); defer { _lock.unlock() }
let bagKey = _disposables?.insert(disposable)
return bagKey.map(DisposeKey.init)
}
/// - returns: Gets the number of disposables contained in the `CompositeDisposable`.
public var count: Int {
_lock.lock(); defer { _lock.unlock() }
return _disposables?.count ?? 0
}
/// Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable.
///
/// - parameter disposeKey: Key used to identify disposable to be removed.
public func remove(for disposeKey: DisposeKey) {
_remove(for: disposeKey)?.dispose()
}
private func _remove(for disposeKey: DisposeKey) -> Disposable? {
_lock.lock(); defer { _lock.unlock() }
return _disposables?.removeKey(disposeKey.key)
}
/// Disposes all disposables in the group and removes them from the group.
public func dispose() {
if let disposables = _dispose() {
disposeAll(in: disposables)
}
}
private func _dispose() -> Bag<Disposable>? {
_lock.lock(); defer { _lock.unlock() }
let disposeBag = _disposables
_disposables = nil
return disposeBag
}
}
extension Disposables {
/// Creates a disposable with the given disposables.
public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) -> Cancelable {
return CompositeDisposable(disposable1, disposable2, disposable3)
}
/// Creates a disposable with the given disposables.
public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposables: Disposable ...) -> Cancelable {
var disposables = disposables
disposables.append(disposable1)
disposables.append(disposable2)
disposables.append(disposable3)
return CompositeDisposable(disposables: disposables)
}
/// Creates a disposable with the given disposables.
public static func create(_ disposables: [Disposable]) -> Cancelable {
switch disposables.count {
case 2:
return Disposables.create(disposables[0], disposables[1])
default:
return CompositeDisposable(disposables: disposables)
}
}
}
|
mit
|
e11c4d0db605f628a97fb55060c7ccd8
| 34.887417 | 157 | 0.656394 | 4.908514 | false | false | false | false |
numist/Tetris
|
Tetris/GameScene.swift
|
1
|
1002
|
import SpriteKit
class GameScene: SKScene {
override func didMoveToView(view: SKView) {
/* Setup your scene here */
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
myLabel.text = "Hello, World!";
myLabel.fontSize = 45;
myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame));
self.addChild(myLabel)
}
override func mouseDown(theEvent: NSEvent) {
/* Called when a mouse click occurs */
let location = theEvent.locationInNode(self)
let sprite = SKSpriteNode(imageNamed:"Spaceship")
sprite.position = location;
sprite.setScale(0.5)
let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)
sprite.runAction(SKAction.repeatActionForever(action))
self.addChild(sprite)
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
|
mit
|
0cb2ffe147800d2d415e088e4b91f34a
| 30.3125 | 93 | 0.620758 | 4.911765 | false | false | false | false |
xipengyang/SwiftApp1
|
we sale assistant/we sale assistant/OrderViewController.swift
|
1
|
7794
|
//
// we sale assistant
//
// Created by xipeng yang on 6/02/15.
// Copyright (c) 2015 xipeng yang. All rights reserved.
//
import UIKit
import CoreData
class OrderViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "background.png")!)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
tableView.reloadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: OrderCell?
cell = self.tableView.dequeueReusableCellWithIdentifier("order") as? OrderCell
if(cell == nil) {
cell = OrderCell(style: UITableViewCellStyle.Default, reuseIdentifier: "order")
}
configureCell(cell!, atIndexPath: indexPath)
return cell!
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
let sectionInfo = fetchedResultsController.sections![section]
return sectionInfo.name
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let order = fetchedResultsController.objectAtIndexPath(indexPath) as! OrderD
let destViewController: AddOrderViewController = self.storyboard?.instantiateViewControllerWithIdentifier("AddOrderViewController") as! AddOrderViewController
if(indexPath.row >= 0) {
destViewController.order = order
}
self.presentViewController(destViewController, animated: true, completion: nil)
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
//Override to support custom action in the order table view
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let completeAction = UITableViewRowAction(style: .Normal, title: "Complete") {
(action: UITableViewRowAction, indexPath: NSIndexPath) -> Void in
let selectedOrder = self.fetchedResultsController.objectAtIndexPath(indexPath) as! OrderD
selectedOrder.status = "Completed"
self.appDel.saveContextAction()
}
completeAction.backgroundColor = UIColor.MKColor.LightGreen
return [completeAction]
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if (editingStyle == UITableViewCellEditingStyle.Delete) {
// handle delete (by removing the data from your array and updating the tableview)
}
}
private func configureCell(cell: OrderCell,
atIndexPath indexPath: NSIndexPath) {
let order = fetchedResultsController.objectAtIndexPath(indexPath) as! OrderD
let customer: Person? = order.customer
cell.topLeftLabel?.text = customer?.name ?? "Customer"
let products: [ProductD] = order.products.allObjects as! [ProductD]
var bodyText :String = ""
for product in products {
bodyText = ("\(bodyText) \(product.productName) (\(product.quantity!))")
}
cell.bodyLabel?.text = bodyText
dateFormatter.dateFormat = dateFormat
cell.topRightLabel?.text = dateFormatter.stringFromDate(order.orderDate)
}
//variables
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
var _fetchedResultsController: NSFetchedResultsController?
var dateFormatter = NSDateFormatter()
var dateFormat = "dd-MM-yyyy"
lazy var fetchedResultsController: NSFetchedResultsController = {
[unowned self] in
// return if already initialized
if self._fetchedResultsController != nil {
return self._fetchedResultsController!
}
let managedObjectContext = self.appDel.cdh.getContext()
let entity = NSEntityDescription.entityForName("OrderD", inManagedObjectContext: managedObjectContext)
let sectionSortDescriptor = NSSortDescriptor(key: "status", ascending: false)
let customerNameSortDescriptor = NSSortDescriptor(key: "customer", ascending: true)
let req = NSFetchRequest()
req.entity = entity
req.sortDescriptors = [sectionSortDescriptor, customerNameSortDescriptor]
/* NSFetchedResultsController initialization
a `nil` `sectionNameKeyPath` generates a single section */
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: req, managedObjectContext: managedObjectContext, sectionNameKeyPath: "status", cacheName: nil)
aFetchedResultsController.delegate = self
self._fetchedResultsController = aFetchedResultsController
// perform initial model fetch
var e: NSError?
do {
try self._fetchedResultsController!.performFetch()
} catch var error as NSError {
e = error
print("fetch error: \(e!.localizedDescription)")
abort();
} catch {
fatalError()
}
return self._fetchedResultsController!
}()
}
extension OrderViewController: NSFetchedResultsControllerDelegate {
func controller(controller: NSFetchedResultsController,
didChangeObject object: AnyObject,
atIndexPath indexPath: NSIndexPath?,
forChangeType type: NSFetchedResultsChangeType,
newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Automatic)
case .Update:
if let i = indexPath, cell = tableView.cellForRowAtIndexPath(i) as? OrderCell {
configureCell(cell, atIndexPath: i)
tableView.reloadRowsAtIndexPaths([i], withRowAnimation: UITableViewRowAnimation.Automatic)
}
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Automatic)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Automatic)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Automatic)
default:
return
}
}
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
/* called last
tells `UITableView` updates are complete */
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
}
|
mit
|
049a464a7a6d982b79b65fe53c710759
| 38.363636 | 175 | 0.668078 | 6.166139 | false | false | false | false |
lukaszwas/mcommerce-api
|
Sources/App/Models/Stripe/Models/Charge.swift
|
1
|
5147
|
//
// Charge.swift
// Stripe
//
// Created by Anthony Castelli on 4/15/17.
//
//
import Foundation
import Vapor
/**
Charge Model
https://stripe.com/docs/api/curl#charge_object
*/
public final class Charge: StripeModelProtocol {
public let id: String
public let object: String
public let amount: Int
public let amountRefunded: Int
public let application: String?
public let applicationFee: Int?
public let balanceTransactionId: String
public let isCaptured: Bool
public let created: Date
public let customerId: String?
public let description: String?
public let destination: String?
public let failureCode: Int?
public let failureMessage: String?
public let invoiceId: String?
public let isLiveMode: Bool
public let isPaid: Bool
public let isRefunded: Bool
public let review: String?
public let sourceTransfer: String?
public let statementDescriptor: String?
public let transferGroup: String?
public private(set) var currency: StripeCurrency?
public private(set) var fraud: FraudDetails?
public private(set) var outcome: Outcome?
public private(set) var refunds: Refund?
public private(set) var status: StripeStatus?
public private(set) var shippingLabel: ShippingLabel?
public private(set) var metadata: Node?
public private(set) var card: Card?
public private(set) var source: Source?
public init(node: Node) throws {
self.id = try node.get("id")
self.object = try node.get("object")
self.amount = try node.get("amount")
self.amountRefunded = try node.get("amount_refunded")
self.application = try node.get("application")
self.applicationFee = try node.get("application_fee")
self.balanceTransactionId = try node.get("balance_transaction")
self.isCaptured = try node.get("captured")
self.created = try node.get("created")
self.customerId = try node.get("customer")
self.description = try node.get("description")
self.destination = try node.get("destination")
self.failureCode = try node.get("failure_code")
self.failureMessage = try node.get("failure_message")
self.invoiceId = try node.get("invoice")
self.isLiveMode = try node.get("livemode")
self.isPaid = try node.get("paid")
self.isRefunded = try node.get("refunded")
self.review = try node.get("review")
self.sourceTransfer = try node.get("source_transfer")
self.statementDescriptor = try node.get("statement_descriptor")
self.transferGroup = try node.get("transfer_group")
self.currency = try StripeCurrency(rawValue: node.get("currency"))
self.fraud = try node.get("fraud_details")
self.outcome = try node.get("outcome")
self.refunds = try node.get("refunds")
self.status = try StripeStatus(rawValue: node.get("status"))
if let _ = node["shipping"]?.object {
self.shippingLabel = try node.get("shipping")
}
self.metadata = try node.get("metadata")
// We have to determine if it's a card or a source item
if let sourceNode: Node = try node.get("source") {
if let object = sourceNode["object"]?.string, object == "card" {
self.card = try node.get("source")
} else if let object = sourceNode["object"]?.string, object == "source" {
self.source = try node.get("source")
}
}
}
public func makeNode(in context: Context?) throws -> Node {
var object: [String : Any?] = [
"id": self.id,
"object": self.object,
"amount": self.amount,
"amount_refunded": self.amountRefunded,
"application": self.application,
"application_fee": self.applicationFee,
"balance_transaction": self.balanceTransactionId,
"captured": self.isCaptured,
"created": self.created,
"currency": self.currency,
"customer": self.customerId,
"description": self.description,
"destination": self.destination,
"failure_code": self.failureCode,
"failure_message": self.failureMessage,
"fraud_details": self.fraud,
"invoice": self.invoiceId,
"livemode": self.isLiveMode,
"metadata": self.metadata,
"outcome": self.outcome,
"paid": self.isPaid,
"refunded": self.isRefunded,
"refunds": self.refunds,
"review": self.review,
"shipping": self.shippingLabel,
"source_transfer": self.sourceTransfer,
"statement_descriptor": self.statementDescriptor,
"status": self.status?.rawValue,
"transfer_group": self.transferGroup
]
if let source = self.source {
object["source"] = source
} else if let card = self.card {
object["source"] = card
}
return try Node(node: object)
}
}
|
mit
|
a1c71f82ac2427a424e2819ea91ebc9e
| 35.764286 | 85 | 0.610841 | 4.347128 | false | false | false | false |
austinzmchen/guildOfWarWorldBosses
|
GoWWorldBosses/Extensions/StringPlus.swift
|
1
|
520
|
//
// StringPlus.swift
// GoWWorldBosses
//
// Created by Austin Chen on 2017-03-07.
// Copyright © 2017 Austin Chen. All rights reserved.
//
import Foundation
// roughly equal to
func ~= (lhs: String?, rhs: String?) -> Bool {
guard var l = lhs,
var r = rhs else { return false } // false if either one is nil
l = l.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
r = r.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
return l.lowercased() == r.lowercased()
}
|
mit
|
eb2350c6e74c3d738dadb8afb2997683
| 26.315789 | 71 | 0.672447 | 3.788321 | false | false | false | false |
Harry-L/5-3-1
|
531/531/SettingsViewController.swift
|
1
|
4439
|
//
// SettingsViewController.swift
// 531
//
// Created by Harry Liu on 2016-01-24.
// Copyright © 2016 HarryLiu. All rights reserved.
//
import UIKit
class SettingsViewController: UITableViewController {
var maximums = [Int]() //[Press, Squat, Bench, Dead]
var nextWorkout = [Int]() //[Week, day]
@IBOutlet weak var pressLabel: UITextField!
@IBOutlet weak var squatLabel: UITextField!
@IBOutlet weak var benchLabel: UITextField!
@IBOutlet weak var deadLabel: UITextField!
@IBAction func pressChanged(sender: AnyObject) {
if let weight = Int(pressLabel.text!) {
maximums[0] = weight
}
else {
pressLabel.text! = String(maximums[0])
}
}
@IBAction func squatChanged(sender: AnyObject) {
if let weight = Int(squatLabel.text!) {
maximums[1] = weight
}
else {
squatLabel.text! = String(maximums[1])
}
}
@IBAction func benchChanged(sender: AnyObject) {
if let weight = Int(benchLabel.text!) {
maximums[2] = weight
}
else {
benchLabel.text! = String(maximums[2])
}
}
@IBAction func deadChanged(sender: AnyObject) {
if let weight = Int(deadLabel.text!) {
maximums[3] = weight
}
else {
deadLabel.text! = String(maximums[3])
}
}
@IBAction func pressChanging(sender: AnyObject) {
pressLabel.text! = ""
}
@IBAction func squatChanging(sender: AnyObject) {
squatLabel.text! = ""
}
@IBAction func benchChanging(sender: AnyObject) {
benchLabel.text! = ""
}
@IBAction func deadChanging(sender: AnyObject) {
deadLabel.text! = ""
}
override func viewDidLoad() {
super.viewDidLoad()
loadData()
colorSetup()
loadKeyboard()
keyboardDismiss()
}
func loadKeyboard() {
pressLabel.keyboardType = UIKeyboardType.NumberPad
squatLabel.keyboardType = UIKeyboardType.NumberPad
benchLabel.keyboardType = UIKeyboardType.NumberPad
deadLabel.keyboardType = UIKeyboardType.NumberPad
}
func loadData() {
let defaults = NSUserDefaults.standardUserDefaults()
maximums = defaults.arrayForKey("maximums") as? [Int] ?? [0, 0, 0, 0]
nextWorkout = defaults.arrayForKey("nextWorkout") as? [Int] ?? [1, 1]
/*
if maximums.count < 4 {
defaults.setObject([0, 0, 0, 0], forKey: "maximums")
maximums = defaults.arrayForKey("maximums") as? [Int] ?? [0, 0, 0, 0]
}
if nextWorkout.count < 2 {
defaults.setObject([1, 1], forKey: "nextWorkout")
nextWorkout = defaults.arrayForKey("nextWorkout") as? [Int] ?? [1, 1]
}*/
//print("loading maximums")
//print(maximums)
pressLabel.text! = String(maximums[0])
squatLabel.text! = String(maximums[1])
benchLabel.text! = String(maximums[2])
deadLabel.text! = String(maximums[3])
//print("loaded maximums")
}
func colorSetup() {
//nav bar consistent
navigationController!.navigationBar.barTintColor = UIColor.blackColor()
navigationController!.navigationBar.tintColor = UIColor.whiteColor()
navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()]
//table view gray
tableView!.backgroundColor = UIColor.init(red: 241.0/255.0, green: 241.0/255.0, blue: 241.0/255.0, alpha: 1)
//status bar white
navigationController!.navigationBar.barStyle = UIBarStyle.Black
}
func keyboardDismiss() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
//MARK NAVIGATION
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
dismissKeyboard()
pressChanged(self)
squatChanged(self)
benchChanged(self)
deadChanged(self)
let vc = segue.destinationViewController as! HistoryViewController
vc.maximums = maximums
}
}
|
mit
|
e26cfc9db41b3fdabd260ef72035c031
| 28.986486 | 120 | 0.591257 | 4.460302 | false | false | false | false |
noppoMan/SwiftKnex
|
Sources/SwiftKnex/Schema/Schema.swift
|
1
|
10093
|
//
// Schema.swift
// SwiftKnex
//
// Created by Yuki Takei on 2017/01/14.
//
//
import Foundation
public enum SchemaError: Error {
case primaryKeyShouldBeOnlyOne
}
public struct Schema {
public enum Charset {
case utf8
}
public enum IndexType {
case index
case unique
}
public class Field {
let name: String
let type: FieldType
var isPrimaryKey = false
var isAutoIncrement = false
var isUnsigned = false
var charset: Charset = .utf8
var index: IndexType?
var isNotNullable = false
var beforeColumn: String?
var defaultValue: Any?
public init(name: String, type: FieldType) {
self.name = name
self.type = type
}
public func `default`(to value: Any) -> Field {
self.defaultValue = value
return self
}
public func after(for name: String) -> Field {
self.beforeColumn = name
return self
}
public func asPrimaryKey() -> Field {
self.isPrimaryKey = true
return self
}
public func asAutoIncrement() -> Field {
self.isAutoIncrement = true
return self
}
public func asNotNullable() -> Field {
self.isNotNullable = true
return self
}
public func asUnsigned() -> Field {
self.isUnsigned = true
return self
}
public func charset(_ char: Charset) -> Field {
self.charset = char
return self
}
public func asUnique() -> Field {
self.index = .unique
return self
}
public func asIndex() -> Field {
self.index = .index
return self
}
}
public enum MYSQLEngine: String {
case innodb = "InnoDB"
}
public enum SchemaStatement {
case create
case drop
case alter
}
public struct Index {
let name: String
let columns: [String]
let isUnique: Bool
}
public struct TimeStampFields {
let forCreated: Schema.Field
let forUpdated: Schema.Field
public init(forCreated: String = "created_at", forUpdated: String = "updated_at"){
self.forCreated = Schema.datetime(forCreated)
self.forUpdated = Schema.datetime(forUpdated)
}
}
final class Buiulder {
let fields: [Schema.Field]
var charset: Charset?
var timezone: String = "Local"
var timestamp: TimeStampFields?
var table: String
var engine: MYSQLEngine = .innodb
var indexes = [Index]()
init(_ table: String, _ fields: [Schema.Field]) {
self.table = table
self.fields = fields
}
func index(name: String? = nil, columns: [String], unique: Bool = false){
indexes.append(
Index(
name: name ?? "\(table)_\(columns.joined(separator: "_and_"))_\(unique ? "unique":"index")",
columns: columns,
isUnique: unique
)
)
}
func engine(_ engine: MYSQLEngine){
self.engine = engine
}
func charset(_ char: Charset) {
self.charset = char
}
func hasTimestamps(_ timestampFields: TimeStampFields){
self.timestamp = timestampFields
}
func buildFields() -> [String] {
var schemaDefiniations = [String]()
var fields = self.fields
if let timestamp = self.timestamp {
fields += [timestamp.forCreated, timestamp.forUpdated]
}
for f in fields {
var str = ""
str += pack(key: f.name)
str += " \(f.type.build())"
if f.isUnsigned {
str += " UNSIGNED"
}
if f.isNotNullable || f.isPrimaryKey {
str += " NOT NULL"
} else {
if let defaultVal = f.defaultValue {
str += " DEFAULT \(defaultVal)"
} else {
str += " DEFAULT NULL"
}
}
if f.isAutoIncrement {
str += " AUTO_INCREMENT"
}
schemaDefiniations.append(str)
}
return schemaDefiniations
}
func buildIndexes() -> [String] {
var indexKeys = [String]()
for f in fields {
if let index = f.index {
let indexStr: String
switch index {
case .index:
indexStr = "KEY `\(table)_\(f.name)_index`(\(pack(key: f.name)))"
case .unique:
indexStr = "UNIQUE KEY `\(table)_\(f.name)_unique`(\(pack(key: f.name)))"
}
indexKeys.append(indexStr)
}
}
for index in indexes {
var key = "KEY `\(index.name)`(\(index.columns.map({ pack(key: $0) }).joined(separator: ", ")))"
if index.isUnique {
key = "UNIQUE \(key)"
}
indexKeys.append(key)
}
return indexKeys
}
func buildPrimaryKey() throws -> String? {
var primaryKey: String?
for f in fields {
if f.isPrimaryKey {
if primaryKey != nil {
throw SchemaError.primaryKeyShouldBeOnlyOne
}
primaryKey = "PRIMARY KEY(\(pack(key: f.name)))"
}
}
return primaryKey
}
}
}
extension Schema {
public enum FieldType {
case integer(length: Int)
case bigInteger(length: Int)
case string(length: Int)
case text(length: Int?)
case mediumText(length: Int?)
case float(digits: Int?, decimalDigits: Int?)
case double(digits: Int?, decimalDigits: Int?)
case boolean
case datetime
case json
func build() -> Swift.String {
switch self {
case .integer(length: let length):
return "INT(\(length))"
case .bigInteger(length: let length):
return "BIGINT(\(length))"
case .string(length: let length):
return "VARCHAR(\(length))"
case .text(length: let length):
if let length = length {
return "TEXT(\(length))"
} else {
return "TEXT"
}
case .mediumText(length: let length):
if let length = length {
return "MEDIUMTEXT(\(length))"
} else {
return "MEDIUMTEXT"
}
case .float(digits: let _digits, decimalDigits: let _decimalDigits):
if let digits = _digits, let decimalDigits = _decimalDigits {
return "FLOAT(\(digits), \(decimalDigits))"
} else {
return "FLOAT"
}
case .double(digits: let _digits, decimalDigits: let _decimalDigits):
if let digits = _digits, let decimalDigits = _decimalDigits {
return "Double(\(digits), \(decimalDigits))"
} else {
return "Double"
}
case .boolean:
return "TINYINT(1)"
case .datetime:
return "DATETIME"
case .json:
return "JSON"
}
}
}
public static func integer(_ name: String, length: Int = 11) -> Field {
return Field(name: name, type: .integer(length: length))
}
public static func bigInteger(_ name: String, length: Int = 20) -> Field {
return Field(name: name, type: .bigInteger(length: length))
}
public static func string(_ name: String, length: Int = 255) -> Field {
return Field(name: name, type: .string(length: length))
}
public static func text(_ name: String, length: Int? = nil) -> Field {
return Field(name: name, type: .text(length: length))
}
public static func mediumText(_ name: String, length: Int? = nil) -> Field {
return Field(name: name, type: .mediumText(length: length))
}
public static func float(_ name: String, digits: Int? = nil, decimalDigits: Int? = nil) -> Field {
return Field(name: name, type: .float(digits: digits, decimalDigits: decimalDigits))
}
public static func double(_ name: String, digits: Int? = nil, decimalDigits: Int? = nil) -> Field {
return Field(name: name, type: .double(digits: digits, decimalDigits: decimalDigits))
}
public static func boolean(_ name: String) -> Field {
return Field(name: name, type: .boolean)
}
public static func datetime(_ name: String) -> Field {
return Field(name: name, type: .datetime)
}
public static func json(_ name: String) -> Field {
return Field(name: name, type: .json)
}
}
|
mit
|
2d7e6b858227ef13d74f7d997886559d
| 27.919771 | 112 | 0.460517 | 5.165302 | false | false | false | false |
iOSWizards/AwesomeUIMagic
|
AwesomeUIMagic/Classes/Custom/DesignableTextView.swift
|
1
|
4478
|
//
// DesignableTextView.swift
// Quests
//
// Created by Leonardo Vinicius Kaminski Ferreira on 14/02/17.
// Copyright © 2017 Mindvalley. All rights reserved.
//
import UIKit
@IBDesignable
open class DesignableTextView: UITextView {
private struct Constants {
static let defaultiOSPlaceholderColor = UIColor(red: 0.0, green: 0.0, blue: 0.0980392, alpha: 0.22)
}
public let placeholderLabel: UILabel = UILabel()
private var placeholderLabelConstraints = [NSLayoutConstraint]()
@IBInspectable open var placeholder: String = "" {
didSet {
placeholderLabel.text = placeholder
}
}
@IBInspectable open var placeholderColor: UIColor = DesignableTextView.Constants.defaultiOSPlaceholderColor {
didSet {
placeholderLabel.textColor = placeholderColor
}
}
override open var font: UIFont! {
didSet {
if placeholderFont == nil {
placeholderLabel.font = font
}
}
}
open var placeholderFont: UIFont? {
didSet {
let font = (placeholderFont != nil) ? placeholderFont : self.font
placeholderLabel.font = font
}
}
override open var textAlignment: NSTextAlignment {
didSet {
placeholderLabel.textAlignment = textAlignment
}
}
override open var text: String! {
didSet {
textDidChange()
}
}
override open var attributedText: NSAttributedString! {
didSet {
textDidChange()
}
}
override open var textContainerInset: UIEdgeInsets {
didSet {
updateConstraintsForPlaceholderLabel()
}
}
override public init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
NotificationCenter.default.addObserver(self,
selector: #selector(textDidChange),
name: UITextView.textDidChangeNotification,
object: nil)
placeholderLabel.font = font
placeholderLabel.textColor = placeholderColor
placeholderLabel.textAlignment = textAlignment
placeholderLabel.text = placeholder
placeholderLabel.numberOfLines = 0
placeholderLabel.backgroundColor = UIColor.clear
placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(placeholderLabel)
updateConstraintsForPlaceholderLabel()
}
private func updateConstraintsForPlaceholderLabel() {
var newConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(\(textContainerInset.left + textContainer.lineFragmentPadding))-[placeholder]",
options: [],
metrics: nil,
views: ["placeholder": placeholderLabel])
newConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-(\(textContainerInset.top))-[placeholder]",
options: [],
metrics: nil,
views: ["placeholder": placeholderLabel])
newConstraints.append(NSLayoutConstraint(
item: placeholderLabel,
attribute: .width,
relatedBy: .equal,
toItem: self,
attribute: .width,
multiplier: 1.0,
constant: -(textContainerInset.left + textContainerInset.right + textContainer.lineFragmentPadding * 2.0)
))
removeConstraints(placeholderLabelConstraints)
addConstraints(newConstraints)
placeholderLabelConstraints = newConstraints
}
@objc private func textDidChange() {
placeholderLabel.isHidden = !text.isEmpty
}
open override func layoutSubviews() {
super.layoutSubviews()
placeholderLabel.preferredMaxLayoutWidth = textContainer.size.width - textContainer.lineFragmentPadding * 2.0
}
deinit {
NotificationCenter.default.removeObserver(self,
name: UITextView.textDidChangeNotification,
object: nil)
}
}
|
mit
|
218c5703abf35591374020219fbe5e8b
| 31.442029 | 163 | 0.603082 | 6.244073 | false | false | false | false |
tlax/GaussSquad
|
GaussSquad/Controller/Calculator/CCalculator.swift
|
1
|
5967
|
import UIKit
class CCalculator:CController
{
let model:MCalculator
var initial:String?
weak var viewCalculator:VCalculator!
init(initial:String?)
{
self.initial = initial
model = MCalculator()
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
deinit
{
NotificationCenter.default.removeObserver(self)
}
override func loadView()
{
let viewCalculator:VCalculator = VCalculator(controller:self)
self.viewCalculator = viewCalculator
view = viewCalculator
}
override func viewDidLoad()
{
super.viewDidLoad()
if let initial:String = self.initial
{
viewCalculator.viewText.insertText(initial)
}
NotificationCenter.default.addObserver(
forName:Notification.keyboardUpdate,
object:nil,
queue:OperationQueue.main)
{ [weak self] (notification:Notification) in
guard
let keyboardState:MKeyboardState = notification.object as? MKeyboardState
else
{
return
}
let item:MCalculatorStepsItemKeyboardState = MCalculatorStepsItemKeyboardState(
keyboardState:keyboardState)
self?.appendStep(item:item)
}
NotificationCenter.default.addObserver(
forName:Notification.functionUpdate,
object:nil,
queue:OperationQueue.main)
{ [weak self] (notification:Notification) in
guard
let descr:String = notification.object as? String
else
{
return
}
let item:MCalculatorStepsItemFunction = MCalculatorStepsItemFunction(
descr:descr)
self?.appendStep(item:item)
}
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidAppear(animated)
parentController.hideBar(barHidden:true)
viewCalculator.viewAppeared()
}
override func viewWillDisappear(_ animated:Bool)
{
super.viewWillDisappear(animated)
UIApplication.shared.keyWindow!.endEditing(true)
parentController.hideBar(barHidden:false)
}
override func viewWillTransition(to size:CGSize, with coordinator:UIViewControllerTransitionCoordinator)
{
if parentController.childViewControllers.last === self
{
UIApplication.shared.keyWindow!.endEditing(true)
coordinator.animate(alongsideTransition:
{ (context:UIViewControllerTransitionCoordinatorContext) in
})
{ [weak self] (context:UIViewControllerTransitionCoordinatorContext) in
self?.viewCalculator.orientationChange()
}
}
}
//MARK: private
private func appendStep(item:MCalculatorStepsItem)
{
model.steps.items.append(item)
viewCalculator.viewHistory.refresh()
}
private func lookForUndo()
{
guard
let lastStep:MCalculatorStepsItem = model.steps.items.popLast()
else
{
undoFinished()
return
}
if let stepKeyboardStatus:MCalculatorStepsItemKeyboardState = lastStep as? MCalculatorStepsItemKeyboardState
{
guard
let keyboard:VKeyboard = viewCalculator.viewText.inputView as? VKeyboard
else
{
undoFinished()
return
}
guard
let keyboardState:MKeyboardState = stepKeyboardStatus.keyboardState
else
{
lookForUndo()
return
}
keyboard.undoToState(
state:keyboardState)
undoFinished()
}
else if let stepBegin:MCalculatorStepsItemBegin = lastStep as? MCalculatorStepsItemBegin
{
model.steps.items.append(stepBegin)
guard
let keyboard:VKeyboard = viewCalculator.viewText.inputView as? VKeyboard
else
{
undoFinished()
return
}
keyboard.restartEditing()
undoFinished()
}
else
{
lookForUndo()
}
}
private func undoFinished()
{
DispatchQueue.main.async
{ [weak self] in
self?.viewCalculator.viewHistory.refresh()
}
}
//MARK: public
func back()
{
UIApplication.shared.keyWindow!.endEditing(true)
parentController.pop(horizontal:CParent.TransitionHorizontal.fromRight)
}
func undo()
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.lookForUndo()
}
}
func showOptions()
{
let controllerOptions:CCalculatorOptions = CCalculatorOptions(
model:model)
parentController.animateOver(
controller:controllerOptions)
}
func help()
{
let modelHelp:MHelpCalculator = MHelpCalculator()
let controllerHelp:CHelp = CHelp(model:modelHelp)
parentController.push(
controller:controllerHelp,
vertical:CParent.TransitionVertical.fromTop,
background:false)
}
}
|
mit
|
ef2f42f20c99e109e1f0208055a86ed5
| 24.5 | 116 | 0.528741 | 5.838552 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/GalleryModernControls.swift
|
1
|
16832
|
//
// GalleryModernControls.swift
// Telegram
//
// Created by Mikhail Filimonov on 28/08/2018.
// Copyright © 2018 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import Postbox
import SwiftSignalKit
class GalleryModernControlsView: View {
fileprivate let photoView: AvatarControl = AvatarControl(font: .avatar(18))
private var nameNode: (TextNodeLayout, TextNode)? = nil
private var dateNode: (TextNodeLayout, TextNode)? = nil
private let shareControl: ImageButton = ImageButton()
private let moreControl: ImageButton = ImageButton()
fileprivate let zoomInControl: ImageButton = ImageButton()
fileprivate let zoomOutControl: ImageButton = ImageButton()
private let rotateControl: ImageButton = ImageButton()
private let fastSaveControl: ImageButton = ImageButton()
fileprivate var interactions: GalleryInteractions?
fileprivate var thumbs: GalleryThumbsControlView? {
didSet {
oldValue?.removeFromSuperview()
if let thumbs = thumbs {
addSubview(thumbs, positioned: .below, relativeTo: self.subviews.first)
thumbs.setFrameOrigin(NSMakePoint((self.frame.width - thumbs.frame.width) / 2 + (thumbs.frame.width - thumbs.documentSize.width) / 2, (self.frame.height - thumbs.frame.height) / 2))
}
needsLayout = true
}
}
private var currentState:(peer: Peer?, timestamp: TimeInterval, account: Account)? {
didSet {
updateInterface()
}
}
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
// backgroundColor = .blackTransparent
photoView.setFrameSize(60, 60)
addSubview(photoView)
addSubview(shareControl)
addSubview(moreControl)
photoView.userInteractionEnabled = false
shareControl.autohighlight = false
moreControl.autohighlight = false
let shareIcon = NSImage(cgImage: theme.icons.galleryShare, size: theme.icons.galleryShare.backingSize).precomposed(NSColor.white.withAlphaComponent(0.7))
let moreIcon = NSImage(cgImage: theme.icons.galleryMore, size: theme.icons.galleryMore.backingSize).precomposed(NSColor.white.withAlphaComponent(0.7))
let fastSaveIcon = NSImage(cgImage: theme.icons.galleryFastSave, size: theme.icons.galleryFastSave.backingSize).precomposed(NSColor.white.withAlphaComponent(0.7))
shareControl.set(image: shareIcon, for: .Normal)
moreControl.set(image: moreIcon, for: .Normal)
fastSaveControl.set(image: fastSaveIcon, for: .Normal)
shareControl.set(image: theme.icons.galleryShare, for: .Hover)
moreControl.set(image: theme.icons.galleryMore, for: .Hover)
shareControl.set(image: theme.icons.galleryShare, for: .Highlight)
moreControl.set(image: theme.icons.galleryMore, for: .Highlight)
fastSaveControl.set(image: theme.icons.galleryFastSave, for: .Hover)
fastSaveControl.set(image: theme.icons.galleryFastSave, for: .Highlight)
_ = moreControl.sizeToFit(NSZeroSize, NSMakeSize(60, 60), thatFit: true)
_ = shareControl.sizeToFit(NSZeroSize, NSMakeSize(60, 60), thatFit: true)
addSubview(fastSaveControl)
addSubview(zoomInControl)
addSubview(zoomOutControl)
addSubview(rotateControl)
let zoomIn = NSImage(cgImage: theme.icons.galleryZoomIn, size: theme.icons.galleryZoomIn.backingSize).precomposed(NSColor.white.withAlphaComponent(0.7))
let zoomOut = NSImage(cgImage: theme.icons.galleryZoomOut, size: theme.icons.galleryZoomOut.backingSize).precomposed(NSColor.white.withAlphaComponent(0.7))
let rotate = NSImage(cgImage: theme.icons.galleryRotate, size: theme.icons.galleryRotate.backingSize).precomposed(NSColor.white.withAlphaComponent(0.7))
zoomInControl.set(image: zoomIn, for: .Normal)
zoomOutControl.set(image: zoomOut, for: .Normal)
rotateControl.set(image: rotate, for: .Normal)
zoomInControl.set(image: theme.icons.galleryZoomIn, for: .Hover)
zoomOutControl.set(image: theme.icons.galleryZoomOut, for: .Hover)
rotateControl.set(image: theme.icons.galleryRotate, for: .Hover)
zoomInControl.set(image: theme.icons.galleryZoomIn, for: .Highlight)
zoomOutControl.set(image: theme.icons.galleryZoomOut, for: .Highlight)
rotateControl.set(image: theme.icons.galleryRotate, for: .Highlight)
_ = zoomInControl.sizeToFit(NSZeroSize, NSMakeSize(60, 60), thatFit: true)
_ = zoomOutControl.sizeToFit(NSZeroSize, NSMakeSize(60, 60), thatFit: true)
_ = rotateControl.sizeToFit(NSZeroSize, NSMakeSize(60, 60), thatFit: true)
_ = fastSaveControl.sizeToFit(NSZeroSize, NSMakeSize(60, 60), thatFit: true)
shareControl.set(handler: { [weak self] control in
_ = self?.interactions?.share(control)
}, for: .Click)
moreControl.set(handler: { [weak self] control in
_ = self?.interactions?.showActions(control)
}, for: .Click)
rotateControl.set(handler: { [weak self] _ in
self?.interactions?.rotateLeft()
}, for: .Click)
zoomInControl.set(handler: { [weak self] _ in
self?.interactions?.zoomIn()
}, for: .Click)
zoomOutControl.set(handler: { [weak self] _ in
self?.interactions?.zoomOut()
}, for: .Click)
fastSaveControl.set(handler: { [weak self] _ in
self?.interactions?.fastSave()
}, for: .Click)
}
override func mouseUp(with event: NSEvent) {
let point = self.convert(event.locationInWindow, from: nil)
if let currentState = currentState {
if NSPointInRect(point, photoView.frame) || NSPointInRect(point, nameRect), let peerId = currentState.peer?.id {
interactions?.openInfo(peerId)
} else if NSPointInRect(point, dateRect) {
interactions?.openMessage()
} else if let thumbs = thumbs, !NSPointInRect(point, thumbs.frame) {
_ = interactions?.dismiss(event)
}
}
}
private var nameRect: NSRect {
if let nameNode = nameNode {
return NSMakeRect(photoView.frame.maxX + 10, photoView.frame.midY - nameNode.0.size.height - 2, nameNode.0.size.width, nameNode.0.size.height)
}
return NSZeroRect
}
private var dateRect: NSRect {
if let dateNode = dateNode {
return NSMakeRect(photoView.frame.maxX + 10, photoView.frame.midY + 2, dateNode.0.size.width, dateNode.0.size.height)
}
return NSZeroRect
}
override func draw(_ layer: CALayer, in ctx: CGContext) {
super.draw(layer, in: ctx)
if let nameNode = nameNode {
var point = NSMakePoint(photoView.frame.maxX + 10, photoView.frame.midY - nameNode.0.size.height - 2)
if dateNode == nil {
point.y = photoView.frame.midY - floorToScreenPixels(backingScaleFactor, (nameNode.0.size.height / 2))
}
nameNode.1.draw(NSMakeRect(point.x, point.y, nameNode.0.size.width, nameNode.0.size.height), in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: .clear)
}
if let dateNode = dateNode {
dateNode.1.draw(NSMakeRect(photoView.frame.maxX + 10, photoView.frame.midY + 2, dateNode.0.size.width, dateNode.0.size.height), in: ctx, backingScaleFactor: backingScaleFactor, backgroundColor: .clear)
}
}
func updateControlsVisible(_ entry: GalleryEntry) {
switch entry {
case let .instantMedia(media, _):
if media.media is TelegramMediaImage {
zoomInControl.isHidden = false
zoomOutControl.isHidden = false
rotateControl.isHidden = false
fastSaveControl.isHidden = false
} else if let file = media.media as? TelegramMediaFile {
if file.isVideo {
zoomInControl.isHidden = false
zoomOutControl.isHidden = false
rotateControl.isHidden = true
fastSaveControl.isHidden = false
}
}
case let .message(message):
let cantSave = message.message?.containsSecretMedia == true || message.message?.isCopyProtected() == true
if message.message?.effectiveMedia is TelegramMediaImage {
zoomInControl.isHidden = false
zoomOutControl.isHidden = false
rotateControl.isHidden = false
fastSaveControl.isHidden = cantSave
} else if let file = message.message?.effectiveMedia as? TelegramMediaFile {
if file.isVideo {
zoomInControl.isHidden = false
zoomOutControl.isHidden = false
rotateControl.isHidden = true
fastSaveControl.isHidden = cantSave
} else if !file.isGraphicFile {
zoomInControl.isHidden = false
zoomOutControl.isHidden = false
rotateControl.isHidden = true
fastSaveControl.isHidden = cantSave
} else {
zoomInControl.isHidden = false
zoomOutControl.isHidden = false
rotateControl.isHidden = false
fastSaveControl.isHidden = cantSave
}
} else if let webpage = message.message?.effectiveMedia as? TelegramMediaWebpage {
if case let .Loaded(content) = webpage.content {
if ExternalVideoLoader.isPlayable(content) {
zoomInControl.isHidden = false
zoomOutControl.isHidden = false
rotateControl.isHidden = true
fastSaveControl.isHidden = true
}
}
} else {
zoomInControl.isHidden = true
zoomOutControl.isHidden = true
rotateControl.isHidden = true
fastSaveControl.isHidden = true
}
case let .photo(_, _, photo, _, _, _, _):
zoomInControl.isHidden = false
zoomOutControl.isHidden = false
rotateControl.isHidden = !photo.videoRepresentations.isEmpty
fastSaveControl.isHidden = false
default:
zoomInControl.isHidden = false
zoomOutControl.isHidden = false
rotateControl.isHidden = false
fastSaveControl.isHidden = false
}
}
func updatePeer(_ peer: Peer?, timestamp: TimeInterval, account: Account, canShare: Bool) {
currentState = (peer, timestamp, account)
shareControl.isHidden = !canShare
needsLayout = true
}
override func viewWillMove(toWindow newWindow: NSWindow?) {
super.viewWillMove(toWindow: newWindow)
if let window = newWindow as? Window {
window.set(mouseHandler: { [weak self] _ -> KeyHandlerResult in
self?.updateVisibility()
return .rejected
}, with: self, for: .mouseMoved)
} else {
(self.window as? Window)?.remove(object: self, for: .mouseMoved)
}
}
private func updateInterface() {
guard let window = window else {return}
let point = self.convert(window.mouseLocationOutsideOfEventStream, from: nil)
if let currentState = currentState {
photoView.setPeer(account: currentState.account, peer: currentState.peer)
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
formatter.doesRelativeDateFormatting = true
formatter.timeZone = NSTimeZone.local
nameNode = TextNode.layoutText(.initialize(string: currentState.peer?.displayTitle.prefixWithDots(30) ?? strings().peerDeletedUser, color: NSPointInRect(point, nameRect) ? .white : .grayText, font: .medium(.huge)), nil, 1, .end, NSMakeSize(frame.width, 20), nil, false, .left)
dateNode = currentState.timestamp == 0 ? nil : TextNode.layoutText(.initialize(string: formatter.string(from: Date(timeIntervalSince1970: currentState.timestamp)), color: NSPointInRect(point, dateRect) ? .white : .grayText, font: .normal(.title)), nil, 1, .end, NSMakeSize(frame.width, 20), nil, false, .left)
}
photoView._change(opacity: NSPointInRect(point, photoView.frame) ? 1 : 0.7, animated: false)
needsDisplay = true
}
fileprivate var isInside: Bool = false {
didSet {
updateInterface()
}
}
func updateVisibility() {
if frame.minY >= 0 {
isInside = mouseInside()
}
}
override func layout() {
super.layout()
photoView.centerY(x: 80)
moreControl.centerY(x: frame.width - moreControl.frame.width - 80)
shareControl.centerY(x: moreControl.frame.minX - shareControl.frame.width)
let alignControl = shareControl.isHidden ? moreControl : shareControl
fastSaveControl.centerY(x: alignControl.frame.minX - fastSaveControl.frame.width)
rotateControl.centerY(x: (fastSaveControl.isHidden ? alignControl.frame.minX : fastSaveControl.frame.minX) - rotateControl.frame.width - 60)
zoomInControl.centerY(x: (rotateControl.isHidden ? alignControl.frame.minX - 60 : rotateControl.frame.minX) - zoomInControl.frame.width)
zoomOutControl.centerY(x: zoomInControl.frame.minX - zoomOutControl.frame.width)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class GalleryModernControls: GenericViewController<GalleryModernControlsView> {
private let context: AccountContext
private let interactions: GalleryInteractions
private let thumbs: GalleryThumbsControl
private let peerDisposable = MetaDisposable()
private let zoomControlsDisposable = MetaDisposable()
init(_ context: AccountContext, interactions: GalleryInteractions, frame: NSRect, thumbsControl: GalleryThumbsControl) {
self.context = context
self.interactions = interactions
thumbs = thumbsControl
super.init(frame: frame)
}
override func viewDidLoad() {
super.viewDidLoad()
genericView.thumbs = thumbs.genericView
genericView.interactions = interactions
thumbs.afterLayoutTransition = { [weak self] animated in
guard let `self` = self else { return }
self.thumbs.genericView.change(pos: NSMakePoint((self.frame.width - self.thumbs.frame.width) / 2 + (self.thumbs.frame.width - self.thumbs.genericView.documentSize.width) / 2, (self.frame.height - self.thumbs.frame.height) / 2), animated: animated)
}
}
deinit {
peerDisposable.dispose()
zoomControlsDisposable.dispose()
}
func update(_ item: MGalleryItem?) {
if let item = item {
if let interfaceState = item.entry.interfaceState {
self.genericView.updateControlsVisible(item.entry)
peerDisposable.set((context.account.postbox.loadedPeerWithId(interfaceState.0) |> deliverOnMainQueue).start(next: { [weak self, weak item] peer in
guard let `self` = self, let item = item else {return}
self.genericView.updatePeer(peer, timestamp: interfaceState.1 == 0 ? 0 : interfaceState.1 - self.context.timeDifference, account: self.context.account, canShare: item.entry.canShare)
}))
zoomControlsDisposable.set((item.magnify.get() |> deliverOnMainQueue).start(next: { [weak self, weak item] value in
if let item = item {
self?.genericView.zoomOutControl.isEnabled = item.minMagnify < value
self?.genericView.zoomInControl.isEnabled = item.maxMagnify > value
}
}))
}
}
}
func animateIn() {
genericView.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
genericView.change(pos: NSMakePoint(0, 0), animated: true, timingFunction: CAMediaTimingFunctionName.spring)
}
func animateOut() {
genericView.layer?.animateAlpha(from: 1, to: 0, duration: 0.2, removeOnCompletion: false)
}
}
|
gpl-2.0
|
fea097016803eb2d663d03b33da288a2
| 43.882667 | 321 | 0.627117 | 4.715887 | false | false | false | false |
Nickelfox/FLAPIClient
|
Source/Classes/Routers/APIRouter.swift
|
2
|
1255
|
//
// APIRouter.swift
// Network
//
// Created by Ravindra Soni on 16/12/16.
// Copyright © 2016 Nickelfox. All rights reserved.
//
import Alamofire
public typealias HTTPMethod = Alamofire.HTTPMethod
public typealias URLRequestConvertible = Alamofire.URLRequestConvertible
public typealias URLEncoding = Alamofire.URLEncoding
public protocol APIRouter: URLRequestConvertible {
var method: HTTPMethod { get }
var path: String { get }
var params: [String: Any] { get }
var baseUrl: URL { get }
var headers: [String: String] { get }
}
extension APIRouter {
public func asURLRequest() throws -> URLRequest {
var request = URLRequest(url: self.baseUrl)
request.httpMethod = self.method.rawValue
request.timeoutInterval = 200
for (key, value) in self.headers {
request.setValue(value, forHTTPHeaderField: key)
}
var parameters: [String: AnyObject]?
if self.method == .post || self.method == .patch || self.method == .put {
do {
request.httpBody = try JSONSerialization.data(withJSONObject: self.params, options: JSONSerialization.WritingOptions())
} catch {
// No-op
}
} else {
parameters = params as [String : AnyObject]?
}
return try URLEncoding.default.encode(request, with: parameters)
}
}
|
mit
|
5826c8fc8ba20af62b3c747969fa76b9
| 25.680851 | 123 | 0.712919 | 3.81155 | false | false | false | false |
wburhan2/TicTacToe
|
tictactoe/MPCHandler.swift
|
1
|
2330
|
//
// MPCHandler.swift
// tictactoe
//
// Created by Wilson Burhan on 10/17/14.
// Copyright (c) 2014 Wilson Burhan. All rights reserved.
//
import UIKit
import MultipeerConnectivity
class MPCHandler: NSObject, MCSessionDelegate {
var peerID:MCPeerID!
var session:MCSession!
var browser:MCBrowserViewController!
var advertiser:MCAdvertiserAssistant? = nil
func setupPeerWithDisplayNames(displayName:String){
peerID = MCPeerID(displayName: displayName)
}
func setupSession() {
session = MCSession(peer: peerID)
session.delegate = self
}
func setupBroser() {
browser = MCBrowserViewController(serviceType: "my-game", session: session)
}
func advertiseSelf(adversite:Bool){
if adversite {
advertiser = MCAdvertiserAssistant(serviceType: "my-game", discoveryInfo: nil, session: session)
advertiser!.start()
}
else {
advertiser!.stop()
advertiser = nil
}
}
func session(session: MCSession!, peer peerID: MCPeerID!, didChangeState state: MCSessionState) {
let userInfo = ["peerId":peerID, "state":state.toRaw()]
dispatch_async(dispatch_get_main_queue(), { () -> Void in
NSNotificationCenter.defaultCenter().postNotificationName("MPC_DidChangeStateNotification", object: nil, userInfo: userInfo)})
}
func session(session: MCSession!, didReceiveData data: NSData!, fromPeer peerID: MCPeerID!) {
let userInfo = ["data":data, "peerID":peerID]
dispatch_async(dispatch_get_main_queue(), { () -> Void in
NSNotificationCenter.defaultCenter().postNotificationName("MPC_DidReceiveDataNotification", object: nil, userInfo: userInfo)})
}
func session(session: MCSession!, didFinishReceivingResourceWithName resourceName: String!, fromPeer peerID: MCPeerID!, atURL localURL: NSURL!, withError error: NSError!) {
}
func session(session: MCSession!, didStartReceivingResourceWithName resourceName: String!, fromPeer peerID: MCPeerID!, withProgress progress: NSProgress!) {
}
func session(session: MCSession!, didReceiveStream stream: NSInputStream!, withName streamName: String!, fromPeer peerID: MCPeerID!) {
}
}
|
apache-2.0
|
e628a4be0c313afd595203d3b400b29c
| 34.318182 | 176 | 0.666953 | 4.978632 | false | false | false | false |
KiiPlatform/Cozy-mock
|
CozyMock/CozyMock/Definitions.swift
|
1
|
457
|
//
// Definitions.swift
// CozyMock
//
// Created by syahRiza on 12/1/15.
// Copyright © 2015 cozy. All rights reserved.
//
import CoreBluetooth
let TRANSFER_SERVICE_UUID = "E20A39F4-73F5-4BC4-A12F-17D1AD666661"
let TRANSFER_CHARACTERISTIC_UUID = "08590F7E-DB05-467E-8757-72F6F66666D4"
let NOTIFY_MTU = 20
let transferServiceUUID = CBUUID(string: TRANSFER_SERVICE_UUID)
let transferCharacteristicUUID = CBUUID(string: TRANSFER_CHARACTERISTIC_UUID)
|
mit
|
b7acb9c3da3b3daf69761906b3e2e6a4
| 25.823529 | 77 | 0.767544 | 2.746988 | false | false | false | false |
stormhouse/SnapDemo
|
SnapDemo/ViewController.swift
|
1
|
4087
|
//
// ViewController.swift
// SnapDemo
//
// Created by stormhouse on 3/27/15.
// Copyright (c) 2015 stormhouse. All rights reserved.
//
import UIKit
import Snap
import Foundation
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView : UITableView?
var items : NSArray?
var addrView: UIView!
var button: UIButton!
var addrText: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "stormhouse"
self.items = ["Snap", "SemiCircleMenu"]
self.tableView = UITableView(frame:self.view.frame, style: UITableViewStyle.Plain)
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
self.view.addSubview(self.tableView!)
/*
button = UIButton.buttonWithType(.System) as? UIButton
button.backgroundColor = UIColor.greenColor()
button.setTitle("Press Me", forState: .Normal)
button.setTitle("I'm Pressed", forState: .Highlighted)
*/
// button.addTarget(self, action: "buttonIsPressed:", forControlEvents: .TouchDown)
// button.addTarget(self, action: "buttonIsTapped:", forControlEvents: .TouchUpInside)
// button.frame = CGRect(x: 110, y: 70, width: 100, height: 44)
// button.snp_makeConstraints { make in
// make.center.equalTo(self.view).offset(CGPointMake(-5, 10))
// return // this return is a fix for implicit returns in Swift and is only required for single line constraints
// }
// addrView = UIView()
// addrView.backgroundColor = UIColor.brownColor()
// view.addSubview(addrView)
// addrView.snp_makeConstraints{ make in
// make.height.equalTo(60)
// make.width.equalTo(self.view)
// }
//
// addrText = UITextField()
// addrText.text = "search"
// addrText.backgroundColor = UIColor.whiteColor()
// addrView.addSubview(addrText)
// addrText.snp_makeConstraints{ make in
// make.height.equalTo(30)
// make.edges.equalTo(self.addrView).insets(UIEdgeInsetsMake(20, 10, 10, 10))
//// make.size.equalTo(self.addrView).offset(CGSizeMake(10, 10))
// return
// }
}
// UITableViewDataSource Methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return self.items!.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
cell.textLabel?.text = self.items?.objectAtIndex(indexPath.row) as String!
return cell
}
// UITableViewDelegate Methods
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
self.tableView!.deselectRowAtIndexPath(indexPath, animated: true)
var title = self.items?.objectAtIndex(indexPath.row) as String!
switch title {
case "Snap":
var snapViewController = SnapViewController()
// var rootNavigationController = UINavigationController(rootViewController: snapViewController)
// rootNavigationController.title = title
self.navigationController!.pushViewController(snapViewController, animated: true)
case "SemiCircleMenu":
var detailViewController = SemiCircleMenuDemoController()
detailViewController.title = title
self.navigationController!.pushViewController(detailViewController, animated: true)
default:
return
}
}
}
|
apache-2.0
|
9f9171398e90eca2e46902e73ca32425
| 34.53913 | 123 | 0.633472 | 5.008578 | false | false | false | false |
xiaomudegithub/viossvc
|
viossvc/Scenes/User/ServerTableView.swift
|
1
|
1908
|
//
// ServerTableView.swift
// viossvc
//
// Created by 木柳 on 2016/12/2.
// Copyright © 2016年 com.yundian. All rights reserved.
//
import UIKit
class ServerCell: UITableViewCell {
@IBOutlet weak var upLine: UIView!
@IBOutlet weak var serverNameLabel: UILabel!
@IBOutlet weak var serverTimeLabel: UILabel!
@IBOutlet weak var serverPriceLabel: UILabel!
}
class ServerTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
var serverData: [UserServerModel] = []
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
delegate = self
dataSource = self
scrollEnabled = false
}
//MARK: --delegate and datasource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return serverData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: ServerCell = tableView.dequeueReusableCellWithIdentifier(ServerCell.className()) as! ServerCell
let model = serverData[indexPath.row]
cell.serverNameLabel.text = model.service_name
cell.serverPriceLabel.text = "¥\(Double(model.service_price)/100)"
cell.serverTimeLabel.text = "\(time(model.service_start))--\(time(model.service_end))"
cell.upLine.hidden = indexPath.row == 0
return cell
}
func time(minus: Int) -> String {
let hour = minus / 60
let leftMinus = minus % 60
let hourStr = hour > 9 ? "\(hour)" : "0\(hour)"
let minusStr = leftMinus > 9 ? "\(minus)" : "0\(leftMinus)"
return "\(hourStr):\(minusStr)"
}
func updateData(data: AnyObject!, complete:CompleteBlock) {
serverData = data as! [UserServerModel]
reloadData()
complete(contentSize.height > 0 ? contentSize.height+20 : 0)
}
}
|
apache-2.0
|
22e1d36360479dd899a0afa7dc367f97
| 34.166667 | 113 | 0.657715 | 4.315909 | false | false | false | false |
tamasoszko/sandbox-ios
|
PassGen/PassGen/ViewController.swift
|
1
|
2270
|
//
// ViewController.swift
// PassGen
//
// Created by Oszkó Tamás on 06/12/15.
// Copyright © 2015 Oszi. All rights reserved.
//
import UIKit
import AudioToolbox
class ViewController: UIViewController {
@IBOutlet weak var lengthLabel: UILabel!
@IBOutlet weak var lengthSlider: UISlider!
@IBOutlet weak var passwordLabel: UILabel!
var passwdLength: Int?
var passwd: String?
var passwdGenerator = SimplePasswdGenerator()
var displayPasswd = false
override func viewDidLoad() {
super.viewDidLoad()
passwdLength = getPasswdLength()
generatePasswd()
let recognizer = UITapGestureRecognizer(target: self, action: Selector("passwdLabelTapped"))
passwordLabel.addGestureRecognizer(recognizer)
}
override func canBecomeFirstResponder() -> Bool {
return true
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
if motion == .MotionShake {
generatePasswd()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func sliderChanged(sender: AnyObject) {
let len = getPasswdLength()
if(len != passwdLength && len % 2 == 0) {
generatePasswd()
}
}
func passwdLabelTapped() {
displayPasswd = !displayPasswd
updateUI()
}
private func generatePasswd() {
passwdLength = getPasswdLength()
passwd = passwdGenerator.generate(passwdLength!)
let pasteboard = UIPasteboard.generalPasteboard()
pasteboard.string = passwd
AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
updateUI()
}
private func getPasswdLength() -> Int {
return Int(lengthSlider.value)
}
private func updateUI() {
lengthLabel.text = "\(passwdLength!)"
passwordLabel.text = passwdDisplayText()
}
private func passwdDisplayText() -> String {
guard passwd != nil else {
return "-"
}
if displayPasswd {
return passwd!
}
return passwd!.sensitiveString()
}
}
|
apache-2.0
|
7b593c19307313adfb192e0903ead507
| 24.761364 | 100 | 0.620203 | 5.152273 | false | false | false | false |
hejunbinlan/BRYXBanner
|
Example/BRYXBanner/ViewController.swift
|
2
|
2167
|
//
// ViewController.swift
// BRYXBanner
//
// Created by Harlan Haskins on 07/27/2015.
// Copyright (c) 2015 Harlan Haskins. All rights reserved.
//
import UIKit
import BRYXBanner
struct BannerColors {
static let red = UIColor(red:198.0/255.0, green:26.00/255.0, blue:27.0/255.0, alpha:1.000)
static let green = UIColor(red:48.00/255.0, green:174.0/255.0, blue:51.5/255.0, alpha:1.000)
static let yellow = UIColor(red:255.0/255.0, green:204.0/255.0, blue:51.0/255.0, alpha:1.000)
static let blue = UIColor(red:31.0/255.0, green:136.0/255.0, blue:255.0/255.0, alpha:1.000)
}
class ViewController: UIViewController {
@IBOutlet weak var imageSwitch: UISwitch!
@IBOutlet weak var springinessSegmentedControl: UISegmentedControl!
@IBOutlet weak var titleField: UITextField!
@IBOutlet weak var subtitleField: UITextField!
@IBOutlet weak var colorSegmentedControl: UISegmentedControl!
@IBOutlet weak var inViewSwitch: UISwitch!
@IBAction func showButtonTapped(sender: UIButton) {
let color = currentColor()
let image = imageSwitch.on ? UIImage(named: "Icon") : nil
let title = titleField.text?.validated
let subtitle = subtitleField.text?.validated
let banner = Banner(title: title, subtitle: subtitle, image: image, backgroundColor: color)
banner.springiness = currentSpringiness()
if inViewSwitch.on {
banner.show(view, duration: 3.0)
} else {
banner.show(duration: 3.0)
}
}
func currentSpringiness() -> BannerSpringiness {
switch springinessSegmentedControl.selectedSegmentIndex {
case 0: return .None
case 1: return .Slight
default: return .Heavy
}
}
func currentColor() -> UIColor {
switch colorSegmentedControl.selectedSegmentIndex {
case 0: return BannerColors.red
case 1: return BannerColors.green
case 2: return BannerColors.yellow
default: return BannerColors.blue
}
}
}
extension String {
var validated: String? {
if self.isEmpty { return nil }
return self
}
}
|
mit
|
f074cc69c589edb154f4c083a7dc6728
| 31.833333 | 99 | 0.659898 | 3.890485 | false | false | false | false |
evgenyneu/sound-fader-ios
|
Cephalopod/AutoCancellingTimer.swift
|
1
|
1892
|
//
// Creates a timer that executes code after delay. The timer lives in an instance of `AutoCancellingTimer` class and is automatically canceled when this instance is deallocated.
// This is an auto-canceling alternative to timer created with `dispatch_after` function.
//
// Source: https://gist.github.com/evgenyneu/516f7dcdb5f2f73d7923
//
// Usage
// -----
//
// class MyClass {
// var timer: AutoCancellingTimer? // Timer will be cancelled with MyCall is deallocated
//
// func runTimer() {
// timer = AutoCancellingTimer(interval: delaySeconds, repeats: true) {
// ... code to run
// }
// }
// }
//
//
// Cancel the timer
// --------------------
//
// Timer is canceled automatically when it is deallocated. You can also cancel it manually:
//
// timer.cancel()
//
import Foundation
final class AutoCancellingTimer {
private var timer: AutoCancellingTimerInstance?
init(interval: TimeInterval, repeats: Bool = false, callback: @escaping ()->()) {
timer = AutoCancellingTimerInstance(interval: interval, repeats: repeats, callback: callback)
}
deinit {
timer?.cancel()
}
func cancel() {
timer?.cancel()
}
}
final class AutoCancellingTimerInstance: NSObject {
private let repeats: Bool
private var timer: Timer?
private var callback: ()->()
init(interval: TimeInterval, repeats: Bool = false, callback: @escaping ()->()) {
self.repeats = repeats
self.callback = callback
super.init()
timer = Timer.scheduledTimer(timeInterval: interval, target: self,
selector: #selector(AutoCancellingTimerInstance.timerFired(_:)), userInfo: nil, repeats: repeats)
}
func cancel() {
timer?.invalidate()
}
@objc func timerFired(_ timer: Timer) {
self.callback()
if !repeats { cancel() }
}
}
|
mit
|
d05cc27d757827545aadd3aa420365c2
| 26.028571 | 177 | 0.638478 | 4.149123 | false | false | false | false |
RickieL/learn-swift
|
swift-functions.playground/section-1.swift
|
1
|
2728
|
// Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
func sayHello(personName: String) -> String {
let greeting = "Hello, \(personName)"
return greeting
}
println(sayHello("Anna"))
func minMax(array: [Int]) -> (min: Int, max: Int)? {
if array.isEmpty { return nil }
var currentMin = array[0]
var currentMax = array[0]
for num in array[1..<array.count] {
if num < currentMin {
currentMin = num
} else if num > currentMax {
currentMax = num
}
}
return (currentMin, currentMax)
}
if let bounds = minMax([8, 6, -2, 3, 18, 0]) {
println("min is \(bounds.min) and max is \(bounds.max)")
}
func join(s1: String, s2: String, joiner: String = " ") -> String {
return s1 + joiner + s2
}
println(join("Hello", "World", joiner: "-"))
// variadic parameters
func arithmeticMean(numbers: Double...) -> Double {
var sum: Double = 0
for num in numbers {
sum += num
}
let avg: Double = sum / Double(numbers.count)
return avg
}
arithmeticMean(1, 2, 3, 18.75, 6.2)
// constant and variable parameters with default value
func alignRight(var string: String, count: Int, pad: Character = " ") -> String {
let padCount = count - countElements(string)
if padCount < 1 { return string }
let padString = String(pad)
for _ in 1...padCount {
string = padString + string
}
return string
}
let originalString = "hello"
let paddedString = alignRight(originalString, 10, pad: "-")
// In-Out Parameters
func swapTwoInts(inout a: Int, inout b: Int) {
let temp = a
a = b
b = temp
}
var a = 3
var b = 8
swapTwoInts(&a, &b)
a
b
// function type
// using function types
var newAlign: (String, Int, pad: Character) -> String = alignRight
println(newAlign(originalString, 20, pad: "a"))
let anotherNewAlign = alignRight
// function types as parameter types
func printNewAlign(newAlign: (String, Int, pad: Character) -> String, string: String, count: Int, pad: Character) {
println("Result: \(newAlign(string, count, pad: pad))")
}
printNewAlign(alignRight, "hello", 30, "a")
// function types as return types
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}
func chooseStepFunction(backwards: Bool) -> (Int) -> Int {
return backwards ? stepBackward : stepForward
}
var currentValue = 3
let moveNearToZero = chooseStepFunction(currentValue > 0)
println("Counting to zero:")
// Counting to zero
while currentValue != 0 {
println("\(currentValue)... ")
currentValue = moveNearToZero(currentValue)
}
println("zero!")
// NESTED functions
|
bsd-3-clause
|
ea29903a39d4609881d9ad6ddd2c21d6
| 20.808 | 115 | 0.641966 | 3.586842 | false | false | false | false |
wireapp/wire-ios
|
Wire-iOS/Sources/Helpers/SemanticColors.swift
|
1
|
11823
|
//
// Wire
// Copyright (C) 2022 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
import WireDataModel
import WireCommonComponents
/// Naming convention:
///
/// The names of all SemanticColors should follow the format:
///
/// "<usage>.<context/role>.<state?>"
/// The last part is optional
public enum SemanticColors {
public enum LegacyColors {
// Legacy accent colors
static let strongBlue = UIColor(red: 0.141, green: 0.552, blue: 0.827, alpha: 1)
static let strongLimeGreen = UIColor(red: 0, green: 0.784, blue: 0, alpha: 1)
static let brightYellow = UIColor(red: 0.996, green: 0.749, blue: 0.007, alpha: 1)
static let vividRed = UIColor(red: 1, green: 0.152, blue: 0, alpha: 1)
static let brightOrange = UIColor(red: 1, green: 0.537, blue: 0, alpha: 1)
static let softPink = UIColor(red: 0.996, green: 0.368, blue: 0.741, alpha: 1)
static let violet = UIColor(red: 0.615, green: 0, blue: 1, alpha: 1)
}
public enum Switch {
static let backgroundOnStateEnabled = UIColor(light: Asset.green600Light, dark: Asset.green700Dark)
static let backgroundOffStateEnabled = UIColor(light: Asset.gray70, dark: Asset.gray70)
static let borderOnStateEnabled = UIColor(light: Asset.green600Light, dark: Asset.green500Dark)
static let borderOffStateEnabled = UIColor(light: Asset.gray70, dark: Asset.gray60)
}
public enum Label {
static let textDefault = UIColor(light: Asset.black, dark: Asset.white)
static let textDefaultWhite = UIColor(light: Asset.white, dark: Asset.black)
static let textSectionFooter = UIColor(light: Asset.gray90, dark: Asset.gray20)
static let textSectionHeader = UIColor(light: Asset.gray70, dark: Asset.gray50)
static let textCellTitle = UIColor(light: Asset.black, dark: Asset.white)
static let textCellSubtitle = UIColor(light: Asset.gray90, dark: Asset.white)
static let textNoResults = UIColor(light: Asset.black, dark: Asset.gray20)
static let textSettingsPasswordPlaceholder = UIColor(light: Asset.gray70, dark: Asset.gray60)
static let textSettingsCellBadge = UIColor(light: Asset.white, dark: Asset.black)
static let textLinkHeaderCellTitle = UIColor(light: Asset.gray100, dark: Asset.white)
static let textUserPropertyCellName = UIColor(light: Asset.gray80, dark: Asset.gray40)
static let textUserPropertyCellValue = UIColor(light: Asset.black, dark: Asset.white)
static let textConversationQuestOptionInfo = UIColor(light: Asset.gray90, dark: Asset.gray20)
static let textConversationListItemTitleField = UIColor(light: Asset.black, dark: Asset.white)
static let textConversationListCell = UIColor(light: Asset.black, dark: Asset.white)
static let conversationListTableViewCellBadge = UIColor(light: Asset.white, dark: Asset.black)
static let conversationListTableViewCellBadgeReverted = UIColor(light: Asset.black, dark: Asset.white)
static let teamImageView = UIColor(light: Asset.black, dark: Asset.white)
static let textConversationListItemSubtitleField = UIColor(light: Asset.gray90, dark: Asset.gray20)
static let textNavigationController = UIColor(light: Asset.black, dark: Asset.white)
static let textLabelMessageActive = UIColor(light: Asset.black, dark: Asset.white)
static let textLabelMessageDetailsActive = UIColor(light: Asset.gray70, dark: Asset.gray40)
static let textMessageDetails = UIColor(light: Asset.gray70, dark: Asset.gray40)
static let textWarning = UIColor(light: Asset.red500Light, dark: Asset.red500Dark)
}
public enum SearchBar {
static let textInputView = UIColor(light: Asset.black, dark: Asset.white)
static let textInputViewPlaceholder = UIColor(light: Asset.gray70, dark: Asset.gray60)
static let backgroundInputView = UIColor(light: Asset.white, dark: Asset.black)
static let borderInputView = UIColor(light: Asset.gray40, dark: Asset.gray80)
static let backgroundButton = UIColor(light: Asset.black, dark: Asset.white)
}
public enum Icon {
static let backgroundIconDefaultConversationView = UIColor(light: Asset.gray70, dark: Asset.gray60)
static let foregroundPlainCheckMark = UIColor(light: Asset.black, dark: Asset.white)
static let foregroundCheckMarkSelected = UIColor(light: Asset.white, dark: Asset.black)
static let borderCheckMark = UIColor(light: Asset.gray80, dark: Asset.gray60)
static let backgroundCheckMark = UIColor(light: Asset.gray20, dark: Asset.gray90)
static let backgroundCheckMarkSelected = UIColor(light: Asset.blue500Light, dark: Asset.blue500Dark)
static let foregroundDefault = UIColor(light: Asset.gray90, dark: Asset.white)
static let foregroundDefaultBlack = UIColor(light: Asset.black, dark: Asset.white)
static let foregroundDefaultWhite = UIColor(light: Asset.white, dark: Asset.black)
static let foregroundPlainDownArrow = UIColor(light: Asset.gray90, dark: Asset.gray20)
static let backgroundJoinCall = UIColor(light: Asset.green500Light, dark: Asset.green500Dark)
static let foregroundAvailabilityAvailable = UIColor(light: Asset.green500Light, dark: Asset.green500Dark)
static let foregroundAvailabilityBusy = UIColor(light: Asset.amber500Light, dark: Asset.amber500Dark)
static let foregroundAvailabilityAway = UIColor(light: Asset.red500Light, dark: Asset.red500Dark)
static let backgroundPhoneCall = UIColor(light: Asset.green500Light, dark: Asset.green500Dark)
static let backgroundMissedPhoneCall = UIColor(light: Asset.red500Light, dark: Asset.red500Dark)
}
public enum View {
static let backgroundDefault = UIColor(light: Asset.gray20, dark: Asset.gray100)
static let backgroundDefaultWhite = UIColor(light: Asset.white, dark: Asset.black)
static let backgroundConversationView = UIColor(light: Asset.gray10, dark: Asset.gray95)
static let backgroundUserCell = UIColor(light: Asset.white, dark: Asset.gray95)
static let backgroundUserCellHightLighted = UIColor(light: Asset.gray40, dark: Asset.gray100)
static let backgroundSeparatorCell = UIColor(light: Asset.gray40, dark: Asset.gray90)
static let backgroundBadgeCell = UIColor(light: Asset.black, dark: Asset.white)
static let backgroundConversationList = UIColor(light: Asset.gray20, dark: Asset.gray100)
static let backgroundConversationListTableViewCell = UIColor(light: Asset.white, dark: Asset.gray95)
static let backgroundConversationListTableViewCellBadge = UIColor(light: Asset.black, dark: Asset.white)
static let backgroundConversationListTableViewCellBadgeReverted = UIColor(light: Asset.white, dark: Asset.black)
static let backgroundTeamImageView = UIColor(light: Asset.white, dark: Asset.black)
static let backgroundSecurityLevel = UIColor(light: Asset.gray20, dark: Asset.gray95)
static let backgroundSeparatorConversationView = UIColor(light: Asset.gray70, dark: Asset.gray60)
static let borderAvailabilityIcon = UIColor(light: Asset.gray10, dark: Asset.gray90)
static let borderConversationListTableViewCellBadgeReverted = UIColor(light: Asset.gray40, dark: Asset.gray70)
static let borderInputBar = UIColor(light: Asset.gray40, dark: Asset.gray100)
}
public enum TabBar {
static let backgroundSeperatorSelected = UIColor(light: Asset.black, dark: Asset.white)
}
public enum Button {
static let backgroundBarItem = UIColor(light: Asset.white, dark: Asset.gray90)
static let backgroundSecondaryEnabled = UIColor(light: Asset.white, dark: Asset.gray95)
static let backgroundSecondaryInConversationViewEnabled = UIColor(light: Asset.white, dark: Asset.gray100)
static let backgroundSecondaryHighlighted = UIColor(light: Asset.white, dark: Asset.gray80)
static let textSecondaryEnabled = UIColor(light: Asset.black, dark: Asset.white)
static let borderSecondaryEnabled = UIColor(light: Asset.gray40, dark: Asset.gray80)
static let borderSecondaryHighlighted = UIColor(light: Asset.gray40, dark: Asset.gray60)
static let backgroundPrimaryEnabled = UIColor(light: Asset.blue500Light, dark: Asset.blue500Dark)
static let backgroundPrimaryHighlighted = UIColor(light: Asset.blue500Light, dark: Asset.blue400Light)
static let textPrimaryEnabled = UIColor(light: Asset.white, dark: Asset.black)
static let textEmptyEnabled = UIColor(light: Asset.black, dark: Asset.white)
static let textBottomBarNormal = UIColor(light: Asset.gray90, dark: Asset.gray50)
static let textBottomBarSelected = UIColor(light: Asset.white, dark: Asset.black)
static let borderBarItem = UIColor(light: Asset.gray40, dark: Asset.gray90)
static let backgroundLikeEnabled = UIColor(light: Asset.gray70, dark: Asset.gray60)
static let backgroundLikeHighlighted = UIColor(light: Asset.red500Light, dark: Asset.red500Dark)
static let backgroundSendDisabled = UIColor(light: Asset.gray70, dark: Asset.gray70)
static let backgroundInputBarItemEnabled = UIColor(light: Asset.white, dark: Asset.gray90)
static let backgroundInputBarItemHighlighted = UIColor(light: Asset.blue50Light, dark: Asset.blue800Dark)
static let borderInputBarItemEnabled = UIColor(light: Asset.gray40, dark: Asset.gray100)
static let borderInputBarItemHighlighted = UIColor(light: Asset.blue300Light, dark: Asset.blue700Dark)
static let textInputBarItemEnabled = UIColor(light: Asset.black, dark: Asset.white)
static let textInputBarItemHighlighted = UIColor(light: Asset.blue500Light, dark: Asset.white)
static let textUnderlineEnabled = UIColor(light: Asset.black, dark: Asset.white)
}
}
extension UIColor {
convenience init(light: ColorAsset, dark: ColorAsset) {
self.init { traits in
return traits.userInterfaceStyle == .dark ? dark.color : light.color
}
}
}
public extension UIColor {
convenience init(for accentColor: AccentColor) {
switch accentColor {
case .blue:
self.init(light: Asset.blue500Light, dark: Asset.blue500Dark)
case .green:
self.init(light: Asset.green500Light, dark: Asset.green500Dark)
case .yellow: // Deprecated
self.init(red: 0.996, green: 0.749, blue: 0.007, alpha: 1)
case .red:
self.init(light: Asset.red500Light, dark: Asset.red500Dark)
case .amber:
self.init(light: Asset.amber500Light, dark: Asset.amber500Dark)
case .turquoise:
self.init(light: Asset.turquoise500Light, dark: Asset.turquoise500Dark)
case .purple:
self.init(light: Asset.purple500Light, dark: Asset.purple500Dark)
}
}
convenience init(fromZMAccentColor accentColor: ZMAccentColor) {
let safeAccentColor = AccentColor(ZMAccentColor: accentColor) ?? .blue
self.init(for: safeAccentColor)
}
}
|
gpl-3.0
|
0a87cd91a6906bb4d2c446d0ba6395ae
| 62.224599 | 120 | 0.725027 | 4.120948 | false | false | false | false |
LoopKit/LoopKit
|
MockKit/MockGlucoseProvider.swift
|
1
|
11685
|
//
// MockGlucoseProvider.swift
// LoopKit
//
// Created by Michael Pangburn on 11/23/18.
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import HealthKit
import LoopKit
/// Returns a value based on the result of a random coin flip.
/// - Parameter chanceOfHeads: The chance of flipping heads. Must be a value in the range `0...1`. Defaults to `0.5`.
/// - Parameter valueIfHeads: An autoclosure producing the value to return if the coin flips heads.
/// - Parameter valueIfTails: An autoclosure producing the value to return if the coin flips tails.
private func coinFlip<Output>(
withChanceOfHeads chanceOfHeads: Double = 0.5,
ifHeads valueIfHeads: @autoclosure () -> Output,
ifTails valueIfTails: @autoclosure () -> Output
) -> Output {
precondition((0...1).contains(chanceOfHeads))
let isHeads = .random(in: 0..<100) < chanceOfHeads * 100
return isHeads ? valueIfHeads() : valueIfTails()
}
struct MockGlucoseProvider {
struct BackfillRequest {
let duration: TimeInterval
let dataPointFrequency: TimeInterval
var dataPointCount: Int {
return Int(duration / dataPointFrequency)
}
init(datingBack duration: TimeInterval, dataPointFrequency: TimeInterval) {
self.duration = duration
self.dataPointFrequency = dataPointFrequency
}
}
/// Given a date, asynchronously produce the CGMReadingResult at that date.
private let fetchDataAt: (_ date: Date, _ completion: @escaping (CGMReadingResult) -> Void) -> Void
func fetchData(at date: Date, completion: @escaping (CGMReadingResult) -> Void) {
fetchDataAt(date, completion)
}
func backfill(_ backfill: BackfillRequest, endingAt date: Date, completion: @escaping (CGMReadingResult) -> Void) {
let dataPointDates = (0...backfill.dataPointCount).map { offset in
return date.addingTimeInterval(-backfill.dataPointFrequency * Double(offset))
}
dataPointDates.asyncMap(fetchDataAt) { allResults in
let allSamples = allResults.flatMap { result -> [NewGlucoseSample] in
if case .newData(let samples) = result {
return samples
} else {
return []
}
}
let result: CGMReadingResult = allSamples.isEmpty ? .noData : .newData(allSamples.reversed())
completion(result)
}
}
}
extension MockGlucoseProvider {
init(model: MockCGMDataSource.Model, effects: MockCGMDataSource.Effects) {
self = effects.transformations.reduce(model.glucoseProvider) { model, transform in transform(model) }
}
private static func glucoseSample(at date: Date, quantity: HKQuantity, condition: GlucoseCondition?, trend: GlucoseTrend?, trendRate: HKQuantity?) -> NewGlucoseSample {
return NewGlucoseSample(
date: date,
quantity: quantity,
condition: condition,
trend: trend,
trendRate: trendRate,
isDisplayOnly: false,
wasUserEntered: false,
syncIdentifier: UUID().uuidString,
device: MockCGMDataSource.device
)
}
}
// MARK: - Models
extension MockGlucoseProvider {
fileprivate static func constant(_ quantity: HKQuantity) -> MockGlucoseProvider {
return MockGlucoseProvider { date, completion in
let sample = glucoseSample(at: date, quantity: quantity, condition: nil, trend: .flat, trendRate: HKQuantity(unit: .milligramsPerDeciliterPerMinute, doubleValue: 0))
completion(.newData([sample]))
}
}
fileprivate static func sineCurve(parameters: MockCGMDataSource.Model.SineCurveParameters) -> MockGlucoseProvider {
let (baseGlucose, amplitude, period, referenceDate) = parameters
precondition(period > 0)
let unit = HKUnit.milligramsPerDeciliter
let trendRateUnit = unit.unitDivided(by: .minute())
precondition(baseGlucose.is(compatibleWith: unit))
precondition(amplitude.is(compatibleWith: unit))
let baseGlucoseValue = baseGlucose.doubleValue(for: unit)
let amplitudeValue = amplitude.doubleValue(for: unit)
let chanceOfNilTrendRate = 1.0/20.0
var prevGlucoseValue: Double?
return MockGlucoseProvider { date, completion in
let timeOffset = date.timeIntervalSince1970 - referenceDate.timeIntervalSince1970
func sine(_ t: TimeInterval) -> Double {
return Double(baseGlucoseValue + amplitudeValue * sin(2 * .pi / period * t)).rounded()
}
let glucoseValue = sine(timeOffset)
var trend: GlucoseTrend?
var trendRate: HKQuantity?
if let prevGlucoseValue = prevGlucoseValue,
let trendRateValue = coinFlip(withChanceOfHeads: chanceOfNilTrendRate, ifHeads: nil, ifTails: glucoseValue - prevGlucoseValue) {
let smallDelta = 0.9
let mediumDelta = 2.0
let largeDelta = 5.0
switch trendRateValue {
case -smallDelta ... smallDelta:
trend = .flat
case -mediumDelta ..< -smallDelta:
trend = .down
case -largeDelta ..< -mediumDelta:
trend = .downDown
case -Double.greatestFiniteMagnitude ..< -largeDelta:
trend = .downDownDown
case smallDelta ... mediumDelta:
trend = .up
case mediumDelta ... largeDelta:
trend = .upUp
case largeDelta ... Double.greatestFiniteMagnitude:
trend = .upUpUp
default:
break
}
trendRate = HKQuantity(unit: trendRateUnit, doubleValue: trendRateValue)
}
let sample = glucoseSample(at: date, quantity: HKQuantity(unit: unit, doubleValue: glucoseValue), condition: nil, trend: trend, trendRate: trendRate)
// capture semantics lets me "stow" the previous glucose value with this static function. A little weird, but it seems to work.
prevGlucoseValue = glucoseValue
completion(.newData([sample]))
}
}
fileprivate static var noData: MockGlucoseProvider {
return MockGlucoseProvider { _, completion in completion(.noData) }
}
fileprivate static var signalLoss: MockGlucoseProvider {
return MockGlucoseProvider { _, _ in }
}
fileprivate static var unreliableData: MockGlucoseProvider {
return MockGlucoseProvider { _, completion in completion(.unreliableData) }
}
fileprivate static func error(_ error: Error) -> MockGlucoseProvider {
return MockGlucoseProvider { _, completion in completion(.error(error)) }
}
}
// MARK: - Effects
private struct MockGlucoseProviderError: Error { }
extension MockGlucoseProvider {
fileprivate func withRandomNoise(upTo magnitude: HKQuantity) -> MockGlucoseProvider {
let unit = HKUnit.milligramsPerDeciliter
precondition(magnitude.is(compatibleWith: unit))
let magnitude = magnitude.doubleValue(for: unit)
return mapGlucoseQuantities { glucose in
let glucoseValue = (glucose.doubleValue(for: unit) + .random(in: -magnitude...magnitude)).rounded()
return HKQuantity(unit: unit, doubleValue: glucoseValue)
}
}
fileprivate func randomlyProducingLowOutlier(withChance chanceOfOutlier: Double, outlierDelta: HKQuantity) -> MockGlucoseProvider {
return randomlyProducingOutlier(withChance: chanceOfOutlier, outlierDeltaMagnitude: outlierDelta, outlierDeltaSign: -)
}
fileprivate func randomlyProducingHighOutlier(withChance chanceOfOutlier: Double, outlierDelta: HKQuantity) -> MockGlucoseProvider {
return randomlyProducingOutlier(withChance: chanceOfOutlier, outlierDeltaMagnitude: outlierDelta, outlierDeltaSign: +)
}
private func randomlyProducingOutlier(
withChance chanceOfOutlier: Double,
outlierDeltaMagnitude: HKQuantity,
outlierDeltaSign: (Double) -> Double
) -> MockGlucoseProvider {
let unit = HKUnit.milligramsPerDeciliter
precondition(outlierDeltaMagnitude.is(compatibleWith: unit))
let outlierDelta = outlierDeltaSign(outlierDeltaMagnitude.doubleValue(for: unit))
return mapGlucoseQuantities { glucose in
return coinFlip(
withChanceOfHeads: chanceOfOutlier,
ifHeads: HKQuantity(unit: unit, doubleValue: (glucose.doubleValue(for: unit) + outlierDelta).rounded()),
ifTails: glucose
)
}
}
fileprivate func randomlyErroringOnNewData(withChance chance: Double) -> MockGlucoseProvider {
return mapResult { result in
return coinFlip(withChanceOfHeads: chance, ifHeads: .error(MockGlucoseProviderError()), ifTails: result)
}
}
private func mapResult(_ transform: @escaping (CGMReadingResult) -> CGMReadingResult) -> MockGlucoseProvider {
return MockGlucoseProvider { date, completion in
self.fetchData(at: date) { result in
completion(transform(result))
}
}
}
private func mapGlucoseQuantities(_ transform: @escaping (HKQuantity) -> HKQuantity) -> MockGlucoseProvider {
return mapResult { result in
return result.mapGlucoseQuantities(transform)
}
}
}
private extension CGMReadingResult {
func mapGlucoseQuantities(_ transform: (HKQuantity) -> HKQuantity) -> CGMReadingResult {
guard case .newData(let samples) = self else {
return self
}
return .newData(
samples.map { sample in
return NewGlucoseSample(
date: sample.date,
quantity: transform(sample.quantity),
condition: sample.condition,
trend: sample.trend,
trendRate: sample.trendRate,
isDisplayOnly: sample.isDisplayOnly,
wasUserEntered: sample.wasUserEntered,
syncIdentifier: sample.syncIdentifier,
syncVersion: sample.syncVersion,
device: sample.device
)
}
)
}
}
private extension MockCGMDataSource.Model {
var glucoseProvider: MockGlucoseProvider {
switch self {
case .constant(let quantity):
return .constant(quantity)
case .sineCurve(parameters: let parameters):
return .sineCurve(parameters: parameters)
case .noData:
return .noData
case .signalLoss:
return .signalLoss
case .unreliableData:
return .unreliableData
}
}
}
private extension MockCGMDataSource.Effects {
var transformations: [(MockGlucoseProvider) -> MockGlucoseProvider] {
// Each effect maps to a transformation on a MockGlucoseProvider
return [
glucoseNoise.map { maximumDeltaMagnitude in { $0.withRandomNoise(upTo: maximumDeltaMagnitude) } },
randomLowOutlier.map { chance, delta in { $0.randomlyProducingLowOutlier(withChance: chance, outlierDelta: delta) } },
randomHighOutlier.map { chance, delta in { $0.randomlyProducingHighOutlier(withChance: chance, outlierDelta: delta) } },
randomErrorChance.map { chance in { $0.randomlyErroringOnNewData(withChance: chance) } }
].compactMap { $0 }
}
}
|
mit
|
d6f509af9a37f96dee2d088a1cb3afd1
| 40.728571 | 177 | 0.64139 | 4.790488 | false | false | false | false |
natecook1000/swift-compiler-crashes
|
crashes-duplicates/03597-swift-nominaltypedecl-getdeclaredtypeincontext.swift
|
11
|
773
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let t: String {
struct B<T where B : e {
struct B<T where B : BooleanType)
class b<Int>
class b: T where g<H : AnyObject) {
func g<b: a {
protocol d : String {
struct S<c>
let f : a {
return "[1)
class a {
class a {
}
struct c>
let f = 0) {
let t: BooleanType)
protocol d : a : AnyObject) {
let f = compose<T where B : BooleanType)
func a
f()
class b: a {
typealias e {
struct d<c>
var e("[1)
struct B<H : AnyObject) {
class c : B<T where h: a {
}
class b: a {
return "
let f : e == e(d<T : Any, A>
var f = e
protocol d : S(d: a
func a
var e
class b: S(")
struct B<T : String {
protocol A {
let t: a : S
|
mit
|
28fb691c6db0b73ea21306b778500182
| 17.404762 | 87 | 0.64295 | 2.75089 | false | false | false | false |
lyle-luan/firefox-ios
|
Client/Frontend/Browser/BrowserLocationView.swift
|
1
|
8734
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
protocol BrowserLocationViewDelegate {
func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView)
func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView)
func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView)
func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView)
}
let ImageReload = UIImage(named: "toolbar_reload.png")
let ImageStop = UIImage(named: "toolbar_stop.png")
class BrowserLocationView : UIView, UIGestureRecognizerDelegate {
var delegate: BrowserLocationViewDelegate?
private var lockImageView: UIImageView!
private var locationLabel: UILabel!
private var stopReloadButton: UIButton!
private var readerModeButton: ReaderModeButton!
var readerModeButtonWidthConstraint: NSLayoutConstraint?
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.whiteColor()
self.layer.cornerRadius = 5
lockImageView = UIImageView(image: UIImage(named: "lock_verified.png"))
lockImageView.hidden = false
lockImageView.isAccessibilityElement = true
lockImageView.accessibilityLabel = NSLocalizedString("Secure connection", comment: "")
addSubview(lockImageView)
locationLabel = UILabel()
locationLabel.font = UIFont(name: "HelveticaNeue-Light", size: 14)
locationLabel.lineBreakMode = NSLineBreakMode.ByClipping
locationLabel.userInteractionEnabled = true
// TODO: This label isn't useful for people. We probably want this to be the page title or URL (see Safari).
locationLabel.accessibilityLabel = NSLocalizedString("URL", comment: "Accessibility label")
addSubview(locationLabel)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "SELtapLocationLabel:")
locationLabel.addGestureRecognizer(tapGestureRecognizer)
stopReloadButton = UIButton()
stopReloadButton.setImage(ImageReload, forState: UIControlState.Normal)
stopReloadButton.addTarget(self, action: "SELtapStopReload", forControlEvents: UIControlEvents.TouchUpInside)
addSubview(stopReloadButton)
readerModeButton = ReaderModeButton(frame: CGRectZero)
readerModeButton.hidden = true
readerModeButton.addTarget(self, action: "SELtapReaderModeButton", forControlEvents: UIControlEvents.TouchUpInside)
addSubview(readerModeButton)
makeConstraints()
}
private func makeConstraints() {
let container = self
lockImageView.snp_remakeConstraints { make in
make.centerY.equalTo(container).centerY
make.leading.equalTo(container).with.offset(8)
make.width.equalTo(self.lockImageView.intrinsicContentSize().width)
}
locationLabel.snp_remakeConstraints { make in
make.centerY.equalTo(container.snp_centerY)
if self.url?.scheme == "https" {
make.leading.equalTo(self.lockImageView.snp_trailing).with.offset(8)
} else {
make.leading.equalTo(container).with.offset(8)
}
if self.readerModeButton.readerModeState == ReaderModeState.Unavailable {
make.trailing.equalTo(self.stopReloadButton.snp_leading).with.offset(-8)
} else {
make.trailing.equalTo(self.readerModeButton.snp_leading).with.offset(-8)
}
}
stopReloadButton.snp_remakeConstraints { make in
make.centerY.equalTo(container).centerY
make.trailing.equalTo(container).with.offset(-4)
make.size.equalTo(20)
}
readerModeButton.snp_remakeConstraints { make in
make.centerY.equalTo(container).centerY
make.trailing.equalTo(self.stopReloadButton.snp_leading).offset(-4)
// We fix the width of the button (to the height of the view) to prevent content
// compression when the locationLabel has more text contents than will fit. It
// would be nice to do this with a content compression priority but that does
// not seem to work.
make.width.equalTo(container.snp_height)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func intrinsicContentSize() -> CGSize {
return CGSize(width: 200, height: 28)
}
func SELtapLocationLabel(recognizer: UITapGestureRecognizer) {
delegate?.browserLocationViewDidTapLocation(self)
}
func SELtapReaderModeButton() {
delegate?.browserLocationViewDidTapReaderMode(self)
}
func SELtapStopReload() {
if loading {
delegate?.browserLocationViewDidTapStop(self)
} else {
delegate?.browserLocationViewDidTapReload(self)
}
}
var url: NSURL? {
didSet {
lockImageView.hidden = (url?.scheme != "https")
if let t = url?.absoluteString {
if t.hasPrefix("http://") {
locationLabel.text = t.substringFromIndex(advance(t.startIndex, 7))
} else if t.hasPrefix("https://") {
locationLabel.text = t.substringFromIndex(advance(t.startIndex, 8))
} else {
locationLabel.text = t
}
}
makeConstraints()
}
}
var loading: Bool = false {
didSet {
if loading {
stopReloadButton.setImage(ImageStop, forState: .Normal)
} else {
stopReloadButton.setImage(ImageReload, forState: .Normal)
}
}
}
var readerModeState: ReaderModeState {
get {
return readerModeButton.readerModeState
}
set (newReaderModeState) {
if newReaderModeState != self.readerModeButton.readerModeState {
self.readerModeButton.readerModeState = newReaderModeState
makeConstraints()
readerModeButton.hidden = (newReaderModeState == ReaderModeState.Unavailable)
UIView.animateWithDuration(0.1, animations: { () -> Void in
if newReaderModeState == ReaderModeState.Unavailable {
self.readerModeButton.alpha = 0.0
} else {
self.readerModeButton.alpha = 1.0
}
self.layoutIfNeeded()
})
}
}
}
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
if let hitView = super.hitTest(point, withEvent: event) {
return hitView
}
// If the hit test failed, offset it by moving it up and try again.
var fuzzPoint = point
fuzzPoint.y -= 20
if let hitView = super.hitTest(fuzzPoint, withEvent: event) {
return hitView
}
// If the hit test failed, offset it by moving it down and try again.
fuzzPoint = point
fuzzPoint.y += 20
if let hitView = super.hitTest(fuzzPoint, withEvent: event) {
return hitView
}
return nil
}
}
private class ReaderModeButton: UIButton {
override init(frame: CGRect) {
super.init(frame: frame)
setImage(UIImage(named: "reader.png"), forState: UIControlState.Normal)
setImage(UIImage(named: "reader_active.png"), forState: UIControlState.Selected)
accessibilityLabel = NSLocalizedString("Reader", comment: "Browser function that presents simplified version of the page with bigger text.")
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var _readerModeState: ReaderModeState = ReaderModeState.Unavailable
var readerModeState: ReaderModeState {
get {
return _readerModeState;
}
set (newReaderModeState) {
_readerModeState = newReaderModeState
switch _readerModeState {
case .Available:
self.enabled = true
self.selected = false
case .Unavailable:
self.enabled = false
self.selected = false
case .Active:
self.enabled = true
self.selected = true
}
}
}
}
|
mpl-2.0
|
c739e6a6a1cb7fe0e796d335eeaf21cb
| 36.973913 | 148 | 0.634761 | 5.5 | false | false | false | false |
vkozlovskyi/JellyView
|
JellyView-Example/JellyView/JellyView.swift
|
1
|
9953
|
//
// JellyView.swift
// JellyView-Example
//
// Created by Vladimir Kozlovskyi on 28.04.16.
// Copyright © 2016 Vladimir Kozlovskyi. All rights reserved.
//
import UIKit
public final class JellyView: UIView {
public enum Side {
case left, right, top, bottom
}
public class Settings {
public var triggerThreshold: CGFloat = 0.4
public var innerPointRatio: CGFloat = 0.4
public var outerPointRatio: CGFloat = 0.25
public var flexibility: CGFloat = 0.7
public var jellyMass: CGFloat = 1.0
public var springStiffness: CGFloat = 400.0
public var innerViewOffset: CGFloat = 0
public init() { }
}
// Interface
public var isEnabled: Bool = true
public var settings: Settings
public var didStartDragging: () -> Void = { }
public var actionDidFire: () -> Void = { }
public var actionDidCancel: () -> Void = { }
public var didEndDragging: () -> Void = { }
public var didDrag: (_ progress: CGFloat) -> Void = { _ in }
public var infoView: UIView? {
willSet {
if let view = infoView {
view.removeFromSuperview()
}
}
didSet {
innerView.addSubview(infoView!)
}
}
// Private
private let pathBuilder: PathBuilder
private let innerViewFrameCalculator: InnerViewFrameCalculator
private let gestureRecognizer: JellyPanGestureRecognizer
private let innerView = UIView()
private var shapeLayer = CAShapeLayer()
private let bezierPath = UIBezierPath()
private weak var containerView: UIView?
private var displayLink: CADisplayLink!
private var colorIndex: Int = 0
private let colors: [UIColor]
private var shouldDisableAnimation = true
private var isRendered = false
private var pathInputData: PathInputData {
return PathInputData(touchPoint: gestureRecognizer.touchPoint(flexibility: settings.flexibility),
frame: frame.translatedFrame(),
innerPointRatio: settings.innerPointRatio,
outerPointRatio: settings.outerPointRatio)
}
public init(side: Side,
colors: [UIColor],
settings: Settings = Settings()) {
self.colors = colors
self.settings = settings
self.pathBuilder = createPathBuilder(side: side)
self.innerViewFrameCalculator = InnerViewFrameCalculator(side: side)
self.gestureRecognizer = createJellyPanGestureRecognizer(with: side)
super.init(frame: CGRect.zero)
shapeLayer.fillColor = colors[colorIndex].cgColor
setupDisplayLink()
self.backgroundColor = UIColor.clear
self.layer.insertSublayer(shapeLayer, at: 0)
self.addSubview(innerView)
}
private func setupDisplayLink() {
displayLink = CADisplayLink(target: self, selector: #selector(JellyView.animationInProgress))
displayLink.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
displayLink.isPaused = true
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
return self.superview
}
public override func layoutSubviews() {
super.layoutSubviews()
if !isRendered {
isRendered = true
setInnerViewInitialPosition()
}
}
public override func didMoveToSuperview() {
super.didMoveToSuperview()
guard let superview = self.superview else { return }
connectGestureRecognizer(toView: superview)
self.frame = superview.bounds
setInnerViewInitialPosition()
}
public override func removeFromSuperview() {
displayLink.invalidate()
guard let superview = self.superview else { return }
disconnectGestureRecognizer(fromView: superview)
super.removeFromSuperview()
}
}
extension JellyView {
private func setInnerViewInitialPosition() {
let path = pathBuilder.buildInitialPath(inputData: pathInputData)
updateInnerViewPosition(with: path)
}
private func updateColors() {
guard let superview = self.superview else { return }
let currentColor = colors[colorIndex]
superview.backgroundColor = currentColor
colorIndex += 1
if colorIndex > colors.count - 1 {
colorIndex = 0
}
shapeLayer.fillColor = colors[colorIndex].cgColor
}
}
// MARK: - Stretching JellyView
extension JellyView: UIGestureRecognizerDelegate {
override public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer == self.gestureRecognizer {
return isEnabled
} else {
return super.gestureRecognizerShouldBegin(gestureRecognizer)
}
}
func connectGestureRecognizer(toView view: UIView) {
gestureRecognizer.addTarget(self, action: #selector(JellyView.handlePanGesture(_:)))
gestureRecognizer.delegate = self
view.addGestureRecognizer(gestureRecognizer)
}
func disconnectGestureRecognizer(fromView view: UIView) {
gestureRecognizer.removeTarget(self, action: #selector(JellyView.handlePanGesture(_:)))
gestureRecognizer.delegate = nil
view.removeGestureRecognizer(gestureRecognizer)
}
@objc private func handlePanGesture(_ pan: UIPanGestureRecognizer) {
switch pan.state {
case .began:
didStartDragging()
modifyShapeLayerForTouch()
case .changed:
modifyShapeLayerForTouch()
case .ended, .cancelled:
didEndDragging()
if shouldInitiateAction() {
animateToFinalPosition()
} else {
actionDidCancel()
animateToInitialPosition()
}
default: break
}
}
private func shouldInitiateAction() -> Bool {
let maxProgress = gestureRecognizer.totalProgressSize * settings.triggerThreshold
if gestureRecognizer.currentProgress(flexibility: settings.flexibility) >= maxProgress {
return true
} else {
return false
}
}
private func modifyShapeLayerForTouch() {
let path = pathBuilder.buildCurrentPath(inputData: pathInputData)
let progress = gestureRecognizer.currentProgress(flexibility: settings.flexibility) / gestureRecognizer.totalProgressSize
didDrag(progress)
applyPath(path)
}
private func modifyShapeLayerForInitialPosition() {
let path = pathBuilder.buildInitialPath(inputData: pathInputData)
applyPath(path)
transformInfoViewToIdentity()
}
private func applyPath(_ path: Path) {
bezierPath.setPath(path)
updateInnerViewPosition(with: path)
transformInfoViewToTouchAngle()
CATransaction.begin()
CATransaction.setDisableActions(true)
shapeLayer.path = bezierPath.cgPath
CATransaction.commit()
}
}
// MARK: - Animations
extension JellyView {
func animateToInitialPosition() {
shouldDisableAnimation = displayLink.isPaused
let path = pathBuilder.buildInitialPath(inputData: pathInputData)
CATransaction.begin()
self.animationToInitialWillStart()
let springAnimation = CASpringAnimation(keyPath: "path")
springAnimation.mass = settings.jellyMass
springAnimation.stiffness = settings.springStiffness
springAnimation.duration = springAnimation.settlingDuration
springAnimation.fromValue = bezierPath.cgPath
bezierPath.setPath(path)
transformInfoViewToIdentity(duration: springAnimation.settlingDuration)
shapeLayer.path = bezierPath.cgPath
CATransaction.setCompletionBlock { self.animationToInitialDidFinish() }
shapeLayer.add(springAnimation, forKey: "path")
CATransaction.commit()
}
func animateToFinalPosition() {
shouldDisableAnimation = displayLink.isPaused
let path = pathBuilder.buildExpandedPath(inputData: pathInputData)
CATransaction.begin()
self.animationToFinalWillStart()
let springAnimation = CASpringAnimation(keyPath: "path")
springAnimation.mass = settings.jellyMass
springAnimation.damping = 1000
springAnimation.stiffness = settings.springStiffness
springAnimation.duration = springAnimation.settlingDuration
springAnimation.fromValue = bezierPath.cgPath
bezierPath.setPath(path)
shapeLayer.path = bezierPath.cgPath
CATransaction.setCompletionBlock { self.animationToFinalDidFinish() }
shapeLayer.add(springAnimation, forKey: "path")
CATransaction.commit()
}
private func animationToInitialWillStart() {
displayLink.isPaused = false
}
@objc private func animationToInitialDidFinish() {
if shouldDisableAnimation {
displayLink.isPaused = true
}
}
private func animationToFinalWillStart() {
gestureRecognizer.isEnabled = false
displayLink.isPaused = false
}
@objc private func animationToFinalDidFinish() {
displayLink.isPaused = true
gestureRecognizer.isEnabled = true
updateColors()
modifyShapeLayerForInitialPosition()
actionDidFire()
}
@objc private func animationInProgress() {
guard let presentationLayer = self.shapeLayer.presentation() else { return }
guard let path = presentationLayer.path else { return }
let bezierPath = UIBezierPath(cgPath: path)
if let path = bezierPath.currentPath() {
updateInnerViewPosition(with: path)
}
}
}
// MARK: - Inner View Processing
extension JellyView {
private func updateInnerViewPosition(with path: Path) {
let frame = innerViewFrameCalculator.calculateFrame(with: path, offset: settings.innerViewOffset)
innerView.frame = frame
infoView?.center = CGPoint(x: innerView.frame.size.width / 2, y: innerView.frame.size.height / 2)
}
private func transformInfoViewToTouchAngle() {
guard let infoView = infoView else { return }
infoView.transform = CGAffineTransform(rotationAngle: gestureRecognizer.innerViewRotationAngle(flexibility: settings.flexibility))
}
private func transformInfoViewToIdentity(duration: TimeInterval = 0) {
guard let infoView = infoView else { return }
UIView.animate(withDuration: duration) {
infoView.transform = CGAffineTransform.identity
}
}
}
|
mit
|
728e97b49ce1048b933355d8dda4a8c6
| 30.1 | 134 | 0.722166 | 4.817038 | false | false | false | false |
buyiyang/iosstar
|
iOSStar/Scenes/User/recharge/RechargeVC.swift
|
3
|
12055
|
//
// RechargeVC.swift
// iOSStar
//
// Created by sum on 2017/4/26.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
import SVProgressHUD
class RechargeVC: BaseTableViewController ,WXApiDelegate,UITextFieldDelegate{
var rid = ""
@IBOutlet var collectView: RechargeCollectView!
@IBOutlet var dobuy: UIButton!
var selectTypeHeight = CGFloat.init(140)
//选中支付方式银行卡号
@IBOutlet weak var payTypeNumber: UILabel!
//选中支付的银行
@IBOutlet weak var payTypeName: UILabel!
//输入金额
@IBOutlet weak var inputMoney: UITextField!
//选中支付方式的图片
var selectBtn : Bool = false
@IBOutlet weak var payTypeImg: UIImageView!
var payView : SelectPayType!
var rechargeMoney : Double = 0.00
var bgview : UIView!
var paytype = 1
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(paysuccess(_:)), name: Notification.Name(rawValue:AppConst.WechatPay.WechatKeyErrorCode), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(alipaysuccess(_:)), name: Notification.Name(rawValue:AppConst.aliPay.aliPayCode), object: nil)
title = "充值"
collectView.resultBlock = { [weak self](result) in
self?.inputMoney.text = result as? String
self?.rechargeMoney = Double.init((result as? String)!)!
}
dobuy.backgroundColor = UIColor.init(hexString: AppConst.Color.orange)
inputMoney.delegate = self
inputMoney.keyboardType = .decimalPad
NotificationCenter.default.addObserver(self, selector: #selector(textFieldDidChange(_:)), name: NSNotification.Name.UITextFieldTextDidChange, object: nil)
loadview()
}
//MARK支付宝充值成功回调充值
func alipaysuccess(_ notice: NSNotification) {
if let errorCode: Int = notice.object as? Int{
if errorCode == 9000 {
SVProgressHUD.showSuccessMessage(SuccessMessage:"充值成功", ForDuration: 2.0, completion: nil)
return
} else if errorCode == 6001 {
cancelRecharge()
SVProgressHUD.showErrorMessage(ErrorMessage:"支付取消", ForDuration: 2.0, completion: nil)
return
} else {
SVProgressHUD.showErrorMessage(ErrorMessage:"支付失败", ForDuration: 2.0, completion: nil)
return
}
}
}
//MARK:微信充值成功回调充值
func paysuccess(_ notice: NSNotification) {
if let errorCode: Int = notice.object as? Int{
if errorCode == 0 {
SVProgressHUD.showSuccessMessage(SuccessMessage: "充值成功", ForDuration: 2.0, completion: nil)
return
}
else if errorCode == -4{
SVProgressHUD.showErrorMessage(ErrorMessage: "支付失败", ForDuration: 2.0, completion: nil)
return
}
else if errorCode == -2{
cancelRecharge()
SVProgressHUD.showErrorMessage(ErrorMessage: "用户中途取消", ForDuration: 2.0, completion: nil)
return
}
}
}
func textFieldDidChange(_ textFile : NSNotification) {
if inputMoney.text != "" {
if Double.init(inputMoney.text!)! > 50000 {
SVProgressHUD.showErrorMessage(ErrorMessage: "金额不能大于50000", ForDuration: 2.0, completion: nil)
inputMoney.text = ""
collectView.setSelect = "true"
return
}
collectView.setSelect = "true"
rechargeMoney = Double.init(inputMoney.text!)!
}
}
// 限制只能输入2位小数点
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
let expression = "^[0-9]*((\\.|,)[0-9]{0,2})?$"
let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
let numberOfMatches = regex.numberOfMatches(in: newString, options:NSRegularExpression.MatchingOptions.reportProgress, range: NSMakeRange(0, (newString as NSString).length))
return numberOfMatches != 0
}
//MARK:去充值
@IBAction func doRecharge(_ sender: Any) {
//微信充值
if rechargeMoney == 0.0 {
SVProgressHUD.showErrorMessage(ErrorMessage: "请输入充值金额", ForDuration: 2.0, completion: nil)
return
}
if paytype == 0 {
doWeiXinPay()
} else {
doAliPay()
}
}
//MARK:选择充值金额
@IBAction func chooseRechargeMoney(_ sender: Any) {
if selectBtn == false{
selectBtn = true
inputMoney.text = ""
rechargeMoney = 0.0
}
let moneyStr = String(stringInterpolationSegment:((sender as! UIButton).tag))
inputMoney.text = moneyStr
inputMoney.resignFirstResponder()
let btn = sender as! UIButton
if rechargeMoney != 0.0{
// let vi :UIButton = self.view.viewWithTag(Int.init(rechargeMoney)) as! UIButton
// vi.backgroundColor = UIColor.white
// vi.setTitleColor(UIColor.init(hexString: AppConst.Color.orange), for: .normal)
// rechargeMoney = Double.init(btn.tag)
// btn.backgroundColor = UIColor.init(hexString: AppConst.Color.orange)
// btn.setTitleColor(UIColor.white, for: .normal)
// rechargeMoney = Double.init(btn.tag)
}else{
btn.backgroundColor = UIColor.init(hexString: AppConst.Color.orange)
btn.setTitleColor(UIColor.white, for: .normal)
rechargeMoney = Double.init(btn.tag)
}
}
//MARK:tableView datasource
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? 10 : 10
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return section == 0 ? 0.001 : 10
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 0 {
inputMoney.resignFirstResponder()
tableView.isScrollEnabled = false
tableView.bringSubview(toFront: bgview)
UIView.animate(withDuration: 0.4, animations: {
self.payView.frame = CGRect.init(x: 0, y: tableView.frame.size.height - self.selectTypeHeight, width: tableView.frame.size.width, height: self.selectTypeHeight)
})
}
}
//MARK: loadview添加支付方式的view
func loadview(){
bgview = UIView.init(frame: CGRect.init(x: 0, y: 0, width: tableView.frame.size.width, height: tableView.frame.size.height))
bgview.backgroundColor = UIColor.init(colorLiteralRed: 1.0, green: 1.0, blue: 1.0, alpha: 0.5)
tableView.addSubview(bgview)
let btn = UIButton.init(type: .custom)
btn.frame = bgview.frame
bgview.addSubview(btn)
btn.addTarget(self, action: #selector(clickBg), for: .touchUpInside)
payView = Bundle.main.loadNibNamed("SelectPayType", owner: nil, options: nil)?.last as? SelectPayType
payView.frame = CGRect.init(x: 0, y: tableView.frame.size.height + 500, width: tableView.frame.size.width, height: 200)
payView.resultBlock = {[weak self](result) in
self?.tableView.isScrollEnabled = true
let object = result
if object is Int {
self?.tableView.sendSubview(toBack: (self?.bgview)!)
UIView.animate(withDuration: 0.25, animations: {
UIView.animate(withDuration: 0.5, animations: {
self?.payView.frame = CGRect.init(x: 0, y: ((self?.tableView.frame.size.height)! + (self?.selectTypeHeight)!), width: (self?.tableView.frame.size.width)!, height: (self?.selectTypeHeight)!)
})
}, completion: { (result ) in
self?.payView.frame = CGRect.init(x: 0, y: ((self?.tableView.frame.size.height)! + 500), width: (self?.tableView.frame.size.width)!, height: (self?.selectTypeHeight)!)
})
}else{
let model = result as! SelectPayTypeModel
self?.payTypeName.text = model.id == 0 ? "微信" : "支付宝"
self?.paytype = model.id
self?.payTypeImg.image = UIImage.init(named: model.img)
}
}
tableView.sendSubview(toBack: bgview)
bgview.addSubview(payView)
}
func clickBg(){
self.tableView.sendSubview(toBack: (self.bgview)!)
UIView.animate(withDuration: 0.25, animations: {
UIView.animate(withDuration: 0.5, animations: {
self.payView.frame = CGRect.init(x: 0, y: ((self.tableView.frame.size.height) + (self.selectTypeHeight)), width: (self.tableView.frame.size.width), height: (self.selectTypeHeight))
})
}, completion: { (result ) in
self.payView.frame = CGRect.init(x: 0, y: ((self.tableView.frame.size.height) + 500), width: (self.tableView.frame.size.width), height: (self.selectTypeHeight))
})
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
// MARK: - 支付处理
extension RechargeVC {
fileprivate func doAliPay() {
SVProgressHUD.show(withStatus: "加载中")
let requestModel = AliPayRequestModel()
requestModel.title = "余额充值"
requestModel.price = rechargeMoney
AppAPIHelper.user().alipay(requestModel: requestModel, complete: { (result) in
SVProgressHUD.dismiss()
if let model = result as? AliPayResultModel {
self.rid = model.rid
self.openAliPay(orderInfo: model.orderinfo)
}
}) { (error) in
}
}
func cancelRecharge() {
let requestModel = CancelRechargeModel()
requestModel.rid = rid
requestModel.payResult = 1
AppAPIHelper.user().cancelRecharge(requestModel: requestModel, complete: { (response) in
}) { (error) in
}
}
func openAliPay(orderInfo:String) {
AlipaySDK.defaultService().payOrder(orderInfo, fromScheme: "iOSStar") { (result) in
}
}
fileprivate func doWeiXinPay() {
SVProgressHUD.show(withStatus: "加载中")
let requestModel = WeChatPayModel()
requestModel.title = "余额充值"
requestModel.price = rechargeMoney
AppAPIHelper.user().wechatPay(requestModel: requestModel, complete: { (result) in
SVProgressHUD.dismiss()
if let model = result as? WeChatPayResultModel {
self.rid = model.rid
let request : PayReq = PayReq()
request.timeStamp = UInt32(model.timestamp)!
request.sign = model.sign
request.package = model.package
request.nonceStr = model.noncestr
request.partnerId = model.partnerid
request.prepayId = model.prepayid
WXApi.send(request)
}
}) { (error) in
SVProgressHUD.dismiss()
print(error)
}
}
}
|
gpl-3.0
|
584b7dae229efcdc4eace4cbb366ce7f
| 39.006803 | 213 | 0.598283 | 4.462064 | false | false | false | false |
foxisintest/vaporTest
|
Sources/App/main.swift
|
1
|
2143
|
import Vapor
import HTTP
import FluentMongo
//demo code
/*
let drop = Droplet()
drop.get { req in
return try drop.view.make("welcome", [
"message": drop.localization[req.lang, "welcome", "title"]
])
}
drop.resource("posts", PostController())
drop.run()
*/
//参考 https://segmentfault.com/a/1190000008421393?utm_source=tuicool&utm_medium=referral
final class UserMongoDB: Model {
var exists: Bool = false
var id: Node?
var name: String
init(name: String) {
self.name = name
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
name = try node.extract("name")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"name": name
])
}
static func prepare(_ database: Database) throws {
try database.create("users") { users in
users.id()
users.string("name")
}
}
static func revert(_ database: Database) throws {
try database.delete("users")
}
}
let mongo = try MongoDriver(database: "fox-db", user: "fox", password: "fox", host: "ds023052.mlab.com", port: 23052)
let db = Database(mongo)
let drop = Droplet()
drop.database = db
drop.preparations.append(UserMongoDB.self)
drop.post("login"){ req in
guard let name = req.data["name"]?.string else{
throw Abort.badRequest
}
var abc = UserMongoDB(name: name)
try abc.save()
return abc
}
drop.get("login"){req in
// var abc = UserMongoDB(name: "abcdefg")
// try abc.save()
// return try JSON(["memo":"mongoDB result id:\(abc.id!), name:\(abc.name)])
return try JSON(["memo":"另可用postman测试post方法, Headers空,Body参数为name=xx!!!!!!!!!!!!!!"])
}
drop.get("index"){ req in
return try drop.view.make("welcome", ["message": "hello vapor1"])
}
drop.get("index2"){ req in
return try drop.view.make("welcome", ["message": "hello vapor index2"])
}
drop.get("crud"){ req in
return try drop.view.make("crud", ["message": "hello vapor index2"])
}
drop.run()
|
mit
|
897ecd464c76b51602bb2e31790e8a0e
| 22.5 | 117 | 0.602364 | 3.484349 | false | false | false | false |
exoplatform/exo-ios
|
eXo/Sources/Models/PushTokenRestClient.swift
|
1
|
6414
|
//
// PushTokenRestClient.swift
// eXo
//
// Created by Paweł Walczak on 29.01.2018.
// Copyright © 2018 eXo. All rights reserved.
//
import Foundation
class PushTokenRestClient {
public static let shared = PushTokenRestClient()
var semaphore = DispatchSemaphore (value: 0)
var sessionCookieValue: String?
var sessionSsoCookieValue: String?
var rememberMeCookieValue: String?
var isDuringSync = false
var canDoRequest: Bool {
return !isDuringSync && sessionCookieValue != nil && sessionSsoCookieValue != nil
}
func registerToken(username: String, token: String, baseUrl: URL, completion: @escaping (Bool) -> Void) {
let params = ["username": username, "token": token, "type": "ios"]
let registerTokenUrl = URL(string: baseUrl.absoluteString.serverDomainWithProtocolAndPort! + "/portal/rest/v1/messaging/device")!
print("==== registerTokenUrl ========> \(registerTokenUrl)")
print("==== Params ==================> \(params)")
let request = createRequest(url: registerTokenUrl, method: "POST", data: try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted))
doRequest(request, completion: completion)
}
func unregisterToken(token: String, baseUrl: URL, completion: @escaping (Bool) -> Void) {
let unregisterTokenUrl = URL(string: baseUrl.absoluteString.serverDomainWithProtocolAndPort! + "/portal/rest/v1/messaging/device/\(token)")!
print("unregisterTokenUrl ========> \(unregisterTokenUrl)")
let request = createRequest(url: unregisterTokenUrl, method: "DELETE", data: nil)
doRequest(request) { result in
if result {
self.sessionSsoCookieValue = nil
self.sessionCookieValue = nil
self.rememberMeCookieValue = nil
}
completion(result)
}
}
private func createRequest(url: URL, method: String, data: Data?) -> URLRequest {
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: Config.timeout)
var headers = ["Content-Type": "application/json"]
if let sessionCookieValue = sessionCookieValue, let sessionSsoCookieValue = sessionSsoCookieValue {
headers["Cookie"] = "\(Cookies.session.rawValue)=\(sessionCookieValue); \(Cookies.sessionSso.rawValue)=\(sessionSsoCookieValue)"
}
request.allHTTPHeaderFields = headers
request.httpMethod = method
request.httpBody = data
return request
}
private func doRequest(_ request: URLRequest, completion: @escaping (Bool) -> Void) {
guard canDoRequest else { return }
isDuringSync = true
URLSession.shared.dataTask(with: request) { (data, response, error) in
self.isDuringSync = false
if let error = error {
print("---REST:\tPush token request has failed \(error.localizedDescription)")
}
if let response = response as? HTTPURLResponse {
switch response.statusCode {
case 200..<300:
print("---REST:\tPush token request completed succesfully")
self.semaphore.signal()
completion(true)
return
default:
self.semaphore.signal()
print("---REST:\tPush token request has failed. Server response: \(response.debugDescription) ---> Answered on request: \(request.debugDescription) : \((request.allHTTPHeaderFields ?? [:]).debugDescription)")
}
}
self.semaphore.signal()
completion(false)
}.resume()
semaphore.wait()
}
func checkUserSession(username: String, baseUrl: URL, completion: @escaping (Bool) -> Void){
guard let checkSessionURL = URL(string: baseUrl.absoluteString.serverDomainWithProtocolAndPort! + "/portal/rest/state/status/\(username)") else {
print("Error: cannot create URL")
return
}
print("==== checkSessionURL ========> \(checkSessionURL)")
// Create the url request
var request = URLRequest(url: checkSessionURL, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: Config.timeout)
var headers = ["Content-Type": "application/json"]
if let sessionCookieValue = sessionCookieValue, let sessionSsoCookieValue = sessionSsoCookieValue {
headers["Cookie"] = "\(Cookies.session.rawValue)=\(sessionCookieValue); \(Cookies.sessionSso.rawValue)=\(sessionSsoCookieValue)"
}
request.allHTTPHeaderFields = headers
request.httpMethod = "GET"
URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
print("Error: error calling GET")
print(error!)
return
}
guard let data = data else {
print("Error: Did not receive data")
return
}
guard let response = response as? HTTPURLResponse, (200 ..< 299) ~= response.statusCode else {
print("Error: HTTP request failed")
completion(true)
return
}
do {
guard let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
print("Error: Cannot convert data to JSON object")
return
}
guard let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) else {
print("Error: Cannot convert JSON object to Pretty JSON data")
return
}
guard let prettyPrintedJson = String(data: prettyJsonData, encoding: .utf8) else {
print("Error: Could print JSON in String")
return
}
print(prettyPrintedJson)
completion(false)
} catch {
print("Error: Trying to convert JSON data to string")
return
}
}.resume()
}
}
|
lgpl-3.0
|
0a23e663b4098999c72a21c8f3bf0da6
| 46.496296 | 228 | 0.583437 | 5.146067 | false | false | false | false |
darwin/textyourmom
|
TextYourMom/Globals.swift
|
1
|
529
|
import UIKit
var model = Model()
var masterController = MasterController()
var sharedLogsModel = LogsModel()
var mainWindow : UIWindow?
var disableScreenSwitching = false
var presentViewControllerQueue = dispatch_queue_create("presentViewControllerQueue", DISPATCH_QUEUE_SERIAL)
var lastError : String?
var mapController : MapController?
var lastLatitude : Double = 0
var lastLongitude : Double = 0
var useSignificantLocationChanges = true
var supressNextStateChangeReport = true
var overrideLocation = 0 // 0 means no override
|
mit
|
9b702db5926c34c90398da90544fd832
| 32.125 | 107 | 0.810964 | 4.6 | false | false | false | false |
folio3/SocialNetwork
|
FacebookDemo/FacebookDemo/ViewController.swift
|
1
|
2474
|
//
// ViewController.swift
// FacebookDemo
//
// Created by Hamza Azad on 30/01/2016.
// Copyright (c) 2014–2016 Folio3 Pvt Ltd (http://www.folio3.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class ViewController: UIViewController {
private let parser = FBProfileParser()
@IBOutlet weak var lblText: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func login() {
AppDelegate.facebookHandler.logout()
AppDelegate.facebookHandler.loginFromViewController(self, completion: { (result, error, cancelled) -> Void in
if var info = result as? [String: AnyObject] {
AppDelegate.facebookHandler.getUserProfile({ (result, error) -> Void in
if let profileInfo = result {
info["profile"] = profileInfo
self.parser.parse(0, object: info, completion: { (result, error) -> Void in
if error == nil {
self.lblText.text = "You are logged in as \((result as! FacebookUserProfile).name)"
}
})
}
})
}
})
}
@IBAction func logout() {
AppDelegate.facebookHandler.logout()
}
}
|
mit
|
49afe2c2d5be1d539e68e937d09bb5ec
| 37.625 | 117 | 0.63835 | 4.646617 | false | false | false | false |
ben-ng/swift
|
validation-test/compiler_crashers_fixed/00073-llvm-errs.swift
|
1
|
1784
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func kj<ts>() -> (ts, ts -> ts) -> ts {
nm ml nm.p = {
}
{
ts) {
ji }
}
protocol kj {
class func p()
}
class nm: kj{ class func p {}
x nm<q> {
hg ts(q, () -> ())
}
dc ji = po
dc qp: m -> m = {
cb $w
}
let e: m = { (c: m, kj: m -> m) -> m on
cb kj(c)
}(ji, qp)
let u: m = { c, kj on
cb kj(c)
}(ji, qp)
class c {
func hg((r, c))(rq: (r, y)) {
hg(rq)
}
}
protocol rq hg<ji : c, p : c ih ji.ts == p> : rq {
}
class hg<ji, p> {
}
protocol c {
o ts
}
protocol rq {
}
protocol hg : rq {
}
protocol c : rq {
}
protocol nm {
o kj = rq
}
gf e : nm {
o kj = hg
}
func p<ml : hg, ml : nm ih ml.kj == ml> (cb: ml) {
}
func p<v : nm ih v.kj == c> (cb: v) {
}
p(e())
func c<nm {
x c {
func e
dc _ = e
}
}
protocol kj {
}
gf v : kj {
}
gf ts<hg, p: kj ih hg.ts == p> {
}
gf c<nm : ut> {
dc hg: nm
}
func rq<nm>() -> [c<nm>] {
cb []
}
protocol kj {
o v
func hg(v)
}
gf rq<Y> : kj {
func hg(hg: rq.lk) {
}
}
class rq<kj : hg, ts : hg ih kj.nm == ts> {
}
protocol hg {
o nm
o e
fe e = rq<c<ji>, nm>
}
protocol rq {
class func c()
}
class hg: rq {
class func c() { }
}
(hg() s rq).t.c()
func sr(ed: ml) -> <q>(() -> q) -> ml {
cb { ts on "\(ed): \(ts())" }
}
gf kj<q> {
let rq: [(q, () -> ())] = []
}
func() {
x hg {
hg c
}
}
func rq(hg: m = w) {
}
let c = rq
|
apache-2.0
|
0c6a1f75d25650a76bfcd330c7ea1103
| 14.513043 | 79 | 0.488789 | 2.464088 | false | false | false | false |
quangvu1994/Exchange
|
Exchange/View/RequestTableViewCell.swift
|
1
|
1060
|
//
// RequestTableViewCell.swift
// Exchange
//
// Created by Quang Vu on 7/17/17.
// Copyright © 2017 Quang Vu. All rights reserved.
//
import UIKit
class RequestTableViewCell: UITableViewCell {
@IBOutlet weak var poster: UILabel!
@IBOutlet weak var itemImage: UIImageView!
@IBOutlet weak var briefDescription: UILabel!
@IBOutlet weak var status: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
itemImage.layer.masksToBounds = true
itemImage.layer.cornerRadius = 3
}
func setStatus(status: String) {
self.status.text = status
if status == "Accepted" {
self.status.textColor = UIColor(red: 121/255, green: 189/255, blue: 143/255, alpha: 1.0)
} else if status == "Rejected" {
self.status.textColor = UIColor(red: 220/255, green: 53/255, blue: 34/255, alpha: 1.0)
} else {
self.status.textColor = UIColor(red: 79/255, green: 146/255, blue: 193/255, alpha: 1.0)
}
}
}
|
mit
|
1db0bc9dcb28913018ad59f0f0332382
| 28.416667 | 100 | 0.624174 | 3.907749 | false | false | false | false |
devpunk/punknote
|
punknote/View/Share/VShareCellScale.swift
|
1
|
4715
|
import UIKit
class VShareCellScale:VShareCell, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
{
private weak var collectionView:VCollection!
private let kBottom:CGFloat = -40
private let kCellWidth:CGFloat = 80
override init(frame:CGRect)
{
super.init(frame:frame)
let collectionView:VCollection = VCollection()
collectionView.bounces = false
collectionView.isScrollEnabled = false
collectionView.delegate = self
collectionView.dataSource = self
collectionView.registerCell(cell:VShareCellScaleCell.self)
self.collectionView = collectionView
if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow
{
flow.scrollDirection = UICollectionViewScrollDirection.horizontal
}
addSubview(collectionView)
NSLayoutConstraint.topToTop(
view:collectionView,
toView:self)
NSLayoutConstraint.bottomToBottom(
view:collectionView,
toView:self,
constant:kBottom)
NSLayoutConstraint.equalsHorizontal(
view:collectionView,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
collectionView.collectionViewLayout.invalidateLayout()
super.layoutSubviews()
}
override func config(controller:CShare)
{
super.config(controller:controller)
collectionView.reloadData()
selectCurrent()
}
//MARK: private
private func modelAtIndex(index:IndexPath) -> CGFloat
{
let item:CGFloat = controller!.model.scales[index.item]
return item
}
private func selectCurrent()
{
guard
let selected:Int = controller?.model.selectedScale
else
{
return
}
let index:IndexPath = IndexPath(item:selected, section:0)
collectionView.selectItem(
at:index,
animated:true,
scrollPosition:UICollectionViewScrollPosition())
}
//MARK: collectionView delegate
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, insetForSectionAt section:Int) -> UIEdgeInsets
{
let width:CGFloat = collectionView.bounds.maxX
let items:CGFloat = CGFloat(controller!.model.scales.count)
let widthItems:CGFloat = items * kCellWidth
let remainWidth:CGFloat = width - widthItems
let marginHorizontal:CGFloat = remainWidth / 2.0
let insets:UIEdgeInsets = UIEdgeInsets(
top:0,
left:marginHorizontal,
bottom:0,
right:marginHorizontal)
return insets
}
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
{
let height:CGFloat = collectionView.bounds.maxY
let size:CGSize = CGSize(width:kCellWidth, height:height)
return size
}
func numberOfSections(in collectionView:UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
guard
let count:Int = self.controller?.model.scales.count
else
{
return 0
}
return count
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let item:CGFloat = modelAtIndex(index:indexPath)
let cell:VShareCellScaleCell = collectionView.dequeueReusableCell(
withReuseIdentifier:
VShareCellScaleCell.reusableIdentifier,
for:indexPath) as! VShareCellScaleCell
cell.config(scale:item)
return cell
}
func collectionView(_ collectionView:UICollectionView, shouldSelectItemAt indexPath:IndexPath) -> Bool
{
guard
let selected:Int = controller?.model.selectedScale
else
{
return false
}
if selected == indexPath.item
{
return false
}
return true
}
func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath)
{
controller?.model.selectedScale = indexPath.item
}
}
|
mit
|
a59f5e75aaa384eae2748189ed8f40e5
| 27.575758 | 157 | 0.621633 | 5.871731 | false | false | false | false |
psharanda/Jetpack
|
Sources/MutableArrayProperty.swift
|
1
|
2992
|
//
// Created by Pavel Sharanda on 30.09.17.
// Copyright © 2017 Jetpack. All rights reserved.
//
import Foundation
#if os(macOS)
import AppKit
#else
import UIKit
#endif
/// Wrapper around some mutable array. ('set/get/subscribe')
public final class MutableArrayProperty<T>: MutableMetaProperty<[T], ArrayEditEvent> {
public override init(_ value: [T] = []) {
super.init(value)
}
public func update(at index: Int, with value: T) {
mutateWithEvent {
$0[index] = value
return .update(index)
}
}
public func remove(at index: Int) {
mutateWithEvent {
$0.remove(at: index)
return .remove(index)
}
}
public func append(_ newElement: T) {
insert(newElement, at: value.count)
}
public func insert(_ newElement: T, at index: Int) {
mutateWithEvent {
$0.insert(newElement, at: index)
return .insert(index)
}
}
public func move(from fromIndex: Int, to toIndex: Int) {
mutateWithEvent {
$0.insert($0.remove(at: fromIndex), at: toIndex)
return .move(fromIndex, toIndex)
}
}
}
/// Wrapper around some mutable 2D array (array of arrays). ('set/get/subscribe')
public final class MutableArray2DProperty<T>: MutableMetaProperty<[[T]], Array2DEditEvent> {
public override init(_ value: [[T]] = []) {
super.init(value)
}
public func updateSection(at: Int, with value: [T]) {
mutateWithEvent {
$0[at] = value
return .updateSection(at)
}
}
public func removeSection(at: Int) {
mutateWithEvent {
$0.remove(at: at)
return .removeSection(at)
}
}
public func insertSection(_ newElement: [T], at: Int) {
mutateWithEvent {
$0.insert(newElement, at: at)
return .insertSection(at)
}
}
public func moveSection(from: Int, to: Int) {
mutateWithEvent {
$0.insert($0.remove(at: from), at: to)
return .moveSection(from, to)
}
}
public func updateItem(at: IndexPath, with value: T) {
mutateWithEvent {
$0[at.section][at.item] = value
return .updateItem(at)
}
}
public func removeItem(at: IndexPath) {
mutateWithEvent {
$0[at.section].remove(at: at.item)
return .removeItem(at)
}
}
public func insertItem(_ newElement: T, at: IndexPath) {
mutateWithEvent {
$0[at.section].insert(newElement, at: at.item)
return .insertItem(at)
}
}
public func moveItem(from: IndexPath, to: IndexPath) {
mutateWithEvent {
$0[to.section].insert($0[from.section].remove(at: from.item), at: to.item)
return .moveItem(from, to)
}
}
}
|
mit
|
3fce3e2b19bd79739e42e5783a948333
| 25.008696 | 92 | 0.546306 | 3.993324 | false | false | false | false |
noppoMan/aws-sdk-swift
|
Sources/Soto/Extensions/APIGateway/APIGatewayMiddleware.swift
|
1
|
968
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import SotoCore
public struct APIGatewayMiddleware: AWSServiceMiddleware {
public func chain(request: AWSRequest, context: AWSMiddlewareContext) throws -> AWSRequest {
var request = request
// have to set Accept header to application/json otherwise errors are not returned correctly
if request.httpHeaders["Accept"].first == nil {
request.httpHeaders.replaceOrAdd(name: "Accept", value: "application/json")
}
return request
}
}
|
apache-2.0
|
5c411b9c95e35aa243f8ceb796fde323
| 36.230769 | 100 | 0.590909 | 5.176471 | false | false | false | false |
937447974/YJCocoa
|
YJCocoa/Classes/AppFrameworks/Foundation/JSONModel/Transform/TransformBasic.swift
|
1
|
5016
|
//
// TransformBasic.swift
// YJCocoa
//
// HomePage:https://github.com/937447974/YJCocoa
// YJ技术支持群:557445088
//
// Created by 阳君 on 2019/6/13.
// Copyright © 2016-现在 YJCocoa. All rights reserved.
//
import UIKit
public extension YJJSONModelTransformBasic {
static func transform(toJSON value: Any) -> Any? {
return value
}
}
extension Bool: YJJSONModelTransformBasic {
public static func transform(fromJSON value: Any) -> Any? {
if let str = value as? String {
return str == "1" || str == "true"
}
return value as? Bool
}
}
extension Int: YJJSONModelTransformBasic {
public static func transform(fromJSON value: Any) -> Any? {
if let str = value as? String {
return Int(str)
}
return value as? Int
}
}
extension Float: YJJSONModelTransformBasic {
public static func transform(fromJSON value: Any) -> Any? {
if let str = value as? String {
return Float(str)
}
return value as? Float
}
}
extension CGFloat: YJJSONModelTransformBasic {
public static func transform(fromJSON value: Any) -> Any? {
guard let float = Float.transform(toJSON: value) as? Float else {
return nil
}
return CGFloat(float)
}
}
extension Double: YJJSONModelTransformBasic {
public static func transform(fromJSON value: Any) -> Any? {
if let str = value as? String {
return Double(str)
}
return value as? Double
}
}
extension String: YJJSONModelTransformBasic {
public static func transform(fromJSON value: Any) -> Any? {
return "\(value)"
}
}
extension Array: YJJSONModelTransformBasic where Element: YJJSONModelTransformBasic {
public static func transform(fromJSON value: Any) -> Any? {
guard let array = value as? [Any] else {
return nil
}
var result = Array<Element>()
for value in array {
if let item = Element.transform(fromJSON: value) as? Element {
result.append(item)
}
}
return result
}
public static func transform(toJSON value: Any) -> Any? {
guard let _value = value as? Array else {
return nil
}
var result = Array<Any>()
for item in _value {
if let _item = Element.transform(toJSON: item) {
result.append(_item)
}
}
return result
}
}
extension Optional: YJJSONModelTransformBasic where Wrapped: YJJSONModelTransformBasic {
public static func transform(fromJSON value: Any) -> Any? {
return Wrapped.transform(fromJSON: value)
}
public static func transform(toJSON value: Any) -> Any? {
return Wrapped.transform(toJSON: value)
}
}
extension URL: YJJSONModelTransformBasic {
public static func transform(fromJSON value: Any) -> Any? {
if let str = value as? String {
return URL(string: str)
}
return value as? URL
}
public static func transform(toJSON value: Any) -> Any? {
guard let url = value as? URL else {
return nil
}
return "\(url)"
}
}
extension Date: YJJSONModelTransformBasic {
public static func transform(fromJSON value: Any) -> Any? {
if let time = value as? TimeInterval {
return Date(timeIntervalSince1970: time)
}
if let str = value as? String, let time = TimeInterval(str) {
return Date(timeIntervalSince1970: time)
}
return value as? Date
}
public static func transform(toJSON value: Any) -> Any? {
guard let _value = value as? Date else {
return nil
}
return _value.timeIntervalSince1970
}
}
extension UIColor: YJJSONModelTransformBasic {
public static func transform(fromJSON value: Any) -> Any? {
if let hex = value as? Int64 {
if hex <= 0xFFFFFF {
return UIColor(red: CGFloat((hex & 0xFF0000) >> 16)/255.0, green: CGFloat((hex & 0xFF00) >> 8)/255.0, blue: CGFloat(hex & 0xFF)/255.0, alpha: 1)
} else {
return UIColor(red: CGFloat((hex & 0xFF000000) >> 24)/255.0, green: CGFloat((hex & 0xFF0000) >> 16)/255.0, blue: CGFloat((hex & 0xFF00) >> 8)/255.0, alpha: CGFloat(hex & 0xFF)/255.0)
}
}
return value as? UIColor
}
public static func transform(toJSON value: Any) -> Any? {
guard let _value = value as? UIColor else {
return nil
}
let comps = _value.cgColor.components!
let r = Int(comps[0] * 255)
let g = Int(comps[1] * 255)
let b = Int(comps[2] * 255)
let a = Int(comps[3] * 255)
if a == 255 {
return r << 16 + g << 8 + b
} else {
return r << 24 + g << 16 + b << 8 + a
}
}
}
|
mit
|
f362647aa0bc814986f04cbc0f4171a8
| 26.607735 | 198 | 0.570142 | 4.082516 | false | false | false | false |
gifsy/Gifsy
|
Frameworks/ConvenienceKit/ConvenienceKit/ConvenienceKit/UIKit/TimelineComponent.swift
|
1
|
5179
|
//
// TimelineComponent.swift
// ConvenienceKit
//
// Created by Benjamin Encz on 4/13/15.
// Copyright (c) 2015 Benjamin Encz. All rights reserved.
//
import UIKit
/**
This protocol needs to be implemented by any class that wants to be the target
of the Timeline Component.
*/
public protocol TimelineComponentTarget: class {
typealias ContentType
/// Defines the range of the timeline that gets loaded initially.
var defaultRange: Range<Int> { get }
/**
Defines the additional amount of items that get loaded
subsequently when a user reaches the last entry.
*/
var additionalRangeSize: Int { get }
/// A reference to the TableView to which the Timeline Component is applied.
var tableView: UITableView! { get }
/**
This method should load the items within the specified range and call the
`completionBlock`, with the items as argument, upon completion.
*/
func loadInRange(range: Range<Int>, completionBlock: ([ContentType]?) -> Void)
}
protocol Refreshable {
func refresh(sender: AnyObject)
}
/**
Adds a Pull-To-Refresh mechanism and endless scrolling behavior to classes that own
a `UITableView`.
Note that this class will handle storage of the content that is relevant to the TableView's Data Source in the
`content` property.
Apply following steps to use this class:
1. Implement the `TimelineComponentTarget` protocol
2. Call the `loadInitialIfRequired()` when you want to load the Data Source's content for the first time
3. Call `targetWillDisplayEntry(entryIndex:)` when a cell becomes visible
*/
public class TimelineComponent <T: Equatable, S: TimelineComponentTarget where S.ContentType == T> : Refreshable {
weak var target: S?
var refreshControl: UIRefreshControl
var currentRange: Range<Int> = 0...0
var loadedAllContent = false
var targetTrampoline: TargetTrampoline!
// MARK: Public Interface
/// Stores the items that should be displayed in the Table View
public var content: [T] = []
/**
Creates a Timeline Component and connects it to its target.
- parameter target: The class on which the Timeline Component shall operate
*/
public init(target: S) {
self.target = target
refreshControl = UIRefreshControl()
target.tableView.insertSubview(refreshControl, atIndex:0)
currentRange = target.defaultRange
targetTrampoline = TargetTrampoline(target: self)
refreshControl.addTarget(targetTrampoline, action: "refresh:", forControlEvents: .ValueChanged)
}
/**
Removes an object from the `content` of the Timeline Component
- parameter object: The object that shall be removed.
*/
public func removeObject(object: T) {
ConvenienceKit.removeObject(object, fromArray: &self.content)
currentRange.endIndex = self.currentRange.endIndex - 1
target?.tableView.reloadData()
}
/**
Triggers an initial request for data, if no data has been loaded so far.
*/
public func loadInitialIfRequired() {
// if no posts are currently loaded, load the default range
if (content == []) {
target!.loadInRange(target!.defaultRange) { posts in
self.content = posts ?? []
self.target!.tableView.reloadData()
}
}
}
/**
Should be called whenever a cell becomes visible. This allows the Timeline Component
to decide when to load additional items.
- parameter entryIndex: The index of the cell that became visible
*/
public func targetWillDisplayEntry(entryIndex: Int) {
if (entryIndex == (currentRange.endIndex - 1) && !loadedAllContent) {
loadMore()
}
}
// MARK: Internal Interface
internal func refresh(sender: AnyObject) {
currentRange = target!.defaultRange
target!.loadInRange(target!.defaultRange) { content in
self.loadedAllContent = false
self.content = content! as [T]
self.refreshControl.endRefreshing()
UIView.transitionWithView(self.target!.tableView,
duration: 0.35,
options: .TransitionCrossDissolve,
animations:
{ () -> Void in
self.target!.tableView.reloadData()
self.target!.tableView.contentOffset = CGPoint(x: 0, y: 0)
},
completion: nil);
}
}
func loadMore() {
let additionalRange = Range(start: currentRange.endIndex, end: currentRange.endIndex + target!.additionalRangeSize)
currentRange = Range(start: currentRange.startIndex, end: additionalRange.endIndex)
target!.loadInRange(additionalRange) { posts in
let newPosts = posts
if (newPosts!.count == 0) {
self.loadedAllContent = true
}
self.content = self.content + newPosts!
self.target!.tableView.reloadData()
}
}
}
/**
Provides a class that can be exposed to Objective-C because it doesn't use generics.
The only purpose of this class is to expose "refresh" and call it on the Swift class
that uses Generics.
*/
class TargetTrampoline: NSObject, Refreshable {
let target: Refreshable
init(target: Refreshable) {
self.target = target
}
func refresh(sender: AnyObject) {
target.refresh(self)
}
}
|
apache-2.0
|
33e68ad55899ecb763cd1a541889502a
| 28.431818 | 119 | 0.693763 | 4.546971 | false | false | false | false |
KrauseFx/fastlane
|
fastlane/swift/SocketResponse.swift
|
6
|
3306
|
// SocketResponse.swift
// Copyright (c) 2022 FastlaneTools
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
import Foundation
struct SocketResponse {
enum ResponseType {
case parseFailure(failureInformation: [String])
case failure(failureInformation: [String], failureClass: String?, failureMessage: String?)
case readyForNext(returnedObject: String?, closureArgumentValue: String?)
case clientInitiatedCancel
init(statusDictionary: [String: Any]) {
guard let status = statusDictionary["status"] as? String else {
self = .parseFailure(failureInformation: ["Message failed to parse from Ruby server"])
return
}
if status == "ready_for_next" {
verbose(message: "ready for next")
let returnedObject = statusDictionary["return_object"] as? String
let closureArgumentValue = statusDictionary["closure_argument_value"] as? String
self = .readyForNext(returnedObject: returnedObject, closureArgumentValue: closureArgumentValue)
return
} else if status == "cancelled" {
self = .clientInitiatedCancel
return
} else if status == "failure" {
guard let failureInformation = statusDictionary["failure_information"] as? [String] else {
self = .parseFailure(failureInformation: ["Ruby server indicated failure but Swift couldn't receive it"])
return
}
let failureClass = statusDictionary["failure_class"] as? String
let failureMessage = statusDictionary["failure_message"] as? String
self = .failure(failureInformation: failureInformation, failureClass: failureClass, failureMessage: failureMessage)
return
}
self = .parseFailure(failureInformation: ["Message status: \(status) not a supported status"])
}
}
let responseType: ResponseType
init(payload: String) {
guard let data = SocketResponse.convertToDictionary(text: payload) else {
responseType = .parseFailure(failureInformation: ["Unable to parse message from Ruby server"])
return
}
guard case let statusDictionary? = data["payload"] as? [String: Any] else {
responseType = .parseFailure(failureInformation: ["Payload missing from Ruby server response"])
return
}
responseType = ResponseType(statusDictionary: statusDictionary)
}
}
extension SocketResponse {
static func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
log(message: error.localizedDescription)
}
}
return nil
}
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.2]
|
mit
|
3555e50ffb2ba6647ebef9670253a5f0
| 38.357143 | 131 | 0.624924 | 5.332258 | false | false | false | false |
xivol/MCS-V3-Mobile
|
examples/swift/SwiftBasics.playground/Pages/Tuples.xcplaygroundpage/Contents.swift
|
1
|
1670
|
/*:
## Tuples
[Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
****
*/
var pair: (String, Int, Double)
pair.0 = "Swift"
pair.1 = 333
pair.2 = 3.4
pair
var namedPair: (name: String, age: Int) = ("Ilya", 30)
namedPair.name = "Ilya"
namedPair.age = 29
namedPair
//: Type inferrence
let point = (x: 0.0, y: -1.0)
type(of: point)
let area = (bottomLeft: (-1.0, -1.0), topRight: (1.0, 1.0))
type(of: area)
//: Tuples of the same type are comparable. Tuples are compared from left to right.
if point > area.bottomLeft && point < area.topRight {
"point is inside the (\(area.bottomLeft), \(area.topRight)) area"
}
if point == (0.0, 0.0) {
"point is zero"
} else if point.x > 0.0 {
if point.y > 0.0 {
"point is in first quarter"
} else {
"point is in fourth quarter"
}
} else {
if point.y < 0.0 {
"point is in third quarter"
} else {
"point is in second quarter"
}
}
//: _Tuples can be decomposed into a set of variables:_
var (first, second) = point
"first: \(first); second: \(second)"
type(of: first)
(first, second) = (second, first)
"swapped first: \(first); second: \(second)"
//: _Underscore `_` can be used to ignore some of tuple values._
let (onlyFirst, _) = point
"first: \(onlyFirst)"
//: _It can also be used in switch cases:_
switch point {
case (0.0, 0.0):
break
case (0.0, _):
"point belongs to the X axis"
case (_, 0.0):
"point belongs to the Y axis"
default:
break
}
//: _(Type) ~ Type_
type(of: ("Hello, Tuple!"))
type(of: (42))
type(of: ()) // () ~ Void
//: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
|
mit
|
8ad2215332b9a2e7a8c270c9dc2aa112
| 22.464789 | 83 | 0.602041 | 2.980322 | false | false | false | false |
MxABC/oclearning
|
swiftLearning/swiftLearning/NetTest.swift
|
1
|
4770
|
//
// NetTest.swift
// swiftLearning
//
// Created by csc on 16/2/14.
// Copyright © 2016年 csc. All rights reserved.
//
import UIKit
import Alamofire
import ObjectMapper
class MsgHead: Mappable {
var errorMsg: String?
var isSuccessful: Bool?
var errorCode: String?
required init?(_ map: Map) {
//
// mapping(map)
}
// Mappable
func mapping(map: Map) {
errorMsg <- map["errorMsg"]
isSuccessful <- map["isSuccessful"]
errorCode <- map["errorCode"]
}
}
class MsgMessage: Mappable {
var citizenCardNum: String?
var citizenCardStatus: String?
var idCardNum: String?
var mobile: String?
var realName: String?
var token: String?
var userId: String?
required init?(_ map: Map) {
// mapping(map)
}
// Mappable
func mapping(map: Map) {
citizenCardNum <- map["citizenCardNum"]
citizenCardStatus <- map["isSuccessful"]
idCardNum <- map["idCardNum"]
mobile <- map["mobile"]
realName <- map["realName"]
token <- map["token"]
userId <- map["userId"]
}
}
class userLog: Mappable {
var head: MsgHead?
var message: MsgMessage?
required init?(_ map: Map) {
// mapping(map)
}
// Mappable
func mapping(map: Map) {
head <- map["head"]
message <- map["message"]
}
}
class NetTest: NSObject {
static func get()->Void
{
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
static func post()->Void
{
let strURL = "http://61.177.137.34:8280/ZCCardServer/users/userLogin.action"
let strAppID = "10010";
let strSign = "7f9abc089fc9c116d14c23ac028a9662";
let strVersion = "1.0";
let strTimeStamp = "20141013171958";
let dicheader = ["appId":strAppID,"sign":strSign,"version":strVersion,"timestamp":strTimeStamp]
let dicMsg = ["password":"dc483e80a7a0bd9ef71d8cf973673924","type":"mobile","userName":"15852509846"]
let dic = ["head":dicheader,"message":dicMsg]
let httpHeader = ["token":"1234567890"]
let re:Request = Alamofire.request(.POST, strURL, parameters: dic, encoding: ParameterEncoding.JSON, headers: httpHeader).responseJSON{response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
// print("statuscode:%ld",response.statusCode)
if let JSON = response.result.value {
print("JSON: \(JSON)")
// let dic:Dictionary = JSON as! Dictionary<String,Dictionary<String,String>>
let userInfo:userLog? = Mapper<userLog>().map(JSON)
if (userInfo != nil)
{
print("mobile:%@",userInfo?.message?.mobile)
//let mobile = userInfo?.message?.mobile;
//print("%@",mobile);
}
/*
JSON: {
head = {
errorCode = "UserController_login_Success";
errorMsg = "\U767b\U5f55\U6210\U529f";
isSuccessful = 1;
};
message = {
citizenCardNum = "";
citizenCardStatus = unbinded;
idCardNum = "";
mobile = 15852509846;
realName = "";
token = "f654513a-ab4b-4da2-a051-f553d66f1770";
userId = 272;
};
}
*/
}
}
// re.responseJSON(completionHandler: <#T##Response<AnyObject, NSError> -> Void#>)
// re.cancel()
// re.resume()
// re.suspend()
}
}
|
mit
|
ae4afa8dd379a1a1345a24cfc09bfd7f
| 25.780899 | 155 | 0.484372 | 4.574856 | false | false | false | false |
qutheory/vapor
|
Sources/Vapor/Error/StackTrace.swift
|
2
|
3637
|
#if os(Linux)
import Backtrace
import CBacktrace
#endif
extension Optional where Wrapped == StackTrace {
public static func capture(skip: Int = 0) -> Self {
StackTrace.capture(skip: 1 + skip)
}
}
public struct StackTrace {
public static var isCaptureEnabled: Bool = true
public static func capture(skip: Int = 0) -> Self? {
guard Self.isCaptureEnabled else {
return nil
}
let frames = Self.captureRaw().dropFirst(1 + skip)
return .init(rawFrames: .init(frames))
}
#if os(Linux)
private static let state = backtrace_create_state(CommandLine.arguments[0], /* supportThreading: */ 1, nil, nil)
#endif
static func captureRaw() -> [RawFrame] {
#if os(Linux)
final class Context {
var frames: [RawFrame]
init() {
self.frames = []
}
}
var context = Context()
backtrace_full(self.state, /* skip: */ 1, { data, pc, filename, lineno, function in
let frame = RawFrame(
file: filename.flatMap { String(cString: $0) } ?? "unknown",
mangledFunction: function.flatMap { String(cString: $0) } ?? "unknown"
)
data!.assumingMemoryBound(to: Context.self)
.pointee.frames.append(frame)
return 0
}, { _, cMessage, _ in
let message = cMessage.flatMap { String(cString: $0) } ?? "unknown"
fatalError("Failed to capture Linux stacktrace: \(message)")
}, &context)
return context.frames
#else
return Thread.callStackSymbols.dropFirst(1).map { line in
let parts = line.split(
separator: " ",
maxSplits: 3,
omittingEmptySubsequences: true
)
let file = String(parts[1])
let functionParts = parts[3].split(separator: "+")
let mangledFunction = String(functionParts[0])
.trimmingCharacters(in: .whitespaces)
return .init(file: file, mangledFunction: mangledFunction)
}
#endif
}
public struct Frame {
public var file: String
public var function: String
}
public var frames: [Frame] {
self.rawFrames.map { frame in
Frame(
file: frame.file,
function: _stdlib_demangleName(frame.mangledFunction)
)
}
}
struct RawFrame {
var file: String
var mangledFunction: String
}
let rawFrames: [RawFrame]
public func description(max: Int = 16) -> String {
return self.frames[..<min(self.frames.count, max)].readable
}
}
extension StackTrace: CustomStringConvertible {
public var description: String {
self.description()
}
}
extension StackTrace.Frame: CustomStringConvertible {
public var description: String {
"\(self.file) \(self.function)"
}
}
extension Collection where Element == StackTrace.Frame {
var readable: String {
let maxIndexWidth = String(self.count).count
let maxFileWidth = self.map { $0.file.count }.max() ?? 0
return self.enumerated().map { (i, frame) in
let indexPad = String(
repeating: " ",
count: maxIndexWidth - String(i).count
)
let filePad = String(
repeating: " ",
count: maxFileWidth - frame.file.count
)
return "\(i)\(indexPad) \(frame.file)\(filePad) \(frame.function)"
}.joined(separator: "\n")
}
}
|
mit
|
adfe1dfab1d12786769a01189ba6bdd1
| 29.563025 | 116 | 0.558152 | 4.419198 | false | false | false | false |
jindulys/EbloVaporServer
|
Sources/App/Models/Company/Company.swift
|
1
|
1700
|
//
// File.swift
// EbloVaporServer
//
// Created by yansong li on 2017-05-30.
//
//
import Foundation
import Vapor
/// Class represents a company
public final class Company: Model {
public var id: Node?
public var exists: Bool = false
/// Company name.
public var companyName: String
/// Company url string.
public var companyUrlString: String
/// The first blog title string.
public var firstBlogTitle: String
public init(node: Node, in context: Context) throws {
id = try node.extract("id")
companyName = try node.extract("companyname")
companyUrlString = try node.extract("companyurlstring")
firstBlogTitle = try node.extract("firstblogtitle")
}
public init(companyName: String,
companyUrlString: String,
firstBlogTitle: String = "") {
self.companyName = companyName
self.companyUrlString = companyUrlString
self.id = nil
self.firstBlogTitle = firstBlogTitle
}
public func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id" : id,
"companyname" : companyName,
"companyurlstring" : companyUrlString,
"firstblogtitle" : firstBlogTitle
])
}
public static func prepare(_ database: Database) throws {
try database.create("companys", closure: { companys in
companys.id()
companys.string("companyname")
companys.string("companyurlstring")
companys.string("firstblogtitle")
})
}
public static func revert(_ database: Database) throws {
try database.delete("companys")
}
}
extension Company: Unique {
public func identifier() -> String {
return self.companyName
}
}
|
mit
|
4d157ce49ff645ad893ff9b7a8f0ccd7
| 22.943662 | 59 | 0.66 | 4.176904 | false | false | false | false |
syoung-smallwisdom/ResearchUXFactory-iOS
|
ResearchUXFactory/SBAResearchKitResultConverter.swift
|
1
|
6953
|
//
// SBAResearchKitResultConverter.swift
// ResearchUXFactory
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import Foundation
/**
Protocol for use in extending ResearchKit model objects and view controllers to
process the results.
*/
public protocol SBAResearchKitResultConverter: class {
/**
Returns an answer format finder that can be used to get the answer format for a
given identifier.
*/
var answerFormatFinder: SBAAnswerFormatFinder? { get }
/**
Find the result associated with a given identifier.
*/
func findResult(for identifier: String) -> ORKResult?
}
/**
The base class of a step view controller can be extended to return the step as a `SBAAnswerFormatFinder`
and to search for a form result as a subresult of this step view controller's `ORKStepResult`
*/
extension ORKStepViewController: SBAResearchKitResultConverter {
public var answerFormatFinder: SBAAnswerFormatFinder? {
return self.step as? SBAAnswerFormatFinder
}
public func findResult(for identifier: String) -> ORKResult? {
// Use the answer format finder to find the result identifier associated with this result
guard let resultIdentifier = self.answerFormatFinder?.resultIdentifier(for: identifier) else { return nil }
// If found, return the result from the results included in this step result
return self.result?.result(forIdentifier: resultIdentifier.identifier)
}
}
/**
Various convenience methods for converting a result into the appropriate object that defines that result.
*/
extension SBAResearchKitResultConverter {
/**
Look for an `ORKTimeOfDayQuestionResult` and get the date components from the result.
*/
public func timeOfDay(for identifier: String) -> DateComponents? {
guard let result = self.findResult(for: identifier) as? ORKTimeOfDayQuestionResult
else {
return nil
}
return result.dateComponentsAnswer
}
/**
If the associated identifier can be mapped to a result from an `HKQuantitySample` then
return the object created from that result.
*/
public func quantitySample(for identifier: String) -> HKQuantitySample? {
guard let profileResult = findResult(for: identifier) as? ORKQuestionResult,
let quantity = quantity(for: identifier),
let quantityType = quantityType(for: identifier)
else {
return nil
}
return HKQuantitySample(type: quantityType, quantity: quantity, start: profileResult.startDate, end: profileResult.endDate)
}
/**
Get the `HKQuantity` associated with a given result to an `ORKFormItem` with a matching type.
*/
public func quantity(for identifier: String) -> HKQuantity? {
guard let profileResult = findResult(for: identifier) as? ORKQuestionResult,
let answer = profileResult.jsonSerializedAnswer(),
let doubleValue = (answer.value as? NSNumber)?.doubleValue,
let unitString = answer.unit
else {
return nil
}
return HKQuantity(unit: HKUnit(from: unitString), doubleValue: doubleValue)
}
/**
Get the `HKQuantityType` associated with a given answer format with a matching type.
*/
public func quantityType(for identifier: String) -> HKQuantityType? {
if let answerFormat = self.answerFormatFinder?.find(for: identifier) as? ORKHealthKitQuantityTypeAnswerFormat {
return answerFormat.quantityType
}
else if let option = SBAProfileInfoOption(rawValue: identifier) {
switch (option) {
case .height:
return HKObjectType.quantityType(forIdentifier: .height)
case .weight:
return HKObjectType.quantityType(forIdentifier: .bodyMass)
default:
break
}
}
return HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: identifier))
}
/**
Convert an `ORKHealthKitCharacteristicTypeAnswerFormat` survey question into
an `HKBiologicalSex` enum value.
*/
public func convertBiologicalSex(for identifier:String) -> HKBiologicalSex? {
guard let result = self.findResult(for: identifier) as? ORKChoiceQuestionResult
else { return nil }
if let answer = (result.choiceAnswers?.first as? NSNumber)?.intValue {
return HKBiologicalSex(rawValue: answer)
}
else if let answer = result.choiceAnswers?.first as? String {
// The ORKHealthKitCharacteristicTypeAnswerFormat uses a string rather
// than using the HKBiologicalSex enum directly so you have to convert
let biologicalSex = ORKBiologicalSexIdentifier(rawValue: answer)
return biologicalSex.healthKitBiologicalSex()
}
else {
return nil
}
}
/**
Convert an `ORKTextQuestionResult` for a given result into a string.
*/
public func textAnswer(for identifier:String) -> String? {
guard let result = self.findResult(for: identifier) as? ORKTextQuestionResult else { return nil }
return result.textAnswer
}
}
|
bsd-3-clause
|
8ba90c6ff2d44285f8f5c48951870596
| 40.879518 | 131 | 0.695771 | 5.037681 | false | false | false | false |
khoren93/SwiftHub
|
SwiftHub/Common/Table View Cells/DefaultTableViewCell.swift
|
1
|
5109
|
//
// DefaultTableViewCell.swift
// SwiftHub
//
// Created by Khoren Markosyan on 6/30/18.
// Copyright © 2018 Khoren Markosyan. All rights reserved.
//
import UIKit
class DefaultTableViewCell: TableViewCell {
lazy var leftImageView: ImageView = {
let view = ImageView(frame: CGRect())
view.contentMode = .scaleAspectFit
view.cornerRadius = 25
view.snp.makeConstraints({ (make) in
make.size.equalTo(50)
})
return view
}()
lazy var badgeImageView: ImageView = {
let view = ImageView(frame: CGRect())
view.backgroundColor = .white
view.cornerRadius = 10
view.borderColor = .white
view.borderWidth = 1
containerView.addSubview(view)
view.snp.makeConstraints({ (make) in
make.bottom.left.equalTo(self.leftImageView)
make.size.equalTo(20)
})
return view
}()
lazy var titleLabel: Label = {
let view = Label()
view.font = view.font.withSize(14)
return view
}()
lazy var detailLabel: Label = {
let view = Label()
view.font = view.font.withSize(12)
view.setPriority(UILayoutPriority.defaultLow, for: NSLayoutConstraint.Axis.vertical)
return view
}()
lazy var secondDetailLabel: Label = {
let view = Label()
view.font = view.font.bold.withSize(11)
return view
}()
lazy var attributedDetailLabel: Label = {
let view = Label()
view.font = view.font.bold.withSize(11)
return view
}()
lazy var textsStackView: StackView = {
let views: [UIView] = [self.titleLabel, self.detailLabel, self.secondDetailLabel, self.attributedDetailLabel]
let view = StackView(arrangedSubviews: views)
view.spacing = 2
return view
}()
lazy var rightImageView: ImageView = {
let view = ImageView(frame: CGRect())
view.image = R.image.icon_cell_disclosure()?.template
view.snp.makeConstraints({ (make) in
make.width.equalTo(20)
})
return view
}()
override func makeUI() {
super.makeUI()
titleLabel.theme.textColor = themeService.attribute { $0.text }
detailLabel.theme.textColor = themeService.attribute { $0.textGray }
secondDetailLabel.theme.textColor = themeService.attribute { $0.text }
leftImageView.theme.tintColor = themeService.attribute { $0.secondary }
rightImageView.theme.tintColor = themeService.attribute { $0.secondary }
stackView.addArrangedSubview(leftImageView)
stackView.addArrangedSubview(textsStackView)
stackView.addArrangedSubview(rightImageView)
stackView.snp.remakeConstraints({ (make) in
let inset = self.inset
make.edges.equalToSuperview().inset(UIEdgeInsets(top: inset/2, left: inset, bottom: inset/2, right: inset))
make.height.greaterThanOrEqualTo(Configs.BaseDimensions.tableRowHeight)
})
}
override func bind(to viewModel: TableViewCellViewModel) {
super.bind(to: viewModel)
guard let viewModel = viewModel as? DefaultTableViewCellViewModel else { return }
viewModel.title.asDriver().drive(titleLabel.rx.text).disposed(by: rx.disposeBag)
viewModel.title.asDriver().replaceNilWith("").map { $0.isEmpty }.drive(titleLabel.rx.isHidden).disposed(by: rx.disposeBag)
viewModel.detail.asDriver().drive(detailLabel.rx.text).disposed(by: rx.disposeBag)
viewModel.detail.asDriver().replaceNilWith("").map { $0.isEmpty }.drive(detailLabel.rx.isHidden).disposed(by: rx.disposeBag)
viewModel.secondDetail.asDriver().drive(secondDetailLabel.rx.text).disposed(by: rx.disposeBag)
viewModel.secondDetail.asDriver().replaceNilWith("").map { $0.isEmpty }.drive(secondDetailLabel.rx.isHidden).disposed(by: rx.disposeBag)
viewModel.attributedDetail.asDriver().drive(attributedDetailLabel.rx.attributedText).disposed(by: rx.disposeBag)
viewModel.attributedDetail.asDriver().map { $0 == nil }.drive(attributedDetailLabel.rx.isHidden).disposed(by: rx.disposeBag)
viewModel.badge.asDriver().drive(badgeImageView.rx.image).disposed(by: rx.disposeBag)
viewModel.badge.map { $0 == nil }.asDriver(onErrorJustReturn: true).drive(badgeImageView.rx.isHidden).disposed(by: rx.disposeBag)
viewModel.badgeColor.asDriver().drive(badgeImageView.rx.tintColor).disposed(by: rx.disposeBag)
viewModel.hidesDisclosure.asDriver().drive(rightImageView.rx.isHidden).disposed(by: rx.disposeBag)
viewModel.image.asDriver().filterNil()
.drive(leftImageView.rx.image).disposed(by: rx.disposeBag)
viewModel.imageUrl.map { $0?.url }.asDriver(onErrorJustReturn: nil).filterNil()
.drive(leftImageView.rx.imageURL).disposed(by: rx.disposeBag)
viewModel.imageUrl.asDriver().filterNil()
.drive(onNext: { [weak self] (url) in
self?.leftImageView.hero.id = url
}).disposed(by: rx.disposeBag)
}
}
|
mit
|
1ab3bf48521e4f0247e56763b20e9028
| 37.992366 | 144 | 0.661903 | 4.403448 | false | false | false | false |
pixelmaid/DynamicBrushes
|
swift/Palette-Knife/models/brushes/Brush.swift
|
1
|
33125
|
//
// Brush.swift
// Palette-Knife
//
// Created by JENNIFER MARY JACOBS on 5/5/16.
// Copyright © 2016 pixelmaid. All rights reserved.
//
import Foundation
struct DeltaStorage{
var dX = Float(0)
var dY = Float(0)
//var pX = Float(0)
//var pY = Float(0)
//var oX = Float(0)
//var oY = Float(0)
var r = Float(0)
var sX = Float(0)
var sY = Float(0)
var rX = Float(0)
var rY = Float(0)
var d = Float(0)
var h = Float(0)
var s = Float(0)
var l = Float(0)
var a = Float(0)
var dist = Float(0);
var xDist = Float(0);
var yDist = Float(0);
}
class Brush: TimeSeries, WebTransmitter, Hashable{
//hierarcical data
var children = [Brush]();
var parent: Brush!
//dictionary to store expressions for emitter->action handlers
var states = [String:State]();
var transitions = [String:StateTransition]();
var currentState:String
//geometric/stylistic properties
let bPosition:Point //actual position
let position:LinkedPoint //settable positon
let x:Observable<Float>
let y:Observable<Float>
let polarPosition:LinkedPoint //settable position for polar coordinates
let theta:Observable<Float>
let radius:Observable<Float>
let delta:LinkedPoint
let dx:Observable<Float>
let dy:Observable<Float>
let origin:Point;
let ox:Observable<Float>
let oy:Observable<Float>
let scaling:Point;
let sx:Observable<Float>
let sy:Observable<Float>
let reflectY:Observable<Float>
let reflectX:Observable<Float>
let rotation:Observable<Float>
let distance:Observable<Float>
let xDistance:Observable<Float>
let yDistance:Observable<Float>
var time:Observable<Float>
let intersections:Observable<Float>
let index:Observable<Float>
let level:Observable<Float>
let siblingcount:Observable<Float>
let diameter:Observable<Float>
let alpha:Observable<Float>
let hue:Observable<Float>
let lightness:Observable<Float>
let saturation:Observable<Float>
let xBuffer:CircularBuffer
let yBuffer:CircularBuffer
let weightBuffer:CircularBuffer
let bufferLimitX:Observable<Float>
let bufferLimitY:Observable<Float>
//list of obeservables (for later disposal)
var currentCanvas:Canvas?
var currentStroke:Stroke?
//Events
var geometryModified = Event<(Geometry,String,String)>()
var transmitEvent = Event<(String)>()
var initEvent = Event<(WebTransmitter,String)>()
var dieEvent = Event<(String)>()
let removeMappingEvent = Event<(Brush,String,Observable<Float>)>()
let removeTransitionEvent = Event<(Brush,String,Emitter)>()
//Events
var id = NSUUID().uuidString;
var behavior_id:String?
var behaviorDef:BehaviorDefinition?
var matrix = Matrix();
var deltaKey = NSUUID().uuidString;
var drawKey = NSUUID().uuidString;
var bufferKey = NSUUID().uuidString;
let childDieHandlerKey = NSUUID().uuidString;
var deltaChangeBuffer = [DeltaStorage]();
var undergoing_transition = false;
init(name:String, behaviorDef:BehaviorDefinition?, parent:Brush?, canvas:Canvas){
//==BEGIN OBSERVABLES==//
self.bPosition = Point(x:0,y:0)
self.position = LinkedPoint(x:0,y:0)
self.x = self.position.x;
self.y = self.position.y;
self.x.printname = "brush_position_x"
self.y.printname = "brush_position_y"
self.position.name = "brush_position";
self.polarPosition = LinkedPoint(x:0,y:0)
self.radius = self.polarPosition.x;
self.theta = self.polarPosition.y;
self.radius.printname = "brush_radius"
self.theta.printname = "brush_theta"
self.polarPosition.name = "brush_polarPosition";
self.delta = LinkedPoint(x:0,y:0)
self.dx = delta.x;
self.dy = delta.y
self.dx.printname = "brush_delta_x"
self.dy.printname = "brush_delta_y"
self.origin = Point(x:0,y:0)
self.ox = origin.x;
self.oy = origin.y;
self.scaling = Point(x:1,y:1)
self.sx = scaling.x;
self.sy = scaling.y;
self.reflectY = Observable<Float>(0)
self.reflectX = Observable<Float>(0)
self.rotation = Observable<Float>(0)
self.distance = Observable<Float>(0)
self.xDistance = Observable<Float>(0)
self.yDistance = Observable<Float>(0)
self.index = Observable<Float>(0)
self.level = Observable<Float>(0)
self.siblingcount = Observable<Float>(0)
self.intersections = Observable<Float>(0)
self.time = Observable<Float>(0)
self.diameter = Observable<Float>(1)
self.diameter.printname = "brush_diameter"
self.alpha = Observable<Float>(100)
self.hue = Observable<Float>(100)
self.lightness = Observable<Float>(100)
self.saturation = Observable<Float>(100)
self.xBuffer = CircularBuffer()
self.yBuffer = CircularBuffer()
self.weightBuffer = CircularBuffer()
self.bufferLimitX = Observable<Float>(0)
self.bufferLimitY = Observable<Float>(0)
//==END OBSERVABLES==//
self.currentState = "start";
super.init()
//TODO: this code is annoying because KVC assigment issues. Find a fix?
self.time = _time
self.kvcDictionary["x"] = self.x;
self.kvcDictionary["y"] = self.y;
self.kvcDictionary["theta"] = self.theta;
self.kvcDictionary["radius"] = self.radius;
self.kvcDictionary["dx"] = self.dx;
self.kvcDictionary["dy"] = self.dy;
self.kvcDictionary["ox"] = self.ox;
self.kvcDictionary["oy"] = self.oy;
self.kvcDictionary["sx"] = self.sx;
self.kvcDictionary["sy"] = self.sy;
self.kvcDictionary["reflectX"] = self.reflectX;
self.kvcDictionary["reflectY"] = self.reflectY;
self.kvcDictionary["rotation"] = self.rotation;
self.kvcDictionary["distance"] = self.distance;
self.kvcDictionary["xDistance"] = self.xDistance;
self.kvcDictionary["yDistance"] = self.yDistance;
self.kvcDictionary["time"] = self.time;
self.kvcDictionary["intersections"] = self.intersections;
self.kvcDictionary["index"] = self.index;
self.kvcDictionary["level"] = self.level;
self.kvcDictionary["siblingcount"] = self.siblingcount;
self.kvcDictionary["diameter"] = self.diameter;
self.kvcDictionary["alpha"] = self.alpha;
self.kvcDictionary["hue"] = self.hue;
self.kvcDictionary["lightness"] = self.lightness;
self.kvcDictionary["saturation"] = self.saturation;
//==BEGIN APPEND OBSERVABLES==//
observables.append(bPosition)
observables.append(delta)
observables.append(position)
observables.append(polarPosition)
observables.append(origin)
observables.append(scaling)
observables.append(reflectY);
observables.append(reflectX);
observables.append(rotation);
observables.append(distance)
observables.append(xDistance)
observables.append(yDistance)
observables.append(index)
observables.append(siblingcount)
observables.append(level)
observables.append(diameter)
observables.append(alpha)
observables.append(hue)
observables.append(lightness)
observables.append(saturation)
observables.append(xBuffer);
observables.append(yBuffer);
observables.append(weightBuffer);
observables.append(bufferLimitX)
observables.append(bufferLimitY)
//==END APPEND OBSERVABLES==//
self.behavior_id = behaviorDef!.id;
self.behaviorDef = behaviorDef;
self.name = name;
//setup events and create listener storage
self.events = ["SPAWN", "STATE_COMPLETE", "DELTA_BUFFER_LIMIT_REACHED", "DISTANCE_INTERVAL", "INTERSECTION"]
self.createKeyStorage();
//setup listener for delta observable
_ = self.delta.didChange.addHandler(target: self, handler:Brush.deltaChange, key:deltaKey)
_ = self.position.didChange.addHandler(target: self, handler:Brush.positionChange, key:deltaKey)
_ = self.polarPosition.didChange.addHandler(target: self, handler:Brush.polarPositionChange, key:deltaKey)
_ = self.xBuffer.bufferEvent.addHandler(target: self, handler: Brush.deltaBufferLimitReached, key: bufferKey)
self.setCanvasTarget(canvas: canvas)
self.parent = parent
//setup behavior
if(behaviorDef != nil){
behaviorDef?.addBrush(targetBrush: self)
}
self.delta.name = "delta_"+self.id;
}
//creates states and transitions for global actions and mappings
func createGlobals(){
let _ = self.createState(id: "global",name: "global");
let globalEmitter = Emitter();
self.addStateTransition(id: "globalTransition", name: "globalTransition", reference: globalEmitter, fromStateId: "global", toStateId: "global")
}
func setupTransition(){
let setupTransition = self.getTransitionByName(name: "setup");
if(setupTransition != nil){
self.transitionToState(transition: setupTransition!)
}
else{
#if DEBUG
print("setup transition does not exist for \(self.id)");
#endif
}
}
//MARK: - Hashable
var hashValue : Int {
get {
return "\(self.id)".hashValue
}
}
//Event handlers
//chains communication between brushes and view controller
func brushDrawHandler(data:(Geometry,String,String),key:String){
self.geometryModified.raise(data: data)
}
func createState(id:String,name:String){
states[id] = State(id:id,name:name);
}
func deltaBufferLimitReached(data:(String), key:String){
bufferLimitX.set(newValue: 1)
}
func positionChange(data:(String,(Float,Float),(Float,Float)),key:String){
print("position change called");
if(!self.undergoing_transition){
let _delta = self.position.sub(point: self.bPosition)
let polarPos = MathUtil.cartToPolar(p1: self.bPosition, p2: self.position);
// self.polarPosition.setSilent(newValue: (polarPos));
self.calculateProperties(_delta:_delta)
}
}
func polarPositionChange(data:(String,(Float,Float),(Float,Float)),key:String){
print("polar change called");
if(!self.undergoing_transition){
let t = MathUtil.map(value: self.polarPosition.y.get(id: nil),low1: 0,high1: 100,low2: 0,high2: 360);
let cartPos = MathUtil.polarToCart(r: self.polarPosition.x.get(id: nil),theta:t);
// self.position.setSilent(newValue: cartPos)
let p = Point(x:cartPos.0+self.origin.x.get(id: nil),y:cartPos.1+self.origin.y.get(id: nil));
let _delta = p.sub(point: self.bPosition)
print("polar change theta:",t,"rad:",self.polarPosition.x.get(id: nil),"cart point:",p.x.get(id:nil),p.y.get(id:nil),"delta",_delta.x.get(id:nil),_delta.y.get(id:nil))
self.calculateProperties(_delta:_delta)
}
}
func deltaChange(data:(String,(Float,Float),(Float,Float)),key:String){
if(!self.undergoing_transition){
self.calculateProperties(_delta: self.delta)
}
}
func calculateProperties(_delta:Point){
let dX = _delta.x.get(id:nil);
let dY = _delta.y.get(id:nil);
let r = MathUtil.map(value: self.rotation.get(id:nil), low1: 0.0, high1: 100.0, low2: 0.0, high2: 360.0)
let sX = self.scaling.x.get(id:nil)
let sY = self.scaling.y.get(id:nil)
let rX = self.reflectX.get(id:nil)
let rY = self.reflectY.get(id:nil)
let mapped_diameter = pow(1.03,self.diameter.get(id:nil))*0.54
let d = mapped_diameter
let h = MathUtil.map(value: self.hue.get(id:nil), low1: 0.0, high1: 100.0, low2: 0.0, high2: 1.0)
let s = MathUtil.map(value: self.saturation.get(id:nil), low1: 0.0, high1: 100.0, low2: 0.0, high2: 1.0)
let l = MathUtil.map(value: self.lightness.get(id:nil), low1: 0.0, high1: 100.0, low2: 0.0, high2: 1.0)
let mapped_alpha = pow(1.054,self.alpha.get(id:nil))*0.54
let a = MathUtil.map(value: mapped_alpha, low1: 0.0, high1: 100.0, low2: 0.0, high2: 1.0)
let dist = self.distance.get(id:nil);
let xDist = self.xDistance.get(id:nil);
let yDist = self.yDistance.get(id:nil);
let ds = DeltaStorage(dX:dX,dY:dY,r:r,sX:sX,sY:sY,rX:rX,rY:rY,d:d,h:h,s:s,l:l,a:a,dist:dist,xDist:xDist,yDist:yDist)
self.deltaChangeBuffer.append(ds);
self.processDeltaBuffer();
}
func processDeltaBuffer(){
var ds:DeltaStorage! = nil
if deltaChangeBuffer.count>0 {
ds = deltaChangeBuffer.remove(at: 0)
}
if(ds != nil){
let centerX = self.origin.x.get(id:nil)
let centerY = self.origin.y.get(id:nil)
self.matrix.reset();
if(self.parent != nil){
self.matrix.prepend(mx: self.parent!.matrix)
}
var xScale = ds.sX
if(ds.rX == 1){
xScale *= -1.0;
}
var yScale = ds.sY
if(ds.rY == 1){
yScale *= -1.0;
}
let r = ds.r
self.matrix.scale(x: xScale, y: yScale, centerX: centerX, centerY: centerY);
self.matrix.rotate(_angle: r, centerX: centerX, centerY: centerY)
let xDelt = ds.dX
let yDelt = ds.dY
let _dx = self.bPosition.x.get(id:nil) + xDelt;
let _dy = self.bPosition.y.get(id:nil) + yDelt;
let transformedCoords = self.matrix.transformPoint(x: _dx, y: _dy)
self.distance.set(newValue: ds.dist + sqrt(pow(xDelt,2)+pow(yDelt,2)));
self.xDistance.set(newValue: ds.xDist + abs(xDelt));
self.yDistance.set(newValue: ds.yDist + abs(yDelt));
// xBuffer.push(v: xDelt);
// yBuffer.push(v: yDelt);
bufferLimitX.set(newValue: 0)
bufferLimitY.set(newValue: 0)
let cweight = ds.d;
//weightBuffer.push(v: cweight);
let color = Color(h: ds.h, s: ds.s, l: ds.l, a: 1)
self.currentCanvas!.addSegmentToStroke(parentID: self.id, point:Point(x:transformedCoords.0,y:transformedCoords.1),weight:cweight , color: color,alpha:ds.a)
self.bPosition.x.setSilent(newValue: _dx)
self.bPosition.y.setSilent(newValue:_dy)
self.distanceIntervalCheck();
self.intersectionCheck();
}
}
func intersectionCheck(){
// let bpx = bPosition.x.get(id: nil);
// let bpy = bPosition.y.get(id: nil);
if((keyStorage["INTERSECTION"]!.count)>0){
if(self.parent != nil){
let hit = self.currentCanvas!.parentHitTest(point: self.bPosition, threshold: 5, id:self.id, parentId:self.parent!.id);
if(hit != nil){
self.intersections.set(newValue: self.intersections.getSilent()+1);
for key in keyStorage["INTERSECTION"]!
{
if(key.1 != nil){
let condition = key.1;
let evaluation = condition?.evaluate();
if(evaluation == true){
NotificationCenter.default.post(name: NSNotification.Name(rawValue: key.0), object: self, userInfo: ["emitter":self,"key":key.2.id,"event":"INTERSECTION"])
}
}
else{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: key.0), object: self, userInfo: ["emitter":self,"key":key.2.id,"event":"INTERSECTION"])
}
}
}
}
}
}
func distanceIntervalCheck()
{
for key in keyStorage["DISTANCE_INTERVAL"]!
{
if(key.1 != nil){
let condition = key.1;
let evaluation = condition?.evaluate();
if(evaluation == true){
NotificationCenter.default.post(name: NSNotification.Name(rawValue: key.0), object: self, userInfo: ["emitter":self,"key":key.2.id,"event":"DISTANCE_INTERVAL"])
}
}
else{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: key.0), object: self, userInfo: ["emitter":self,"key":key.2.id,"event":"DISTANCE_INTERVAL"])
}
}
}
func setOrigin(p:Point){
self.origin.set(val:p);
let pol = MathUtil.cartToPolar(p1: Point(x:0,y:0), p2: p);
self.polarPosition.x.setSilent(newValue: pol.0);
self.polarPosition.y.setSilent(newValue: pol.1);
self.position.x.setSilent(newValue: self.origin.x.get(id: nil))
self.position.y.setSilent(newValue: self.origin.y.get(id: nil))
self.bPosition.x.setSilent(newValue: self.origin.x.get(id: nil))
self.bPosition.y.setSilent(newValue: self.origin.y.get(id: nil))
#if DEBUG
//print("origin set =",stylus.x.get(id:nil),p.x.get(id: nil),p.y.get(id:nil));
#endif
}
@objc dynamic func stateTransitionHandler(notification: NSNotification){
let key = notification.userInfo?["key"] as! String
if(key == self.id){
let mapping = states[currentState]?.getTransitionMapping(key: notification.name.rawValue)
if(mapping != nil){
let stateTransition = mapping
self.raiseBehaviorEvent(d: stateTransition!.toJSON(), event: "transition")
self.transitionToState(transition: stateTransition!)
}
}
}
func transitionToState(transition:StateTransition){
var constraint_mappings:[String:Constraint];
print("transitioning to state:\(currentState) from state: \(transition.toStateId)");
if(states[currentState] != nil){
constraint_mappings = states[currentState]!.constraint_mappings
for (_, value) in constraint_mappings{
self.setConstraint(constraint: value)
value.relativeProperty.constrained = false;
}
}
self.currentState = transition.toStateId;
if(states[currentState] != nil){
self.raiseBehaviorEvent(d: states[currentState]!.toJSON(), event: "state")
self.executeTransitionMethods(methods: transition.methods)
constraint_mappings = states[currentState]!.constraint_mappings
for (_, value) in constraint_mappings{
value.relativeProperty.constrained = true;
}
//execute methods
//check constraints
//trigger state complete after functions are executed
_ = Timer.scheduledTimer(timeInterval: 0.00001, target: self, selector: #selector(Brush.completeCallback), userInfo: nil, repeats: false)
if(states[currentState]?.name == "die"){
self.die();
}}
}
func raiseBehaviorEvent(d:String, event:String){
var data = "{\"brush_id\":\""+self.id+"\","
data+="\"brush_name\":\""+self.name+"\","
data+="\"behavior_id\":\""+self.behavior_id!+"\","
data += "\"event\":\""+event+"\",";
data += "\"type\":\"behavior_change\","
data += "\"data\":"+d;
data += "}"
// if(self.name != "rootBehaviorBrush"){
self.transmitEvent.raise(data: data);
//}
}
@objc func completeCallback(){
for key in self.keyStorage["STATE_COMPLETE"]! {
if(key.1 != nil){
let condition = key.1;
if(condition?.evaluate())!{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: key.0), object: self, userInfo: ["emitter":self,"key":key.2.id,"event":"STATE_COMPLETE"])
}
}
else{
NotificationCenter.default.post(name: NSNotification.Name(rawValue: key.0), object: self, userInfo: ["emitter":self,"key":key.2.id,"event":"STATE_COMPLETE"])
}
}
}
func executeTransitionMethods(methods:[Method]){
for i in 0..<methods.count{
let method = methods[i];
let methodName = method.name;
#if DEBUG
//print("executing method:\(method.name,self.id,self.name)");
#endif
switch (methodName){
case "newStroke":
let arg = method.arguments![0];
if let arg_string = arg as? String {
if(arg_string == "parent_position"){
if(self.parent != nil){
self.setOrigin(p: self.parent!.bPosition)
}
else{
#if DEBUG
print("cannot set origin, no parent position")
#endif
}
}
else if(arg_string == "parent_origin"){
if(self.parent != nil){
self.setOrigin(p: self.parent!.origin)
}
else{
#if DEBUG
print("cannot set origin, no parent position")
#endif
}
}
}else {
self.setOrigin(p: method.arguments![0] as! Point)
}
self.newStroke();
break;
case "startTimer":
self.startInterval();
break;
case "stopTimer":
self.stopInterval();
break;
case "setOrigin":
let arg = method.arguments![0];
if let arg_string = arg as? String {
if(arg_string == "parent_position"){
self.setOrigin(p: self.parent!.bPosition)
}
else if(arg_string == "parent_origin"){
self.setOrigin(p: self.parent!.origin)
}
}else {
self.setOrigin(p: method.arguments![0] as! Point)
}
case "destroy":
self.destroy();
break;
case "spawn":
let arg = method.arguments![0];
var behaviorDef:BehaviorDefinition! = nil;
let arg_string = arg as? String
if(arg_string == "parent"){
behaviorDef = self.parent!.behaviorDef!;
}
else if(arg_string == "self"){
behaviorDef = self.behaviorDef!;
}
else{
behaviorDef = BehaviorManager.getBehaviorById(id:arg_string!);
}
if(behaviorDef != nil){
self.spawn(behavior:behaviorDef,num:(method.arguments![1] as! Int));
}
break;
default:
break;
}
}
}
//sets canvas target to output geometry into
func setCanvasTarget(canvas:Canvas){
self.currentCanvas = canvas;
}
/* addConstraint
//adds a property mapping constraint.
//property mappings can take two forms, active and passive
//active: when reference changes, relative is updated to reflect change. This is for properties which are updated manually by the artist
//like the stylus properties, or properties with an internal interval, like a timed buffer
//passive: this for constraints which are not actively modifed by an interval or an external change. This can include constants
//or generators and buffers which will return a new value each time they are accessed
*/
func addConstraint(id:String,reference:Observable<Float>, relative:Observable<Float>, stateId:String, type:String){
/*#if DEBUG
if let expref = reference as? TextExpression{
for (_, val) in expref.operandList{
print("reference,relative",val.printname,relative.printname)
}
}
#endif*/
if(type == "active"){
reference.subscribe(id: self.id);
_ = reference.didChange.addHandler(target: self, handler: Brush.setHandler, key:id)
}
else if(type == "passive"){
relative.passiveConstrain(target: reference);
}
states[stateId]!.addConstraintMapping(key: id,reference:reference,relativeProperty: relative,type:type)
}
//setHandler: triggered when constraint is changed, evaluates if brush is in correct state to encact constraint
func setHandler(data:(String,Float,Float),stateKey:String){
// let reference = notification.userInfo?["emitter"] as! Emitter
let mapping = states[currentState]?.getConstraintMapping(key: stateKey)
if(mapping != nil){
//let constraint = mapping as! Constraint
self.setConstraint(constraint: mapping!)
}
}
func childDieHandler(data:(String),key:String){
let id = data;
for c in children.reversed(){
if c.id == id{
_ = self.removeChildAt(index: Int(c.index.get(id: nil)))
}
}
for i in 0..<children.count{
self.children[i].index.set(newValue: Float(i));
}
}
func setConstraint(constraint:Constraint){
#if DEBUG
print("calling set constraint on", constraint.relativeProperty.name,constraint.relativeProperty,constraint.reference.get(id: self.id))
#endif
constraint.relativeProperty.set(newValue: constraint.reference.get(id: self.id));
}
func addStateTransition(id:String, name:String, reference:Emitter, fromStateId: String, toStateId:String){
let transition:StateTransition
let state = self.states[fromStateId]
transition = state!.addStateTransitionMapping(id: id,name:name,reference: reference, toStateId:toStateId)
self.transitions[id] = transition;
}
func removeStateTransition(data:(Brush, String, Emitter),key:String){
NotificationCenter.default.removeObserver(data.0, name: NSNotification.Name(rawValue: data.1), object: data.2)
data.2.removeKey(key: data.1)
}
func addMethod(transitionId:String, methodId:String, methodName:String, arguments:[Any]?){
(transitions[transitionId]!).addMethod(id: methodId, name:methodName,arguments:arguments)
}
func getTransitionByName(name:String)->StateTransition?{
for(_,transition) in self.transitions{
if(transition.name == name){
return transition;
}
}
return nil
}
func getStateByName(name:String)->State?{
for(_,state) in self.states{
if(state.name == name){
return state;
}
}
return nil
}
func removeTransition(key:String){
for (key,val) in states {
if(val.hasTransitionKey(key: key)){
let removal = val.removeTransitionMapping(key: key)!
let data = (self, key, removal.reference)
removeTransitionEvent.raise(data: data)
break
}
}
}
func resetDistance(){
self.distance.set(newValue: 0);
self.xDistance.set(newValue: 0);
self.yDistance.set(newValue: 0)
for key in keyStorage["DISTANCE_INTERVAL"]!{
if(key.1 != nil){
let eventCondition = key.1;
eventCondition!.reset();
}
}
}
//===============METHODS AVAILABLE TO USER===============//
func newStroke(){
self.currentCanvas!.currentDrawing!.retireCurrentStrokes(parentID: self.id)
self.currentStroke = self.currentCanvas!.currentDrawing!.newStroke(parentID: self.id);
self.resetDistance();
}
//creates number of clones specified by num and adds them as childre n
func spawn(behavior:BehaviorDefinition,num:Int) {
if(num > 0){
for _ in 0...num-1{
let child = Brush(name:name, behaviorDef: behavior, parent:self, canvas:self.currentCanvas!)
self.children.append(child);
child.index.set(newValue: Float(self.children.count-1));
child.level.set(newValue: Float(self.level.get(id: nil)+1));
self.initEvent.raise(data: (child,"brush_init"));
/* #if DEBUG
print("spawn called")
#endif*/
behavior.initBrushBehavior(targetBrush: child);
_ = child.dieEvent.addHandler(target: self, handler: Brush.childDieHandler, key: childDieHandlerKey)
}
for c in children{
c.siblingcount.set(newValue: Float(self.children.count))
}
//notify listeners of spawn event
for key in keyStorage["SPAWN"]! {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: key.2.id), object: self, userInfo: ["emitter":self,"key":key.0,"event":"SPAWN"])
}
}
}
//=============END METHODS AVAILABLE TO USER==================//
//========= CLEANUP METHODS ==================//
//removes child at an index and returns it
// removes listener on child, but does not destroy it
func removeChildAt(index:Int)->Brush{
let child = self.children.remove(at: index)
return child
}
func die(){
self.dieEvent.raise(data:(self.id));
self.destroy();
}
func destroyChildren(){
for child in self.children as [Brush] {
child.destroy();
}
self.children.removeAll();
}
func clearBehavior(){
for (_,state) in self.states{
let removedTransitions = state.removeAllTransitions();
for i in 0..<removedTransitions.count{
let transition = removedTransitions[i]
self.removeTransitionEvent.raise(data: (self,transition.id,transition.reference));
}
state.removeAllConstraintMappings(brush:self);
}
self.transitions.removeAll();
self.states.removeAll();
}
func clearAllEventHandlers(){
self.initEvent.removeAllHandlers()
self.geometryModified.removeAllHandlers()
self.transmitEvent.removeAllHandlers()
self.removeMappingEvent.removeAllHandlers()
self.removeTransitionEvent.removeAllHandlers()
self.dieEvent.removeAllHandlers()
}
override func destroy() {
self.stopInterval();
#if DEBUG
//print("destroying brush: \(self.id)");
#endif
currentCanvas!.currentDrawing!.retireCurrentStrokes(parentID: self.id)
self.clearBehavior();
self.clearAllEventHandlers();
super.destroy();
}
//========= END CLEANUP METHODS ==================//
}
// MARK: Equatable
func ==(lhs:Brush, rhs:Brush) -> Bool {
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
|
mit
|
132a93ad239a78df66476526347d29ec
| 32.973333 | 183 | 0.555972 | 4.305732 | false | false | false | false |
ul7290/realm-cocoa
|
RealmSwift-swift2.0/Realm.swift
|
2
|
24091
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm 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 Foundation
import Realm
import Realm.Private
/**
A Realm instance (also referred to as "a realm") represents a Realm
database.
Realms can either be stored on disk (see `init(path:)`) or in
memory (see `Configuration`).
Realm instances are cached internally, and constructing equivalent Realm
objects (with the same path or identifier) produces limited overhead.
If you specifically want to ensure a Realm object is
destroyed (for example, if you wish to open a realm, check some property, and
then possibly delete the realm file and re-open it), place the code which uses
the realm within an `autoreleasepool {}` and ensure you have no other
strong references to it.
- warning: Realm instances are not thread safe and can not be shared across
threads or dispatch queues. You must construct a new instance on each thread you want
to interact with the realm on. For dispatch queues, this means that you must
call it in each block which is dispatched, as a queue is not guaranteed to run
on a consistent thread.
*/
public final class Realm {
// MARK: Properties
/// Path to the file where this Realm is persisted.
public var path: String { return rlmRealm.path }
/// Indicates if this Realm was opened in read-only mode.
public var readOnly: Bool { return rlmRealm.readOnly }
/// The Schema used by this realm.
public var schema: Schema { return Schema(rlmRealm.schema) }
/// Returns the `Configuration` that was used to create this `Realm` instance.
public var configuration: Configuration { return Configuration.fromRLMRealmConfiguration(rlmRealm.configuration) }
/// Indicates if this Realm contains any objects.
public var isEmpty: Bool { return rlmRealm.isEmpty }
// MARK: Initializers
/**
Obtains a Realm instance with the given configuration. Defaults to the default Realm configuration,
which can be changed by setting `Realm.Configuration.defaultConfiguration`.
- parameter configuration: The configuration to use when creating the Realm instance.
*/
public convenience init(configuration: Configuration = Configuration.defaultConfiguration) throws {
let rlmRealm = try RLMRealm(configuration: configuration.rlmConfiguration)
self.init(rlmRealm)
}
/**
Obtains a Realm instance persisted at the specified file path.
- parameter path: Path to the realm file.
*/
public convenience init(path: String) throws {
let rlmRealm = try RLMRealm(path: path, key: nil, readOnly: false, inMemory: false, dynamic: false, schema: nil)
self.init(rlmRealm)
}
// MARK: Transactions
/**
Performs actions contained within the given block inside a write transation.
Write transactions cannot be nested, and trying to execute a write transaction
on a `Realm` which is already in a write transaction will throw an exception.
Calls to `write` from `Realm` instances in other threads will block
until the current write transaction completes.
Before executing the write transaction, `write` updates the `Realm` to the
latest Realm version, as if `refresh()` was called, and generates notifications
if applicable. This has no effect if the `Realm` was already up to date.
- parameter block: The block to be executed inside a write transaction.
*/
public func write(@noescape block: (() -> Void)) throws {
try rlmRealm.transactionWithBlock(block)
}
/**
Begins a write transaction in a `Realm`.
Only one write transaction can be open at a time. Write transactions cannot be
nested, and trying to begin a write transaction on a `Realm` which is
already in a write transaction will throw an exception. Calls to
`beginWrite` from `Realm` instances in other threads will block
until the current write transaction completes.
Before beginning the write transaction, `beginWrite` updates the
`Realm` to the latest Realm version, as if `refresh()` was called, and
generates notifications if applicable. This has no effect if the `Realm`
was already up to date.
It is rarely a good idea to have write transactions span multiple cycles of
the run loop, but if you do wish to do so you will need to ensure that the
`Realm` in the write transaction is kept alive until the write transaction
is committed.
*/
public func beginWrite() {
rlmRealm.beginWriteTransaction()
}
/**
Commits all writes operations in the current write transaction, and ends
the transaction.
Calling this when not in a write transaction will throw an exception.
*/
public func commitWrite() throws {
try rlmRealm.commitWriteTransaction()
}
/**
Revert all writes made in the current write transaction and end the transaction.
This rolls back all objects in the Realm to the state they were in at the
beginning of the write transaction, and then ends the transaction.
This restores the data for deleted objects, but does not revive invalidated
object instances. Any `Object`s which were added to the Realm will be
invalidated rather than switching back to standalone objects.
Given the following code:
```swift
let oldObject = objects(ObjectType).first!
let newObject = ObjectType()
realm.beginWrite()
realm.add(newObject)
realm.delete(oldObject)
realm.cancelWrite()
```
Both `oldObject` and `newObject` will return `true` for `invalidated`,
but re-running the query which provided `oldObject` will once again return
the valid object.
Calling this when not in a write transaction will throw an exception.
*/
public func cancelWrite() {
rlmRealm.cancelWriteTransaction()
}
/**
Indicates if this Realm is currently in a write transaction.
- warning: Wrapping mutating operations in a write transaction if this property returns `false`
may cause a large number of write transactions to be created, which could negatively
impact Realm's performance. Always prefer performing multiple mutations in a single
transaction when possible.
*/
public var inWriteTransaction: Bool {
return rlmRealm.inWriteTransaction
}
// MARK: Adding and Creating objects
/**
Adds or updates an object to be persisted it in this Realm.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
When added, all (child) relationships referenced by this object will also be
added to the Realm if they are not already in it. If the object or any related
objects already belong to a different Realm an exception will be thrown. Use one
of the `create` functions to insert a copy of a persisted object into a different
Realm.
The object to be added must be valid and cannot have been previously deleted
from a Realm (i.e. `invalidated` must be false).
- parameter object: Object to be added to this Realm.
- parameter update: If true will try to update existing objects with the same primary key.
*/
public func add(object: Object, update: Bool = false) {
if update && object.objectSchema.primaryKeyProperty == nil {
throwRealmException("'\(object.objectSchema.className)' does not have a primary key and can not be updated")
}
RLMAddObjectToRealm(object, rlmRealm, update)
}
/**
Adds or updates objects in the given sequence to be persisted it in this Realm.
- see: add(_:update:)
- warning: This method can only be called during a write transaction.
- parameter objects: A sequence which contains objects to be added to this Realm.
- parameter update: If true will try to update existing objects with the same primary key.
*/
public func add<S: SequenceType where S.Generator.Element: Object>(objects: S, update: Bool = false) {
for obj in objects {
add(obj, update: update)
}
}
/**
Create an `Object` with the given value.
Creates or updates an instance of this object and adds it to the `Realm` populating
the object with the given value.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
- warning: This method can only be called during a write transaction.
- parameter type: The object type to create.
- parameter value: The value used to populate the object. This can be any key/value coding compliant
object, or a JSON dictionary such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
When passing in an `Array`, all properties must be present,
valid and in the same order as the properties defined in the model.
- parameter update: If true will try to update existing objects with the same primary key.
- returns: The created object.
*/
public func create<T: Object>(type: T.Type, value: AnyObject = [:], update: Bool = false) -> T {
// FIXME: use T.className()
let className = (type as Object.Type).className()
if update && schema[className]?.primaryKeyProperty == nil {
throwRealmException("'\(className)' does not have a primary key and can not be updated")
}
return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, className, value, update), T.self)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `create(_:value:update:)`.
Creates or updates an object with the given class name and adds it to the `Realm`, populating
the object with the given value.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
- warning: This method can only be called during a write transaction.
- parameter className: The class name of the object to create.
- parameter value: The value used to populate the object. This can be any key/value coding compliant
object, or a JSON dictionary such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
When passing in an `Array`, all properties must be present,
valid and in the same order as the properties defined in the model.
- parameter update: If true will try to update existing objects with the same primary key.
- returns: The created object.
:nodoc:
*/
public func dynamicCreate(className: String, value: AnyObject = [:], update: Bool = false) -> DynamicObject {
if update && schema[className]?.primaryKeyProperty == nil {
throwRealmException("'\(className)' does not have a primary key and can not be updated")
}
return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, className, value, update), DynamicObject.self)
}
// MARK: Deleting objects
/**
Deletes the given object from this Realm.
- warning: This method can only be called during a write transaction.
- parameter object: The object to be deleted.
*/
public func delete(object: Object) {
RLMDeleteObjectFromRealm(object, rlmRealm)
}
/**
Deletes the given objects from this Realm.
- warning: This method can only be called during a write transaction.
- parameter objects: The objects to be deleted. This can be a `List<Object>`, `Results<Object>`,
or any other enumerable SequenceType which generates Object.
*/
public func delete<S: SequenceType where S.Generator.Element: Object>(objects: S) {
for obj in objects {
delete(obj)
}
}
/**
Deletes the given objects from this Realm.
- warning: This method can only be called during a write transaction.
- parameter objects: The objects to be deleted. Must be `List<Object>`.
:nodoc:
*/
public func delete<T: Object>(objects: List<T>) {
rlmRealm.deleteObjects(objects._rlmArray)
}
/**
Deletes the given objects from this Realm.
- warning: This method can only be called during a write transaction.
- parameter objects: The objects to be deleted. Must be `Results<Object>`.
:nodoc:
*/
public func delete<T: Object>(objects: Results<T>) {
rlmRealm.deleteObjects(objects.rlmResults)
}
/**
Deletes all objects from this Realm.
- warning: This method can only be called during a write transaction.
*/
public func deleteAll() {
RLMDeleteAllObjectsFromRealm(rlmRealm)
}
// MARK: Object Retrieval
/**
Returns all objects of the given type in the Realm.
- parameter type: The type of the objects to be returned.
- returns: All objects of the given type in Realm.
*/
public func objects<T: Object>(type: T.Type) -> Results<T> {
// FIXME: use T.className()
return Results<T>(RLMGetObjects(rlmRealm, (type as Object.Type).className(), nil))
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objects(type:)`.
Returns all objects for a given class name in the Realm.
- warning: This method is useful only in specialized circumstances.
- parameter className: The class name of the objects to be returned.
- returns: All objects for the given class name as dynamic objects
:nodoc:
*/
public func dynamicObjects(className: String) -> Results<DynamicObject> {
return Results<DynamicObject>(RLMGetObjects(rlmRealm, className, nil))
}
/**
Get an object with the given primary key.
Returns `nil` if no object exists with the given primary key.
This method requires that `primaryKey()` be overridden on the given subclass.
- see: Object.primaryKey()
- parameter type: The type of the objects to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `type` or `nil` if an object with the given primary key does not exist.
*/
public func objectForPrimaryKey<T: Object>(type: T.Type, key: AnyObject) -> T? {
// FIXME: use T.className()
return unsafeBitCast(RLMGetObject(rlmRealm, (type as Object.Type).className(), key), Optional<T>.self)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objectForPrimaryKey(_:key:)`.
Get a dynamic object with the given class name and primary key.
Returns `nil` if no object exists with the given class name and primary key.
This method requires that `primaryKey()` be overridden on the given subclass.
- see: Object.primaryKey()
- warning: This method is useful only in specialized circumstances.
- parameter className: The class name of the object to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `DynamicObject` or `nil` if an object with the given primary key does not exist.
:nodoc:
*/
public func dynamicObjectForPrimaryKey(className: String, key: AnyObject) -> DynamicObject? {
return unsafeBitCast(RLMGetObject(rlmRealm, className, key), Optional<DynamicObject>.self)
}
// MARK: Notifications
/**
Add a notification handler for changes in this Realm.
- parameter block: A block which is called to process Realm notifications.
It receives the following parameters:
- `Notification`: The incoming notification.
- `Realm`: The realm for which this notification occurred.
- returns: A notification token which can later be passed to `removeNotification(_:)`
to remove this notification.
*/
public func addNotificationBlock(block: NotificationBlock) -> NotificationToken {
return rlmRealm.addNotificationBlock(rlmNotificationBlockFromNotificationBlock(block))
}
/**
Remove a previously registered notification handler using the token returned
from `addNotificationBlock(_:)`
- parameter notificationToken: The token returned from `addNotificationBlock(_:)`
corresponding to the notification block to remove.
*/
public func removeNotification(notificationToken: NotificationToken) {
rlmRealm.removeNotification(notificationToken)
}
// MARK: Autorefresh and Refresh
/**
Whether this Realm automatically updates when changes happen in other threads.
If set to `true` (the default), changes made on other threads will be reflected
in this Realm on the next cycle of the run loop after the changes are
committed. If set to `false`, you must manually call `refresh()` on the Realm to
update it to get the latest version.
Note that on background threads, the run loop is not run by default and you will
will need to manually call `refresh()` in order to update to the latest version,
even if `autorefresh` is set to `true`.
Even with this enabled, you can still call `refresh()` at any time to update the
Realm before the automatic refresh would occur.
Notifications are sent when a write transaction is committed whether or not
this is enabled.
Disabling this on a `Realm` without any strong references to it will not
have any effect, and it will switch back to YES the next time the `Realm`
object is created. This is normally irrelevant as it means that there is
nothing to refresh (as persisted `Object`s, `List`s, and `Results` have strong
references to the containing `Realm`), but it means that setting
`Realm().autorefresh = false` in
`application(_:didFinishLaunchingWithOptions:)` and only later storing Realm
objects will not work.
Defaults to true.
*/
public var autorefresh: Bool {
get {
return rlmRealm.autorefresh
}
set {
rlmRealm.autorefresh = newValue
}
}
/**
Update a `Realm` and outstanding objects to point to the most recent
data for this `Realm`.
- returns: Whether the realm had any updates.
Note that this may return true even if no data has actually changed.
*/
public func refresh() -> Bool {
return rlmRealm.refresh()
}
// MARK: Invalidation
/**
Invalidate all `Object`s and `Results` read from this Realm.
A Realm holds a read lock on the version of the data accessed by it, so
that changes made to the Realm on different threads do not modify or delete the
data seen by this Realm. Calling this method releases the read lock,
allowing the space used on disk to be reused by later write transactions rather
than growing the file. This method should be called before performing long
blocking operations on a background thread on which you previously read data
from the Realm which you no longer need.
All `Object`, `Results` and `List` instances obtained from this
`Realm` on the current thread are invalidated, and can not longer be used.
The `Realm` itself remains valid, and a new read transaction is implicitly
begun the next time data is read from the Realm.
Calling this method multiple times in a row without reading any data from the
Realm, or before ever reading any data from the Realm is a no-op. This method
cannot be called on a read-only Realm.
*/
public func invalidate() {
rlmRealm.invalidate()
}
// MARK: Writing a Copy
/**
Write an encrypted and compacted copy of the Realm to the given path.
The destination file cannot already exist.
Note that if this is called from within a write transaction it writes the
*current* data, and not data when the last write transaction was committed.
- parameter path: Path to save the Realm to.
- parameter encryptionKey: Optional 64-byte encryption key to encrypt the new file with.
*/
public func writeCopyToPath(path: String, encryptionKey: NSData? = nil) throws {
if let encryptionKey = encryptionKey {
try rlmRealm.writeCopyToPath(path, encryptionKey: encryptionKey)
} else {
try rlmRealm.writeCopyToPath(path)
}
}
// MARK: Internal
internal var rlmRealm: RLMRealm
internal init(_ rlmRealm: RLMRealm) {
self.rlmRealm = rlmRealm
}
}
// MARK: Equatable
extension Realm: Equatable { }
/// Returns whether the two realms are equal.
public func ==(lhs: Realm, rhs: Realm) -> Bool {
return lhs.rlmRealm == rhs.rlmRealm
}
// MARK: Notifications
/// A notification due to changes to a realm.
public enum Notification: String {
/**
Posted when the data in a realm has changed.
DidChange is posted after a realm has been refreshed to reflect a write transaction, i.e. when
an autorefresh occurs, `refresh()` is called, after an implicit refresh from
`write(_:)`/`beginWrite()`, and after a local write transaction is committed.
*/
case DidChange = "RLMRealmDidChangeNotification"
/**
Posted when a write transaction has been committed to a Realm on a different thread for the same
file. This is not posted if `autorefresh` is enabled or if the Realm is refreshed before the
notification has a chance to run.
Realms with autorefresh disabled should normally have a handler for this notification which
calls `refresh()` after doing some work.
While not refreshing is allowed, it may lead to large Realm files as Realm has to keep an extra
copy of the data for the un-refreshed Realm.
*/
case RefreshRequired = "RLMRealmRefreshRequiredNotification"
}
/// Closure to run when the data in a Realm was modified.
public typealias NotificationBlock = (notification: Notification, realm: Realm) -> Void
internal func rlmNotificationBlockFromNotificationBlock(notificationBlock: NotificationBlock) -> RLMNotificationBlock {
return { rlmNotification, rlmRealm in
return notificationBlock(notification: Notification(rawValue: rlmNotification)!, realm: Realm(rlmRealm))
}
}
|
apache-2.0
|
a7b6dd4f99f9a599896de807fe59220c
| 38.364379 | 120 | 0.694907 | 4.914525 | false | false | false | false |
IvanVorobei/RateApp
|
SPRateApp - project/SPRateApp/sparrow/ui/views/views/SPShadowWithMaskView.swift
|
1
|
6388
|
// The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class SPShadowWithMaskView<ContentView: UIView>: UIView {
public let contentView: ContentView = ContentView()
public init() {
super.init(frame: CGRect.zero)
commonInit()
}
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.contentView.layer.masksToBounds = true
self.layer.masksToBounds = false
self.contentView.layer.masksToBounds = true
self.backgroundColor = UIColor.clear
self.addSubview(contentView)
self.updateShadow()
}
public override func layoutSubviews() {
super.layoutSubviews()
self.contentView.frame = self.bounds
self.layer.cornerRadius = self.contentView.layer.cornerRadius
}
public override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
self.updateShadow()
}
private var xTranslationFactor: CGFloat = 0
private var yTranslationFactor: CGFloat = 0
private var widthRelativeFactor: CGFloat = 0
private var heightRelativeFactor: CGFloat = 0
private var blurRadiusFactor: CGFloat = 0
private var shadowOpacity: CGFloat = 0
public override func setShadow(xTranslationFactor: CGFloat, yTranslationFactor: CGFloat, widthRelativeFactor: CGFloat, heightRelativeFactor: CGFloat, blurRadiusFactor: CGFloat, shadowOpacity: CGFloat, cornerRadiusFactor: CGFloat = 0) {
super.setShadow(xTranslationFactor: xTranslationFactor, yTranslationFactor: yTranslationFactor, widthRelativeFactor: widthRelativeFactor, heightRelativeFactor: heightRelativeFactor, blurRadiusFactor: blurRadiusFactor, shadowOpacity: shadowOpacity, cornerRadiusFactor: cornerRadiusFactor)
self.xTranslationFactor = xTranslationFactor
self.yTranslationFactor = yTranslationFactor
self.widthRelativeFactor = widthRelativeFactor
self.heightRelativeFactor = heightRelativeFactor
self.blurRadiusFactor = blurRadiusFactor
self.shadowOpacity = shadowOpacity
}
private func updateShadow() {
self.setShadow(
xTranslationFactor: self.xTranslationFactor,
yTranslationFactor: self.yTranslationFactor,
widthRelativeFactor: self.widthRelativeFactor,
heightRelativeFactor: self.heightRelativeFactor,
blurRadiusFactor: self.blurRadiusFactor,
shadowOpacity: self.shadowOpacity
)
}
}
public class SPShadowWithMaskControl: UIControl {
public let contentView: UIView = UIView()
public init() {
super.init(frame: CGRect.zero)
commonInit()
}
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.contentView.layer.masksToBounds = true
self.layer.masksToBounds = false
self.backgroundColor = UIColor.clear
self.addSubview(contentView)
self.updateShadow()
}
public override func layoutSubviews() {
super.layoutSubviews()
self.contentView.frame = self.bounds
self.layer.cornerRadius = self.contentView.layer.cornerRadius
}
public override func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
self.updateShadow()
}
private var xTranslationFactor: CGFloat = 0
private var yTranslationFactor: CGFloat = 0
private var widthRelativeFactor: CGFloat = 0
private var heightRelativeFactor: CGFloat = 0
private var blurRadiusFactor: CGFloat = 0
private var shadowOpacity: CGFloat = 0
public override func setShadow(xTranslationFactor: CGFloat, yTranslationFactor: CGFloat, widthRelativeFactor: CGFloat, heightRelativeFactor: CGFloat, blurRadiusFactor: CGFloat, shadowOpacity: CGFloat, cornerRadiusFactor: CGFloat = 0) {
super.setShadow(xTranslationFactor: xTranslationFactor, yTranslationFactor: yTranslationFactor, widthRelativeFactor: widthRelativeFactor, heightRelativeFactor: heightRelativeFactor, blurRadiusFactor: blurRadiusFactor, shadowOpacity: shadowOpacity, cornerRadiusFactor: cornerRadiusFactor)
self.xTranslationFactor = xTranslationFactor
self.yTranslationFactor = yTranslationFactor
self.widthRelativeFactor = widthRelativeFactor
self.heightRelativeFactor = heightRelativeFactor
self.blurRadiusFactor = blurRadiusFactor
self.shadowOpacity = shadowOpacity
}
private func updateShadow() {
self.setShadow(
xTranslationFactor: self.xTranslationFactor,
yTranslationFactor: self.yTranslationFactor,
widthRelativeFactor: self.widthRelativeFactor,
heightRelativeFactor: self.heightRelativeFactor,
blurRadiusFactor: self.blurRadiusFactor,
shadowOpacity: self.shadowOpacity
)
}
}
|
mit
|
d7e2e8878d384fbc10542bfb9caf4efc
| 39.681529 | 295 | 0.711915 | 5.077107 | false | false | false | false |
Chaosspeeder/YourGoals
|
YourGoals/Business/WatchConnectivity/WatchTasksContextProvider.swift
|
1
|
1688
|
//
// WatchTasksContextProvider.swift
// YourGoals
//
// Created by André Claaßen on 24.05.18.
// Copyright © 2018 André Claaßen. All rights reserved.
//
import Foundation
class WatchTasksContextProvider:StorageManagerWorker {
let committedTasksDataSource:CommittedTasksDataSource!
let activeTasksDataSource:ActiveTasksDataSource!
override init(manager: GoalsStorageManager) {
self.committedTasksDataSource = CommittedTasksDataSource(manager: manager, mode: .activeTasksNotIncluded)
self.activeTasksDataSource = ActiveTasksDataSource(manager: manager)
super.init(manager: manager)
}
/// retrieve the tasks for today in a representation format processable for the watch extneion
///
/// - Parameters:
/// - date: for this date
/// - backburnedGoals: true, if backburnedGoals: tasks should be included
/// - Returns: a colleciton of watch task infos
/// - Throws: core data exception
func todayTasks(referenceDate date: Date, withBackburned backburnedGoals: Bool) throws -> [WatchTaskInfo] {
let activeTasks = try activeTasksDataSource.fetchItems(forDate: date, withBackburned: backburnedGoals, andSection: nil)
let todayTasks = try committedTasksDataSource.fetchItems(forDate: date, withBackburned: backburnedGoals, andSection: nil)
let allTasks = activeTasks + todayTasks
let watchTasks = allTasks.map { item -> WatchTaskInfo in
let task = item.actionable as! Task
let watchTaskInfo = WatchTaskInfo(task: task, date: Date())
return watchTaskInfo
}
return watchTasks
}
}
|
lgpl-3.0
|
2569a1d85d64cd9b0879a4625732311a
| 37.25 | 129 | 0.697564 | 4.636364 | false | false | false | false |
NorthernRealities/Rainbow-Creator
|
Rainbow-Creator.swift
|
1
|
7052
|
//
// Rainbow-Creator.swift
// Rainbow Creator UIColor & NSColor Extension
//
// Created by Reid Gravelle on 2015-03-18.
// Copyright (c) 2015 Northern Realities Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
#if os(iOS)
import UIKit
public typealias Color = UIColor
#else
import AppKit
public typealias Color = NSColor
#endif
extension Color {
/**
Returns a color object representing the color with the given RGB component values and has the specified opacity.
- parameter redValue: The red component of the color object, specified as a value between 0 and 255.
- parameter greenValue: The green component of the color object, specified as a value between 0 and 255.
- parameter blueValue: The blue component of the color object, specified as a value between 0 and 255.
- parameter alphaValue: A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
- returns: The color object
*/
convenience init ( redValue: Int, greenValue: Int, blueValue: Int, alphaValue: CGFloat = 1.0 ) {
let redFloat = CGFloat ( redValue ) / 255.0
let greenFloat = CGFloat ( greenValue ) / 255.0
let blueFloat = CGFloat ( blueValue ) / 255.0
self.init ( red: redFloat, green: greenFloat, blue: blueFloat, alpha: alphaValue )
}
/**
Returns a color object representing the color with the given RGB component values with an opacity (alpha) of 1.0. Values below 0 will be treated as 0 and values above 1 will be treated as 1.
- parameter red: The red component of the color, specified between 0 and 1.
- parameter green: The green component of the color, specified between 0 and 1.
- parameter blue: The blue component of the color, specified between 0 and 1.
- returns: The color object.
*/
convenience init ( red: CGFloat, green: CGFloat, blue: CGFloat ) {
self.init ( red: red, green: green, blue: blue, alpha: 1.0 )
}
/**
Returns a color object representing the color with the given RGB value passed in as a hexadecimal integer and has the specified opacity.
- parameter hex: The red, green, and blue components that compromise the color combined into a single hexadecimal number. Each component has two digits which range from 0 through to f.
- parameter alphaValue: A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
- returns: The color object
*/
convenience init ( hex : Int, alpha : CGFloat = 1.0 ) {
let red = ( hex >> 16 ) & 0xff
let green = ( hex >> 08 ) & 0xff
let blue = hex & 0xff
self.init ( redValue: red, greenValue: green, blueValue: blue, alphaValue: alpha )
}
/**
Returns a color object representing the color with the given RGB value passed in as a hexadecimal integer and has the specified opacity.
- parameter hex: The red, green, and blue components that compromise the color combined into a single hexadecimal string. Each component has two characters which range from 0 through to f. The string may be optionally prefixed with a '#' sign.
- parameter alphaValue: A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
- returns: The color object
*/
convenience init ( hexString : String, alpha : CGFloat = 1.0 ) {
var hexIntValue : UInt32 = 0x000000
let stringSize = hexString.characters.count
if ( ( stringSize == 6 ) || ( stringSize == 7 ) ) {
let range = NSMakeRange( 0, stringSize )
let pattern = "#?[0-9A-F]{6}"
do {
let regex = try NSRegularExpression ( pattern: pattern, options: .CaseInsensitive)
let matchRange = regex.rangeOfFirstMatchInString( hexString, options: .ReportProgress, range: range )
if matchRange.location != NSNotFound {
var workingString = hexString
if ( stringSize == 7 ) {
workingString = workingString.substringFromIndex( workingString.startIndex.advancedBy(1 ) )
}
NSScanner ( string: workingString ).scanHexInt ( &hexIntValue )
}
} catch let error as NSError {
print ( "Error creating regular expression to check validity of hex string \"\(hexString)\" - \(error.localizedDescription)" )
}
}
self.init ( hex: Int( hexIntValue ), alpha: alpha )
}
/**
Returns a color object representing the color with the given HSB component values and has the specified opacity. No error checking is performed to ensure that numbers are within the expected bounds. If a number is below the expected value it is treated as the expected value. The same applies for the upper bound.
- parameter hueDegrees: The hue component of the color object, specified as the number of degrees between 0 and 359.
- parameter saturationPercent: The saturation component of the color object, specified as a percentage value between 0 and 100.
- parameter brightnessPercent: The brightness component of the color object, specified as a percentage value between 0 and 100.
- parameter alphaValue: A CGFloat between 0.0 and 1.0 representing the opacity with a default value of 1.0.
- returns: The color object
*/
convenience init ( hueDegrees: Int, saturationPercent: Int, brightnessPercent: Int, alpha: CGFloat = 1.0 ) {
self.init ( calibratedHue: CGFloat ( Double ( hueDegrees ) / 360.0 ), saturation: CGFloat ( Double ( saturationPercent ) / 100.0 ), brightness: CGFloat ( Double ( brightnessPercent ) / 100.0 ), alpha: alpha )
}
}
|
mit
|
54c87fd62e82eec56d29ecff69af185f
| 44.496774 | 320 | 0.664067 | 4.752022 | false | false | false | false |
tomoponzoo/TagsView
|
Classes/LayoutEngine.swift
|
1
|
9802
|
//
// TagsViewLayoutEngine.swift
// TagsView
//
// Created by Tomoki Koga on 2017/09/25.
// Copyright © 2017年 tomoponzoo. All rights reserved.
//
import Foundation
class LayoutEngine {
let tagsView: TagsView
let preferredMaxLayoutWidth: CGFloat
init(tagsView: TagsView, preferredMaxLayoutWidth: CGFloat) {
self.tagsView = tagsView
self.preferredMaxLayoutWidth = preferredMaxLayoutWidth
}
func layout() -> Layout {
let rowsLayout = RowsLayout(tagsView: tagsView, preferredMaxLayoutWidth: preferredMaxLayoutWidth)
rowsLayout.layout()
return Layout(layout: rowsLayout)
}
}
class RowsLayout {
let tagsView: TagsView
let preferredMaxLayoutWidth: CGFloat
var layouts = [ColumnsLayout]()
var size: CGSize {
guard let layout = layouts.last else { return .zero }
return CGSize(width: layout.frame.width + tagsView.padding.left + tagsView.padding.right, height: layout.frame.maxY + tagsView.padding.top + tagsView.padding.bottom)
}
var columns: [CGRect] {
return layouts.flatMap { $0.alignedColumns(self.tagsView.layoutProperties.alignment) }
}
var supplementaryColumn: CGRect? {
return tailLayout?.alignedSupplementaryColumn(tagsView.layoutProperties.alignment)
}
var tailLayout: ColumnsLayout? {
if let layout = layouts.filter({ $0.isLimited }).first {
return layout
} else {
return layouts.last
}
}
init(tagsView: TagsView, preferredMaxLayoutWidth: CGFloat) {
self.tagsView = tagsView
self.preferredMaxLayoutWidth = preferredMaxLayoutWidth - tagsView.padding.left - tagsView.padding.right
}
func layout() {
let tagViews = (0..<tagsView.layoutProperties.numberOfTags).flatMap { (index) -> TagView? in
return tagsView.tagViews[index]
}
let tagViewSizes = tagViews.map { $0.intrinsicContentSize }
let supplementaryTagView = tagsView.supplementaryTagView
let supplementaryTagViewSize = supplementaryTagView?.intrinsicContentSize
let h = tagViewSizes.reduce(supplementaryTagViewSize?.height ?? 0) { max($0, $1.height) }
let frame = CGRect(x: 0, y: 0, width: preferredMaxLayoutWidth, height: h)
let layout = ColumnsLayout(tagsView: tagsView, frame: frame, index: 0)
_ = tagViewSizes.reduce(layout) { (layout, size) -> ColumnsLayout in
return layout.push(size: size)
}
layouts = [ColumnsLayout](layout)
tailLayout?.set(wishSupplementaryTagViewSize: supplementaryTagViewSize)
}
}
class ColumnsLayout {
let tagsView: TagsView
let frame: CGRect
let index: Int
var columns = [CGRect]()
var supplementaryColumn: CGRect?
var x: CGFloat
var nextLayout: ColumnsLayout?
var spacer: Spacer {
return tagsView.layoutProperties.spacer
}
var endIndex: Int? {
if case let .rows(num) = tagsView.layoutProperties.numberOfRows {
return num - 1
} else {
return nil
}
}
var isLimited: Bool {
guard let endIndex = endIndex else { return false }
return index == endIndex
}
var isOutOfLimited: Bool {
guard let endIndex = endIndex else { return false }
return index > endIndex
}
init(tagsView: TagsView, frame: CGRect, index: Int) {
self.tagsView = tagsView
self.frame = frame
self.index = index
self.x = frame.minX
}
func push(size: CGSize) -> ColumnsLayout {
if columns.isEmpty {
// 要素なし
if size.width <= frame.width {
// 収まる
columns.append(CGRect(x: x, y: frame.minY, width: size.width, height: frame.height))
x += size.width
return self
} else {
// 収まらない (タグサイズをフレーム幅にリサイズ)
columns.append(CGRect(x: x, y: frame.minY, width: frame.width, height: frame.height))
let nextFrame = CGRect(x: frame.minX, y: frame.maxY + spacer.vertical, width: frame.width, height: frame.height)
let nextLayout = ColumnsLayout(tagsView: tagsView, frame: nextFrame, index: index + 1)
self.nextLayout = nextLayout
return nextLayout
}
} else {
// 要素あり
if x + size.width <= frame.width {
// 収まる
x += spacer.horizontal
columns.append(CGRect(x: x, y: frame.minY, width: size.width, height: frame.height))
x += size.width
return self
} else {
// 収まらない (次の行にタグを配置する)
let nextFrame = CGRect(x: frame.minX, y: frame.maxY + spacer.vertical, width: frame.width, height: frame.height)
let nextLayout = ColumnsLayout(tagsView: tagsView, frame: nextFrame, index: index + 1)
self.nextLayout = nextLayout
return nextLayout.push(size: size)
}
}
}
func pop() -> CGRect? {
guard let column = columns.popLast() else { return nil }
x -= column.width
if !columns.isEmpty {
x -= spacer.horizontal
}
return column
}
func set(wishSupplementaryTagViewSize size: CGSize?) {
guard let size = size else { return }
let isVisible = tagsView.dataSource?.isVisibleSupplementaryTagView(
in: tagsView,
rows: tagsView.numberOfRows,
row: index,
hasNextRow: nextLayout != nil
) ?? false
var column: CGRect?
while (x + spacer.horizontal + size.width > frame.width) && isVisible {
column = pop()
}
if let _ = column, columns.isEmpty {
let newFrame = CGRect(x: frame.minX, y: frame.minY, width: frame.width - spacer.horizontal - size.width, height: frame.height)
columns.append(newFrame)
x += newFrame.width
}
if isVisible {
x += spacer.horizontal
x += size.width
supplementaryColumn = CGRect(x: x - size.width, y: frame.minY, width: size.width, height: frame.height)
}
}
func alignedColumns(_ alignment: Alignment) -> [CGRect] {
guard let tailColumn = columns.last, alignment != .left else {
return columns.map {
CGRect(
x: $0.minX + tagsView.padding.left,
y: $0.minY + tagsView.padding.top,
width: $0.width,
height: $0.height
)
}
}
let offset: CGFloat
let div: CGFloat = alignment == .center ? 2.0 : 1.0
if let supplementaryColumn = supplementaryColumn {
offset = (frame.width - supplementaryColumn.maxX) / div
} else {
offset = (frame.width - tailColumn.maxX) / div
}
return columns.map {
CGRect(
x: $0.minX + offset + tagsView.padding.left,
y: $0.minY + tagsView.padding.top,
width: $0.width,
height: $0.height
)
}
}
func alignedSupplementaryColumn(_ alignment: Alignment) -> CGRect? {
guard let supplementaryColumn = supplementaryColumn, alignment != .left else {
return self.supplementaryColumn.map {
CGRect(
x: $0.minX + tagsView.padding.left,
y: $0.minY + tagsView.padding.top,
width: $0.width,
height: $0.height
)
}
}
let div: CGFloat = alignment == .center ? 2.0 : 1.0
let offset = (frame.width - supplementaryColumn.maxX) / div
return CGRect(
x: supplementaryColumn.minX + offset + tagsView.padding.left,
y: supplementaryColumn.minY + tagsView.padding.top,
width: supplementaryColumn.width,
height: supplementaryColumn.height
)
}
}
extension ColumnsLayout: Sequence {
func makeIterator() -> ColumnsLayoutIterator {
return ColumnsLayoutIterator(self)
}
}
struct ColumnsLayoutIterator: IteratorProtocol {
typealias Element = ColumnsLayout
var currentLayout: ColumnsLayout?
init(_ layout: ColumnsLayout) {
self.currentLayout = layout
}
mutating func next() -> ColumnsLayout? {
guard let currentLayout = currentLayout else { return nil }
if let nextLayout = currentLayout.nextLayout, !nextLayout.isOutOfLimited {
self.currentLayout = currentLayout.nextLayout
} else {
self.currentLayout = nil
}
return currentLayout
}
}
struct LayoutProperties {
let numberOfTags: Int
let numberOfRows: Rows
let alignment: Alignment
let padding: UIEdgeInsets
let spacer: Spacer
init(numberOfTags: Int = 0, numberOfRows: Rows = .infinite, alignment: Alignment = .left, padding: UIEdgeInsets = .zero, spacer: Spacer = .zero) {
self.numberOfTags = numberOfTags
self.numberOfRows = numberOfRows
self.alignment = alignment
self.padding = padding
self.spacer = spacer
}
}
|
mit
|
bf468c6c6f4dd3f7748e15458f858b08
| 31.215947 | 173 | 0.565639 | 4.718735 | false | false | false | false |
naoyashiga/AkutagawaPrize
|
AkutagawaPrize/Color.swift
|
1
|
1921
|
//
// Color.swift
// AkutagawaPrize
//
// Created by naoyashiga on 2015/08/31.
// Copyright (c) 2015年 naoyashiga. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
class func hexStr (var hexStr : NSString, alpha : CGFloat) -> UIColor {
hexStr = hexStr.stringByReplacingOccurrencesOfString("#", withString: "")
let scanner = NSScanner(string: hexStr as String)
var color: UInt32 = 0
if scanner.scanHexInt(&color) {
let r = CGFloat((color & 0xFF0000) >> 16) / 255.0
let g = CGFloat((color & 0x00FF00) >> 8) / 255.0
let b = CGFloat(color & 0x0000FF) / 255.0
return UIColor(red:r,green:g,blue:b,alpha:alpha)
} else {
print("invalid hex string", terminator: "")
return UIColor.whiteColor();
}
}
class func viewBackgroundColor() -> UIColor {
return UIColor.hexStr("e5e5e5", alpha: 1)
}
class func navigationBarTintColor() -> UIColor {
return UIColor.hexStr("ffa633", alpha: 1)
}
class func cellLightBackgroundColor() -> UIColor {
return UIColor.hexStr("ffffff", alpha: 1)
}
class func cellSelectedBackgroundColor() -> UIColor {
return UIColor.hexStr("AAD9D1", alpha: 0.6)
}
//MARK: Tab Color
class func scrollMenuBackgroundColor() -> UIColor {
return UIColor.hexStr("AAD9D1", alpha: 1)
}
class func selectionIndicatorColor() -> UIColor {
return UIColor.hexStr("72505E", alpha: 1)
}
class func bottomMenuHairlineColor() -> UIColor {
return UIColor.hexStr("efefef", alpha: 1)
}
class func selectedMenuItemLabelColor() -> UIColor {
return UIColor.hexStr("72505E", alpha: 1)
}
class func unselectedMenuItemLabelColor() -> UIColor {
return UIColor.hexStr("efefef", alpha: 1)
}
}
|
mit
|
4b5f0b10c2366ff7134afcd30309c33a
| 29 | 81 | 0.605003 | 4.236203 | false | false | false | false |
fqhuy/minimind
|
minimind/covariance/rbf.swift
|
1
|
6872
|
//
// rbf.swift
// minimind
//
// Created by Phan Quoc Huy on 5/31/17.
// Copyright © 2017 Phan Quoc Huy. All rights reserved.
//
import Foundation
import Surge
public class RBF: Kernel {
public typealias ScalarT = Float
public typealias MatrixT = Matrix<ScalarT>
public var parametersData: [ScalarT]
public var trainables: [String] = []
public var lockedParams: [String] = []
public var parametersIds: [String:[IndexType]]
public var nFeatures: Int
public var nDataPoints: Int
public var XUpdateMask: [Bool] = []
public var X: MatrixT {
get {
return MatrixT(nDataPoints, nFeatures, parametersData[parametersIds["X"]!])
}
set(val) {
parametersData[parametersIds["X"]!] = val.grid
}
}
public var variance: ScalarT {
get {
return exp(logVariance)
// return log(1 + exp(logVariance))
}
set(val) {
logVariance = exp(val)
// logVariance = log(exp(val) - 1)
}
}
public var lengthscale: ScalarT {
get {
return exp(logLengthscale)
// return log(1 + exp(logLengthscale))
}
set(val) {
logLengthscale = exp(val)
// logLengthscale = log(exp(val) - 1)
}
}
public var logVariance: ScalarT {
get {
return parametersData[parametersIds["logVariance"]!][0]
}
set(val) {
parametersData[parametersIds["logVariance"]!] = [val]
}
}
public var logLengthscale: ScalarT {
get {
return parametersData[parametersIds["logLengthscale"]!][0]
}
set(val) {
parametersData[parametersIds["logLengthscale"]!] = [val]
}
}
public var logPrior: ScalarT {
get {
return 0.5 * ( pow(logVariance, 2.0) + pow(logLengthscale, 2.0) )
}
}
public var nDims: Int {
get {
return trainableIds.count
}
}
required public init() {
nFeatures = 0
nDataPoints = 0
parametersData = zeros(2)
parametersIds = ["logVariance": [0], "logLengthscale": [1], "X": []]
variance = 100.0
lengthscale = 100.0
X = MatrixT()
}
public convenience init(variance: ScalarT, lengthscale: ScalarT, X: MatrixT, trainables: [String] = ["logVariance"], capacity: Int = 10000) {
self.init()
self.trainables = trainables
(nDataPoints, nFeatures) = X.shape
parametersData = []
parametersData.reserveCapacity(capacity)
parametersIds["logVariance"] = [parametersData.count]
parametersData.append(log(variance))
parametersIds["logLengthscale"] = [parametersData.count]
parametersData.append(log(lengthscale))
parametersIds["X"] = arange(parametersData.count, parametersData.count + X.size, 1)
parametersData.append(contentsOf: X.grid)
self.X = X
}
public func initParams() -> MatrixT {
var params: [Float] = []
for t in trainableIds {
params.append(parametersData[t])
}
return MatrixT([params])
}
public func K(_ X: MatrixT,_ Y: MatrixT) -> MatrixT {
let dist = scaledDist(X, Y)
let Kxx = K(r: dist)
return Kxx
}
public func K(r: MatrixT) -> MatrixT {
return variance * exp((-0.5 * (r ** 2.0)))
}
func dKdr(r: MatrixT) -> MatrixT {
return -r ∘ K(r: r)
}
public func gradientX(_ X: MatrixT, _ Y: MatrixT, _ dLdK: MatrixT) -> MatrixT {
let r = scaledDist(X, Y)
let (N, D) = X.shape
let dLdr = dKdr(r: r) ∘ dLdK
var tmp = dLdr ∘ invDist(r)
// TODO: detect X == Y here, should use Y: MatrixT? in the future
if X.rows == Y.rows {
if all(diag(r) == 0) {
tmp = tmp + tmp.t
}
}
// tmp = tmp + tmp.t
var grad: MatrixT = zeros(N ,D)
for i in 0..<D {
grad[forall, i] = reduce_sum(tmp ∘ cross_add(X[forall, i], -Y[forall, i]), axis: 1)
}
grad = grad / (lengthscale * lengthscale)
return grad
}
public func gradient(_ X: MatrixT, _ Y: MatrixT, _ dLdK: MatrixT) -> MatrixT {
// let (N, D) = X.shape
var dGrid: [ScalarT] = []
let r = scaledDist(X, Y)
let Kr = K(r: r)
let dLdr = dKdr(r: r) ∘ dLdK
// variance
if trainables.contains("logVariance") {
dGrid.append((reduce_sum(Kr ∘ dLdK))[0, 0] / variance + logVariance )
}
// lengthscale
if trainables.contains("logLengthscale") {
// dGrid.append(-(reduce_sum((dLdK ∘ Kr) ∘ (r ∘ r) ))[0,0] / lengthscale) // 0.5 *
dGrid.append(-reduce_sum(dLdr ∘ r)[0,0] / lengthscale + logLengthscale )
}
// gradient wrt X
if trainables.contains("X") {
let xGrad = gradientX(X, Y, dLdK)
dGrid.append(contentsOf: xGrad.grid)
// var tmp = dLdr ∘ invDist(r)
// tmp = tmp + tmp.t
// var grad: MatrixT = zeros(N ,D)
// for i in 0..<D {
// grad[forall, i] = reduce_sum(tmp ∘ cross_add(X[forall, i], -Y[forall, i]), 1)
// }
//
// grad = grad / (lengthscale * lengthscale)
// dGrid.append(contentsOf: grad.grid)
}
return MatrixT([dGrid])
}
public func dist(_ X: MatrixT, _ Y: MatrixT) -> MatrixT {
let xx = reduce_sum(X ∘ X, axis: 1)
let yy = reduce_sum(Y ∘ Y, axis: 1)
var dist = cross_add(xx, yy) - 2.0 * (X * Y′)
if X.rows == Y.rows {
// detects X == Y, should use Y: MatrixT? instead
if diag(dist).sum() < 1e-4 {
for r in 0..<dist.rows {
dist[r, r] = 0.0
}
}
}
dist = clip(dist, 0.0, 1e10)
return sqrt(dist)
}
public func scaledDist(_ X: MatrixT, _ Y: MatrixT) -> MatrixT {
return dist(X, Y) / lengthscale
}
private func invDist(_ X: MatrixT, _ Y: MatrixT) -> MatrixT {
let dist = scaledDist(X, Y)
return invDist(dist)
}
private func invDist(_ r: MatrixT) -> MatrixT {
var dist = r
for r in 0..<dist.rows {
for c in 0..<dist.columns {
if dist[r, c] == 0 {
dist[r, c] = 0
}
else {
dist[r, c] = 1.0 / dist[r, c]
}
}
}
return dist
}
}
|
mit
|
1f006e9f6d57c66ae69116c37b88ac2e
| 27.864979 | 145 | 0.496565 | 3.666131 | false | false | false | false |
xedin/swift
|
stdlib/public/core/SetVariant.swift
|
7
|
10152
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// This protocol is only used for compile-time checks that
/// every buffer type implements all required operations.
internal protocol _SetBuffer {
associatedtype Element
associatedtype Index
var startIndex: Index { get }
var endIndex: Index { get }
func index(after i: Index) -> Index
func index(for element: Element) -> Index?
var count: Int { get }
func contains(_ member: Element) -> Bool
func element(at i: Index) -> Element
}
extension Set {
@usableFromInline
@frozen
internal struct _Variant {
@usableFromInline
internal var object: _BridgeStorage<__RawSetStorage>
@inlinable
@inline(__always)
init(dummy: ()) {
#if arch(i386) || arch(arm)
self.init(native: _NativeSet())
#else
self.object = _BridgeStorage(taggedPayload: 0)
#endif
}
@inlinable
@inline(__always)
init(native: __owned _NativeSet<Element>) {
self.object = _BridgeStorage(native: native._storage)
}
#if _runtime(_ObjC)
@inlinable
@inline(__always)
init(cocoa: __owned __CocoaSet) {
self.object = _BridgeStorage(objC: cocoa.object)
}
#endif
}
}
extension Set._Variant {
#if _runtime(_ObjC)
@usableFromInline
@_transparent
internal var guaranteedNative: Bool {
return _canBeClass(Element.self) == 0
}
#endif
@inlinable
internal mutating func isUniquelyReferenced() -> Bool {
return object.isUniquelyReferencedUnflaggedNative()
}
#if _runtime(_ObjC)
@usableFromInline @_transparent
internal var isNative: Bool {
if guaranteedNative { return true }
return object.isUnflaggedNative
}
#endif
@usableFromInline @_transparent
internal var asNative: _NativeSet<Element> {
get {
return _NativeSet(object.unflaggedNativeInstance)
}
set {
self = .init(native: newValue)
}
_modify {
var native = _NativeSet<Element>(object.unflaggedNativeInstance)
self = .init(dummy: ())
defer {
// This is in a defer block because yield might throw, and we need to
// preserve Set's storage invariants when that happens.
object = .init(native: native._storage)
}
yield &native
}
}
#if _runtime(_ObjC)
@inlinable
internal var asCocoa: __CocoaSet {
return __CocoaSet(object.objCInstance)
}
#endif
/// Reserves enough space for the specified number of elements to be stored
/// without reallocating additional storage.
internal mutating func reserveCapacity(_ capacity: Int) {
#if _runtime(_ObjC)
guard isNative else {
let cocoa = asCocoa
let capacity = Swift.max(cocoa.count, capacity)
self = .init(native: _NativeSet(cocoa, capacity: capacity))
return
}
#endif
let isUnique = isUniquelyReferenced()
asNative.reserveCapacity(capacity, isUnique: isUnique)
}
/// The number of elements that can be stored without expanding the current
/// storage.
///
/// For bridged storage, this is equal to the current count of the
/// collection, since any addition will trigger a copy of the elements into
/// newly allocated storage. For native storage, this is the element count
/// at which adding any more elements will exceed the load factor.
@inlinable
internal var capacity: Int {
#if _runtime(_ObjC)
guard isNative else {
return asCocoa.count
}
#endif
return asNative.capacity
}
}
extension Set._Variant: _SetBuffer {
@usableFromInline
internal typealias Index = Set<Element>.Index
@inlinable
internal var startIndex: Index {
#if _runtime(_ObjC)
guard isNative else {
return Index(_cocoa: asCocoa.startIndex)
}
#endif
return asNative.startIndex
}
@inlinable
internal var endIndex: Index {
#if _runtime(_ObjC)
guard isNative else {
return Index(_cocoa: asCocoa.endIndex)
}
#endif
return asNative.endIndex
}
@inlinable
internal func index(after index: Index) -> Index {
#if _runtime(_ObjC)
guard isNative else {
return Index(_cocoa: asCocoa.index(after: index._asCocoa))
}
#endif
return asNative.index(after: index)
}
@inlinable
internal func formIndex(after index: inout Index) {
#if _runtime(_ObjC)
guard isNative else {
let isUnique = index._isUniquelyReferenced()
asCocoa.formIndex(after: &index._asCocoa, isUnique: isUnique)
return
}
#endif
index = asNative.index(after: index)
}
@inlinable
@inline(__always)
internal func index(for element: Element) -> Index? {
#if _runtime(_ObjC)
guard isNative else {
let cocoaElement = _bridgeAnythingToObjectiveC(element)
guard let index = asCocoa.index(for: cocoaElement) else { return nil }
return Index(_cocoa: index)
}
#endif
return asNative.index(for: element)
}
@inlinable
internal var count: Int {
@inline(__always)
get {
#if _runtime(_ObjC)
guard isNative else {
return asCocoa.count
}
#endif
return asNative.count
}
}
@inlinable
@inline(__always)
internal func contains(_ member: Element) -> Bool {
#if _runtime(_ObjC)
guard isNative else {
return asCocoa.contains(_bridgeAnythingToObjectiveC(member))
}
#endif
return asNative.contains(member)
}
@inlinable
@inline(__always)
internal func element(at index: Index) -> Element {
#if _runtime(_ObjC)
guard isNative else {
let cocoaMember = asCocoa.element(at: index._asCocoa)
return _forceBridgeFromObjectiveC(cocoaMember, Element.self)
}
#endif
return asNative.element(at: index)
}
}
extension Set._Variant {
@inlinable
internal mutating func update(with value: __owned Element) -> Element? {
#if _runtime(_ObjC)
guard isNative else {
// Make sure we have space for an extra element.
var native = _NativeSet<Element>(asCocoa, capacity: asCocoa.count + 1)
let old = native.update(with: value, isUnique: true)
self = .init(native: native)
return old
}
#endif
let isUnique = self.isUniquelyReferenced()
return asNative.update(with: value, isUnique: isUnique)
}
@inlinable
internal mutating func insert(
_ element: __owned Element
) -> (inserted: Bool, memberAfterInsert: Element) {
#if _runtime(_ObjC)
guard isNative else {
// Make sure we have space for an extra element.
let cocoaMember = _bridgeAnythingToObjectiveC(element)
let cocoa = asCocoa
if let m = cocoa.member(for: cocoaMember) {
return (false, _forceBridgeFromObjectiveC(m, Element.self))
}
var native = _NativeSet<Element>(cocoa, capacity: cocoa.count + 1)
native.insertNew(element, isUnique: true)
self = .init(native: native)
return (true, element)
}
#endif
let (bucket, found) = asNative.find(element)
if found {
return (false, asNative.uncheckedElement(at: bucket))
}
let isUnique = self.isUniquelyReferenced()
asNative.insertNew(element, at: bucket, isUnique: isUnique)
return (true, element)
}
@inlinable
@discardableResult
internal mutating func remove(at index: Index) -> Element {
#if _runtime(_ObjC)
guard isNative else {
// We have to migrate the data first. But after we do so, the Cocoa
// index becomes useless, so get the element first.
let cocoa = asCocoa
let cocoaMember = cocoa.member(for: index._asCocoa)
let nativeMember = _forceBridgeFromObjectiveC(cocoaMember, Element.self)
return _migrateToNative(cocoa, removing: nativeMember)
}
#endif
let isUnique = isUniquelyReferenced()
let bucket = asNative.validatedBucket(for: index)
return asNative.uncheckedRemove(at: bucket, isUnique: isUnique)
}
@inlinable
@discardableResult
internal mutating func remove(_ member: Element) -> Element? {
#if _runtime(_ObjC)
guard isNative else {
let cocoa = asCocoa
let cocoaMember = _bridgeAnythingToObjectiveC(member)
guard cocoa.contains(cocoaMember) else { return nil }
return _migrateToNative(cocoa, removing: member)
}
#endif
let (bucket, found) = asNative.find(member)
guard found else { return nil }
let isUnique = isUniquelyReferenced()
return asNative.uncheckedRemove(at: bucket, isUnique: isUnique)
}
#if _runtime(_ObjC)
@inlinable
internal mutating func _migrateToNative(
_ cocoa: __CocoaSet,
removing member: Element
) -> Element {
// FIXME(performance): fuse data migration and element deletion into one
// operation.
var native = _NativeSet<Element>(cocoa)
let (bucket, found) = native.find(member)
_precondition(found, "Bridging did not preserve equality")
let old = native.uncheckedRemove(at: bucket, isUnique: true)
_precondition(member == old, "Bridging did not preserve equality")
self = .init(native: native)
return old
}
#endif
@inlinable
internal mutating func removeAll(keepingCapacity keepCapacity: Bool) {
if !keepCapacity {
self = .init(native: _NativeSet<Element>())
return
}
guard count > 0 else { return }
#if _runtime(_ObjC)
guard isNative else {
self = .init(native: _NativeSet(capacity: asCocoa.count))
return
}
#endif
let isUnique = isUniquelyReferenced()
asNative.removeAll(isUnique: isUnique)
}
}
extension Set._Variant {
/// Returns an iterator over the elements.
///
/// - Complexity: O(1).
@inlinable
@inline(__always)
internal __consuming func makeIterator() -> Set<Element>.Iterator {
#if _runtime(_ObjC)
guard isNative else {
return Set.Iterator(_cocoa: asCocoa.makeIterator())
}
#endif
return Set.Iterator(_native: asNative.makeIterator())
}
}
|
apache-2.0
|
253ac863f503bd9e12043378b71ffe2a
| 26.437838 | 80 | 0.665386 | 4.170912 | false | false | false | false |
groue/GRDB.swift
|
Tests/GRDBTests/RecordPrimaryKeySingleTests.swift
|
1
|
26749
|
import XCTest
import GRDB
// Pet has a non-RowID primary key.
class Pet : Record, Hashable {
var UUID: String?
var name: String
init(UUID: String? = nil, name: String) {
self.UUID = UUID
self.name = name
super.init()
}
static func setup(inDatabase db: Database) throws {
try db.execute(sql: """
CREATE TABLE pets (
UUID TEXT NOT NULL PRIMARY KEY,
name TEXT NOT NULL)
""")
}
// Record
override class var databaseTableName: String {
"pets"
}
required init(row: Row) throws {
UUID = row["UUID"]
name = row["name"]
try super.init(row: row)
}
override func encode(to container: inout PersistenceContainer) throws {
container["UUID"] = UUID
container["name"] = name
}
static func == (lhs: Pet, rhs: Pet) -> Bool {
lhs.UUID == rhs.UUID && lhs.name == rhs.name
}
func hash(into hasher: inout Hasher) {
hasher.combine(UUID)
hasher.combine(name)
}
}
class RecordPrimaryKeySingleTests: GRDBTestCase {
override func setup(_ dbWriter: some DatabaseWriter) throws {
var migrator = DatabaseMigrator()
migrator.registerMigration("createPet", migrate: Pet.setup)
try migrator.migrate(dbWriter)
}
// MARK: - Insert
func testInsertWithNilPrimaryKeyThrowsDatabaseError() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(name: "Bobby")
XCTAssertTrue(record.UUID == nil)
do {
try record.insert(db)
XCTFail("Expected DatabaseError")
} catch is DatabaseError {
// Expected DatabaseError
}
}
}
func testInsertWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
let row = try Row.fetchOne(db, sql: "SELECT * FROM pets WHERE UUID = ?", arguments: [record.UUID])!
try assert(record, isEncodedIn: row)
}
}
func testInsertWithNotNilPrimaryKeyThatMatchesARowThrowsDatabaseError() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
do {
try record.insert(db)
XCTFail("Expected DatabaseError")
} catch is DatabaseError {
// Expected DatabaseError
}
}
}
func testInsertAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
try record.delete(db)
try record.insert(db)
let row = try Row.fetchOne(db, sql: "SELECT * FROM pets WHERE UUID = ?", arguments: [record.UUID])!
try assert(record, isEncodedIn: row)
}
}
// MARK: - Update
func testUpdateWithNilPrimaryKeyThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: nil, name: "Bobby")
do {
try record.update(db)
XCTFail("Expected PersistenceError.recordNotFound")
} catch let PersistenceError.recordNotFound(databaseTableName: databaseTableName, key: key) {
// Expected PersistenceError.recordNotFound
XCTAssertEqual(databaseTableName, "pets")
XCTAssertEqual(key, ["UUID": .null])
}
}
}
func testUpdateWithNotNilPrimaryKeyThatDoesNotMatchAnyRowThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
do {
try record.update(db)
XCTFail("Expected PersistenceError.recordNotFound")
} catch let PersistenceError.recordNotFound(databaseTableName: databaseTableName, key: key) {
// Expected PersistenceError.recordNotFound
XCTAssertEqual(databaseTableName, "pets")
XCTAssertEqual(key, ["UUID": "BobbyUUID".databaseValue])
}
}
}
func testUpdateWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
record.name = "Carl"
try record.update(db)
let row = try Row.fetchOne(db, sql: "SELECT * FROM pets WHERE UUID = ?", arguments: [record.UUID])!
try assert(record, isEncodedIn: row)
}
}
func testUpdateAfterDeleteThrowsRecordNotFound() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
try record.delete(db)
do {
try record.update(db)
XCTFail("Expected PersistenceError.recordNotFound")
} catch let PersistenceError.recordNotFound(databaseTableName: databaseTableName, key: key) {
// Expected PersistenceError.recordNotFound
XCTAssertEqual(databaseTableName, "pets")
XCTAssertEqual(key, ["UUID": "BobbyUUID".databaseValue])
}
}
}
// MARK: - Save
func testSaveWithNilPrimaryKeyThrowsDatabaseError() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(name: "Bobby")
XCTAssertTrue(record.UUID == nil)
do {
try record.save(db)
XCTFail("Expected DatabaseError")
} catch is DatabaseError {
// Expected DatabaseError
}
}
}
func testSaveWithNotNilPrimaryKeyThatDoesNotMatchAnyRowInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.save(db)
let row = try Row.fetchOne(db, sql: "SELECT * FROM pets WHERE UUID = ?", arguments: [record.UUID])!
try assert(record, isEncodedIn: row)
}
}
func testSaveWithNotNilPrimaryKeyThatMatchesARowUpdatesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
try record.save(db) // Test that useless update succeeds. It is a proof that save() has performed an UPDATE statement, and not an INSERT statement: INSERT would have throw a database error for duplicated key.
record.name = "Carl"
try record.save(db) // Actual update
let row = try Row.fetchOne(db, sql: "SELECT * FROM pets WHERE UUID = ?", arguments: [record.UUID])!
try assert(record, isEncodedIn: row)
}
}
func testSaveAfterDeleteInsertsARow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
try record.delete(db)
try record.save(db)
let row = try Row.fetchOne(db, sql: "SELECT * FROM pets WHERE UUID = ?", arguments: [record.UUID])!
try assert(record, isEncodedIn: row)
}
}
// MARK: - Delete
func testDeleteWithNilPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: nil, name: "Bobby")
let deleted = try record.delete(db)
XCTAssertFalse(deleted)
}
}
func testDeleteWithNotNilPrimaryKeyThatDoesNotMatchAnyRowDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
let deleted = try record.delete(db)
XCTAssertFalse(deleted)
}
}
func testDeleteWithNotNilPrimaryKeyThatMatchesARowDeletesThatRow() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
let deleted = try record.delete(db)
XCTAssertTrue(deleted)
let row = try Row.fetchOne(db, sql: "SELECT * FROM pets WHERE UUID = ?", arguments: [record.UUID])
XCTAssertTrue(row == nil)
}
}
func testDeleteAfterDeleteDoesNothing() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
var deleted = try record.delete(db)
XCTAssertTrue(deleted)
deleted = try record.delete(db)
XCTAssertFalse(deleted)
}
}
// MARK: - Fetch With Key
func testFetchCursorWithKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let cursor = try Pet.fetchCursor(db, keys: [])
try XCTAssertNil(cursor.next())
}
do {
let cursor = try Pet.fetchCursor(db, keys: [["UUID": record1.UUID], ["UUID": record2.UUID]])
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try Pet.fetchCursor(db, keys: [["UUID": record1.UUID], ["UUID": nil]])
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.UUID!, record1.UUID!)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let fetchedRecords = try Pet.fetchAll(db, keys: [])
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Pet.fetchAll(db, keys: [["UUID": record1.UUID], ["UUID": record2.UUID]])
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
}
do {
let fetchedRecords = try Pet.fetchAll(db, keys: [["UUID": record1.UUID], ["UUID": nil]])
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!)
}
}
}
func testFetchSetWithKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let fetchedRecords = try Pet.fetchSet(db, keys: [])
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Pet.fetchSet(db, keys: [["UUID": record1.UUID], ["UUID": record2.UUID]])
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
}
do {
let fetchedRecords = try Pet.fetchSet(db, keys: [["UUID": record1.UUID], ["UUID": nil]])
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!)
}
}
}
func testFetchOneWithKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
let fetchedRecord = try Pet.fetchOne(db, key: ["UUID": record.UUID])!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
XCTAssertTrue(fetchedRecord.name == record.name)
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"pets\" WHERE \"UUID\" = '\(record.UUID!)'")
}
}
// MARK: - Fetch With Key Request
func testFetchCursorWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let cursor = try Pet.filter(keys: []).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let cursor = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
XCTAssertTrue(try cursor.next() == nil) // end
}
do {
let cursor = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchCursor(db)
let fetchedRecord = try cursor.next()!
XCTAssertEqual(fetchedRecord.UUID!, record1.UUID!)
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let fetchedRecords = try Pet.filter(keys: []).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
}
do {
let fetchedRecords = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!)
}
}
}
func testFetchSetWithKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let fetchedRecords = try Pet.filter(keys: []).fetchSet(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let fetchedRecords = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": record2.UUID]]).fetchSet(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set([record1.UUID!, record2.UUID!]))
}
do {
let fetchedRecords = try Pet.filter(keys: [["UUID": record1.UUID], ["UUID": nil]]).fetchSet(db)
XCTAssertEqual(fetchedRecords.count, 1)
XCTAssertEqual(fetchedRecords.first!.UUID, record1.UUID!)
}
}
}
func testFetchOneWithKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
let fetchedRecord = try Pet.filter(key: ["UUID": record.UUID]).fetchOne(db)!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
XCTAssertTrue(fetchedRecord.name == record.name)
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"pets\" WHERE \"UUID\" = '\(record.UUID!)'")
}
}
// MARK: - Order By Primary Key
func testOrderByPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let request = Pet.orderByPrimaryKey()
try assertEqualSQL(db, request, "SELECT * FROM \"pets\" ORDER BY \"UUID\"")
}
}
// MARK: - Fetch With Primary Key
func testFetchCursorWithPrimaryKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let UUIDs: [String] = []
let cursor = try Pet.fetchCursor(db, keys: UUIDs)
try XCTAssertNil(cursor.next())
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let cursor = try Pet.fetchCursor(db, keys: UUIDs)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let UUIDs: [String] = []
let fetchedRecords = try Pet.fetchAll(db, keys: UUIDs)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let fetchedRecords = try Pet.fetchAll(db, keys: UUIDs)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
}
}
}
func testFetchSetWithPrimaryKeys() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let UUIDs: [String] = []
let fetchedRecords = try Pet.fetchSet(db, keys: UUIDs)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let fetchedRecords = try Pet.fetchSet(db, keys: UUIDs)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
}
}
}
func testFetchOneWithPrimaryKey() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
do {
let id: String? = nil
let fetchedRecord = try Pet.fetchOne(db, key: id)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try Pet.fetchOne(db, key: record.UUID)!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
XCTAssertTrue(fetchedRecord.name == record.name)
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"pets\" WHERE \"UUID\" = '\(record.UUID!)'")
}
}
}
// MARK: - Fetch With Primary Key Request
func testFetchCursorWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let UUIDs: [String] = []
let cursor = try Pet.filter(keys: UUIDs).fetchCursor(db)
try XCTAssertNil(cursor.next())
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let cursor = try Pet.filter(keys: UUIDs).fetchCursor(db)
let fetchedRecords = try [cursor.next()!, cursor.next()!]
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
XCTAssertTrue(try cursor.next() == nil) // end
}
}
}
func testFetchAllWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let UUIDs: [String] = []
let fetchedRecords = try Pet.filter(keys: UUIDs).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let fetchedRecords = try Pet.filter(keys: UUIDs).fetchAll(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
}
}
}
func testFetchSetWithPrimaryKeysRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record1 = Pet(UUID: "BobbyUUID", name: "Bobby")
try record1.insert(db)
let record2 = Pet(UUID: "CainUUID", name: "Cain")
try record2.insert(db)
do {
let UUIDs: [String] = []
let fetchedRecords = try Pet.filter(keys: UUIDs).fetchSet(db)
XCTAssertEqual(fetchedRecords.count, 0)
}
do {
let UUIDs = [record1.UUID!, record2.UUID!]
let fetchedRecords = try Pet.filter(keys: UUIDs).fetchSet(db)
XCTAssertEqual(fetchedRecords.count, 2)
XCTAssertEqual(Set(fetchedRecords.map { $0.UUID! }), Set(UUIDs))
}
}
}
func testFetchOneWithPrimaryKeyRequest() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
do {
let id: String? = nil
let fetchedRecord = try Pet.filter(key: id).fetchOne(db)
XCTAssertTrue(fetchedRecord == nil)
}
do {
let fetchedRecord = try Pet.filter(key: record.UUID).fetchOne(db)!
XCTAssertTrue(fetchedRecord.UUID == record.UUID)
XCTAssertTrue(fetchedRecord.name == record.name)
XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"pets\" WHERE \"UUID\" = '\(record.UUID!)'")
}
}
}
// MARK: - Exists
func testExistsWithNilPrimaryKeyReturnsFalse() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: nil, name: "Bobby")
XCTAssertFalse(try record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatDoesNotMatchAnyRowReturnsFalse() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
XCTAssertFalse(try record.exists(db))
}
}
func testExistsWithNotNilPrimaryKeyThatMatchesARowReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
XCTAssertTrue(try record.exists(db))
}
}
func testExistsAfterDeleteReturnsTrue() throws {
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
let record = Pet(UUID: "BobbyUUID", name: "Bobby")
try record.insert(db)
try record.delete(db)
XCTAssertFalse(try record.exists(db))
}
}
}
|
mit
|
ea1b22a660144664a41a286de3ef736e
| 36.62166 | 222 | 0.54088 | 4.831828 | false | true | false | false |
tad-iizuka/swift-sdk
|
Source/DiscoveryV1/Models/DisambiguatedLinks.swift
|
2
|
4294
|
/**
* Copyright IBM Corporation 2015
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/**
**DisambiguatedLinks**
Disambiguate detected entities
*/
public struct DisambiguatedLinks: JSONDecodable {
/** Detected language. */
public let language: String?
/** Content URL. */
public let url: String?
/**
Link to the US Census for this concept tag.
Note: Provided only for entities that exist in this linked data-set.
*/
public let census: String?
/**
Link to the CIA World Factbook for this concept tag;
Note: Provided only for entities that exist in this linked data-set.
*/
public let ciaFactbook: String?
/**
Link to CrunchBase for this concept tag.
Note: Provided only for entities that exist in CrunchBase.
*/
public let crunchbase: String?
/**
Link to DBpedia for this concept tag.
Note: Provided only for entities that exist in this linked data-set.
*/
public let dbpedia: String?
/**
Link to Freebase for this concept tag.
Note: Provided only for entities that exist in this linked data-set.
*/
public let freebase: String?
/**
latitude longitude - the geographic coordinates associated with this concept tag.
*/
public let geo: String?
/**
Link to Geonames for this concept tag.
Note: Provided only for entities that exist in this linked data-set.
*/
public let geonames: String?
/**
* The music link to MusicBrainz for the disambiguated entity. Note: Provided only for
* entities that exist in this linked data-set.
*/
public let musicBrainz: String?
/** The entity name. */
public let name: String?
/**
* The link to OpenCyc for the disambiguated entity. Note: Provided only for entities
* that exist in this linked data-set.
*/
public let opencyc: String?
/** The disambiguated entity subType. */
public let subType: [String]?
/**
* The link to UMBEL for the disambiguated entity. Note: Provided only for entities
* that exist in this linked data-set.
*/
public let umbel: String?
/** The website. */
public let website: String?
/**
* The link to YAGO for the disambiguated entity. Note: Provided only for entities
* that exist in this linked data-set.
*/
public let yago: String?
/// The raw JSON object used to construct this model.
public let json: [String: Any]
/// Used internally to initialize a `DisambiguatedLinks` object.
public init(json: JSON) throws {
language = try? json.getString(at: "language")
url = try? json.getString(at: "url")
census = try? json.getString(at: "census")
ciaFactbook = try? json.getString(at: "ciaFactbook")
crunchbase = try? json.getString(at: "crunchbase")
dbpedia = try? json.getString(at: "dbpedia")
freebase = try? json.getString(at: "freebase")
geo = try? json.getString(at: "geo")
geonames = try? json.getString(at: "geonames")
musicBrainz = try? json.getString(at: "musicBrainz")
name = try? json.getString(at: "name")
opencyc = try? json.getString(at: "opencyc")
subType = try? json.decodedArray(at: "subType", type: Swift.String)
umbel = try? json.getString(at: "umbel")
website = try? json.getString(at: "website")
yago = try? json.getString(at: "yago")
self.json = try json.getDictionaryObject()
}
/// Used internally to serialize a 'DisambiguatedLinks' model to JSON.
public func toJSONObject() -> Any {
return json
}
}
|
apache-2.0
|
235b5f07cb35d416795d31a556285693
| 29.892086 | 90 | 0.64136 | 4.189268 | false | false | false | false |
nmdias/FeedKit
|
Sources/FeedKit/Models/Namespaces/Media/MediaSubTitle.swift
|
2
|
2859
|
//
// MediaSubTitle.swift
//
// Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
// 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
/// Optional link to specify the machine-readable license associated with the
/// content.
public class MediaSubTitle {
/// The element's attributes.
public class Attributes {
/// The type of the subtitle.
public var type: String?
/// The subtitle language based on the RFC 3066.
public var lang: String?
/// The location of the subtitle.
public var href: String?
}
/// The element's attributes.
public var attributes: Attributes?
public init() { }
}
// MARK: - Initializers
extension MediaSubTitle {
convenience init(attributes attributeDict: [String : String]) {
self.init()
self.attributes = MediaSubTitle.Attributes(attributes: attributeDict)
}
}
extension MediaSubTitle.Attributes {
convenience init?(attributes attributeDict: [String : String]) {
if attributeDict.isEmpty {
return nil
}
self.init()
self.type = attributeDict["type"]
self.lang = attributeDict["lang"]
self.href = attributeDict["href"]
}
}
// MARK: - Equatable
extension MediaSubTitle: Equatable {
public static func ==(lhs: MediaSubTitle, rhs: MediaSubTitle) -> Bool {
return lhs.attributes == rhs.attributes
}
}
extension MediaSubTitle.Attributes: Equatable {
public static func ==(lhs: MediaSubTitle.Attributes, rhs: MediaSubTitle.Attributes) -> Bool {
return
lhs.type == rhs.type &&
lhs.lang == rhs.lang &&
lhs.href == rhs.href
}
}
|
mit
|
c66148dc82d9373173904889bd6df796
| 27.59 | 97 | 0.652676 | 4.641234 | false | false | false | false |
BradLarson/GPUImage2
|
framework/Source/Linux/PictureInput.swift
|
1
|
2929
|
#if canImport(COpenGL)
import COpenGL
#else
import COpenGLES.gles2
#endif
// apt-get install libgd-dev
import Foundation
import SwiftGD
public class PictureInput: ImageSource {
public let targets = TargetContainer()
var imageFramebuffer:Framebuffer!
var hasProcessedImage:Bool = false
public init?(path:String, smoothlyScaleOutput:Bool = false, orientation:ImageOrientation = .portrait) {
let location = URL(fileURLWithPath: path)
guard let image = Image(url: location) else { return nil }
let bitmapImage = try! image.export(as:.bmp(compression:false))
let widthToUseForTexture = GLint(image.size.width)
let heightToUseForTexture = GLint(image.size.height)
sharedImageProcessingContext.runOperationSynchronously{
do {
self.imageFramebuffer = try Framebuffer(context:sharedImageProcessingContext, orientation:orientation, size:GLSize(width:widthToUseForTexture, height:heightToUseForTexture), textureOnly:true)
print("Framebuffer created")
} catch {
fatalError("ERROR: Unable to initialize framebuffer of size (\(widthToUseForTexture), \(heightToUseForTexture)) with error: \(error)")
}
glBindTexture(GLenum(GL_TEXTURE_2D), self.imageFramebuffer.texture)
// if (smoothlyScaleOutput) {
// glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR_MIPMAP_LINEAR)
// }
bitmapImage.withUnsafeBytes { (u8Ptr: UnsafePointer<UInt8>) in
let imageData = UnsafeRawPointer(u8Ptr) + 54
glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, widthToUseForTexture, heightToUseForTexture, 0, GLenum(GL_RGB), GLenum(GL_UNSIGNED_BYTE), imageData)
}
// if (smoothlyScaleOutput) {
// glGenerateMipmap(GLenum(GL_TEXTURE_2D))
// }
glBindTexture(GLenum(GL_TEXTURE_2D), 0)
}
}
public func processImage(synchronously:Bool = false) {
if synchronously {
sharedImageProcessingContext.runOperationSynchronously{
sharedImageProcessingContext.makeCurrentContext()
self.updateTargetsWithFramebuffer(self.imageFramebuffer)
self.hasProcessedImage = true
}
} else {
sharedImageProcessingContext.runOperationAsynchronously{
sharedImageProcessingContext.makeCurrentContext()
self.updateTargetsWithFramebuffer(self.imageFramebuffer)
self.hasProcessedImage = true
}
}
}
public func transmitPreviousImage(to target:ImageConsumer, atIndex:UInt) {
if hasProcessedImage {
imageFramebuffer.lock()
target.newFramebufferAvailable(imageFramebuffer, fromSourceIndex:atIndex)
}
}
}
|
bsd-3-clause
|
65020cb9a76b7a62daf80cf8b9f3da5a
| 41.449275 | 207 | 0.652441 | 4.793781 | false | false | false | false |
nathawes/swift
|
test/Frontend/dependencies-fine.swift
|
20
|
7060
|
// REQUIRES: shell
// Also uses awk:
// XFAIL OS=windows
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-dependencies-path - -resolve-imports "%S/../Inputs/empty file.swift" | %FileCheck -check-prefix=CHECK-BASIC %s
// RUN: %target-swift-frontend -emit-reference-dependencies-path - -typecheck -primary-file "%S/../Inputs/empty file.swift" > %t.swiftdeps
// RUN: %S/../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-BASIC-YAML %s <%t-processed.swiftdeps
// RUN: %target-swift-frontend -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -typecheck -primary-file "%S/../Inputs/empty file.swift"
// RUN: %FileCheck -check-prefix=CHECK-BASIC %s < %t.d
// RUN: %S/../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-BASIC-YAML %s < %t-processed.swiftdeps
// CHECK-BASIC-LABEL: - :
// CHECK-BASIC: Inputs/empty\ file.swift
// CHECK-BASIC: Swift.swiftmodule
// CHECK-BASIC-NOT: {{ }}:{{ }}
// CHECK-BASIC-YAML-NOT: externalDepend {{.*}}empty
// CHECK-BASIC-YAML: externalDepend {{.*}} '{{.*}}Swift.swiftmodule{{(/.+[.]swiftmodule)?}}'
// RUN: %target-swift-frontend -emit-dependencies-path %t.d -emit-reference-dependencies-path %t.swiftdeps -typecheck "%S/../Inputs/empty file.swift" 2>&1 | %FileCheck -check-prefix=NO-PRIMARY-FILE %s
// NO-PRIMARY-FILE: warning: ignoring -emit-reference-dependencies (requires -primary-file)
// RUN: %target-swift-frontend -emit-dependencies-path - -emit-module "%S/../Inputs/empty file.swift" -o "%t/empty file.swiftmodule" -emit-module-doc-path "%t/empty file.swiftdoc" -emit-objc-header-path "%t/empty file.h" -emit-module-interface-path "%t/empty file.swiftinterface" | %FileCheck -check-prefix=CHECK-MULTIPLE-OUTPUTS %s
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftmodule :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftdoc :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.swiftinterface :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-LABEL: empty\ file.h :
// CHECK-MULTIPLE-OUTPUTS: Inputs/empty\ file.swift
// CHECK-MULTIPLE-OUTPUTS: Swift.swiftmodule
// CHECK-MULTIPLE-OUTPUTS-NOT: {{ }}:{{ }}
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-dependencies-path - -resolve-imports %s | %FileCheck -check-prefix=CHECK-IMPORT %s
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/dependencies/extra-header.h -track-system-dependencies -emit-dependencies-path - -resolve-imports %s | %FileCheck -check-prefix=CHECK-IMPORT-TRACK-SYSTEM %s
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-objc-interop -disable-objc-attr-requires-foundation-module -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-reference-dependencies-path %t.swiftdeps -typecheck -primary-file %s
// RUN: %S/../Inputs/process_fine_grained_swiftdeps.sh %swift-dependency-tool %t.swiftdeps %t-processed.swiftdeps
// RUN: %FileCheck -check-prefix=CHECK-IMPORT-YAML %s <%t-processed.swiftdeps
// CHECK-IMPORT-LABEL: - :
// CHECK-IMPORT: dependencies-fine.swift
// CHECK-IMPORT-DAG: Swift.swiftmodule
// CHECK-IMPORT-DAG: Inputs/dependencies/$$$$$$$$$$.h
// CHECK-IMPORT-DAG: Inputs/dependencies{{/|\\}}UserClangModule.h
// CHECK-IMPORT-DAG: Inputs/dependencies/extra-header.h
// CHECK-IMPORT-DAG: Inputs/dependencies{{/|\\}}module.modulemap
// CHECK-IMPORT-DAG: ObjectiveC.swift
// CHECK-IMPORT-DAG: Foundation.swift
// CHECK-IMPORT-DAG: CoreGraphics.swift
// CHECK-IMPORT-NOT: {{[^\\]}}:
// CHECK-IMPORT-TRACK-SYSTEM-LABEL: - :
// CHECK-IMPORT-TRACK-SYSTEM: dependencies-fine.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Swift.swiftmodule
// CHECK-IMPORT-TRACK-SYSTEM-DAG: SwiftOnoneSupport.swiftmodule
// CHECK-IMPORT-TRACK-SYSTEM-DAG: CoreFoundation.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: CoreGraphics.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Foundation.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: ObjectiveC.swift
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/$$$$$$$$$$.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies{{/|\\}}UserClangModule.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies/extra-header.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: Inputs/dependencies{{/|\\}}module.modulemap
// CHECK-IMPORT-TRACK-SYSTEM-DAG: swift{{/|\\}}shims{{/|\\}}module.modulemap
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}CoreFoundation.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}CoreGraphics.apinotes
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}CoreGraphics.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}Foundation.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}objc{{/|\\}}NSObject.h
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}objc{{/|\\}}ObjectiveC.apinotes
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}objc{{/|\\}}module.map
// CHECK-IMPORT-TRACK-SYSTEM-DAG: usr{{/|\\}}include{{/|\\}}objc{{/|\\}}objc.h
// CHECK-IMPORT-TRACK-SYSTEM-NOT: {{[^\\]}}:
// CHECK-IMPORT-YAML-NOT: externalDepend {{.*}}dependencies-fine.swift
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}{{/|\\}}Swift.swiftmodule{{(/.+[.]swiftmodule)?}}'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}Inputs/dependencies/$$$$$.h'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}Inputs/dependencies{{/|\\\\}}UserClangModule.h'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}Inputs/dependencies/extra-header.h'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}Inputs/dependencies{{/|\\\\}}module.modulemap'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}{{/|\\\\}}ObjectiveC.swift'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}{{/|\\\\}}Foundation.swift'
// CHECK-IMPORT-YAML-DAG: externalDepend {{.*}} '{{.*}}{{/|\\\\}}CoreGraphics.swift'
// CHECK-ERROR-YAML: # Dependencies are unknown because a compilation error occurred.
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -DERROR -import-objc-header %S/Inputs/dependencies/extra-header.h -emit-dependencies-path - -typecheck %s | %FileCheck -check-prefix=CHECK-IMPORT %s
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -DERROR -import-objc-header %S/Inputs/dependencies/extra-header.h -typecheck -primary-file %s - %FileCheck -check-prefix=CHECK-ERROR-YAML %s
import Foundation
import UserClangModule
class Test: NSObject {}
_ = A()
_ = USER_VERSION
_ = EXTRA_VERSION
_ = MONEY
#if ERROR
_ = someRandomUndefinedName
#endif
|
apache-2.0
|
51cf140f622d353b7de19df71ea5d82f
| 59.34188 | 332 | 0.714731 | 3.514186 | false | false | false | false |
mokemokechicken/ObjectJsonMapperGenerator
|
test/run_book.swift
|
1
|
384
|
import Foundation
let args = Process.arguments
let filename = args[1]
var data = NSData(contentsOfFile: filename)!
var hash = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
if let book = Book.fromJsonDictionary(hash) {
println("\(book.toJsonDictionary())")
} else {
println("JSON parse error")
}
|
mit
|
1d558fe308ce03517a07e7914e7ac56b
| 23 | 131 | 0.757813 | 4.314607 | false | false | false | false |
frtlupsvn/Vietnam-To-Go
|
VietNamToGo/CustomView/Cells/ZCCMoneySliderTableViewCell.swift
|
1
|
2071
|
//
// ZCCMoneySliderTableViewCell.swift
// Fuot
//
// Created by Zoom Nguyen on 1/2/16.
// Copyright © 2016 Zoom Nguyen. All rights reserved.
//
import UIKit
class ZCCMoneySliderTableViewCell: UITableViewCell {
@IBOutlet weak var viewView: UIVisualEffectView!
@IBOutlet weak var lblValueLocationPicked: UILabel!
@IBOutlet weak var lblPickLocation: UILabel!
@IBOutlet weak var imgIcon: UIImageView!
var money:Int = 0
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = UIColor.clearColor()
self.viewView.layer.cornerRadius = self.viewView.frame.size.height/2
self.viewView.layer.masksToBounds = true
self.lblValueLocationPicked.text = String(money) + " vnd"
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
@IBAction func btnPlusTapped(sender: AnyObject) {
PlusMoney(100000)
setMoneylabel()
}
@IBAction func btnMinusTapped(sender: AnyObject) {
MinusMoney(100000)
setMoneylabel()
}
@IBAction func btnPlusTappedRepeat(sender: AnyObject) {
PlusMoney(500000)
setMoneylabel()
}
@IBAction func btnMinusTappedRepeat(sender: AnyObject) {
MinusMoney(500000)
setMoneylabel()
}
func setMoneylabel(){
self.lblValueLocationPicked.text = String(money.stringFormatedWithSepator) + " vnd"
}
func PlusMoney(distance:Int){
if (money < 100000000) {
money += distance
}
}
func MinusMoney(distance:Int){
if (money > 0) {
money -= distance
}
}
func loadDataToCell(location:String){
self.lblValueLocationPicked.text = location
}
func setIcon(image:UIImage){
self.imgIcon.image = image
}
static func heightOfCell() -> CGFloat {
return CGFloat(heightOfCellPickTrip)
}
}
|
mit
|
aa85671e036f5bb175cbd4e95ca4f141
| 25.883117 | 91 | 0.641063 | 4.259259 | false | false | false | false |
pattypatpat2632/EveryoneGetsToDJ
|
EveryoneGetsToDJ/EveryoneGetsToDJ/Jukebox.swift
|
1
|
1096
|
//
// Jukebox.swift
// EveryoneGetsToDJ
//
// Created by Patrick O'Leary on 6/19/17.
// Copyright © 2017 Patrick O'Leary. All rights reserved.
//
import Foundation
struct Jukebox {
let id: String
let creatorID: String
let name: String
var tracks = [Track]()
}
extension Jukebox {
init(id: String, dictionary: [String: Any]) {
self.id = id
self.creatorID = dictionary["creatorID"] as? String ?? "No Creator"
self.name = dictionary["name"] as? String ?? "No Name"
let allTracks = dictionary["tracks"] as? [String: Any] ?? [:]
for track in allTracks {
let trackValue = track.value as? [String: Any] ?? [:]
let newTrack = Track(trackValue)
self.tracks.append(newTrack)
}
}
}
extension Jukebox: Serializing {
func asDictionary() -> [String: Any]{
let dictionary: [String: Any] = [
"creatorID": FirebaseManager.sharedInstance.uid,
"name": self.name,
"id": self.id
]
return dictionary
}
}
|
mit
|
b5d04eddf011937fc3964d48b0846ea5
| 25.071429 | 75 | 0.564384 | 3.896797 | false | false | false | false |
alloyapple/GooseGtk
|
Sources/GooseGtk/GTKTreeViewColumn.swift
|
1
|
4091
|
//
// Created by color on 12/7/17.
//
import Foundation
import CGTK
public enum GTKTreeViewColumnSizing {
case TREE_VIEW_COLUMN_GROW_ONLY
case TREE_VIEW_COLUMN_AUTOSIZE
case TREE_VIEW_COLUMN_FIXED
var treeViewColumnSizing: GtkTreeViewColumnSizing {
get {
switch self {
case .TREE_VIEW_COLUMN_AUTOSIZE:
return GTK_TREE_VIEW_COLUMN_GROW_ONLY
case .TREE_VIEW_COLUMN_FIXED:
return GTK_TREE_VIEW_COLUMN_AUTOSIZE
case .TREE_VIEW_COLUMN_GROW_ONLY:
return GTK_TREE_VIEW_COLUMN_FIXED
}
}
}
}
public class GTKTreeViewColumn {
public let treeViewColumn: UnsafeMutablePointer<GtkTreeViewColumn>
public init() {
self.treeViewColumn = gtk_tree_view_column_new()
}
public func addAttribute(cellRenderer: UnsafeMutablePointer<GtkCellRenderer>, attribute: String, column: Int32) {
gtk_tree_view_column_add_attribute(treeViewColumn, cellRenderer, attribute, column)
}
public var title: String {
get {
guard let v = gtk_tree_view_column_get_title(treeViewColumn) else {
return ""
}
return String(cString: v)
}
set {
gtk_tree_view_column_set_title(treeViewColumn, newValue)
}
}
public var spacing: Int32 {
get {
return gtk_tree_view_column_get_spacing(treeViewColumn)
}
set {
gtk_tree_view_column_set_spacing(treeViewColumn, newValue)
}
}
public var visible: Bool {
get {
return gtk_tree_view_column_get_visible(treeViewColumn) == 1
}
set {
gtk_tree_view_column_set_visible(treeViewColumn, newValue.gboolean)
}
}
public var resizable: Bool {
get {
return gtk_tree_view_column_get_resizable(treeViewColumn) == 1
}
set {
gtk_tree_view_column_set_resizable(treeViewColumn, newValue.gboolean)
}
}
public var sizing: GTKTreeViewColumnSizing {
get {
let v = gtk_tree_view_column_get_sizing(treeViewColumn)
switch v {
case GTK_TREE_VIEW_COLUMN_GROW_ONLY:
return .TREE_VIEW_COLUMN_GROW_ONLY
case GTK_TREE_VIEW_COLUMN_AUTOSIZE:
return .TREE_VIEW_COLUMN_FIXED
default:
return .TREE_VIEW_COLUMN_AUTOSIZE
}
}
set {
gtk_tree_view_column_set_sizing(treeViewColumn, newValue.treeViewColumnSizing)
}
}
public var width: Int32 {
get {
return gtk_tree_view_column_get_width(treeViewColumn)
}
}
public var fixedWidth: Int32 {
get {
return gtk_tree_view_column_get_fixed_width(treeViewColumn)
}
set {
gtk_tree_view_column_set_fixed_width(treeViewColumn, newValue)
}
}
public var minWidth: Int32 {
get {
return gtk_tree_view_column_get_min_width(treeViewColumn)
}
set {
gtk_tree_view_column_set_min_width(treeViewColumn, newValue)
}
}
public var maxWidth: Int32 {
get {
return gtk_tree_view_column_get_max_width(treeViewColumn)
}
set {
gtk_tree_view_column_set_max_width(treeViewColumn, newValue)
}
}
public func packStart(cell: UnsafeMutablePointer<GtkCellRenderer>, expand: Bool) {
gtk_tree_view_column_pack_start(treeViewColumn, cell, expand.gboolean)
}
public func packEnd(cell: UnsafeMutablePointer<GtkCellRenderer>, expand: Bool) {
gtk_tree_view_column_pack_end(treeViewColumn, cell, expand.gboolean)
}
public func clear() {
gtk_tree_view_column_clear(treeViewColumn)
}
public func clearAttributes(cell: UnsafeMutablePointer<GtkCellRenderer>) {
gtk_tree_view_column_clear_attributes(treeViewColumn, cell)
}
}
|
apache-2.0
|
bacd2a59d166cf5b47bea70c929b54a4
| 25.745098 | 117 | 0.585431 | 4.095095 | false | false | false | false |
Geraud-Vercasson/Melenchon-bot
|
Sources/Run/GfycatController.swift
|
1
|
2761
|
//
// GfycatController.swift
// Melenchon_bot
//
// Created by Géraud Vercasson on 05/06/2017.
//
//
import Foundation
import JSON
func getYoutubeGif (videoId: String, startDate: Double=0, endDate: Double=0, captionText: String = "") -> (idGif: String, gfyToken: String)? {
do {
let duration = (endDate - startDate)
var text = captionText
if text.characters.count > 50 { // Taille arbitraire au delà de laquelle la phrase est coupée en 2 sans couper de mot
let characters = text.characters.array
let distanceMoyenne = characters.count / 2
var distanceMin = characters.count
for i in 0..<characters.count{
if characters[i] == " " && abs(i - distanceMoyenne) < abs(distanceMin - distanceMoyenne) {
distanceMin = i
}
}
text = text.replacingCharacters(in: text.index(text.startIndex, offsetBy: distanceMin)..<text.index(text.startIndex, offsetBy: distanceMin+1), with: "\\n")
}
if let json = try? JSON(node: [
"grant_type":"client_credentials",
"client_id":gfycatClientId,
"client_secret":gfycatClientSecret]) {
let gifJson = try JSON(node: [
"fetchUrl":"https://www.youtube.com/watch?v=" + videoId,
"cut" : ["duration":duration,"start":startDate],
"captions": [["text":text.folding(options: .diacriticInsensitive, locale: .current), "fontHeight": 40]]])
let tokenResponse = try drop.client.post("https://api.gfycat.com/v1/oauth/token", [:], json)
if let bodyBytes = tokenResponse.body.bytes, let responseJson = try? JSON(bytes: bodyBytes) {
if let accessToken = responseJson["access_token"]?.string {
let gifPost = try drop.client.post("https://api.gfycat.com/v1/gfycats",["Authorization" : "Bearer " + accessToken, "Content-Type" : "application/json"],gifJson)
if let bodyBytes = gifPost.body.bytes, let responseJson = try? JSON(bytes: bodyBytes), let gfyname = (responseJson["gfyname"]?.string) {
return (idGif: gfyname, gfyToken: accessToken)
}
}
}
}
}
catch {
// will print error catched in try calls
print("error")
}
return nil
}
|
mit
|
947e80048d5b1ccbce31209a60c38a94
| 33.475 | 180 | 0.507252 | 4.682513 | false | false | false | false |
trvslhlt/CalcLater
|
CalcLater/CalcLaterSymbols.swift
|
1
|
4057
|
//
// CalcLaterSymbols.swift
// CalcLater
//
// Created by trvslhlt on 11/4/15.
// Copyright © 2015 travis holt. All rights reserved.
//
import Foundation
import UIKit
enum CalcLaterSymbol: String {
case Zero = "0"
case One = "1"
case Two = "2"
case Three = "3"
case Four = "4"
case Five = "5"
case Six = "6"
case Seven = "7"
case Eight = "8"
case Nine = "9"
case DecimalSign = "."
case PlusSign = "+"
case MinusSign = "-"
case MultiplySign = "x"
case DivideSign = "/"
case PercentSign = "%"
case EqualsSign = "="
case ClearSign = "c"
case ClearAllSign = "ac"
case NegateSign = "+/-"
case NegativeSign = "~"
}
extension CalcLaterSymbol {
static let arithmeticOperatorSet: Set<CalcLaterSymbol> = [
.PlusSign,
.MinusSign,
.MultiplySign,
.DivideSign]
func isDigit() -> Bool {
let digitSet: Set<CalcLaterSymbol> = [
.Zero,
.One,
.Two,
.Three,
.Four,
.Five,
.Six,
.Seven,
.Eight,
.Nine,
]
return digitSet.contains(self)
}
static func lastIsDigit(sequence: [CalcLaterSymbol]) -> Bool {
if let last = sequence.last { return last.isDigit() }
return false
}
static func lastIsDecimal(sequence: [CalcLaterSymbol]) -> Bool {
if let last = sequence.last { return last == .DecimalSign }
return false
}
static func lastIsEquals(sequence: [CalcLaterSymbol]) -> Bool {
if let last = sequence.last { return last == .EqualsSign }
return false
}
static func containsArithmeticOperator(sequence: [CalcLaterSymbol]) -> Bool {
return sequence.reduce(false) { CalcLaterSymbol.arithmeticOperatorSet.contains($1) || $0 }
}
static func tailDigitSequenceContainsDecimal(sequence: [CalcLaterSymbol]) -> Bool {
if let last = sequence.last {
if last == .DecimalSign {
return true
} else if last.isDigit() {
return tailDigitSequenceContainsDecimal(Array(sequence.dropLast()))
} else {
return false
}
} else {
return false
}
}
static func tailDigitSequence(sequence: [CalcLaterSymbol]) -> [CalcLaterSymbol] {
guard let last = sequence.last else { return [] }
if last.isDigit() || last == .DecimalSign {
return tailDigitSequence(Array(sequence.dropLast())) + [last]
} else {
return []
}
let views = [""]
let superviews = views.getSuperviews()
print(views, superviews)
}
}
//TODO: Attempt at extending [CalcLaterSymbol]. This would be better than the current solution
extension Array where Element: String {
func getSuperviews() -> [UIView] {
return [UIView]()
}
}
//extension Array where Element: CalcLaterSymbol {
// func lastIsDigit() -> Bool {
// if let last = self.last { return isDigit(last) }
// }
//
// func lastIsDecimal() -> Bool {
// if let last = self.last { return last == .DecimalSign }
// }
//
// func lastIsEquals() -> Bool {
// if let last = self.last { return last == .EqualsSign }
// }
//
// func containsArithmeticOperator() -> Bool {
// return sequence.reduce(false) { CalcLaterSymbol.arithmeticOperatorSet().contains($1) || $0 }
// }
//
// func tailDigitSequenceContainsDecimal() -> Bool {
// if let last = self.last {
// if last == .DecimalSign {
// return true
// } else if CalcLaterSymbol.isDigit(last) {
// return symbolSequenceTailDigitSequenceContainsDecimal(Array(self.dropLast()))
// } else {
// return false
// }
// } else {
// return false
// }
// }
//}
|
mit
|
eb76de626c7aed5cbf5426816bfe1cde
| 25.167742 | 102 | 0.540927 | 4.11359 | false | false | false | false |
mitchtreece/Bulletin
|
Example/Pods/Espresso/Espresso/Classes/Core/UIKit/UITableViewCell+Espresso.swift
|
1
|
2498
|
//
// UITableViewCell+Espresso.swift
// Espresso
//
// Created by Mitch Treece on 4/24/18.
//
import UIKit
public extension UITableViewCell /* Register */ {
// NOTE: `UITableViewCell` conforms to `Identifiable`
/**
Registers a cell's nib in a table view with a specified name. If no name is provided, the cell's class name will be used.
- Parameter tableView: The table view to register the cell in.
- Parameter nibName: The cell's nib name.
*/
static func registerNib(in tableView: UITableView, nibName: String? = nil) {
let name = nibName ?? self.identifier
let nib = UINib(nibName: name, bundle: nil)
tableView.register(nib, forCellReuseIdentifier: self.identifier)
}
/**
Registers a cell in a specified table view.
- Parameter tableView: The table view to register the cell in.
*/
static func register(in tableView: UITableView) {
tableView.register(self, forCellReuseIdentifier: self.identifier)
}
/**
Dequeue's a cell for a specified table view & index path.
- Parameter tableView: The table view.
- Parameter indexPath: The index path.
- Returns: A typed cell.
*/
static func dequeue(for tableView: UITableView, at indexPath: IndexPath) -> Self {
return _cell(dequeuedFor: tableView, indexPath: indexPath)
}
/**
Dequeue's _or_ creates a cell for a specified table view & nib name. If no name is provided, the cell's class name will be used.
- Parameter tableView: The table view.
- Parameter nibName: The cell's nib name.
- Returns: A typed cell.
*/
static func cell(for tableView: UITableView, nibName: String? = nil) -> Self {
return _cell(for: tableView, nibName: nibName)
}
private class func _cell<T: UITableViewCell>(for tableView: UITableView, nibName: String? = nil) -> T {
let name = nibName ?? T.identifier
if let cell = tableView.dequeueReusableCell(withIdentifier: T.identifier) as? T {
return cell
}
else {
return Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as! T
}
}
private class func _cell<T: UITableViewCell>(dequeuedFor tableView: UITableView, indexPath: IndexPath) -> T {
return tableView.dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as! T
}
}
|
mit
|
a7a47769898b05c58746d9fa1b56991a
| 31.868421 | 133 | 0.632106 | 4.583486 | false | false | false | false |
liuchuo/iOS9-practise
|
learniostable/learniostable/TableViewController.swift
|
1
|
3344
|
//
// TableViewController.swift
// learniostable
//
// Created by ChenXin on 16/3/23.
// Copyright © 2016年 ChenXin. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
let TAG_CELL_LABEL = 1
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 3
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
// Configure the cell...
var label = cell.viewWithTag(TAG_CELL_LABEL) as! UILabel
label.text = "hello"
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
gpl-3.0
|
25e5baeb90a01aac920775d1ecf4b032
| 32.747475 | 157 | 0.683029 | 5.45915 | false | false | false | false |
raymondshadow/SwiftDemo
|
SwiftApp/Pods/Swiftz/Sources/Swiftz/Arrow.swift
|
3
|
6673
|
//
// Arrow.swift
// Swiftz
//
// Created by Robert Widmann on 1/18/15.
// Copyright (c) 2015-2016 TypeLift. All rights reserved.
//
#if SWIFT_PACKAGE
import Operadics
import Swiftx
#endif
/// An Arrow is most famous for being a "Generalization of a Monad". They're
/// probably better described as a more general view of computation. Where a
/// monad M<A> yields a value of type A given some context, an Arrow A<B, C> is
/// a function from B -> C in some context A. Functions are the simplest kind
/// of Arrow (pun intended). Their context parameter, A, is essentially empty.
/// From there, the B -> C part of the arrow gets alpha-reduced to the A -> B
/// part of the function type.
///
/// Arrows can be modelled with circuit-esque diagrams, and indeed that can
/// often be a better way to envision the various arrow operators.
///
/// - >>> a -> [ f ] -> b -> [ g ] -> c
/// - <<< a -> [ g ] -> b -> [ f ] -> c
///
/// - arr a -> [ f ] -> b
///
/// - first a -> [ f ] -> b
/// c - - - - - -> c
///
/// - second c - - - - - -> c
/// a -> [ f ] -> b
///
///
/// - *** a - [ f ] -> b - •
/// \
/// o - -> (b, d)
/// /
/// c - [ g ] -> d - •
///
///
/// • a - [ f ] -> b - •
/// | \
/// - &&& a - o o - -> (b, c)
/// | /
/// • a - [ g ] -> c - •
///
/// Arrows inherit from Category so we can get Composition For Free™.
public protocol Arrow : Category {
/// Some arbitrary target our arrow can compose with.
associatedtype D
/// Some arbitrary target our arrow can compose with.
associatedtype E
/// Type of the result of first().
associatedtype FIRST = K2<(A, D), (B, D)>
/// Type of the result of second().
associatedtype SECOND = K2<(D, A), (D, B)>
/// Some arrow with an arbitrary target and source. Used in split().
associatedtype ADE = K2<D, E>
/// Type of the result of ***.
associatedtype SPLIT = K2<(A, D), (B, E)>
/// Some arrow from our target to some other arbitrary target. Used in
/// fanout().
associatedtype ABD = K2<A, D>
/// Type of the result of &&&.
associatedtype FANOUT = K2<B, (B, D)>
/// Lift a function to an arrow.
static func arr(_ : (A) -> B) -> Self
/// Splits the arrow into two tuples that model a computation that applies
/// our Arrow to an argument on the "left side" and sends the "right side"
/// through unchanged.
///
/// The mirror image of second().
func first() -> FIRST
/// Splits the arrow into two tuples that model a computation that applies
/// our Arrow to an argument on the "right side" and sends the "left side"
/// through unchanged.
///
/// The mirror image of first().
func second() -> SECOND
/// Split | Splits two computations and combines the result into one Arrow
/// yielding a tuple of the result of each side.
static func ***(_ : Self, _ : ADE) -> SPLIT
/// Fanout | Given two functions with the same source but different targets,
/// this function splits the computation and combines the result of each
/// Arrow into a tuple of the result of each side.
static func &&&(_ : Self, _ : ABD) -> FANOUT
}
/// Arrows that can produce an identity arrow.
public protocol ArrowZero : Arrow {
/// An arrow from A -> B. Colloquially, the "zero arrow".
associatedtype ABC = K2<A, B>
/// The identity arrow.
static func zeroArrow() -> ABC
}
/// A monoid for Arrows.
public protocol ArrowPlus : ArrowZero {
/// A binary function that combines two arrows.
// static func <+>(_ : ABC, _ : ABC) -> ABC
}
/// Arrows that permit "choice" or selecting which side of the input to apply
/// themselves to.
///
/// - left a - - [ f ] - - > b
/// |
/// a - [f] -> b - o------EITHER------
/// |
/// d - - - - - - - > d
///
/// - right d - - - - - - - > d
/// |
/// a - [f] -> b - o------EITHER------
/// |
/// a - - [ f ] - - > b
///
/// - +++ a - [ f ] -> b - • • a - [ f ] -> b
/// \ |
/// o - -> o-----EITHER-----
/// / |
/// d - [ g ] -> e - • • d - [ g ] -> e
///
/// - ||| a - [ f ] -> c - • • a - [ f ] -> c •
/// \ | \
/// o - -> o-----EITHER-------o - -> c
/// / | /
/// b - [ g ] -> c - • • b - [ g ] -> c •
///
public protocol ArrowChoice : Arrow {
/// The result of left
associatedtype LEFT = K2<Either<A, D>, Either<B, D>>
/// The result of right
associatedtype RIGHT = K2<Either<D, A>, Either<D, B>>
/// The result of +++
associatedtype SPLAT = K2<Either<A, D>, Either<B, E>>
/// Some arrow from a different source and target for fanin.
associatedtype ACD = K2<B, D>
/// The result of |||
associatedtype FANIN = K2<Either<A, B>, D>
/// Feed marked inputs through the argument arrow, passing the rest through
/// unchanged to the output.
func left() -> LEFT
/// The mirror image of left.
func right() -> RIGHT
/// Splat | Split the input between both argument arrows, then retag and
/// merge their outputs into Eithers.
static func +++(_ : Self, _ : ADE) -> SPLAT
/// Fanin | Split the input between two argument arrows and merge their
/// ouputs.
// static func |||(_ : ABD, _ : ACD) -> FANIN
}
/// Arrows that allow application of arrow inputs to other inputs. Such arrows
/// are equivalent to monads.
///
/// - app (_ f : a -> b) - •
/// \
/// o - a - [ f ] -> b
/// /
/// a -------> a - •
///
public protocol ArrowApply : Arrow {
associatedtype APP = K2<(Self, A), B>
static func app() -> APP
}
/// Arrows that admit right-tightening recursion.
///
/// The 'loop' operator expresses computations in which an output value is fed
/// back as input, although the computation occurs only once.
///
/// •-------•
/// | |
/// - loop a - - [ f ] - -> b
/// | |
/// d-------•
///
public protocol ArrowLoop : Arrow {
associatedtype LOOP = K2<(A, D), (B, D)>
static func loop(_ : LOOP) -> Self
}
|
apache-2.0
|
709b73aa7de899a393a90d7a0edaa6be
| 31.816832 | 80 | 0.490723 | 3.624385 | false | false | false | false |
finngaida/spotify2applemusic
|
Spotify2AppleMusic/Itunes.swift
|
1
|
2070
|
//
// Itunes.swift
// Spotify2AppleMusic
//
// Created by Mathias Quintero on 3/1/17.
// Copyright © 2017 Finn Gaida. All rights reserved.
//
import Sweeft
enum ItunesEndpoint: String, APIEndpoint {
case search = "search"
}
struct Itunes: API {
typealias Endpoint = ItunesEndpoint
let baseURL: String = "https://itunes.apple.com/WebObjects/MZStore.woa/wa/"
}
extension JSON {
var isSong: Bool {
let offers = self["offers"].array => { $0["price"].double } |> { $0 == 0.0 }
return self["kind"].string == "song" && !offers.isEmpty
}
}
extension Itunes {
func search(for song: SpotifySong) -> Promise<Song?, APIError> {
return doJSONRequest(to: .search,
headers: ["X-Apple-Store-Front" : "143446-10,32 ab:rSwnYxS0 t:music2", "X-Apple-Tz" : "7200"],
queries: ["clientApplication": "MusicPlayer", "term": song.term, "entity": "song"]).nested { json, promise in
let songs = json["storePlatformData"]["lockup"]["results"].dict => lastArgument |> { $0.isSong }
let possibleSongs = songs |> song.artistMatches
let matchingSongs = possibleSongs |> song.nameMatches
let albumMatchingSongs = matchingSongs |> song.albumMatches
let dict = albumMatchingSongs.first ?? matchingSongs.first
if dict == nil {
print("Didn't find \(song.term)")
}
let song = dict?["id"].string | Song.initializer(for: song)
promise.success(with: song)
}
}
func search(for songs: [SpotifySong]) -> Promise<[Song], APIError> {
return BulkPromise(promises: songs => { self.search(for: $0) }).nested {
return $0.flatMap { $0 }
}
}
}
|
mit
|
baa82066cc7c5023ea2f8c11ff9e7120
| 35.946429 | 138 | 0.505075 | 4.478355 | false | false | false | false |
enstulen/ARKitAnimation
|
Pods/SwiftCharts/SwiftCharts/Views/ChartPointViewBarStacked.swift
|
2
|
5731
|
//
// ChartPointViewBarStacked.swift
// Examples
//
// Created by ischuetz on 15/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public struct TappedChartPointViewBarStacked {
public let barView: ChartPointViewBarStacked
public let stackFrame: (index: Int, view: UIView, viewFrameRelativeToBarSuperview: CGRect)?
}
private class ChartBarStackFrameView: UIView {
var isSelected: Bool = false
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
public typealias ChartPointViewBarStackedFrame = (rect: CGRect, color: UIColor)
open class ChartPointViewBarStacked: ChartPointViewBar {
fileprivate var stackViews: [(index: Int, view: ChartBarStackFrameView, targetFrame: CGRect)] = []
var stackFrameSelectionViewUpdater: ChartViewSelector?
var stackedTapHandler: ((TappedChartPointViewBarStacked) -> Void)? {
didSet {
if stackedTapHandler != nil && gestureRecognizers?.isEmpty ?? true {
enableTap()
}
}
}
public required init(p1: CGPoint, p2: CGPoint, width: CGFloat, bgColor: UIColor?, stackFrames: [ChartPointViewBarStackedFrame], settings: ChartBarViewSettings, stackFrameSelectionViewUpdater: ChartViewSelector? = nil) {
self.stackFrameSelectionViewUpdater = stackFrameSelectionViewUpdater
super.init(p1: p1, p2: p2, width: width, bgColor: bgColor, settings: settings)
for (index, stackFrame) in stackFrames.enumerated() {
let (targetFrame, firstFrame): (CGRect, CGRect) = {
if isHorizontal {
let initFrame = CGRect(x: 0, y: stackFrame.rect.origin.y, width: 0, height: stackFrame.rect.size.height)
return (stackFrame.rect, initFrame)
} else { // vertical
let initFrame = CGRect(x: stackFrame.rect.origin.x, y: self.frame.height, width: stackFrame.rect.size.width, height: 0)
return (stackFrame.rect, initFrame)
}
}()
let v = ChartBarStackFrameView(frame: firstFrame)
v.backgroundColor = stackFrame.color
if settings.cornerRadius > 0 {
let corners: UIRectCorner
if (stackFrames.count == 1) {
corners = UIRectCorner.allCorners
} else {
switch (index, isHorizontal) {
case (0, true):
corners = [.bottomLeft, .topLeft]
case (0, false):
corners = [.bottomLeft, .bottomRight]
case (stackFrames.count - 1, true):
corners = [.topRight, .bottomRight]
case (stackFrames.count - 1, false):
corners = [.topLeft, .topRight]
default:
corners = []
}
}
let bounds = CGRect(x: 0, y: 0, width: stackFrame.rect.width, height: stackFrame.rect.height)
let path = UIBezierPath(
roundedRect: bounds,
byRoundingCorners: corners,
cornerRadii: CGSize(width: settings.cornerRadius, height: settings.cornerRadius)
)
if !corners.isEmpty {
let maskLayer = CAShapeLayer()
maskLayer.frame = bounds
maskLayer.path = path.cgPath
v.layer.mask = maskLayer
}
}
stackViews.append((index, v, targetFrame))
addSubview(v)
}
}
override func onTap(_ sender: UITapGestureRecognizer) {
let loc = sender.location(in: self)
guard let tappedStackFrame = (stackViews.filter{$0.view.frame.contains(loc)}.first) else {
stackedTapHandler?(TappedChartPointViewBarStacked(barView: self, stackFrame: nil))
return
}
toggleSelection()
tappedStackFrame.view.isSelected = !tappedStackFrame.view.isSelected
let f = tappedStackFrame.view.frame.offsetBy(dx: frame.origin.x, dy: frame.origin.y)
stackFrameSelectionViewUpdater?.displaySelected(tappedStackFrame.view, selected: tappedStackFrame.view.isSelected)
stackedTapHandler?(TappedChartPointViewBarStacked(barView: self, stackFrame: (tappedStackFrame.index, tappedStackFrame.view, f)))
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public required init(p1: CGPoint, p2: CGPoint, width: CGFloat, bgColor: UIColor?, settings: ChartBarViewSettings) {
super.init(p1: p1, p2: p2, width: width, bgColor: bgColor, settings: settings)
}
override open func didMoveToSuperview() {
func targetState() {
frame = targetFrame
for stackFrame in stackViews {
stackFrame.view.frame = stackFrame.targetFrame
}
layoutIfNeeded()
}
if settings.animDuration =~ 0 {
targetState()
} else {
UIView.animate(withDuration: CFTimeInterval(settings.animDuration), delay: CFTimeInterval(settings.animDelay), options: .curveEaseOut, animations: {
targetState()
}, completion: nil)
}
}
}
|
mit
|
f3b0ebdbdbef8994f052946403816893
| 36.953642 | 223 | 0.573024 | 5.229015 | false | false | false | false |
jgainfort/FRPlayer
|
FRPlayer/PlayerViewModel.swift
|
1
|
2434
|
//
// PlayerViewModel.swift
// FRPlayer
//
// Created by John Gainfort Jr on 4/4/17.
// Copyright © 2017 John Gainfort Jr. All rights reserved.
//
import Foundation
import ReSwift
import RxSwift
import AVFoundation
class PlayerViewModel: StoreSubscriber {
let buffering: Variable<Bool> = Variable(true)
let controlbarHidden: Variable<Bool> = Variable(true)
var controlbarHiddenTimer: Disposable?
init() {
mainStore.subscribe(self)
}
deinit {
mainStore.unsubscribe(self)
}
func newState(state: State) {
let playerState = state.playerState
let controlbarState = state.controlbarState
setBufferState(item: playerState.currentItem)
controlbarHidden.value = controlbarState.hidden
}
func showHideControlbar(hidden: Bool) {
mainStore.dispatch(ShowHideControlbar(hidden: hidden))
}
func updatePlayerStatus(status: AVPlayerStatus) {
mainStore.dispatch(UpdatePlayerStatus(status: status))
}
func updatePlayerTimeControlStatus(status: AVPlayerTimeControlStatus) {
mainStore.dispatch(UpdateTimeControlStatus(status: status))
}
func updatePlayerItem(item: AVPlayerItem) {
mainStore.dispatch(UpdatePlayerItem(item: item))
}
func updatePlayerItemStatus(status: AVPlayerItemStatus) {
mainStore.dispatch(UpdatePlayerItemStatus(status: status))
}
func updateCurrentTime(time: CMTime) {
mainStore.dispatch(UpdatePlayerCurrentTime(currentTime: time.seconds))
}
func addControlbarHiddenTimer() {
let startTime = RxTimeInterval(10)
let interval = RxTimeInterval(10)
controlbarHiddenTimer = Observable<Int>.timer(startTime, period: interval, scheduler: MainScheduler.instance)
.subscribe(
onNext: { [weak self] _ in
self?.showHideControlbar(hidden: false)
self?.removeControlbarHiddenTimer()
}
)
}
func removeControlbarHiddenTimer() {
controlbarHiddenTimer?.dispose()
}
private func setBufferState(item: AVPlayerItem) {
if item.isPlaybackBufferEmpty {
buffering.value = true
} else if item.isPlaybackBufferFull || item.isPlaybackLikelyToKeepUp {
buffering.value = false
}
}
}
|
mit
|
87bcba55f9c2b1f7668f934700d540d4
| 27.290698 | 117 | 0.648582 | 4.78937 | false | false | false | false |
BillZong/ChessManualOfGo
|
ChessManualOfGo/ChessManualOfGo/Model/SGFParser.swift
|
1
|
3011
|
//
// SGFParser.swift
// ChessManualOfGo
//
// Created by BillZong on 16/1/9.
// Copyright © 2016年 BillZong. All rights reserved.
//
// SGF File Format Info(Come from wikipedia && SGF official guide):
// An SGF file is composed of pairs of properties and property values, each of which describes a feature of the game. A partial list of properties appears below. Full information can be found in the Official Guide.
//
// AB Add Black: locations of Black stones to be placed on the board prior to the first move
// AW Add White: locations of White stones to be placed on the board prior to the first move.
// AN Annotations: name of the person commenting the game.
// AP Application: application that was used to create the SGF file (e.g. CGOban2,...).
// B a move by Black at the location specified by the property value.
// BR Black Rank: rank of the Black player.
// BT Black Team: name of the Black team.
// C Comment: a comment.
// CP Copyright: copyright information.
// DT Date: date of the game.
// EV Event: name of the event (e.g. 58th Honinbō Title Match).
// FF File format: version of SGF specification governing this SGF file.
// GM Game: type of game represented by this SGF file. A property value of 1 refers to Go.
// GN Game Name: name of the game record.
// HA Handicap: the number of handicap stones given to Black. Placement of the handicap stones are set using the AB property.
// KM Komi: komi.
// ON Opening: information about the opening (Fuseki), rarely used in any file.
// OT Overtime: overtime system.
// PB Black Name: name of the black player.
// PC Place: place where the game was played (e.g.: Tokyo).
// PL Player: color of player to start.
// PW White Name: name of the white player.
// RE Result: result, usually in the format "B+R" (Black wins by resign) or "B+3.5" (black wins by 3.5).
// RO Round: round (e.g.: 5th game).
// RU Rules: ruleset (e.g.: Japanese).
// SO Source: source of the SGF file.
// SZ Size: size of the board, non-square boards are supported.
// TM Time limit: time limit in seconds.
// US User: name of the person who created the SGF file.
// W a move by White at the location specified by the property value.
// WR White Rank: rank of the White player.
// WT White Team: name of the White team.
import Foundation
public class SGFParser {
func parse(kifu: String)-> GameInfo {
let game = GameInfo()
// // Check out how many game in it.
// let gameNodes = kifu.components
let nodes = kifu.characters.split{ $0 == ";" }.map(String.init)
if nodes.count >= 2 { // It has to be larger than 2 for game info and move info.
let metaNode = nodes[1]
}
let moves = kifu.characters.split { $0 == ";" }
.map(String.init)
.filter { ($0.hasPrefix("B[") || $0.hasPrefix("W[")) && $0.characters.count == 5 }
.map { Move(step: $0 as String) }
print(moves)
game.allMoves = moves
return game
}
}
|
gpl-3.0
|
8d62935c68c65ed39e170b88de0b89ec
| 43.895522 | 214 | 0.669438 | 3.468281 | false | false | false | false |
ethansinjin/LoginKit
|
LoginKit/LoginKitRootViewController.swift
|
1
|
5670
|
//
// LoginKitRootViewController.swift
// LoginKit
//
// Created by Ethan eLink on 10/4/16.
// Copyright © 2016 Ethan Gill. All rights reserved.
//
import UIKit
public enum LoginKitErrorIndication {
case credentials
case network
case unknown
}
public class LoginKitRootViewController: UIViewController {
@IBOutlet weak var logoImageView: UIImageView!
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var usernameTextField: LoginKitTextField!
@IBOutlet weak var passwordTextField: LoginKitTextField!
@IBOutlet weak var loginBackgroundView: LoginKitSlantedView!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var scrollView: UIScrollView!
var backgroundImage: UIImage?
var logoImage: UIImage?
var interfaceTintColor: UIColor?
var buttonTextColor: UIColor?
var buttonText: String?
var callback: ((_ username:String, _ password:String, _ errorFunction: @escaping ((LoginKitErrorIndication) -> Void)) -> Void)?
public convenience init(backgroundImage: UIImage, logoImage: UIImage, tintColor: UIColor, buttonTextColor: UIColor, buttonText: String, callback: @escaping (_ username:String, _ password:String, _ errorFunction: @escaping ((LoginKitErrorIndication) -> Void)) -> Void) {
self.init(nibName: "LoginKitRootViewController", bundle: Bundle(for: type(of: self)))
self.backgroundImage = backgroundImage
self.logoImage = logoImage
self.interfaceTintColor = tintColor
self.buttonTextColor = buttonTextColor
self.buttonText = buttonText
self.callback = callback
}
public override func viewDidLoad() {
super.viewDidLoad()
backgroundImageView.image = backgroundImage
logoImageView.image = logoImage
loginBackgroundView.backgroundColor = interfaceTintColor
loginButton.setTitleColor(buttonTextColor, for: .normal)
usernameTextField.tintColor = UIColor.white
passwordTextField.tintColor = UIColor.white
usernameTextField.textColor = UIColor.white
passwordTextField.textColor = UIColor.white
let font = UIFont.systemFont(ofSize: 16.0, weight:UIFontWeightThin)
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center
paragraphStyle.lineBreakMode = NSLineBreakMode.byTruncatingTail
let attributes : [String: Any] = [
NSFontAttributeName : font,
NSParagraphStyleAttributeName : paragraphStyle,
NSForegroundColorAttributeName: UIColor.white
]
if let placeholder = usernameTextField.placeholder {
usernameTextField.attributedPlaceholder = NSAttributedString(string:placeholder, attributes: attributes)
}
if let placeholder = passwordTextField.placeholder {
passwordTextField.attributedPlaceholder = NSAttributedString(string:placeholder, attributes: attributes)
}
NotificationCenter.default.addObserver(self, selector:#selector(keyboardShown(_:)), name: .UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector:#selector(keyboardHidden(_:)), name: .UIKeyboardWillHide, object: nil)
}
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func signInPressed(_ sender: AnyObject) {
//guard text exists
guard let username = usernameTextField.text,
let password = passwordTextField.text else {
usernameTextField.shake()
passwordTextField.shake()
return
}
if let callback = callback {
callback(username, password, indicateError)
}
}
func keyboardShown(_ notification:NSNotification) {
if let userInfo = notification.userInfo {
if let keyboardSize = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {
let insets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
scrollView.contentInset = insets
scrollView.scrollIndicatorInsets = insets
var frameRect = self.view.frame
frameRect.size.height -= keyboardSize.height
if !frameRect.contains(passwordTextField.frame.origin) {
scrollView.scrollRectToVisible(passwordTextField.frame, animated: true)
}
}
}
}
func keyboardHidden(_ notification:NSNotification) {
let insets = UIEdgeInsets.zero
scrollView.contentInset = insets
scrollView.scrollIndicatorInsets = insets
}
public func indicateError(error: LoginKitErrorIndication) {
switch error {
case .credentials:
usernameTextField.shake()
passwordTextField.shake()
case .network:
// TODO: show an error message
break
case .unknown:
break
// TODO: show an error message
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
66263e284852c28a387ff2e311d8b170
| 37.828767 | 273 | 0.659023 | 5.76704 | false | false | false | false |
Mahmoud333/FileManager-Swift
|
FileManager-Swift/Classes/FileManagerVC.swift
|
1
|
18826
|
//
// FileManagerVC.swift
// NoorMagazine
//
// Created by mac on 7/12/17.
// Copyright © 2017 yassin abdelmaguid. All rights reserved.
//
import UIKit
//Controller - FileManagerVC
@available(iOS 9.0, *)
public class FileManagerVC: UIViewController {
var filess = [File]()
var ourDirectory: String? //our app my computer
var ourPathSteps = [String]() //every time we go inside folder will append its path & when press back will remove last path from array and go to last path before deleted one
//acts like a history for us
var currentPath: String?
//switches
var markIs = false {
didSet {
markBTN.setTitleColor(markIs == true ? UIColor.white : UIColor.lightGray, for: .normal)
markBTN.setImage(markIs == true ? UIImage(named: "messageindicatorchecked1") : UIImage(named: "messageindicator1"), for: .normal)
}
}
var markedFiles = [File]() { //files we marked and will deleted them
didSet {
deleteBtn.setTitleColor(markedFiles.count > 0 ? UIColor.white : UIColor.lightGray, for: .normal)
}
}
lazy var headerView: FancyView = self.configuerHeaderView()
lazy var collectionView: UICollectionView = self.configuerCollectionView()
lazy var markBTN: UIButton = self.configuerMarkBtn()
lazy var deleteBtn: UIButton = self.configuerDeleteBtn()
lazy var backBtn: UIButton = self.configuerBackBtn()
override public func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
collectionView.delegate = self; collectionView.dataSource = self
view.addSubview(collectionView)
view.addSubview(headerView)
view.addSubview(markBTN)
view.addSubview(backBtn)
view.addSubview(deleteBtn)
setHeaderViewConstraints()
setCollectionViewConstraints()
setButtonsContrainsts()
//register our cell
collectionView.register(FileCell.self, forCellWithReuseIdentifier: "FileCell")
ourDirectory = getDirectoryPath()
//ourPathSteps.append(ourDirectory!) dont need it but keep it 27teate
debugFM("\(ourDirectory)")
readFilesHere(path: ourDirectory!)
}
func readFilesHere(path: String) { //dont add nil or a path again to our list we did one
if currentPath != nil, !ourPathSteps.contains(currentPath!) {
}
//get the files inside this new path
let filesNames = contentsOfDirectoryAtPath(path: path)
currentPath = path //currentPath = the new path
ourPathSteps.append(currentPath!) //add our currentPath to history
printFM("currentPath \(currentPath)")
var thisPathFiles = [File]()
for file in filesNames! {
let cleanedFileName = file.replacingOccurrences(of: "\(currentPath!)/", with: "") //remove first path
var file: File?
//let fileType = cleanedFileName.remove before the .
if !cleanedFileName.contains(".") {
file = File(fileName: cleanedFileName, fileType: "file", filePath: currentPath!)
} else {
let fileType = cleanedFileName.components(separatedBy: ".").last
file = File(fileName: cleanedFileName, fileType: fileType!, filePath: currentPath!)
}
debugFM("fileName \(file?.fileName), filetype \(file?.fileType)")
thisPathFiles.append(file!)
}
filess = thisPathFiles
collectionView.reloadData()
}
@IBAction func markTapped(_ sender: Any) {
markIs = markIs == false ? true : false
}
@IBAction func deleteFilesPressed(_ sender: Any){
AlertDismiss(t: "Deleting Files", msg: "Are you sure you wanna delete this files") { [unowned self] _ in
debugFM("User tapped yes delete")
if self.markIs == true {
if (self.collectionView.indexPathsForSelectedItems?.count)! > 0 {
//if markedFiles.count > 0 {
let selectedCellsIndex = self.collectionView.indexPathsForSelectedItems
for index in selectedCellsIndex! {
let file = self.filess[index.row]
self.markedFiles.append(file)
}
for markedFile in self.markedFiles { //loop through markedFiles
var fileName: String!
//get its name.type
if markedFile.fileType != "file" {
fileName = markedFile.fileName
} else {
fileName = markedFile.fileName
}
//get its path mycomputer/name.type
let fullMarkedFilePath = "\(self.currentPath!)/\(fileName!)"
//start deleting operation
do {
let fileManager = FileManager.default
// Check if file exists
if fileManager.fileExists(atPath: fullMarkedFilePath) {
// Delete file
try fileManager.removeItem(atPath: fullMarkedFilePath)
printFM("File deleted")
} else {
printFM("File does not exist at path \(fullMarkedFilePath)")
}
}
catch let error as NSError {
printFM("error with deleting -- \(error)")
}
}
//after delete cV will select cell instead of the removed one
for cell in self.collectionView.visibleCells {
cell.backgroundColor = UIColor(white: 0.92, alpha: 1.0)
}
self.readFilesHere(path: self.currentPath!)
self.collectionView.reloadData()
self.markIs = false
}
}
}
}
@IBAction func backTapped(_ sender: Any) {
if ourPathSteps.count <= 1 { //we are in mycomputer cant go more back
debugFM("backButton count \(ourPathSteps.count)")
//AlertDismiss(t: "Leaving File Manager", msg: "Are you sure?")
AlertDismiss(t: "Leaving File Manager", msg: "Are you sure?", yesCompletion: {
self.dismiss(animated: true, completion: nil)
})
;return
}
ourPathSteps.removeLast() //remove the last(our current)
debugFM("backButton ourPathSteps after last one removed \(ourPathSteps)")
readFilesHere(path: ourPathSteps.last!) //go to the one before our current
debugFM("backButton ourPathSteps.last! \(ourPathSteps.last!)")
markedFiles.removeAll()
ourPathSteps.removeLast() //remove again, had a bug that when we enter folder and back from it it will add the documents address, + 1, 2 , 3, 4 so have to do it twice, remove current, remove the new back(opened)
}
}
@available(iOS 9.0, *)
extension FileManagerVC: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FileCell", for: indexPath) as? FileCell {
let fileName = filess[indexPath.row].fileName
let fileType = filess[indexPath.row].fileType
let filePath = filess[indexPath.row].filePath
cell.configuerCell(fileName: fileName, fileType: fileType, filePath: filePath)
//People Decide the images by code Version
/*
//New Edit
//Set Image
switch fileType {
case "file" : cell.fileImageV.image = FileManagerVC._imagess["file"]
case "zip" : cell.fileImageV.image = FileManagerVC._imagess["zip"]
case "3gp" : cell.fileImageV.image = FileManagerVC._imagess["3gp"]
case "jpg" : cell.fileImageV.image = FileManagerVC._imagess["jpg"]
case "json" : cell.fileImageV.image = FileManagerVC._imagess["json"]
case "mp4" : cell.fileImageV.image = FileManagerVC._imagess["mp4"]
case "pdf" : cell.fileImageV.image = FileManagerVC._imagess["pdf"]
case "png" : cell.fileImageV.image = FileManagerVC._imagess["png"]
case "txt" : cell.fileImageV.image = FileManagerVC._imagess["txt"]
case "xml" : cell.fileImageV.image = FileManagerVC._imagess["xml"]
case "zip" : cell.fileImageV.image = FileManagerVC._imagess["zip"]
default:
break;
}*/
return cell
}
return UICollectionViewCell()
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return filess.count
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedFile = filess[indexPath.row]
if markIs == false {
if selectedFile.fileType == "file" {
readFilesHere(path: "\(currentPath!)/\(selectedFile.fileName)")
//currentPath + . + selectedFile type
//go to this path, show whats inside it, update collectionV
}
} else {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor.darkGray
}
}
public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath)
cell?.backgroundColor = UIColor(white: 0.92, alpha: 1.0)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if customizations.cellType == .titleAndSize {
return CGSize(width: 114, height: 130)
} else {
return CGSize(width: 114, height: 114)
}
}
/*
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 50.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 100.0
}*/
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(14, 20, 14, 20)
}
}
//Model - File
class File {
private var _fileName: String?
private var _fileType: String?
private var _filePath: String?
init(fileName: String, fileType: String,filePath: String) {
_fileName = fileName
_fileType = fileType
_filePath = filePath
}
var fileName: String {
get { if _fileName == nil { return "" }
return _fileName!
} set {
_fileName = newValue
}
}
var fileType: String {
get { if _fileType == nil { return "" }
return _fileType!
} set {
_fileType = newValue
}
}
var filePath: String {
get { if _filePath == nil { return "" }
return _filePath!
} set {
_filePath = newValue
}
}
}
//View - FileCell
@available(iOS 9.0, *)
class FileCell: UICollectionViewCell {
var fileImageV: UIImageView = {
let piv = UIImageView()
piv.translatesAutoresizingMaskIntoConstraints = false
piv.clipsToBounds = true
piv.contentMode = .scaleAspectFit
return piv
}()
var fileNameLbl: UILabel = {
let lbl = UILabel()
lbl.translatesAutoresizingMaskIntoConstraints = false
lbl.font = UIFont(name: "Avenir", size: 18)
lbl.minimumScaleFactor = 0.5
lbl.textAlignment = .center
lbl.numberOfLines = 0
return lbl
}()
var fileSubTitleLbl: UILabel = {
let lbl = UILabel()
lbl.translatesAutoresizingMaskIntoConstraints = false
lbl.font = UIFont(name: "Avenir", size: 12)
lbl.textColor = .darkGray
lbl.minimumScaleFactor = 0.5
lbl.textAlignment = .center
lbl.numberOfLines = 0
return lbl
}()
var cellTitle: CellType = customizations.cellType ?? .title
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(fileImageV)
self.addSubview(fileNameLbl)
self.contentMode = .center
self.clipsToBounds = true
if customizations.cellType == .titleAndSize {
self.addSubview(fileSubTitleLbl)
//fileSize label constraints
fileSubTitleLbl.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor).isActive = true
fileSubTitleLbl.topAnchor.constraint(equalTo: fileNameLbl.bottomAnchor).isActive = true
fileSubTitleLbl.widthAnchor.constraint(equalTo: self.contentView.widthAnchor, constant: -6).isActive = true
fileSubTitleLbl.heightAnchor.constraint(greaterThanOrEqualTo: self.contentView.heightAnchor, multiplier: 0.20).isActive = true
//fileName label constraints
fileNameLbl.bottomAnchor.constraint(equalTo: fileSubTitleLbl.topAnchor, constant: 2).isActive = true
fileNameLbl.widthAnchor.constraint(equalTo: self.contentView.widthAnchor, constant: -6).isActive = true
fileNameLbl.heightAnchor.constraint(greaterThanOrEqualTo: self.contentView.heightAnchor, multiplier: 0.18).isActive = true
//Image constraints
fileImageV.topAnchor.constraint(equalTo: self.topAnchor, constant: 2).isActive = true
fileImageV.widthAnchor.constraint(equalTo: self.contentView.widthAnchor, constant: -6).isActive = true
fileImageV.bottomAnchor.constraint(equalTo: fileNameLbl.topAnchor, constant: -5).isActive = true
//fileImageV.heightAnchor.constraint(equalTo: contentView.heightAnchor, multiplier: 0.67).isActive = true
} else {
//Image constraints
fileImageV.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor).isActive = true
fileImageV.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
fileImageV.widthAnchor.constraint(equalTo: self.contentView.widthAnchor, constant: -6).isActive = true
fileImageV.heightAnchor.constraint(equalTo: contentView.heightAnchor, multiplier: 0.75).isActive = true
//fileName label constraints
fileNameLbl.centerXAnchor.constraint(equalTo: self.contentView.centerXAnchor).isActive = true
fileNameLbl.topAnchor.constraint(equalTo: fileImageV.bottomAnchor).isActive = true
fileNameLbl.widthAnchor.constraint(equalTo: self.contentView.widthAnchor, constant: -6).isActive = true
fileNameLbl.heightAnchor.constraint(greaterThanOrEqualTo: self.contentView.heightAnchor, multiplier: 0.25).isActive = true
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func configuerCell(fileName: String, fileType: String, filePath: String) {
self.backgroundColor = UIColor(white: 0.92, alpha: 1.0)
self.layer.cornerRadius = 7
self.layer.masksToBounds = true
switch cellTitle {
case .title:
fileNameLbl.text = fileName
case .titleAndSize:
//Get File Size
//let filePath = "\(filePath)/\(fileName).\(fileType)"
let filePath = "\(filePath)/\(fileName)"
//Set Title
switch fileType {
case "file":
fileNameLbl.text = fileName
fileSubTitleLbl.text = "Directory"
case "zip", "3gp", "jpg", "json", "mp4", "pdf", "txt", "xml", "zip", "png","jpg","jpeg":
let size = fileSize(fromPath: filePath)
fileNameLbl.text = fileName
fileSubTitleLbl.text = size ?? String()
default:
fileNameLbl.text = fileName
break;
}
}
//Set Image Part
switch fileType {
case "file" : fileImageV.image = UIImage(named: "file")
case "zip" : fileImageV.image = UIImage(named: "zip")
case "3gp" : fileImageV.image = UIImage(named: "3gp")
case "jpg" : fileImageV.image = UIImage(named: "jpg")
case "json" : fileImageV.image = UIImage(named: "json")
case "mp4" : fileImageV.image = UIImage(named: "mp4")
case "pdf" : fileImageV.image = UIImage(named: "pdf")
case "txt" : fileImageV.image = UIImage(named: "txt")
case "xml" : fileImageV.image = UIImage(named: "xml")
case "zip" : fileImageV.image = UIImage(named: "zip")
case "png","jpg","jpeg":
//debugFM("\(filePath)/\(fileName).\(fileType)")
let url = URL(fileURLWithPath: "\(filePath)/\(fileName).\(fileType)")
fileImageV.image = UIImage(contentsOfFile: url.path)
default:
break;
}
}
}
|
mit
|
37e070314cd6f32765ec1f9a65353d69
| 38.883475 | 233 | 0.574024 | 5.207469 | false | false | false | false |
mateuszfidosBLStream/MFCircleDialPad
|
MFCircleDialPad/MFDialPadLayerAnimator.swift
|
1
|
2262
|
//
// DialPadAnimator.swift
// CircleDialPad
//
// Created by Mateusz Fidos on 24.05.2016.
// Copyright © 2016 mateusz.fidos. All rights reserved.
//
import Foundation
import UIKit
let kDefaultLayerAnimationDuration:CGFloat = 0.5
let kDefaultItemAnimationDuration:CGFloat = 0.2
let kDefaultStartAngle:Float = 90.0;
class MFDialPadLayerAnimator
{
let items:[MFDialPadItemView]
let dial:MFDialPadDialingLayer
init(items:[MFDialPadItemView], dialLayer:MFDialPadDialingLayer)
{
self.items = items
self.dial = dialLayer
}
func fillDialLayerAnimation(duration: CGFloat, startAngle: Float)
{
guard let animationLayer = self.dial.dialLayer else
{
return
}
let rotateTransform = CATransform3DMakeRotation(CGFloat(startAngle.degrees), 0, 0, 1)
self.dial.layer.transform = rotateTransform
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.duration = CFTimeInterval(duration)
animation.fromValue = (0)
animation.toValue = (1)
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
animationLayer.addAnimation(animation, forKey: nil)
}
func hideDialLayerAnimation(duration: CGFloat, delay: CGFloat)
{
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.toValue = 1.2
scaleAnimation.duration = CFTimeInterval(duration)
scaleAnimation.fillMode = kCAFillModeForwards
scaleAnimation.removedOnCompletion = false
scaleAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
scaleAnimation.beginTime = CACurrentMediaTime() + Double(delay)
self.dial.layer.addAnimation(scaleAnimation, forKey: nil)
UIView.animateWithDuration(
CFTimeInterval(duration),
delay: Double(delay),
options: UIViewAnimationOptions.CurveEaseIn,
animations: { () -> Void in
self.dial.alpha = 0
},
completion: { (success) -> Void in
self.dial.removeFromSuperview()
})
}
}
|
mit
|
58baea25376c01283147d77180f28dac
| 30.859155 | 103 | 0.658116 | 5.002212 | false | false | false | false |
benlangmuir/swift
|
test/attr/attr_availability_transitive_osx.swift
|
4
|
6462
|
// RUN: %target-typecheck-verify-swift -parse-as-library
// REQUIRES: OS=macosx
// Allow referencing unavailable API in situations where the caller is marked unavailable in the same circumstances.
@available(OSX, unavailable)
@discardableResult
func osx() -> Int { return 0 } // expected-note * {{'osx()' has been explicitly marked unavailable here}}
@available(OSXApplicationExtension, unavailable)
func osx_extension() {}
@available(OSX, unavailable)
func osx_pair() -> (Int, Int) { return (0, 0) } // expected-note * {{'osx_pair()' has been explicitly marked unavailable here}}
func call_osx_extension() {
osx_extension() // OK; osx_extension is only unavailable if -application-extension is passed.
}
func call_osx() {
osx() // expected-error {{'osx()' is unavailable}}
}
@available(OSX, unavailable)
func osx_call_osx_extension() {
osx_extension() // OK; osx_extension is only unavailable if -application-extension is passed.
}
@available(OSX, unavailable)
func osx_call_osx() {
osx() // OK; same
}
@available(OSXApplicationExtension, unavailable)
func osx_extension_call_osx_extension() {
osx_extension()
}
@available(OSXApplicationExtension, unavailable)
func osx_extension_call_osx() {
osx() // expected-error {{'osx()' is unavailable}}
}
@available(OSX, unavailable)
var osx_init_osx = osx() // OK
@available(OSXApplicationExtension, unavailable)
var osx_extension_init_osx = osx() // expected-error {{'osx()' is unavailable}}
@available(OSX, unavailable)
var osx_inner_init_osx = { let inner_var = osx() } // OK
@available(OSXApplicationExtension, unavailable)
var osx_extension_inner_init_osx = { let inner_var = osx() } // expected-error {{'osx()' is unavailable}}
struct Outer {
@available(OSX, unavailable)
var osx_init_osx = osx() // OK
@available(OSX, unavailable)
lazy var osx_lazy_osx = osx() // OK
@available(OSXApplicationExtension, unavailable)
var osx_extension_init_osx = osx() // expected-error {{'osx()' is unavailable}}
@available(OSXApplicationExtension, unavailable)
var osx_extension_lazy_osx = osx() // expected-error {{'osx()' is unavailable}}
@available(OSX, unavailable)
var osx_init_multi1_osx = osx(), osx_init_multi2_osx = osx() // OK
@available(OSXApplicationExtension, unavailable)
var osx_extension_init_multi1_osx = osx(), osx_extension_init_multi2_osx = osx() // expected-error 2 {{'osx()' is unavailable}}
@available(OSX, unavailable)
var (osx_init_deconstruct1_osx, osx_init_deconstruct2_osx) = osx_pair() // OK
@available(OSXApplicationExtension, unavailable)
var (osx_extension_init_deconstruct1_osx, osx_extension_init_deconstruct2_osx) = osx_pair() // expected-error {{'osx_pair()' is unavailable}}
@available(OSX, unavailable)
var (_, osx_init_deconstruct2_only_osx) = osx_pair() // OK
@available(OSXApplicationExtension, unavailable)
var (_, osx_extension_init_deconstruct2_only_osx) = osx_pair() // expected-error {{'osx_pair()' is unavailable}}
@available(OSX, unavailable)
var (osx_init_deconstruct1_only_osx, _) = osx_pair() // OK
@available(OSXApplicationExtension, unavailable)
var (osx_extension_init_deconstruct1_only_osx, _) = osx_pair() // expected-error {{'osx_pair()' is unavailable}}
@available(OSX, unavailable)
var osx_inner_init_osx = { let inner_var = osx() } // OK
@available(OSXApplicationExtension, unavailable)
var osx_extension_inner_init_osx = { let inner_var = osx() } // expected-error {{'osx()' is unavailable}}
}
extension Outer {
@available(OSX, unavailable)
static var also_osx_init_osx = osx() // OK
@available(OSXApplicationExtension, unavailable)
static var also_osx_extension_init_osx = osx() // expected-error {{'osx()' is unavailable}}
}
@available(OSX, unavailable)
extension Outer {
// expected-note@+1 {{'outer_osx_init_osx' has been explicitly marked unavailable here}}
static var outer_osx_init_osx = osx() // OK
// expected-note@+1 {{'osx_call_osx()' has been explicitly marked unavailable here}}
func osx_call_osx() {
osx() // OK
}
func osx_call_osx_extension() {
osx_extension() // OK; osx_extension is only unavailable if -application-extension is passed.
}
func takes_and_returns_osx(_ x: NotOnOSX) -> NotOnOSX {
return x // OK
}
// This @available should be ignored; inherited unavailability takes precedence
@available(OSX 999, *)
// expected-note@+1 {{'osx_more_available_but_still_unavailable_call_osx()' has been explicitly marked unavailable here}}
func osx_more_available_but_still_unavailable_call_osx() {
osx() // OK
}
// rdar://92551870
func osx_call_osx_more_available_but_still_unavailable() {
osx_more_available_but_still_unavailable_call_osx() // OK
}
}
func takesOuter(_ o: Outer) {
_ = Outer.outer_osx_init_osx // expected-error {{'outer_osx_init_osx' is unavailable in macOS}}
o.osx_call_osx() // expected-error {{'osx_call_osx()' is unavailable in macOS}}
o.osx_more_available_but_still_unavailable_call_osx() // expected-error {{'osx_more_available_but_still_unavailable_call_osx()' is unavailable in macOS}}
}
@available(OSX, unavailable)
struct NotOnOSX { // expected-note {{'NotOnOSX' has been explicitly marked unavailable here}}
var osx_init_osx = osx() // OK
lazy var osx_lazy_osx = osx() // OK
var osx_init_multi1_osx = osx(), osx_init_multi2_osx = osx() // OK
var (osx_init_deconstruct1_osx, osx_init_deconstruct2_osx) = osx_pair() // OK
var (_, osx_init_deconstruct2_only_osx) = osx_pair() // OK
var (osx_init_deconstruct1_only_osx, _) = osx_pair() // OK
}
@available(OSX, unavailable)
extension NotOnOSX {
func osx_call_osx() {
osx() // OK
}
func osx_call_osx_extension() {
osx_extension() // OK; osx_extension is only unavailable if -application-extension is passed.
}
}
@available(OSXApplicationExtension, unavailable)
extension NotOnOSX { } // expected-error {{'NotOnOSX' is unavailable in macOS}}
@available(OSXApplicationExtension, unavailable)
struct NotOnOSXApplicationExtension { }
@available(OSX, unavailable)
extension NotOnOSXApplicationExtension { } // OK; NotOnOSXApplicationExtension is only unavailable if -application-extension is passed.
@available(OSXApplicationExtension, unavailable)
extension NotOnOSXApplicationExtension {
func osx_call_osx() {
osx() // expected-error {{'osx()' is unavailable in macOS}}
}
func osx_call_osx_extension() {
osx_extension() // OK
}
}
|
apache-2.0
|
2a9a5e72f75c616d1f1e2654f57595a5
| 34.311475 | 155 | 0.702414 | 3.694683 | false | false | false | false |
fizx/jane
|
ruby/lib/vendor/grpc-swift/Sources/SwiftGRPC/Runtime/ServerSessionBidirectionalStreaming.swift
|
4
|
3066
|
/*
* Copyright 2018, gRPC Authors 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 Dispatch
import Foundation
import SwiftProtobuf
public protocol ServerSessionBidirectionalStreaming: ServerSession {
func waitForSendOperationsToFinish()
}
open class ServerSessionBidirectionalStreamingBase<InputType: Message, OutputType: Message>: ServerSessionBase, ServerSessionBidirectionalStreaming, StreamReceiving, StreamSending {
public typealias ReceivedType = InputType
public typealias SentType = OutputType
public typealias ProviderBlock = (ServerSessionBidirectionalStreamingBase) throws -> ServerStatus?
private var providerBlock: ProviderBlock
public init(handler: Handler, providerBlock: @escaping ProviderBlock) {
self.providerBlock = providerBlock
super.init(handler: handler)
}
public func run() throws -> ServerStatus? {
try sendInitialMetadataAndWait()
do {
return try self.providerBlock(self)
} catch {
// Errors thrown by `providerBlock` should be logged in that method;
// we return the error as a status code to avoid `ServiceServer` logging this as a "really unexpected" error.
return (error as? ServerStatus) ?? .processingError
}
}
}
/// Simple fake implementation of ServerSessionBidirectionalStreaming that returns a previously-defined set of results
/// and stores sent values for later verification.
open class ServerSessionBidirectionalStreamingTestStub<InputType: Message, OutputType: Message>: ServerSessionTestStub, ServerSessionBidirectionalStreaming {
open var lock = Mutex()
open var inputs: [InputType] = []
open var outputs: [OutputType] = []
open var status: ServerStatus?
open func _receive(timeout: DispatchTime) throws -> InputType? {
return lock.synchronize {
defer { if !inputs.isEmpty { inputs.removeFirst() } }
return inputs.first
}
}
open func receive(completion: @escaping (ResultOrRPCError<InputType?>) -> Void) throws {
completion(.result(try self._receive(timeout: .distantFuture)))
}
open func send(_ message: OutputType, completion _: @escaping (Error?) -> Void) throws {
lock.synchronize { outputs.append(message) }
}
open func _send(_ message: OutputType, timeout: DispatchTime) throws {
lock.synchronize { outputs.append(message) }
}
open func close(withStatus status: ServerStatus, completion: (() -> Void)?) throws {
lock.synchronize { self.status = status }
completion?()
}
open func waitForSendOperationsToFinish() {}
}
|
mit
|
cb2346e509e9ab94034a8b4e9ec080b6
| 35.939759 | 181 | 0.741357 | 4.576119 | false | false | false | false |
SuPair/iContactU
|
iContactU/ContactCellTableViewCell.swift
|
2
|
880
|
//
// ContactCellTableViewCell.swift
// ContactU
//
// Created by Training on 21/07/14.
// Copyright (c) 2014 Training. All rights reserved.
//
import UIKit
class ContactCellTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel! = UILabel()
@IBOutlet weak var phoneLabel: UILabel! = UILabel()
@IBOutlet weak var emailLabel: UILabel! = UILabel()
@IBOutlet weak var contactImageView: UIImageView! = UIImageView()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func layoutSubviews() {
//RESIZE IMAGE VIEW!
self.contactImageView.frame = CGRectMake(0, 0, 75, 75)
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
ec32bb7a3a2b8bfba4cb26e91353f1ef
| 25.666667 | 69 | 0.668182 | 4.512821 | false | false | false | false |
avito-tech/Paparazzo
|
Example/PaparazzoTests/Mocks/PhotoKit/PHAssetFetchResultChangeDetailsMock.swift
|
1
|
5674
|
import Photos
final class PHAssetFetchResultChangeDetailsMock: PHFetchResultChangeDetails<PHAsset> {
private let isStrict: Bool
private var mockedFetchResultBeforeChanges: PHAssetFetchResultMock?
private var mockedFetchResultAfterChanges: PHAssetFetchResultMock?
private var mockedRemovedIndexes: IndexSet??
private var mockedRemovedObjects: [PHAssetMock]?
private var mockedInsertedIndexes: IndexSet??
private var mockedInsertedObjects: [PHAssetMock]?
private var mockedChangedIndexes: IndexSet??
private var mockedChangedObjects: [PHAssetMock]?
private var mockedMoves: [(Int, Int)]?
/**
Strict mock will fail if method is being called for which mock value hasn't been provided by the user.
If mock is not strict, it will try to substitude default values for such calls whenever possible.
*/
init(isStrict: Bool) {
self.isStrict = isStrict
}
// MARK: - Setting mock values
func setFetchResultBeforeChanges(_ fetchResultBeforeChanges: PHAssetFetchResultMock) {
mockedFetchResultBeforeChanges = fetchResultBeforeChanges
}
func setFetchResultAfterChanges(_ fetchResultAfterChanges: PHAssetFetchResultMock) {
mockedFetchResultAfterChanges = fetchResultAfterChanges
}
func setRemovedIndexes(_ removedIndexes: IndexSet?) {
mockedRemovedIndexes = removedIndexes
}
func setRemovedObjects(_ removedObjects: [PHAssetMock]) {
mockedRemovedObjects = removedObjects
}
func setInsertedIndexes(_ insertedIndexes: IndexSet?) {
mockedInsertedIndexes = insertedIndexes
}
func setInsertedObjects(_ insertedObjects: [PHAssetMock]) {
mockedInsertedObjects = insertedObjects
}
func setChangedIndexes(_ changedIndexes: IndexSet?) {
mockedChangedIndexes = changedIndexes
}
func setChangedObjects(_ changedObjects: [PHAssetMock]) {
mockedChangedObjects = changedObjects
}
func setMoves(_ moves: [(Int, Int)]) {
mockedMoves = moves
}
// MARK: - PHFetchResultChangeDetails
override var fetchResultBeforeChanges: PHFetchResult<PHAsset> {
if let mockedFetchResultBeforeChanges = mockedFetchResultBeforeChanges {
return mockedFetchResultBeforeChanges
} else if isStrict {
fatalError("`fetchResultBeforeChanges` is not mocked. Call `setFetchResultBeforeChanges(_:)` first.")
} else {
return PHAssetFetchResultMock(assets: [])
}
}
override var fetchResultAfterChanges: PHFetchResult<PHAsset> {
if let mockedFetchResultAfterChanges = mockedFetchResultAfterChanges {
return mockedFetchResultAfterChanges
} else if isStrict {
fatalError("`fetchResultAfterChanges` is not mocked. Call `setFetchResultAfterChanges(_:)` first.")
} else {
return PHAssetFetchResultMock(assets: [])
}
}
override var hasIncrementalChanges: Bool {
fatalError("`hasIncrementalChanges` is not mocked. Call `setHasIncrementalChanges(_:)` first.")
}
override var removedIndexes: IndexSet? {
if let mockedRemovedIndexes = mockedRemovedIndexes {
return mockedRemovedIndexes
} else if isStrict {
fatalError("`removedIndexes` is not mocked. Call `setRemovedIndexes(_:)` first.")
} else {
return nil
}
}
override var removedObjects: [PHAsset] {
if let mockedRemovedObjects = mockedRemovedObjects {
return mockedRemovedObjects
} else if isStrict {
fatalError("`removedObjects` is not mocked. Call `setRemovedObjects(_:)` first.")
} else {
return []
}
}
override var insertedIndexes: IndexSet? {
if let mockedInsertedIndexes = mockedInsertedIndexes {
return mockedInsertedIndexes
} else if isStrict {
fatalError("`insertedIndexes` is not mocked. Call `setInsertedIndexes(_:)` first.")
} else {
return nil
}
}
override var insertedObjects: [PHAsset] {
if let mockedInsertedObjects = mockedInsertedObjects {
return mockedInsertedObjects
} else if isStrict {
fatalError("`insertedObjects` is not mocked. Call `setInsertedObjects(_:)` first.")
} else {
return []
}
}
override var changedIndexes: IndexSet? {
if let mockedChangedIndexes = mockedChangedIndexes {
return mockedChangedIndexes
} else if isStrict {
fatalError("`changedIndexes` is not mocked. Call `setChangedIndexes(_:)` first.")
} else {
return nil
}
}
override var changedObjects: [PHAsset] {
if let mockedChangedObjects = mockedChangedObjects {
return mockedChangedObjects
} else if isStrict {
fatalError("`changedObjects` is not mocked. Call `setChangedObjects(_:)` first.")
} else {
return []
}
}
override func enumerateMoves(_ handler: @escaping (Int, Int) -> Void) {
if let mockedMoves = mockedMoves {
mockedMoves.forEach { from, to in
handler(from, to)
}
} else if isStrict {
fatalError("`enumerateMoves(_:)` is not mocked. Call `setMoves(_:)` first.")
} else {
// Nothing to enumerate
}
}
override var hasMoves: Bool {
fatalError("`hasMoves` is not mocked. Call `setHasMoves(_:)` first.")
}
}
|
mit
|
0d3fb1a2e854c859d665f22a48ad127a
| 34.242236 | 113 | 0.640994 | 5.546432 | false | false | false | false |
adrfer/swift
|
test/SILGen/objc_final.swift
|
14
|
1028
|
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -emit-verbose-sil | FileCheck %s
// REQUIRES: objc_interop
import Foundation
final class Foo {
@objc func foo() {}
// CHECK-LABEL: sil hidden [thunk] @_TToFC10objc_final3Foo3foo
@objc var prop: Int = 0
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC10objc_final3Foog4propSi
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC10objc_final3Foos4propSi
}
// CHECK-LABEL: sil hidden @_TF10objc_final7callFooFCS_3FooT_
func callFoo(x: Foo) {
// Calls to the final @objc method statically reference the native entry
// point.
// CHECK: function_ref @_TFC10objc_final3Foo3foo
x.foo()
// Final @objc properties are still accessed directly.
// CHECK: [[PROP:%.*]] = ref_element_addr {{%.*}} : $Foo, #Foo.prop
// CHECK: load [[PROP]] : $*Int
let prop = x.prop
// CHECK: [[PROP:%.*]] = ref_element_addr {{%.*}} : $Foo, #Foo.prop
// CHECK: assign {{%.*}} to [[PROP]] : $*Int
x.prop = prop
}
|
apache-2.0
|
9ad882697ea5b3e569915d809d8fe66f
| 33.266667 | 129 | 0.656615 | 3.242902 | false | false | false | false |
Frainbow/ShaRead.frb-swift
|
ShaRead/ShaRead/BookStatusViewController.swift
|
1
|
3979
|
//
// BookStatusViewController.swift
// ShaRead
//
// Created by martin on 2016/4/26.
// Copyright © 2016年 Frainbow. All rights reserved.
//
import UIKit
import PKHUD
protocol BookStatusDelegate: class {
func statusSaved()
}
class BookStatusViewController: UIViewController {
@IBOutlet weak var inputTextView: UITextView!
@IBOutlet weak var placeholder: UILabel!
@IBOutlet weak var inputLengthLabel: UILabel!
weak var delegate: BookStatusDelegate?
weak var book: ShaBook?
let maxInputLength: Int = 60
override func viewDidLoad() {
super.viewDidLoad()
if let book = self.book {
if book.status.characters.count > 0 {
inputTextView.text = book.status
placeholder.hidden = true
}
}
inputLengthLabel.text = "(\(inputTextView.text.characters.count) / \(maxInputLength))"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func save(sender: AnyObject) {
if let inputText = inputTextView.text {
if inputText.characters.count == 0 {
let controller = UIAlertController(title: "錯誤", message: "請描述一下這本書的概況", preferredStyle: .Alert)
controller.addAction(UIAlertAction(title: "確定", style: .Default, handler: nil))
presentViewController(controller, animated: true, completion: nil)
return
}
if let book = self.book {
let originStatus = book.status
self.book?.status = inputText
HUD.show(.Progress)
ShaManager.sharedInstance.updateAdminBook(book, column: [.ShaBookStatus],
success: {
HUD.hide()
self.delegate?.statusSaved()
self.navigationController?.popViewControllerAnimated(true)
},
failure: {
self.book?.status = originStatus
HUD.flash(.Error)
}
)
}
} else {
let controller = UIAlertController(title: "錯誤", message: "請描述一下這本書的概況", preferredStyle: .Alert)
controller.addAction(UIAlertAction(title: "確定", style: .Default, handler: nil))
presentViewController(controller, animated: true, completion: nil)
}
}
@IBAction func dismissKeyboard(sender: AnyObject) {
self.view.endEditing(true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func navBack(sender: AnyObject) {
self.navigationController?.popViewControllerAnimated(true)
}
}
extension BookStatusViewController: UITextViewDelegate {
func textViewDidChange(textView: UITextView) {
let length = textView.text.characters.count
if length <= maxInputLength {
inputLengthLabel.text = "(\(length) / \(maxInputLength))"
} else {
textView.text = String(textView.text.characters.dropLast())
}
}
func textViewDidBeginEditing(textView: UITextView) {
placeholder.hidden = true
}
func textViewDidEndEditing(textView: UITextView) {
let length = textView.text.characters.count
if length == 0 {
placeholder.hidden = false
}
}
}
|
mit
|
ef69e84d3c772890cef4d468827ef0f3
| 29.834646 | 111 | 0.582737 | 5.15942 | false | false | false | false |
jemartti/Hymnal
|
Hymnal/Hymn.swift
|
1
|
815
|
//
// Hymn.swift
// Hymnal
//
// Created by Jacob Marttinen on 5/9/17.
// Copyright © 2017 Jacob Marttinen. All rights reserved.
//
import Foundation
// MARK: - Hymn
struct Hymn {
// MARK: Properties
let verses: [String]
let chorus: String?
let refrain: String?
// MARK: Initialisers
init(dictionary: [String:AnyObject]) {
verses = dictionary["verses"] as! [String]
chorus = dictionary["chorus"] as? String
refrain = dictionary["refrain"] as? String
}
static func hymnsFromDictionary(_ results: [[String:AnyObject]]) -> [Hymn] {
var hymns = [Hymn]()
for result in results {
let hymn = Hymn(dictionary: result)
hymns.append(hymn)
}
return hymns
}
}
|
mit
|
b76fd14110fa45529f3a69b392773079
| 19.871795 | 80 | 0.561425 | 3.650224 | false | false | false | false |
LYM-mg/DemoTest
|
其他功能/Demo/Demo/LoadDataTool.swift
|
1
|
1996
|
//
// LoadDataTool.swift
// yifanjie
//
// Created by i-Techsys.com on 2017/7/18.
// Copyright © 2017年 hsiao. All rights reserved.
//
import UIKit
class LoadDataTool {
static func loadAreaData() -> [Area] {
let path = Bundle.main.path(forResource: "area", ofType: "json")
let data: Data = NSData(contentsOfFile: path!)! as Data
guard let rootArr = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [[String: Any]] else { return []}
var tempArr: [Area] = [Area]()
for dict in rootArr! {
tempArr.append(Area(dict: dict))
}
return tempArr
}
}
class Area: BaseModel {
var area_id: String = ""
var title: String = ""
var pid: String = ""
var sort: String = ""
var son: [City]!
override func setValue(_ value: Any?, forKey key: String) {
// 1.判断当前取出的key是否是Area
if key == "son" {
// 如果是Area就交给下一级的model去处理
var models = [City]()
for dict in value as! [[String: AnyObject]] {
models.append(City(dict: dict))
}
son = models
return
}
// 2.否则,父类初始化
super.setValue(value, forKey: key)
}
}
class City: BaseModel {
var area_id:String = ""
var title:String = ""
var pid:String = ""
var sort:String = ""
var son:Int = 0
}
class BaseModel: NSObject {
override init(){
super.init()
}
init(dict: [String: Any]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {
}
}
/**
"area_id":"110000","title":"北京市","pid":"0","sort":"1","son":[{"area_id":"110100","title":"北京市","pid":"110000","sort":"1"},{"area_id":"110200","title":"县","pid":"110000","sort":"2"}]},{"area_id":"120000","title":"天津市","pid":"0","sort":"2",
*/
|
mit
|
3c79bddb68c60c6842d06a4421a8e1be
| 25.915493 | 239 | 0.543694 | 3.60566 | false | false | false | false |
joerocca/GitHawk
|
Classes/Issues/Comments/Markdown/MMElement+Attributes.swift
|
1
|
3494
|
//
// MMElement+Attributes.swift
// Freetime
//
// Created by Ryan Nystrom on 6/17/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import MMMarkdown
func PushAttributes(
element: MMElement,
current: [NSAttributedStringKey: Any],
listLevel: Int
) -> [NSAttributedStringKey: Any] {
let currentFont: UIFont = current[.font] as? UIFont ?? Styles.Fonts.body
// TODO: cleanup
let paragraphStyleCopy: NSMutableParagraphStyle
if let para = (current[.paragraphStyle] as? NSParagraphStyle)?.mutableCopy() as? NSMutableParagraphStyle {
paragraphStyleCopy = para
} else {
paragraphStyleCopy = NSMutableParagraphStyle()
}
var newAttributes: [NSAttributedStringKey: Any]
switch element.type {
case .strikethrough: newAttributes = [
.strikethroughStyle: NSUnderlineStyle.styleSingle.rawValue,
.strikethroughColor: current[.foregroundColor]
?? Styles.Colors.Gray.dark.color
]
case .strong: newAttributes = [
.font: currentFont.addingTraits(traits: .traitBold)
]
case .em: newAttributes = [
.font: currentFont.addingTraits(traits: .traitItalic)
]
case .codeSpan: newAttributes = [
.font: Styles.Fonts.code,
NSAttributedStringKey.backgroundColor: Styles.Colors.Gray.lighter.color,
.foregroundColor: Styles.Colors.Gray.dark.color,
MarkdownAttribute.usernameDisabled: true,
MarkdownAttribute.linkShorteningDisabled: true
]
case .link: newAttributes = [
.foregroundColor: Styles.Colors.Blue.medium.color,
MarkdownAttribute.url: element.href ?? ""
]
case .header:
switch element.level {
case 1: newAttributes = [
.font: UIFont.boldSystemFont(ofSize: Styles.Sizes.Text.h1)
]
case 2: newAttributes = [
.font: UIFont.boldSystemFont(ofSize: Styles.Sizes.Text.h2)
]
case 3: newAttributes = [
.font: UIFont.boldSystemFont(ofSize: Styles.Sizes.Text.h3)
]
case 4: newAttributes = [
.font: UIFont.boldSystemFont(ofSize: Styles.Sizes.Text.h4)
]
case 5: newAttributes = [
.font: UIFont.boldSystemFont(ofSize: Styles.Sizes.Text.h5)
]
default: newAttributes = [
.foregroundColor: Styles.Colors.Gray.medium.color,
.font: UIFont.boldSystemFont(ofSize: Styles.Sizes.Text.h6)
]
}
case .bulletedList, .numberedList:
let indent: CGFloat = (CGFloat(listLevel) - 1) * 18
paragraphStyleCopy.firstLineHeadIndent = indent
paragraphStyleCopy.firstLineHeadIndent = indent
newAttributes = [.paragraphStyle: paragraphStyleCopy]
case .listItem:
// if after the first element, tighten list spacing
if element.numberedListPosition > 1 || listLevel > 1 {
paragraphStyleCopy.paragraphSpacingBefore = 2
}
newAttributes = [.paragraphStyle: paragraphStyleCopy]
case .blockquote: newAttributes = [
.foregroundColor: Styles.Colors.Gray.medium.color
]
case .mailTo: newAttributes = [
.foregroundColor: Styles.Colors.Blue.medium.color,
MarkdownAttribute.email: element.href ?? ""
]
default: newAttributes = [:]
}
var attributes = current
for (k, v) in newAttributes {
attributes[k] = v
}
return attributes
}
|
mit
|
ba4be12977562400d18682d6ccc82ce6
| 34.642857 | 110 | 0.638992 | 4.536364 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/AvatarConstructorController.swift
|
1
|
53261
|
//
// AvatarConstructorController.swift
// Telegram
//
// Created by Mike Renoir on 13.04.2022.
// Copyright © 2022 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import Postbox
import TelegramCore
import SwiftSignalKit
import ThemeSettings
import ColorPalette
import ObjcUtils
import AppKit
private final class Arguments {
let context: AccountContext
let dismiss:()->Void
let select:(State.Item)->Void
let selectOption:(State.Item.Option)->Void
let selectColor:(AvatarColor)->Void
let selectForeground:(TelegramMediaFile)->Void
let set:()->Void
let zoom:(CGFloat)->Void
let updateText:(String)->Void
let stickersView:()->NSView?
let emojisView:()->NSView?
let updateOffset:(NSPoint)->Void
init(context: AccountContext, dismiss:@escaping()->Void, select:@escaping(State.Item)->Void, selectOption:@escaping(State.Item.Option)->Void, selectColor:@escaping(AvatarColor)->Void, selectForeground:@escaping(TelegramMediaFile)->Void, set: @escaping()->Void, zoom:@escaping(CGFloat)->Void, updateText:@escaping(String)->Void, stickersView: @escaping()->NSView?, emojisView:@escaping()->NSView?, updateOffset:@escaping(NSPoint)->Void) {
self.context = context
self.dismiss = dismiss
self.select = select
self.selectOption = selectOption
self.selectColor = selectColor
self.selectForeground = selectForeground
self.set = set
self.zoom = zoom
self.updateText = updateText
self.stickersView = stickersView
self.emojisView = emojisView
self.updateOffset = updateOffset
}
}
struct AvatarColor : Equatable {
enum Content : Equatable {
case gradient([NSColor])
case wallpaper(Wallpaper, ColorPalette)
static func == (lhs: Content, rhs: Content) -> Bool {
switch lhs {
case let .gradient(colors):
if case .gradient(colors) = rhs {
return true
}
case let .wallpaper(wallpaper, lhsPalette):
if case .wallpaper(wallpaper, let rhsPalette) = rhs {
return lhsPalette.isDark == rhsPalette.isDark
}
}
return false
}
}
var selected: Bool
var content: Content
var isWallpaper: Bool {
switch content {
case .wallpaper:
return true
default:
return false
}
}
var wallpaper: Wallpaper? {
switch content {
case let .wallpaper(wallpaper, _):
return wallpaper
default:
return nil
}
}
var colors: ColorPalette? {
switch content {
case let .wallpaper(_, palette):
return palette
default:
return nil
}
}
}
private struct State : Equatable {
struct Item : Equatable, Identifiable, Comparable {
struct Option : Equatable {
var key: String
var title: String
var selected: Bool
}
var key: String
var index: Int
var title: String
var thumb: MenuAnimation
var selected: Bool
var options:[Option]
var foreground: TelegramMediaFile?
var text: String?
var selectedOption:Option {
return self.options.first(where: { $0.selected })!
}
static func <(lhs: Item, rhs: Item) -> Bool {
return lhs.index < rhs.index
}
var stableId: String {
return self.key
}
}
struct Preview : Equatable {
var zoom: CGFloat = 1.0
var offset: NSPoint = .zero
var animated: Bool?
}
var items: [Item]
var preview: Preview = Preview()
var emojies:[StickerPackItem] = []
var colors: [AvatarColor] = []
var selected: Item {
return self.items.first(where: { $0.selected })!
}
var selectedColor: AvatarColor {
return self.colors.first(where: { $0.selected })!
}
}
private final class AvatarLeftView: View {
private final class PreviewView: View {
final class CursorView : View {
override func cursorUpdate(with event: NSEvent) {
super.cursorUpdate(with: event)
NSCursor.pointingHand.set()
}
var move:(CGPoint, Bool)->Void = { _, _ in }
var drop:()->Void = { }
private var isFirst: Bool = true
private var startPoint: CGPoint?
override func mouseDown(with event: NSEvent) {
startPoint = self.convert(event.locationInWindow, from: nil)
isFirst = true
super.mouseDown(with: event)
}
override func mouseUp(with event: NSEvent) {
startPoint = nil
if event.clickCount == 2 {
self.drop()
}
super.mouseUp(with: event)
}
override func mouseDragged(with event: NSEvent) {
let currentPoint = self.convert(event.locationInWindow, from: nil)
guard let startPoint = startPoint else {
return
}
let gap = NSMakePoint(currentPoint.x - startPoint.x, currentPoint.y - startPoint.y)
self.move(gap, isFirst)
isFirst = false
super.mouseDragged(with: event)
}
}
private let imageView: CursorView = CursorView(frame: NSMakeRect(0, 0, 150, 150))
private var backgroundColorView: ImageView?
private var backgroundPatternView: TransformImageView?
private var foregroundView: StickerMediaContentView? = nil
private var foregroundTextView: TextView? = nil
private let textView = TextView()
private var state: State?
private var arguments: Arguments?
private let slider: LinearProgressControl = LinearProgressControl(progressHeight: 4)
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(textView)
addSubview(imageView)
addSubview(slider)
slider.scrubberImage = generateImage(NSMakeSize(14, 14), contextGenerator: { size, ctx in
let rect = CGRect(origin: .zero, size: size)
ctx.clear(rect)
ctx.setFillColor(theme.colors.accent.cgColor)
ctx.fillEllipse(in: rect)
ctx.setFillColor(theme.colors.background.cgColor)
ctx.fillEllipse(in: rect.insetBy(dx: 2, dy: 2))
})
slider.roundCorners = true
slider.alignment = .center
slider.containerBackground = theme.colors.grayBackground
slider.style = ControlStyle(foregroundColor: theme.colors.accent, backgroundColor: .clear, highlightColor: .clear)
slider.set(progress: 0.8)
imageView.layer?.cornerRadius = imageView.frame.height / 2
let text = TextViewLayout(.initialize(string: strings().avatarPreview, color: theme.colors.grayText, font: .normal(.text)))
text.measure(width: .greatestFiniteMagnitude)
textView.update(text)
textView.userInteractionEnabled = false
textView.isSelectable = false
imageView.backgroundColor = theme.colors.listBackground
imageView.move = { [weak self] point, isFirst in
self?.move(point, isFirst)
}
imageView.drop = { [weak self] in
self?.arguments?.updateOffset(.zero)
}
}
private var startOffset: CGPoint?
private func move(_ point: NSPoint, _ isFirst: Bool) {
guard let state = state, let arguments = self.arguments else {
return
}
let startOffset = isFirst ? state.preview.offset : self.startOffset
if isFirst {
self.startOffset = state.preview.offset
}
guard let foregroundView = foregroundView, let startOffset = startOffset else {
return
}
let rect = foregroundView.centerFrame()
let maxX = rect.minX
let maxY = rect.minY
let mx = 2 + (1 - state.preview.zoom)
let mn = -2 - (1 - state.preview.zoom)
let offset = NSMakePoint(startOffset.x + point.x / maxX, startOffset.y + point.y / maxY)
arguments.updateOffset(offset)
}
func updateState(_ state: State, arguments: Arguments, animated: Bool) {
self.state = state
self.arguments = arguments
self.slider.set(progress: state.preview.zoom)
let selectedBg = state.colors.first(where: { $0.selected })!
self.applyBg(selectedBg, context: arguments.context, animated: animated)
self.applyFg(state.selected.foreground, text: state.selected.text, zoom: state.preview.zoom, offset: state.preview.offset, context: arguments.context, animated: animated)
slider.onUserChanged = { value in
arguments.zoom(CGFloat(value))
}
needsLayout = true
}
private var previousFile: TelegramMediaFile?
private var previousText: String?
private func applyFg(_ file: TelegramMediaFile?, text: String?, zoom: CGFloat, offset: CGPoint, context: AccountContext, animated: Bool) {
if let text = text {
if let view = foregroundView {
performSubviewRemoval(view, animated: animated, scale: true)
self.foregroundView = nil
}
if self.previousText != text {
if let view = foregroundTextView {
performSubviewRemoval(view, animated: animated, scale: true)
self.foregroundTextView = nil
}
let foregroundTextView = TextView()
foregroundTextView.userInteractionEnabled = false
foregroundTextView.isSelectable = false
let layout = TextViewLayout(.initialize(string: text, color: .white, font: .avatar(80)))
layout.measure(width: .greatestFiniteMagnitude)
foregroundTextView.update(layout)
self.imageView.addSubview(foregroundTextView)
foregroundTextView.center()
foregroundTextView.frame.origin.y += 4
self.foregroundTextView = foregroundTextView
if animated {
foregroundTextView.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
foregroundTextView.layer?.animateScaleSpring(from: 0.1, to: 1, duration: 0.2)
}
}
} else {
if let view = foregroundTextView {
performSubviewRemoval(view, animated: animated, scale: true)
self.foregroundTextView = nil
}
if let file = file, self.previousFile != file {
if let view = foregroundView {
performSubviewRemoval(view, animated: animated, scale: true)
self.foregroundView = nil
}
let size = file.dimensions?.size.aspectFitted(NSMakeSize(120, 120)) ?? NSMakeSize(120, 120)
let foregroundView = StickerMediaContentView(frame: size.bounds)
foregroundView.update(with: file, size: foregroundView.frame.size, context: context, parent: nil, table: nil)
self.imageView.addSubview(foregroundView)
var frame = foregroundView.centerFrame()
frame.origin.x += offset.x * frame.origin.x
frame.origin.y += offset.y * frame.origin.y
foregroundView.frame = frame
self.foregroundView = foregroundView
if animated {
foregroundView.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
foregroundView.layer?.animateScaleSpring(from: 0.1, to: 1, duration: 0.2)
}
} else if file == nil {
if let view = foregroundView {
performSubviewRemoval(view, animated: animated, scale: true)
self.foregroundView = nil
}
}
}
if let foregroundView = foregroundView {
var frame = foregroundView.centerFrame()
frame.origin.x += offset.x * frame.origin.x
frame.origin.y += offset.y * frame.origin.y
foregroundView.frame = frame
let zoom = mappingRange(zoom, 0, 1, 0.5, 1)
let valueScale = CGFloat(truncate(double: Double(zoom), places: 2))
let rect = foregroundView.bounds
var fr = CATransform3DIdentity
fr = CATransform3DTranslate(fr, rect.width / 2, rect.height / 2, 0)
fr = CATransform3DScale(fr, valueScale, valueScale, 1)
fr = CATransform3DTranslate(fr, -(rect.width / 2), -(rect.height / 2), 0)
foregroundView.layer?.transform = fr
}
if let foregroundView = foregroundTextView {
let zoom = mappingRange(zoom, 0, 1, 0.5, 1)
let valueScale = CGFloat(truncate(double: Double(zoom), places: 2))
let rect = foregroundView.bounds
var fr = CATransform3DIdentity
fr = CATransform3DTranslate(fr, rect.width / 2, rect.height / 2, 0)
fr = CATransform3DScale(fr, valueScale, valueScale, 1)
fr = CATransform3DTranslate(fr, -(rect.width / 2), -(rect.height / 2), 0)
foregroundView.layer?.transform = fr
}
self.previousText = text
self.previousFile = file
}
private func applyBg(_ color: AvatarColor, context: AccountContext, animated: Bool) {
var colors: [NSColor] = []
switch color.content {
case let .gradient(c):
colors = c
default:
break
}
if !colors.isEmpty {
if let view = backgroundPatternView {
performSubviewRemoval(view, animated: animated)
self.backgroundPatternView = nil
}
let current: ImageView
if let view = backgroundColorView {
current = view
} else {
current = ImageView(frame: imageView.bounds)
self.backgroundColorView = current
self.imageView.addSubview(current, positioned: .below, relativeTo: foregroundView ?? foregroundTextView)
}
current.animates = animated
current.image = generateImage(current.frame.size, contextGenerator: { size, ctx in
ctx.clear(size.bounds)
let imageRect = size.bounds
if colors.count == 1, let color = colors.first {
ctx.setFillColor(color.cgColor)
ctx.fill(imageRect)
} else {
let gradientColors = colors.map { $0.cgColor } as CFArray
let delta: CGFloat = 1.0 / (CGFloat(colors.count) - 1.0)
var locations: [CGFloat] = []
for i in 0 ..< colors.count {
locations.append(delta * CGFloat(i))
}
let colorSpace = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradient(colorsSpace: colorSpace, colors: gradientColors, locations: &locations)!
ctx.drawLinearGradient(gradient, start: CGPoint(x: 0.0, y: 0.0), end: CGPoint(x: 0.0, y: imageRect.height), options: [.drawsBeforeStartLocation, .drawsAfterEndLocation])
}
})
} else if let wallpaper = color.wallpaper {
if let view = backgroundColorView {
performSubviewRemoval(view, animated: animated)
self.backgroundColorView = nil
}
let current: TransformImageView
if let view = backgroundPatternView {
current = view
} else {
current = TransformImageView(frame: imageView.bounds)
self.backgroundPatternView = current
self.imageView.addSubview(current, positioned: .below, relativeTo: foregroundView ?? foregroundTextView)
}
let emptyColor: TransformImageEmptyColor
let colors = wallpaper.settings.colors.compactMap { NSColor($0) }
if colors.count > 1 {
let colors = colors.map {
return $0.withAlphaComponent($0.alpha == 0 ? 0.5 : $0.alpha)
}
emptyColor = .gradient(colors: colors, intensity: colors.first!.alpha, rotation: nil)
} else if let color = colors.first {
emptyColor = .color(color)
} else {
emptyColor = .color(NSColor(rgb: 0xd6e2ee, alpha: 0.5))
}
let arguments = TransformImageArguments(corners: ImageCorners(radius: 0), imageSize: wallpaper.dimensions.aspectFilled(NSMakeSize(300, 300)), boundingSize: current.frame.size, intrinsicInsets: NSEdgeInsets(), emptyColor: emptyColor)
current.set(arguments: arguments)
switch wallpaper {
case let .file(_, file, _, _):
var representations:[TelegramMediaImageRepresentation] = []
if let dimensions = file.dimensions {
representations.append(TelegramMediaImageRepresentation(dimensions: dimensions, resource: file.resource, progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false))
} else {
representations.append(TelegramMediaImageRepresentation(dimensions: PixelDimensions(current.frame.size), resource: file.resource, progressiveSizes: [], immediateThumbnailData: nil, hasVideo: false))
}
let updateImageSignal = chatWallpaper(account: context.account, representations: representations, file: file, mode: .thumbnail, isPattern: true, autoFetchFullSize: true, scale: backingScaleFactor, isBlurred: false, synchronousLoad: false, drawPatternOnly: false, palette: color.colors!)
current.setSignal(signal: cachedMedia(media: file, arguments: arguments, scale: backingScaleFactor), clearInstantly: false)
if !current.isFullyLoaded {
current.setSignal(updateImageSignal, animate: true, cacheImage: { result in
cacheMedia(result, media: file, arguments: arguments, scale: System.backingScale)
})
}
default:
break
}
} else {
if let view = backgroundColorView {
performSubviewRemoval(view, animated: animated)
self.backgroundColorView = nil
}
if let view = backgroundPatternView {
performSubviewRemoval(view, animated: animated)
self.backgroundPatternView = nil
}
}
}
override func layout() {
super.layout()
textView.centerX(y: 0)
imageView.centerX(y: textView.frame.maxY + 10)
backgroundColorView?.frame = imageView.bounds
backgroundPatternView?.frame = imageView.bounds
if let foregroundView = foregroundView, let state = state {
var rect = foregroundView.centerFrame()
rect.origin.x += state.preview.offset.x * rect.origin.x
rect.origin.y += state.preview.offset.y * rect.origin.y
foregroundView.frame = rect
}
if let foregroundTextView = foregroundTextView {
var center = foregroundTextView.centerFrame()
center.origin.y += 4
foregroundTextView.setFrameOrigin(center.origin)
}
slider.setFrameSize(NSMakeSize(imageView.frame.width, 14))
slider.centerX(y: imageView.frame.maxY + 10)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private final class ItemView: Control {
private let textView = TextView()
private let player = LottiePlayerView(frame: NSMakeRect(0, 0, 20, 20))
private var animation: LottieAnimation?
private var item: State.Item?
private var select:((State.Item)->Void)? = nil
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(textView)
addSubview(player)
layer?.cornerRadius = .cornerRadius
scaleOnClick = true
set(background: theme.colors.background, for: .Normal)
textView.userInteractionEnabled = false
textView.isEventLess = true
textView.isSelectable = false
player.isEventLess = true
player.userInteractionEnabled = false
self.set(handler: { [weak self] _ in
if let item = self?.item {
self?.select?(item)
}
}, for: .Click)
}
override func layout() {
super.layout()
player.centerY(x: 10)
textView.centerY(x: player.frame.maxX + 10)
}
func set(item: State.Item, select: @escaping(State.Item)->Void, animated: Bool) {
let text = TextViewLayout(.initialize(string: item.title, color: theme.colors.text, font: .normal(.text)))
text.measure(width: 150)
textView.update(text)
self.select = select
self.item = item
if item.selected {
set(background: theme.colors.grayBackground, for: .Normal)
} else {
set(background: theme.colors.background, for: .Normal)
}
if let data = item.thumb.data {
let colors:[LottieColor] = [.init(keyPath: "", color: theme.colors.accent)]
let animation = LottieAnimation(compressed: data, key: LottieAnimationEntryKey(key: .bundle(item.thumb.rawValue), size: player.frame.size), type: .lottie, cachePurpose: .none, playPolicy: .framesCount(1), maximumFps: 60, colors: colors, metalSupport: false)
self.animation = animation
player.set(animation, reset: true, saveContext: false, animated: false)
}
needsLayout = true
}
override func stateDidUpdate(_ state: ControlState) {
super.stateDidUpdate(state)
switch state {
case .Hover:
if player.animation?.playPolicy == .framesCount(1) {
player.set(self.animation?.withUpdatedPolicy(.once), reset: false)
} else {
player.playAgain()
}
default:
break
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private let itemsView: View = View()
private let previewView: PreviewView
private var state: State?
required init(frame frameRect: NSRect) {
previewView = PreviewView(frame: NSMakeRect(0, 0, frameRect.width, frameRect.height / 2))
super.init(frame: frameRect)
addSubview(itemsView)
addSubview(previewView)
border = [.Right]
borderColor = theme.colors.border
itemsView.layer?.cornerRadius = .cornerRadius
}
func updateState(_ state: State, arguments: Arguments, animated: Bool) {
previewView.updateState(state, arguments: arguments, animated: animated)
let (deleteIndices, indicesAndItems, updateIndices) = mergeListsStableWithUpdates(leftList: self.state?.items ?? [], rightList: state.items)
for rdx in deleteIndices.reversed() {
itemsView.subviews[rdx].removeFromSuperview()
}
for (idx, item, _) in indicesAndItems {
let view = ItemView(frame: NSMakeRect(0, CGFloat(idx) * 30, itemsView.frame.width, 30))
itemsView.addSubview(view, positioned: .above, relativeTo: idx == 0 ? nil : itemsView.subviews[idx - 1])
view.set(item: item, select: arguments.select, animated: animated)
}
for (idx, item, _) in updateIndices {
let item = item
(itemsView.subviews[idx] as? ItemView)?.set(item: item, select: arguments.select, animated: animated)
}
self.state = state
self.updateLayout(frame.size, transition: animated ? .animated(duration: 0.2, curve: .easeOut) : .immediate)
}
override func layout() {
super.layout()
self.updateLayout(self.frame.size, transition: .immediate)
}
func updateLayout(_ size: NSSize, transition: ContainedViewLayoutTransition) {
transition.updateFrame(view: itemsView, frame: NSMakeRect(0, 0, size.width, size.height / 2).insetBy(dx: 10, dy: 10))
transition.updateFrame(view: previewView, frame: NSMakeRect(0, size.height - 230, size.width, 230).insetBy(dx: 10, dy: 10))
for (i, itemView) in itemsView.subviews.enumerated() {
transition.updateFrame(view: itemView, frame: NSMakeRect(0, CGFloat(i) * 30, itemsView.frame.width, 30))
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private final class AvatarRightView: View {
private final class HeaderView : View {
let segment: CatalinaStyledSegmentController
let dismiss = ImageButton()
private var state: State?
required init(frame frameRect: NSRect) {
segment = CatalinaStyledSegmentController(frame: NSMakeRect(0, 0, frameRect.width, 30))
super.init(frame: frameRect)
addSubview(segment.view)
addSubview(dismiss)
self.border = [.Bottom]
borderColor = theme.colors.border
backgroundColor = theme.colors.background
segment.theme = CatalinaSegmentTheme(backgroundColor: theme.colors.listBackground, foregroundColor: theme.colors.background, activeTextColor: theme.colors.text, inactiveTextColor: theme.colors.listGrayText)
}
func updateState(_ state: State, arguments: Arguments, animated: Bool) {
if state.selected.key != self.state?.selected.key {
segment.removeAll()
for option in state.selected.options {
segment.add(segment: .init(title: option.title, handler: {
arguments.selectOption(option)
}))
}
}
for i in 0 ..< state.selected.options.count {
if state.selected.options[i].selected {
segment.set(selected: i, animated: animated)
}
}
dismiss.set(image: theme.icons.modalClose, for: .Normal)
dismiss.sizeToFit()
dismiss.removeAllHandlers()
dismiss.set(handler: { _ in
arguments.dismiss()
}, for: .Click)
self.state = state
needsLayout = true
}
override func layout() {
super.layout()
segment.view.setFrameSize(frame.width - 140, 30)
segment.view.center()
dismiss.centerY(x: frame.width - dismiss.frame.width - 10)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private let headerView = HeaderView(frame: .zero)
private let content = View()
private var state: State?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(headerView)
addSubview(content)
content.backgroundColor = theme.colors.listBackground
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layout() {
super.layout()
self.updateLayout(self.frame.size, transition: .immediate)
}
func updateState(_ state: State, arguments: Arguments, animated: Bool) {
self.headerView.updateState(state, arguments: arguments, animated: animated)
self.updateContent(state, previous: self.state, arguments: arguments, animated: animated)
self.state = state
needsLayout = true
}
private func updateContent(_ state: State, previous: State?, arguments: Arguments, animated: Bool) {
if state.selected != previous?.selected {
if let content = content.subviews.last, let previous = previous {
if makeContentView(state.selected) != makeContentView(previous.selected) {
performSubviewRemoval(content, animated: animated)
let content = makeContentView(state.selected)
let initiedContent = content.init(frame: self.content.bounds)
self.content.addSubview(initiedContent)
if animated {
initiedContent.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
}
}
} else {
let content = makeContentView(state.selected)
let initiedContent = content.init(frame: self.content.bounds)
self.content.addSubview(initiedContent)
}
}
if state.selected.key == "e", let content = self.content.subviews.last as? Avatar_StickersList, let view = arguments.emojisView() {
content.set(view: view, context: arguments.context, animated: animated)
} else if let content = self.content.subviews.last as? Avatar_BgListView {
content.set(colors: state.colors, context: arguments.context, select: arguments.selectColor, animated: animated)
} else if let content = self.content.subviews.last as? Avatar_MonogramView {
content.set(text: state.selected.text, updateText: arguments.updateText, animated: animated)
} else if let content = self.content.subviews.last as? Avatar_StickersList, let view = arguments.stickersView() {
content.set(view: view, context: arguments.context, animated: animated)
}
}
private func makeContentView(_ item: State.Item) -> View.Type {
if item.selectedOption.key == "b" {
return Avatar_BgListView.self
} else if item.key == "e" {
return Avatar_StickersList.self
} else if item.key == "m" {
return Avatar_MonogramView.self
} else if item.key == "s" {
return Avatar_StickersList.self
} else {
return View.self
}
}
func updateLayout(_ size: NSSize, transition: ContainedViewLayoutTransition) {
transition.updateFrame(view: headerView, frame: NSMakeRect(0, 0, size.width, 50))
transition.updateFrame(view: content, frame: NSMakeRect(0, headerView.frame.height, size.width, size.height - headerView.frame.height))
for subview in content.subviews {
transition.updateFrame(view: subview, frame: content.bounds)
}
}
var firstResponder: NSResponder? {
if let view = self.content.subviews.last as? Avatar_MonogramView {
return view.firstResponder
}
return content.subviews.last
}
}
private final class AvatarConstructorView : View {
private let leftView: AvatarLeftView = AvatarLeftView(frame: .zero)
private let rightView: AvatarRightView = AvatarRightView(frame: .zero)
private var state: State?
private var premiumView: StickerPremiumHolderView?
let setView = TitleButton()
private let containerView: View = View()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
containerView.addSubview(leftView)
containerView.addSubview(rightView)
addSubview(containerView)
addSubview(setView)
updateLayout(frameRect.size, transition: .immediate)
setView.style = ControlStyle(font:.medium(.text), foregroundColor: theme.colors.accent, backgroundColor: theme.colors.background)
setView.set(text: strings().modalSet, for: .Normal)
setView.disableActions()
_ = setView.sizeToFit(NSZeroSize, NSMakeSize(0, 50), thatFit: true)
setView.set(background: theme.colors.background, for: .Normal)
setView.set(background: theme.colors.grayForeground.withAlphaComponent(0.25), for: .Highlight)
setView.border = [.Top]
}
func previewPremium(_ file: TelegramMediaFile, context: AccountContext, view: NSView, animated: Bool) {
let current: StickerPremiumHolderView
if let view = premiumView {
current = view
} else {
current = StickerPremiumHolderView(frame: bounds)
self.premiumView = current
addSubview(current)
if animated {
current.layer?.animateAlpha(from: 0, to: 1, duration: 0.2)
}
}
current.set(file: file, context: context, callback: { [weak self] in
showModal(with: PremiumBoardingController(context: context, source: .premium_stickers), for: context.window)
self?.closePremium()
})
current.close = { [weak self] in
self?.closePremium()
}
}
var isPremium: Bool {
return self.premiumView != nil
}
func closePremium() {
if let view = premiumView {
performSubviewRemoval(view, animated: true)
self.premiumView = nil
}
}
override func layout() {
super.layout()
self.updateLayout(self.frame.size, transition: .immediate)
}
func updateLayout(_ size: NSSize, transition: ContainedViewLayoutTransition) {
transition.updateFrame(view: setView, frame: NSMakeRect(0, frame.height - 50, size.width, 50))
transition.updateFrame(view: containerView, frame: NSMakeRect(0, 0, size.width, frame.height - setView.frame.height))
transition.updateFrame(view: leftView, frame: NSMakeRect(0, 0, 180, containerView.frame.height))
leftView.updateLayout(leftView.frame.size, transition: transition)
transition.updateFrame(view: rightView, frame: NSMakeRect(leftView.frame.maxX, 0, size.width - leftView.frame.width, containerView.frame.height))
rightView.updateLayout(rightView.frame.size, transition: transition)
if let premiumView = premiumView {
transition.updateFrame(view: premiumView, frame: bounds)
}
}
func updateState(_ state: State, arguments: Arguments, animated: Bool) {
self.state = state
self.leftView.updateState(state, arguments: arguments, animated: animated)
self.rightView.updateState(state, arguments: arguments, animated: animated)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var firstResponder: NSResponder? {
return self.rightView.firstResponder
}
}
final class AvatarConstructorController : ModalViewController {
enum Target {
case avatar
case peer(PeerId)
}
private let context: AccountContext
private let target: Target
private let disposable = MetaDisposable()
private var contextObject: AnyObject?
private let videoSignal:(MediaObjectToAvatar)->Void
private var setPressed:(()->Void)?
private let stickersController: NStickersViewController
private let emojisController: EmojiesController
init(_ context: AccountContext, target: Target, videoSignal:@escaping(MediaObjectToAvatar)->Void) {
self.context = context
self.target = target
self.stickersController = .init(context)
self.emojisController = .init(context, mode: .selectAvatar, selectedItems: [])
self.videoSignal = videoSignal
super.init(frame: NSMakeRect(0, 0, 350, 450))
stickersController.mode = .selectAvatar
bar = .init(height: 0)
}
override func measure(size: NSSize) {
if let contentSize = self.modal?.window.contentView?.frame.size {
self.modal?.resize(with: effectiveSize(contentSize), animated: false)
}
}
func effectiveSize(_ size: NSSize) -> NSSize {
let updated = size - NSMakeSize(50, 20)
return NSMakeSize(min(updated.width, 540), min(updated.height, 540))
}
func updateSize(_ animated: Bool) {
if let contentSize = self.modal?.window.contentView?.frame.size {
self.modal?.resize(with: effectiveSize(contentSize), animated: animated)
}
}
override var dynamicSize: Bool {
return true
}
override func viewClass() -> AnyClass {
return AvatarConstructorView.self
}
private var genericView: AvatarConstructorView {
return self.view as! AvatarConstructorView
}
override func viewDidLoad() {
super.viewDidLoad()
let context = self.context
let actionsDisposable = DisposableSet()
onDeinit = {
actionsDisposable.dispose()
}
let initialState = State.init(items: [])
let statePromise = ValuePromise(initialState, ignoreRepeated: true)
let stateValue = Atomic(value: initialState)
let updateState: ((State) -> State) -> Void = { f in
statePromise.set(stateValue.modify (f))
}
updateState { current in
var current = current
current.items.append(.init(key: "e", index: 0, title: "Emoji", thumb: MenuAnimation.menu_smile, selected: false, options: [
.init(key: "e", title: "Emoji", selected: true),
.init(key: "b", title: "Background", selected: false)
]))
current.items.append(.init(key: "s", index: 1, title: "Sticker", thumb: MenuAnimation.menu_view_sticker_set, selected: true, options: [
.init(key: "s", title: "Sticker", selected: true),
.init(key: "b", title: "Background", selected: false)
]))
current.items.append(.init(key: "m", index: 2, title: "Monogram", thumb: MenuAnimation.menu_monogram, selected: false, options: [
.init(key: "t", title: "Text", selected: true),
.init(key: "b", title: "Background", selected: false)
]))
var colors: [AvatarColor] = []
colors.append(.init(selected: false, content: .gradient([dayClassicPalette.peerColors(0).top, dayClassicPalette.peerColors(0).bottom])))
colors.append(.init(selected: true, content: .gradient([dayClassicPalette.peerColors(1).top, dayClassicPalette.peerColors(1).bottom])))
colors.append(.init(selected: false, content: .gradient([dayClassicPalette.peerColors(2).top, dayClassicPalette.peerColors(2).bottom])))
colors.append(.init(selected: false, content: .gradient([dayClassicPalette.peerColors(3).top, dayClassicPalette.peerColors(3).bottom])))
colors.append(.init(selected: false, content: .gradient([dayClassicPalette.peerColors(4).top, dayClassicPalette.peerColors(4).bottom])))
colors.append(.init(selected: false, content: .gradient([dayClassicPalette.peerColors(5).top, dayClassicPalette.peerColors(5).bottom])))
colors.append(.init(selected: false, content: .gradient([dayClassicPalette.peerColors(6).top, dayClassicPalette.peerColors(6).bottom])))
current.colors = colors
return current
}
let emojies = context.engine.stickers.loadedStickerPack(reference: .animatedEmoji, forceActualized: false)
let stickers = context.account.postbox.itemCollectionsView(orderedItemListCollectionIds: [Namespaces.OrderedItemList.CloudRecentStickers, Namespaces.OrderedItemList.CloudSavedStickers], namespaces: [Namespaces.ItemCollection.CloudStickerPacks], aroundIndex: nil, count: 1)
let wallpapers = telegramWallpapers(postbox: context.account.postbox, network: context.account.network) |> map { wallpapers -> [Wallpaper] in
return wallpapers.compactMap { wallpaper in
switch wallpaper {
case let .file(file):
return file.isPattern ? Wallpaper(wallpaper) : nil
default:
return nil
}
}
} |> deliverOnMainQueue
let peerId: PeerId
switch self.target {
case .avatar:
peerId = context.peerId
case let .peer(pid):
peerId = pid
}
let _video:(MediaObjectToAvatar)->Void = { [weak self] convertor in
self?.videoSignal(convertor)
self?.close()
}
let peer = context.account.postbox.loadedPeerWithId(peerId)
actionsDisposable.add(combineLatest(wallpapers, emojies, peer, stickers).start(next: { wallpapers, pack, peer, stickers in
switch pack {
case let .result(_, items, _):
updateState { current in
var current = current
current.emojies = items
var itms = current.items
for i in 0 ..< itms.count {
var item = itms[i]
if item.key == "e" {
item.foreground = items.first(where: { $0.file.stickerText == "🤖" })?.file ?? items.first?.file
} else if item.key == "m" {
item.text = peer.displayLetters.joined()
} else if item.key == "s" {
let saved = stickers.orderedItemListsViews[1].items.compactMap {
$0.contents.get(SavedStickerItem.self)?.file
}.first
let recent = stickers.orderedItemListsViews[0].items.compactMap {
$0.contents.get(RecentMediaItem.self)?.media
}.first
let sticker = stickers.entries.first?.item as? StickerPackItem
item.foreground = saved ?? recent ?? sticker?.file
}
itms[i] = item
}
current.items = itms
current.colors += wallpapers.filter { !$0.settings.colors.isEmpty }.map { .init(selected: false, content: .wallpaper($0, dayClassicPalette)) }
current.colors += wallpapers.filter { !$0.settings.colors.isEmpty }.map { .init(selected: false, content: .wallpaper($0, nightAccentPalette)) }
return current
}
default:
break
}
}))
let arguments = Arguments(context: context, dismiss: { [weak self] in
self?.close()
}, select: { selected in
updateState { current in
var current = current
var items = current.items
for i in 0 ..< items.count {
var item = items[i]
item.selected = false
if selected.key == item.key {
item.selected = true
}
items[i] = item
}
current.items = items
return current
}
}, selectOption: { selected in
updateState { current in
var current = current
var items = current.items
for i in 0 ..< items.count {
var item = items[i]
if item.selected {
for j in 0 ..< item.options.count {
var option = item.options[j]
option.selected = option.key == selected.key
item.options[j] = option
}
}
items[i] = item
}
current.items = items
return current
}
}, selectColor: { selected in
updateState { current in
var current = current
for i in 0 ..< current.colors.count {
var color = current.colors[i]
color.selected = color.content == selected.content
current.colors[i] = color
}
return current
}
}, selectForeground: { file in
updateState { current in
var current = current
var items = current.items
for i in 0 ..< items.count {
var item = items[i]
if item.selected {
item.foreground = file
}
items[i] = item
}
current.preview.zoom = 1.0
current.preview.offset = .zero
current.items = items
return current
}
}, set: {
let state = stateValue.with { $0 }
let background:MediaObjectToAvatar.Object.Background
let source: MediaObjectToAvatar.Object.Foreground.Source
switch state.selectedColor.content {
case let .gradient(colors):
background = .colors(colors)
case let .wallpaper(wallpaper, pattern):
background = .pattern(wallpaper, pattern)
}
if let file = state.selected.foreground {
if file.isAnimated && file.isVideo {
source = .gif(file)
} else if file.isVideoSticker || file.isAnimatedSticker || file.isVideoEmoji {
source = .animated(file)
} else {
source = .sticker(file)
}
} else if let text = state.selected.text {
source = .emoji(text, NSColor(0xffffff))
} else {
alert(for: context.window, info: strings().unknownError)
return
}
let zoom = mappingRange(state.preview.zoom, 0, 1, 0.5, 0.8)
let object = MediaObjectToAvatar(context: context, object: .init(foreground: .init(type: source, zoom: zoom, offset: state.preview.offset), background: background))
_video(object)
}, zoom: { value in
updateState { current in
var current = current
current.preview.zoom = value
let mx = 2 + (1 - current.preview.zoom)
let mn = -2 - (1 - current.preview.zoom)
let offset = NSMakePoint(min(mx, max(mn, current.preview.offset.x)), min(mx, max(current.preview.offset.y, mn)))
current.preview.offset = offset
return current
}
}, updateText: { text in
updateState { current in
var current = current
var items = current.items
for i in 0 ..< items.count {
var item = items[i]
if item.selected {
item.text = text
}
items[i] = item
}
current.items = items
return current
}
}, stickersView: { [weak self] in
return self?.stickersController.view
}, emojisView: { [weak self] in
return self?.emojisController.view
}, updateOffset: { offset in
updateState { current in
var current = current
let mx = 2 + (1 - current.preview.zoom)
let mn = -2 - (1 - current.preview.zoom)
let offset = NSMakePoint(min(mx, max(mn, offset.x)), min(mx, max(offset.y, mn)))
current.preview.offset = offset
return current
}
})
let signal = statePromise.get() |> deliverOnMainQueue
let first: Atomic<Bool> = Atomic(value: true)
disposable.set(signal.start(next: { [weak self] state in
self?.genericView.updateState(state, arguments: arguments, animated: !first.swap(false))
self?.readyOnce()
}))
let interactions = EntertainmentInteractions(.stickers, peerId: context.peerId)
interactions.sendSticker = { file, _, _, _ in
arguments.selectForeground(file)
}
interactions.sendGIF = { file, _, _ in
arguments.selectForeground(file)
}
interactions.sendAnimatedEmoji = { item, _, _, _ in
arguments.selectForeground(item.file)
}
interactions.showStickerPremium = { [weak self] file, view in
self?.genericView.previewPremium(file, context: context, view: view, animated: true)
}
let c_interactions = ChatInteraction(chatLocation: .peer(context.peerId), context: context)
stickersController.update(with: interactions, chatInteraction: c_interactions)
stickersController.loadViewIfNeeded()
emojisController.update(with: interactions, chatInteraction: c_interactions)
emojisController.loadViewIfNeeded()
setPressed = arguments.set
genericView.setView.set(handler: { _ in
arguments.set()
}, for: .Click)
}
override func escapeKeyAction() -> KeyHandlerResult {
if genericView.isPremium {
genericView.closePremium()
return .invoked
}
return super.escapeKeyAction()
}
override var canBecomeResponder: Bool {
return true
}
override func firstResponder() -> NSResponder? {
return genericView.firstResponder
}
}
|
gpl-2.0
|
810b72afd8bdbf24dec81f75ad3b9778
| 39.133384 | 441 | 0.546538 | 5.193778 | false | false | false | false |
zachmokahn/SUV
|
Sources/SUV/Handle/PipeHandle.swift
|
1
|
859
|
public class PipeHandle: HandleType {
public typealias Pointer = UnsafeMutablePointer<UVPipeType>
public let pointer: Pointer
public let loop: Loop
public let status: Status
public init(_ loop: Loop, uv_pipe_init: PipeInit = UVPipeInit, interprocessCommuncation: Bool = false) {
self.pointer = Pointer.alloc(sizeof(UVPipeType))
self.loop = loop
self.status = Status(uv_pipe_init(self.loop.pointer, self.pointer, interprocessCommuncation ? 1 : 0))
}
public func open(output: FileDescriptor, uv_pipe_open: PipeOpen = UVPipeOpen) {
uv_pipe_open(self.pointer, UVFile(output))
}
public func close(uv_close uv_close: Close = UVClose, _ callback: (Handle -> Void)? = nil) {
if let cb = callback {
Handle(self).close(uv_close: uv_close) { cb($0) }
} else {
Handle(self).close(uv_close: uv_close)
}
}
}
|
mit
|
66397ea50040109524aaaed12e298023
| 32.038462 | 106 | 0.685681 | 3.436 | false | false | false | false |
elslooo/hoverboard
|
OnboardKit/OnboardKit/Badge View/OnboardBadgeView.swift
|
1
|
3132
|
/*
* Copyright (c) 2017 Tim van Elsloo
*
* 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
/**
* This is the badge view that we incorporate in onboard item cells to indicate
* the order and state of steps.
*/
internal class OnboardBadgeView : NSView {
/**
* We initialize 3 views: one for each badge style. To transition between
* each state, we simply fade between those views.
*/
private var views: [OnboardBadgeStyle : OnboardBadgeStyleView] = [:]
/**
* The default style is transparent. Upon changing this value, we switch the
* alpha values of the views that correspond to the old and new badge style.
*/
internal var style: OnboardBadgeStyle = .transparent {
didSet {
if let oldView = self.views[oldValue] {
oldView.alphaValue = 0.0
}
if let newView = self.views[self.style] {
newView.alphaValue = 1.0
}
}
}
/**
* This is the text that should be shown in the badge. We propagate changes
* to the individual styled badge views.
*/
internal var text: String = "" {
didSet {
for view in self.views.values {
view.text = text
}
}
}
/**
* This function initializes the badge view with the given frame.
*/
override init(frame frameRect: NSRect) {
super.init(frame: frameRect.insetBy(dx: -2, dy: -2))
self.wantsLayer = true
for style in [ OnboardBadgeStyle.transparent,
OnboardBadgeStyle.focused,
OnboardBadgeStyle.checkmark ] {
let view = OnboardBadgeStyleView(frame: self.bounds, style: style)
if style != .transparent {
view.alphaValue = 0
}
self.addSubview(view)
// Keep a reference to this view for this particular style.
views[style] = view
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
cf74c6d2e055afeee64aa0c67035611c
| 33.417582 | 80 | 0.641443 | 4.612666 | false | false | false | false |
sjtu-meow/iOS
|
Meow/Moment.swift
|
1
|
1059
|
//
// Moment.swift
// Meow
//
// Created by 林树子 on 2017/6/30.
// Copyright © 2017年 喵喵喵的伙伴. All rights reserved.
//
import Foundation
import SwiftyJSON
struct Moment: ItemProtocol {
var id: Int!
var type: ItemType!
var profile: Profile!
var createTime: Date!
var content: String?
var medias: [Media]?
var comments: [Comment]?
var likeCount: Int? // FIXME: not empty
var commentCount: Int?
}
extension Moment: JSONConvertible {
static func fromJSON(_ json: JSON) -> Moment? {
let item = Item.fromJSON(json)!
var moment = self.init()
moment.id = item.id
moment.type = item.type
moment.profile = item.profile
moment.createTime = item.createTime
moment.content <- json["content"]
moment.medias <- json["medias"]
moment.comments <- json["comments"]
moment.likeCount <- json["likeCount"]
moment.commentCount <- json["commentCount"]
return moment
}
}
|
apache-2.0
|
62c12080c10b6fab627d6f55c39e433f
| 21.085106 | 51 | 0.591522 | 4.119048 | false | false | false | false |
benlangmuir/swift
|
test/Distributed/distributed_actor_accessor_section_coff.swift
|
9
|
6587
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift
// RUN: %target-swift-frontend -emit-irgen -module-name distributed_actor_accessors-disable-availability-checking -I %t 2>&1 %s | %IRGenFileCheck %s
// UNSUPPORTED: back_deploy_concurrency
// REQUIRES: concurrency
// REQUIRES: distributed
// REQUIRES: OS=windows-msvc
// FIXME: Test is temporary disabled (no way to debug)
// REQUIRES: fix
import Distributed
import FakeDistributedActorSystems
@available(SwiftStdlib 5.5, *)
typealias DefaultDistributedActorSystem = FakeActorSystem
enum SimpleE : Codable {
case a
}
enum E : Codable {
case a, b, c
}
enum IndirectE : Codable {
case empty
indirect case test(_: Int)
}
final class Obj : Codable, Sendable {
let x: Int
init(x: Int) {
self.x = x
}
}
struct LargeStruct : Codable {
var a: Int
var b: Int
var c: String
var d: Double
}
@available(SwiftStdlib 5.7, *)
public distributed actor MyActor {
distributed func simple1(_: Int) {
}
// `String` would be a direct result as a struct type
distributed func simple2(_: Int) -> String {
return ""
}
// `String` is an object that gets exploded into two parameters
distributed func simple3(_: String) -> Int {
return 42
}
// Enum with a single case are special because they have an empty
// native schema so they are dropped from parameters/result.
distributed func single_case_enum(_ e: SimpleE) -> SimpleE {
return e
}
distributed func with_indirect_enums(_: IndirectE, _: Int) -> IndirectE {
return .empty
}
// Combination of multiple arguments, reference type and indirect result
//
// Note: Tuple types cannot be used here is either position because they
// cannot conform to protocols.
distributed func complex(_: [Int], _: Obj, _: String?, _: LargeStruct) -> LargeStruct {
fatalError()
}
// Make sure that Sendable doesn't show up in the mangled name
distributed func generic<T: Codable & Sendable>(_: T) {
}
}
@available(SwiftStdlib 5.7, *)
public distributed actor MyOtherActor {
distributed func empty() {
}
}
/// ---> Let's check that distributed accessors and thunks are emitted as accessible functions
/// -> `MyActor.simple1`
// CHECK: @"$s27distributed_actor_accessors7MyActorC7simple1yySiYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic Si___________pIetMHygzo_ 27distributed_actor_accessors7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple1yySiYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section ".sw5acfn$B", {{.*}}
/// -> `MyActor.simple2`
// CHECK: @"$s27distributed_actor_accessors7MyActorC7simple2ySSSiYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic Si_____SS______pIetMHygozo_ 27distributed_actor_accessors7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple2ySSSiYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section ".sw5acfn$B", {{.*}}
/// -> `MyActor.simple3`
// CHECK: @"$s27distributed_actor_accessors7MyActorC7simple3ySiSSYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic SS_____Si______pIetMHggdzo_ 27distributed_actor_accessors7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7simple3ySiSSYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section ".sw5acfn$B", {{.*}}
/// -> `MyActor.single_case_enum`
// CHECK: @"$s27distributed_actor_accessors7MyActorC16single_case_enumyAA7SimpleEOAFYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic __________AA______pIetMHygdzo_ 27distributed_actor_accessors7SimpleEO AA7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC16single_case_enumyAA7SimpleEOAFYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section ".sw5acfn$B", {{.*}}
/// -> `MyActor.with_indirect_enums`
// CHECK: @"$s27distributed_actor_accessors7MyActorC19with_indirect_enumsyAA9IndirectEOAF_SitYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic _____Si_____AA______pIetMHgygozo_ 27distributed_actor_accessors9IndirectEO AA7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC19with_indirect_enumsyAA9IndirectEOAF_SitYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section ".sw5acfn$B", {{.*}}
/// -> `MyActor.complex`
// CHECK: @"$s27distributed_actor_accessors7MyActorC7complexyAA11LargeStructVSaySiG_AA3ObjCSSSgAFtYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic SaySiG_____SSSg__________AD______pIetMHgggngrzo_ 27distributed_actor_accessors3ObjC AA11LargeStructV AA7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7complexyAA11LargeStructVSaySiG_AA3ObjCSSSgAFtYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section ".sw5acfn$B", {{.*}}
/// -> `MyActor.generic`
// CHECK: @"$s27distributed_actor_accessors7MyActorC7genericyyxYaKSeRzSERzlFTEHF" = private constant
// CHECK-SAME: @"symbolic x___________pSeRzSERzlIetMHngzo_ 27distributed_actor_accessors7MyActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors7MyActorC7genericyyxYaKSeRzSERzlFTETFTu" to i{{32|64}})
// CHECK-SAME: , section ".sw5acfn$B", {{.*}}
/// -> `MyOtherActor.empty`
// CHECK: @"$s27distributed_actor_accessors12MyOtherActorC5emptyyyYaKFTEHF" = private constant
// CHECK-SAME: @"symbolic ___________pIetMHgzo_ 27distributed_actor_accessors12MyOtherActorC s5ErrorP"
// CHECK-SAME: (%swift.async_func_pointer* @"$s27distributed_actor_accessors12MyOtherActorC5emptyyyYaKFTETFTu" to i{{32|64}})
// CHECK-SAME: , section ".sw5acfn$B", {{.*}}
// CHECK: @llvm.used = appending global [{{.*}} x i8*] [
// CHECK-SAME: @"$s27distributed_actor_accessors7MyActorC7simple1yySiYaKFTEHF"
// CHECK-SAME: @"$s27distributed_actor_accessors7MyActorC7simple2ySSSiYaKFTEHF"
// CHECK-SAME: @"$s27distributed_actor_accessors7MyActorC7simple3ySiSSYaKFTEHF"
// CHECK-SAME: @"$s27distributed_actor_accessors7MyActorC16single_case_enumyAA7SimpleEOAFYaKFTEHF"
// CHECK-SAME: @"$s27distributed_actor_accessors7MyActorC19with_indirect_enumsyAA9IndirectEOAF_SitYaKFTEHF"
// CHECK-SAME: @"$s27distributed_actor_accessors7MyActorC7complexyAA11LargeStructVSaySiG_AA3ObjCSSSgAFtYaKFTEHF"
// CHECK-SAME: @"$s27distributed_actor_accessors12MyOtherActorC5emptyyyYaKFTEHF"
// CHECK-SAME: ], section "llvm.metadata"
|
apache-2.0
|
823b2b5895d9ccb633f3bf0a428ac560
| 42.913333 | 219 | 0.734022 | 3.518697 | false | false | false | false |
tomkowz/Swifternalization
|
Swifternalization/Swifternalization.swift
|
1
|
8899
|
//
// Swifternalization.swift
// Swifternalization
//
// Created by Tomasz Szulc on 27/06/15.
// Copyright (c) 2015 Tomasz Szulc. All rights reserved.
//
import Foundation
/// Handy typealias that can be used instead of longer `Swifternalization`
public typealias I18n = Swifternalization
/**
This is the main class of Swifternalization library. It exposes methods
that can be used to get localized strings.
The framework uses json files and work with them. There are two types of files.
First is "expressions.json" that contains shared expressions used among other
localizable json files. The other files are files with translation for specific
languages. Each file is just for one language. E.g. you can have "base.json",
"en.json", "pl.json" which are accordingly used for Base, English and Polish
localizations.
Before calling any method that return localized string call `configure:`.
*/
final public class Swifternalization {
/**
Shared instance of Swifternalization used internally.
*/
private static let sharedInstance = Swifternalization()
/**
Array of translations that contain expressions and localized values.
*/
private var translations = [Translation]()
/**
Determine whether Swifternalization is configured.
It should be considered configured after `load(bundle:)` method is called.
*/
private var configured = false
// MARK: Public Methods
/**
Call the method to configure Swifternalization.
:param: bundle A bundle when expressions.json and other files are located.
*/
public class func configure(_ bundle: Bundle = Bundle.main) {
sharedInstance.load(bundle)
}
/**
Configures Swifternalization if you didn't do that before calling
`localizedString...` methods.
*/
private class func configureIfNeeded(_ bundle: Bundle = Bundle.main) {
if sharedInstance.configured == false {
configure(bundle)
}
}
/**
Get localized value for a key.
:param: key A key to which localized string is assigned.
:param: fittingWidth A max width that value should fit to. If there is no
value specified the full-length localized string is returned. If a
passed fitting width is greater than highest available then a value for
highest available width is returned.
:param: defaultValue A default value that is returned when there is no
localized value for passed `key`.
:param: comment A comment about the key and localized value. Just for
developer use for describing key-value pair.
:returns: localized string if found, otherwise `defaultValue` is returned if
specified or `key` if `defaultValue` is not specified.
*/
public class func localizedString(_ key: String, fittingWidth: Int? = nil, defaultValue: String? = nil, comment: String? = nil) -> String {
return localizedString(key, stringValue: key, fittingWidth: fittingWidth, defaultValue: defaultValue, comment: comment)
}
/**
Get localized value for a key and string value.
:param: key A key to which localized string is assigned.
:param: stringValue A value that is matched by expressions.
:param: fittingWidth A max width that value should fit to. If there is no
value specified the full-length localized string is returned. If a
passed fitting width is greater than highest available then a value for
highest available width is returned.
:param: defaultValue A default value that is returned when there is no
localized value for passed `key`.
:param: comment A comment about the key and localized value. Just for
developer use for describing key-value pair.
:returns: localized string if found, otherwise `defaultValue` is returned if
specified or `key` if `defaultValue` is not specified.
*/
public class func localizedString(_ key: String, stringValue: String, fittingWidth: Int? = nil, defaultValue: String? = nil, comment: String? = nil) -> String {
configureIfNeeded()
/**
Filter translations and get only these that match passed `key`.
In ideal case when all is correctly filled by a developer it should be
at most only one key so we're getting just first found key.
*/
let filteredTranslations = sharedInstance.translations.filter({$0.key == key})
if let translation = filteredTranslations.first {
/**
If there is translation for the `key` it should validate passed
`stringValue`and `fittingWidth`. Translation returns localized
string (that matches `fittingWidth` if specified or nil.
If `fittingWidth` is not specified then full length localized string
is returned if translation matches the validated `stringValue`.
*/
if let localizedValue = translation.validate(stringValue, fittingWidth: fittingWidth) {
return localizedValue
}
}
/**
If there is not translation that validated `stringValue` successfully
then return `defaultValue` if not nil or the `key`.
*/
return (defaultValue != nil) ? defaultValue! : key
}
/**
Get localized value for a key and string value.
:param: key A key to which localized string is assigned.
:param: intValue A value that is matched by expressions.
:param: fittingWidth A max width that value should fit to. If there is no
value specified the full-length localized string is returned. If a
passed fitting width is greater than highest available then a value for
highest available width is returned.
:param: defaultValue A default value that is returned when there is no
localized value for passed `key`.
:param: comment A comment about the key and localized value. Just for
developer use for describing key-value pair.
:returns: localized string if found, otherwise `defaultValue` is returned if
specified or `key` if `defaultValue` is not specified.
*/
public class func localizedString(_ key: String, intValue: Int, fittingWidth: Int? = nil, defaultValue: String? = nil, comment: String? = nil) -> String {
return localizedString(key, stringValue: "\(intValue)", fittingWidth: fittingWidth, defaultValue: defaultValue, comment: comment)
}
// MARK: Private Methods
/**
Loads expressions and translations from expression.json and translation
json files.
:param: bundle A bundle when files are located.
*/
private func load(_ bundle: Bundle = Bundle.main) {
// Set base and prefered languages.
let base = "base"
let language = getPreferredLanguage(bundle)
/*
Load base and prefered language expressions from expressions.json,
convert them into SharedExpression objects and process them and return
array only of unique expressions. `SharedExpressionsProcessor` do its
own things inside like check if expression is unique or overriding base
expressions by prefered language ones if there is such expression.
*/
let baseExpressions = SharedExpressionsLoader.loadExpressions(JSONFileLoader.loadExpressions(base, bundle: bundle))
let languageExpressions = SharedExpressionsLoader.loadExpressions(JSONFileLoader.loadExpressions(language, bundle: bundle))
let expressions = SharedExpressionsProcessor.processSharedExpression(language, preferedLanguageExpressions: languageExpressions, baseLanguageExpressions: baseExpressions)
/*
Load base and prefered language translations from proper language files
specified by `language` constant. Convert them into arrays of
`LoadedTranslation`s and then process and convert into `Translation`
objects using `LoadedTranslationsProcessor`.
*/
let baseTranslations = TranslationsLoader.loadTranslations(JSONFileLoader.loadTranslations(base, bundle: bundle))
let languageTranslations = TranslationsLoader.loadTranslations(JSONFileLoader.loadTranslations(language, bundle: bundle))
// Store processed translations in `translations` variable for future use.
translations = LoadedTranslationsProcessor.processTranslations(baseTranslations, preferedLanguageTranslations: languageTranslations, sharedExpressions: expressions)
configured = true
}
/**
Get preferred language of user's device.
*/
private func getPreferredLanguage(_ bundle: Bundle) -> CountryCode {
// Get preferred language, the one which is set on user's device
return bundle.preferredLocalizations.first! as CountryCode
}
}
|
mit
|
3ce19f41a30fd12397ecd79419d66c23
| 44.172589 | 178 | 0.696483 | 5.228555 | false | true | false | false |
brentdax/swift
|
test/SILGen/call_chain_reabstraction.swift
|
2
|
1038
|
// RUN: %target-swift-emit-silgen -module-name call_chain_reabstraction -enable-sil-ownership %s | %FileCheck %s
struct A {
func g<U>(_ recur: (A, U) -> U) -> (A, U) -> U {
return { _, x in return x }
}
// CHECK-LABEL: sil hidden @$s24call_chain_reabstraction1AV1f{{[_0-9a-zA-Z]*}}F
// CHECK: [[G:%.*]] = function_ref @$s24call_chain_reabstraction1AV1g{{[_0-9a-zA-Z]*}}F
// CHECK: [[G2:%.*]] = apply [[G]]<A>
// CHECK: [[REABSTRACT_THUNK:%.*]] = function_ref @$s24call_chain_reabstraction1AVA2CIegynr_A3CIegyyd_TR
// CHECK: [[REABSTRACT:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT_THUNK]]([[G2]])
// CHECK: [[BORROW:%.*]] = begin_borrow [[REABSTRACT]]
// CHECK: apply [[BORROW]]([[SELF:%.*]], [[SELF]])
// CHECK: destroy_value [[REABSTRACT]]
func f() {
let recur: (A, A) -> A = { c, x in x }
let b = g(recur)(self, self)
}
}
|
apache-2.0
|
895b7cf0b46de295b0be0fedaa8f8561
| 50.9 | 120 | 0.491329 | 3.471572 | false | false | false | false |
cubixlabs/GIST-Framework
|
GISTFramework/Classes/Extensions/Gradient+Utility.swift
|
1
|
2835
|
//
// GradientUtility.swift
// GistDev
//
// Created by Shoaib on 2/5/18.
// Copyright © 2018 Social Cubix. All rights reserved.
//
import UIKit
public extension UIView {
func applyGradient(_ colors:[UIColor], type:GradientType, locations:[NSNumber]? = nil) -> CAGradientLayer{
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.bounds
gradientLayer.colors = colors.map { (c) -> CGColor in
return c.cgColor
}
gradientLayer.setGradient(type);
gradientLayer.locations = locations;
self.layer.insertSublayer(gradientLayer, at: 0);
return gradientLayer;
} //F.E.
} //F.E.
public extension CAGradientLayer {
func setGradient(_ type:GradientType) {
let points = type.points();
self.startPoint = points.start;
self.endPoint = points.end;
} //F.E.
} //E.E.
public enum GradientType {
case leftRight
case rightLeft
case topBottom
case bottomTop
case topLeftBottomRight
case bottomRightTopLeft
case topRightBottomLeft
case bottomLeftTopRight
fileprivate func points() -> (start: CGPoint, end: CGPoint) {
switch self {
case .leftRight:
return (start: CGPoint(x: 0, y: 0.5), end: CGPoint(x: 1, y: 0.5))
case .rightLeft:
return (start: CGPoint(x: 1, y: 0.5), end: CGPoint(x: 0, y: 0.5))
case .topBottom:
return (start: CGPoint(x: 0.5, y: 0), end: CGPoint(x: 0.5, y: 1))
case .bottomTop:
return (start: CGPoint(x: 0.5, y: 1), end: CGPoint(x: 0.5, y: 0))
case .topLeftBottomRight:
return (start: CGPoint(x: 0, y: 0), end: CGPoint(x: 1, y: 1))
case .bottomRightTopLeft:
return (start: CGPoint(x: 1, y: 1), end: CGPoint(x: 0, y: 0))
case .topRightBottomLeft:
return (start: CGPoint(x: 1, y: 0), end: CGPoint(x: 0, y: 1))
case .bottomLeftTopRight:
return (start: CGPoint(x: 0, y: 1), end: CGPoint(x: 1, y: 0))
}
}
public static func gradientType(for type:String) -> GradientType {
switch type {
case "leftRight":
return .leftRight
case "rightLeft":
return .rightLeft
case "topBottom":
return .topBottom
case "bottomTop":
return .bottomTop
case "topLeftBottomRight":
return .topLeftBottomRight
case "bottomRightTopLeft":
return .bottomRightTopLeft
case "topRightBottomLeft":
return .topRightBottomLeft
case "bottomLeftTopRight":
return .bottomLeftTopRight
default:
return .leftRight
}
} //F.E.
} //E.E.
|
agpl-3.0
|
344f5063d652ff82e5e1c0f805215688
| 27.626263 | 110 | 0.564573 | 4.155425 | false | false | false | false |
coinbase/coinbase-ios-sdk
|
Example/Source/ViewControllers/User/UserViewController.swift
|
1
|
2312
|
//
// UserViewController.swift
// iOS Example
//
// Copyright © 2018 Coinbase All rights reserved.
//
import UIKit
import CoinbaseSDK
class UserViewController: UIViewController {
@IBOutlet weak var userHeaderView: UserHeaderView!
@IBOutlet weak var userDetailsView: UserDetailsStackView!
@IBOutlet weak var authorizationInfoView: AuthorizationInfoStackView!
private let coinbase = Coinbase.default
private weak var activityIndicator: UIActivityIndicatorView?
// MARK: - Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
userDetailsView.isHidden = true
authorizationInfoView.isHidden = true
activityIndicator = view.addCenteredActivityIndicator()
loadUserDetails()
loadAuthorizationInfo()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Clear shadow image.
navigationController?.navigationBar.shadowImage = UIImage()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Restore system shadow image.
navigationController?.navigationBar.shadowImage = nil
}
// MARK: - Private Methods
private func loadUserDetails() {
coinbase.userResource.current { [weak self] result in
switch result {
case .success(let user):
self?.userHeaderView.setup(with: user)
self?.userDetailsView.setup(with: user)
self?.userDetailsView.isHidden = false
self?.activityIndicator?.removeFromSuperview()
case .failure(let error):
self?.present(error: error)
}
}
}
private func loadAuthorizationInfo() {
coinbase.userResource.authorizationInfo { [weak self] result in
switch result {
case .success(let info):
self?.authorizationInfoView.setup(with: info)
self?.authorizationInfoView.isHidden = false
self?.activityIndicator?.removeFromSuperview()
case .failure(let error):
self?.present(error: error)
}
}
}
}
|
apache-2.0
|
ede4abfb436ba6b4ae50515690166c86
| 29.012987 | 73 | 0.614885 | 5.622871 | false | false | false | false |
jish/twitter
|
twitter/ComposeController.swift
|
1
|
1639
|
//
// ComposeController.swift
// twitter
//
// Created by Josh Lubaway on 2/22/15.
// Copyright (c) 2015 Frustrated Inc. All rights reserved.
//
import UIKit
class ComposeController: UIViewController {
var replyTo: String?
@IBOutlet weak var composeTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
if let handle = replyTo {
composeTextView.text = "@\(handle) "
replyTo = nil
}
}
@IBAction func onSubmitTweet(sender: AnyObject) {
let status = composeTextView.text
println("Submit tweet requested \(status)")
TwitterClient.sharedInstance.submitTweet(composeTextView.text) { (response, error) in
if let r = response as? NSDictionary {
println("Tweeted \(r)")
self.navigationController?.popViewControllerAnimated(true)
} else {
println("Error tweeting \(error)")
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
425661a3cf0495e4d5a8cee9bf38b85d
| 26.779661 | 106 | 0.632093 | 4.996951 | false | false | false | false |
CD1212/Doughnut
|
Pods/FeedKit/Sources/FeedKit/Models/Atom/AtomFeedEntryContributor.swift
|
2
|
2567
|
//
// AtomFeedEntryContributor.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// 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
/// The "atom:contributor" element is a Person construct that indicates a
/// person or other entity who contributed to the entry or feed.
public class AtomFeedEntryContributor {
/// The "atom:name" element's content conveys a human-readable name for
/// the person. The content of atom:name is Language-Sensitive. Person
/// constructs MUST contain exactly one "atom:name" element.
public var name: String?
/// The "atom:email" element's content conveys an e-mail address
/// associated with the person. Person constructs MAY contain an
/// atom:email element, but MUST NOT contain more than one. Its content
/// MUST conform to the "addr-spec" production in [RFC2822].
public var email: String?
/// The "atom:uri" element's content conveys an IRI associated with the
/// person. Person constructs MAY contain an atom:uri element, but MUST
/// NOT contain more than one. The content of atom:uri in a Person
/// construct MUST be an IRI reference [RFC3987].
public var uri: String?
}
// MARK: - Equatable
extension AtomFeedEntryContributor: Equatable {
public static func ==(lhs: AtomFeedEntryContributor, rhs: AtomFeedEntryContributor) -> Bool {
return
lhs.name == rhs.name &&
lhs.email == rhs.email &&
lhs.uri == rhs.uri
}
}
|
gpl-3.0
|
71847a3a533ac0f0b613e1513d055b4e
| 41.081967 | 97 | 0.70822 | 4.425862 | false | false | false | false |
sonsongithub/reddift
|
framework/Model/Oembed.swift
|
1
|
2500
|
//
// Oembed.swift
// reddift
//
// Created by sonson on 2015/04/20.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import HTMLSpecialCharacters
/**
Media represents the content which is embeded a link.
*/
public struct Oembed {
/**
example, "http://i.imgur.com",
*/
public let providerUrl: String
/**
example, "The Internet's visual storytelling community. Explore, share, and discuss the best visual stories the Internet has to offer.",
*/
public let description: String
/**
example, "Imgur GIF",
*/
public let title: String
/**
example, 245,
*/
public let thumbnailWidth: Int
/**
example, 333,
*/
public let height: Int
/**
example, 245,
*/
public let width: Int
/**
example, "<iframe class=\"embedly-embed\" src=\"//cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fi.imgur.com%2FkhgfcrQ.mp4&src_secure=1&url=http%3A%2F%2Fi.imgur.com%2FkhgfcrQ.gifv&image=http%3A%2F%2Fi.imgur.com%2FkhgfcrQ.gif&key=2aa3c4d5f3de4f5b9120b660ad850dc9&type=video%2Fmp4&schema=imgur\" width=\"245\" height=\"333\" scrolling=\"no\" frameborder=\"0\" allowfullscreen></iframe>",
*/
public let html: String
/**
example, "1.0",
*/
public let version: String
/**
example, "Imgur",
*/
public let providerName: String
/**
example, "http://i.imgur.com/khgfcrQ.gif",
*/
public let thumbnailUrl: String
/**
example, "video",
*/
public let type: String
/**
example, 333
*/
public let thumbnailHeight: Int
/**
Update each property with JSON object.
- parameter json: JSON object which is included "t2" JSON.
*/
public init (json: JSONDictionary) {
self.providerUrl = json["provider_url"] as? String ?? ""
self.description = json["description"] as? String ?? ""
self.title = json["title"] as? String ?? ""
self.thumbnailWidth = json["thumbnail_width"] as? Int ?? 0
self.height = json["height"] as? Int ?? 0
self.width = json["width"] as? Int ?? 0
let tempHtml = json["html"] as? String ?? ""
self.html = tempHtml.unescapeHTML
self.version = json["version"] as? String ?? ""
self.providerName = json["provider_name"] as? String ?? ""
self.thumbnailUrl = json["thumbnail_url"] as? String ?? ""
self.type = json["type"] as? String ?? ""
self.thumbnailHeight = json["thumbnail_height"] as? Int ?? 0
}
}
|
mit
|
0993a97aa340ef303eea8de3f8e409d3
| 28.738095 | 431 | 0.625701 | 3.366577 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.