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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
darkFunction/Gloss | Sources/ExtensionDictionary.swift | 2 | 4974 | //
// ExtensionDictionary.swift
// Gloss
//
// Copyright (c) 2015 Harlan Kellaway
//
// 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
public extension Dictionary {
// MARK: - Public functions
/**
Parses the nested dictionary from the keyPath
components separated with a delimiter and gets the value
:parameter: keyPath KeyPath with delimiter
:parameter: delimiter Delimiter
:returns: Value from the nested dictionary
*/
public func valueForKeyPath(keyPath: String, withDelimiter delimiter: String = GlossKeyPathDelimiter()) -> AnyObject? {
let keys = keyPath.componentsSeparatedByString(delimiter)
guard let first = keys.first as? Key else {
print("[Gloss] Unable to use string as key on type: \(Key.self)")
return nil
}
guard let value = self[first] as? AnyObject else {
return nil
}
if keys.count > 1, let subDict = value as? JSON {
let rejoined = keys[1..<keys.endIndex].joinWithSeparator(delimiter)
return subDict.valueForKeyPath(rejoined, withDelimiter: delimiter)
}
return value
}
// MARK: - Internal functions
/**
Creates a dictionary from a list of elements, this allows us to map, flatMap
and filter dictionaries.
:parameter: elements Elements to add to the new dictionary
*/
init(elements: [Element]) {
self.init()
for (key, value) in elements {
self[key] = value
}
}
/**
Flat map for dictionary.
:parameter: transform Transform
*/
func flatMap<KeyPrime : Hashable, ValuePrime>(transform: (Key, Value) throws -> (KeyPrime, ValuePrime)?) rethrows -> [KeyPrime : ValuePrime] {
return Dictionary<KeyPrime,ValuePrime>(elements: try flatMap({ (key, value) in
return try transform(key, value)
}))
}
/**
Adds entries from provided dictionary
:parameter: other Dictionary to add entries from
:parameter: delimiter Keypath delimiter
*/
mutating func add(other: Dictionary, delimiter: String = GlossKeyPathDelimiter()) -> () {
for (key, value) in other {
if let key = key as? String {
self.setValue(valueToSet: value, forKeyPath: key, withDelimiter: delimiter)
} else {
self.updateValue(value, forKey:key)
}
}
}
// MARK: - Private functions
/**
Creates a nested dictionary from the keyPath
components separated with a delimiter and sets the value
:parameter: valueToSet Value to set
:parameter: keyPath KeyPath of the value
*/
private mutating func setValue(valueToSet val: Any, forKeyPath keyPath: String, withDelimiter delimiter: String = GlossKeyPathDelimiter()) {
var keys = keyPath.componentsSeparatedByString(delimiter)
guard let first = keys.first as? Key else {
print("[Gloss] Unable to use string as key on type: \(Key.self)")
return
}
keys.removeAtIndex(0)
if keys.isEmpty, let settable = val as? Value {
self[first] = settable
} else {
let rejoined = keys.joinWithSeparator(delimiter)
var subdict: JSON = [:]
if let sub = self[first] as? JSON {
subdict = sub
}
subdict.setValue(valueToSet: val, forKeyPath: rejoined, withDelimiter: delimiter)
if let settable = subdict as? Value {
self[first] = settable
} else {
print("[Gloss] Unable to set value: \(subdict) to dictionary of type: \(self.dynamicType)")
}
}
}
}
| mit | 59c1c8abaeae2b74c9a47f7646862eac | 33.303448 | 146 | 0.618014 | 5.034413 | false | false | false | false |
gottesmm/swift | test/IRGen/sil_generic_witness_methods.swift | 3 | 4516 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
// FIXME: These should be SIL tests, but we can't parse generic types in SIL
// yet.
protocol P {
func concrete_method()
static func concrete_static_method()
func generic_method<Z>(_ x: Z)
}
struct S {}
// CHECK-LABEL: define hidden void @_T027sil_generic_witness_methods05call_D0{{[_0-9a-zA-Z]*}}F(%swift.opaque* noalias nocapture, %swift.opaque* noalias nocapture, %swift.type* %T, %swift.type* %U, i8** %T.P)
func call_methods<T: P, U>(_ x: T, y: S, z: U) {
// CHECK: [[STATIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 1
// CHECK: [[STATIC_METHOD_PTR:%.*]] = load i8*, i8** [[STATIC_METHOD_ADDR]], align 8
// CHECK: [[STATIC_METHOD:%.*]] = bitcast i8* [[STATIC_METHOD_PTR]] to void (%swift.type*, %swift.type*, i8**)*
// CHECK: call void [[STATIC_METHOD]](%swift.type* %T, %swift.type* %T, i8** %T.P)
T.concrete_static_method()
// CHECK: [[CONCRETE_METHOD_PTR:%.*]] = load i8*, i8** %T.P, align 8
// CHECK: [[CONCRETE_METHOD:%.*]] = bitcast i8* [[CONCRETE_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, i8**)*
// CHECK: call void [[CONCRETE_METHOD]](%swift.opaque* noalias nocapture {{%.*}}, %swift.type* %T, i8** %T.P)
x.concrete_method()
// CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 2
// CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8
// CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)*
// CHECK: call void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* {{.*}} @_T027sil_generic_witness_methods1SVMf, {{.*}} %swift.opaque* {{.*}}, %swift.type* %T, i8** %T.P)
x.generic_method(y)
// CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** %T.P, i32 2
// CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8
// CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)*
// CHECK: call void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* %U, %swift.opaque* {{.*}}, %swift.type* %T, i8** %T.P)
x.generic_method(z)
}
// CHECK-LABEL: define hidden void @_T027sil_generic_witness_methods017call_existential_D0{{[_0-9a-zA-Z]*}}F(%P27sil_generic_witness_methods1P_* noalias nocapture dereferenceable({{.*}}))
func call_existential_methods(_ x: P, y: S) {
// CHECK: [[METADATA_ADDR:%.*]] = getelementptr inbounds %P27sil_generic_witness_methods1P_, %P27sil_generic_witness_methods1P_* [[X:%0]], i32 0, i32 1
// CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]], align 8
// CHECK: [[WTABLE_ADDR:%.*]] = getelementptr inbounds %P27sil_generic_witness_methods1P_, %P27sil_generic_witness_methods1P_* [[X]], i32 0, i32 2
// CHECK: [[WTABLE:%.*]] = load i8**, i8*** [[WTABLE_ADDR]], align 8
// CHECK: [[CONCRETE_METHOD_PTR:%.*]] = load i8*, i8** [[WTABLE]], align 8
// CHECK: [[CONCRETE_METHOD:%.*]] = bitcast i8* [[CONCRETE_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, i8**)*
// CHECK: call void [[CONCRETE_METHOD]](%swift.opaque* noalias nocapture {{%.*}}, %swift.type* [[METADATA]], i8** [[WTABLE]])
x.concrete_method()
// CHECK: [[METADATA_ADDR:%.*]] = getelementptr inbounds %P27sil_generic_witness_methods1P_, %P27sil_generic_witness_methods1P_* [[X]], i32 0, i32 1
// CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** [[METADATA_ADDR]], align 8
// CHECK: [[WTABLE_ADDR:%.*]] = getelementptr inbounds %P27sil_generic_witness_methods1P_, %P27sil_generic_witness_methods1P_* [[X:%.*]], i32 0, i32 2
// CHECK: [[WTABLE:%.*]] = load i8**, i8*** [[WTABLE_ADDR]], align 8
// CHECK: [[GENERIC_METHOD_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[WTABLE]], i32 2
// CHECK: [[GENERIC_METHOD_PTR:%.*]] = load i8*, i8** [[GENERIC_METHOD_ADDR]], align 8
// CHECK: [[GENERIC_METHOD:%.*]] = bitcast i8* [[GENERIC_METHOD_PTR]] to void (%swift.opaque*, %swift.type*, %swift.opaque*, %swift.type*, i8**)*
// CHECK: call void [[GENERIC_METHOD]](%swift.opaque* noalias nocapture {{.*}}, %swift.type* {{.*}} @_T027sil_generic_witness_methods1SVMf, {{.*}} %swift.opaque* noalias nocapture {{%.*}}, %swift.type* [[METADATA]], i8** [[WTABLE]])
x.generic_method(y)
}
| apache-2.0 | 6f77ef533e1b648c2edbcdc8e93032e6 | 74.266667 | 234 | 0.628654 | 3.169123 | false | false | false | false |
BalestraPatrick/Tweetometer | Carthage/Checkouts/twitter-kit-ios/DemoApp/DemoApp/Navigation/RootViewController.swift | 2 | 2603 | //
// RootViewController.swift
// DemoApp
//
// Created by Rajul Arora on 10/26/17.
// Copyright © 2017 Twitter. All rights reserved.
//
import UIKit
class RootViewController: UIViewController {
// MARK: - Private Variables
private var currentViewController: UIViewController?
private var animationController: RootAnimationController = RootAnimationController()
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
navigateToHome()
}
// MARK: - Private Methods
fileprivate func navigateToHome() {
let homeViewController = HomeViewController()
homeViewController.delegate = self
let navigationController = UINavigationController(rootViewController: homeViewController)
setCurrentViewController(with: navigationController)
}
fileprivate func navigateToAuthentication() {
let authenticationViewController = AuthenticationViewController()
authenticationViewController.delegate = self
let navigationController = UINavigationController(rootViewController: authenticationViewController)
setCurrentViewController(with: navigationController)
}
private func setCurrentViewController(with viewController: UIViewController) {
var transitionContext = RootTransitionContext(from: currentViewController, to: viewController, in: self)
transitionContext.animationCompletion = { [weak self] in
self?.currentViewController = viewController
self?.setupConstraints()
}
animationController.transition(using: transitionContext)
}
private func setupConstraints() {
guard let viewController = currentViewController else { return }
viewController.view.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
viewController.view.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
viewController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
viewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
}
}
// MARK: - HomeViewControllerDelegate
extension RootViewController: HomeViewControllerDelegate {
func homeViewControllerDidTapProfileButton(viewController: HomeViewController) {
navigateToAuthentication()
}
}
// MARK: - AuthenticationViewControllerDelegate
extension RootViewController: AuthenticationViewControllerDelegate {
func authenticationViewControllerDidTapHome(viewController: AuthenticationViewController) {
navigateToHome()
}
}
| mit | c33accebb136af6c793b7b0d61413ff5 | 34.162162 | 112 | 0.746733 | 6.195238 | false | false | false | false |
XCEssentials/UniFlow | Sources/5_MutationDecriptors/2-TransitionOf.swift | 1 | 1799 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([email protected])
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation /// for access to `Date` type
//---
public
struct TransitionOf<F: SomeFeature>: SomeMutationDecriptor
{
public
let oldState: SomeStateBase
public
let newState: SomeStateBase
public
let timestamp: Date
public
init?(
from report: Storage.HistoryElement
) {
guard
report.feature == F.self,
let transition = Transition(from: report)
else
{
return nil
}
//---
self.oldState = transition.oldState
self.newState = transition.newState
self.timestamp = report.timestamp
}
}
| mit | 46fdedd572aef72da86dcbd5b0641f1c | 28.016129 | 79 | 0.697054 | 4.997222 | false | false | false | false |
Anviking/Decodable | Sources/Operators.swift | 5 | 1464 | //
// Operators.swift
// Decodable
//
// Created by Johannes Lund on 2015-07-08.
// Copyright © 2015 anviking. All rights reserved.
//
import Foundation
// MARK: - Operators
precedencegroup DecodingPrecedence {
associativity: right
higherThan: CastingPrecedence
}
infix operator => : DecodingPrecedence
infix operator =>? : DecodingPrecedence
public func => (lhs: Any, rhs: KeyPath) throws -> Any {
return try parse(lhs, keyPath: rhs, decoder: { $0 })
}
public func =>? (lhs: Any, rhs: OptionalKeyPath) throws -> Any? {
return try parse(lhs, keyPath: rhs, decoder: Optional.decoder({$0}))
}
// MARK: - JSONPath
/// Enables parsing nested objects e.g json => "a" => "b"
public func => (lhs: KeyPath, rhs: KeyPath) -> KeyPath {
return KeyPath(lhs.keys + rhs.keys)
}
public func => (lhs: OptionalKeyPath, rhs: OptionalKeyPath) -> OptionalKeyPath {
return OptionalKeyPath(keys: lhs.keys + rhs.markingFirst(required: true).keys)
}
public func =>? (lhs: OptionalKeyPath, rhs: OptionalKeyPath) -> OptionalKeyPath {
return OptionalKeyPath(keys: lhs.keys + rhs.keys)
}
public func => (lhs: OptionalKeyPath, rhs: KeyPath) -> OptionalKeyPath {
return OptionalKeyPath(keys: lhs.keys + rhs.keys.map { OptionalKey(key: $0, isRequired: true) })
}
public func =>? (lhs: KeyPath, rhs: OptionalKeyPath) -> OptionalKeyPath {
return OptionalKeyPath(keys: lhs.keys.map { OptionalKey(key: $0, isRequired: true) } + rhs.keys )
}
| mit | 2c93145d6779f5988506f1381265cb88 | 26.603774 | 102 | 0.688312 | 3.732143 | false | false | false | false |
iOS-mamu/SS | P/PotatsoLibraryTests/PotatsoLibraryTests.swift | 1 | 7703 | //
// PotatsoLibraryTests.swift
// PotatsoLibraryTests
//
// Created by LEI on 4/8/16.
// Copyright © 2016 TouchingApp. All rights reserved.
//
import XCTest
import RealmSwift
import PotatsoModel
@testable import PotatsoLibrary
class PotatsoLibraryTests: XCTestCase {
let realm = try! Realm(configuration: Realm.Configuration(inMemoryIdentifier: "test"))
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testEmptyString() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
// let config = Config()
// do {
// try config.setup(string: "")
// }catch ProxyError.InvalidConfig {
//
// }catch {
// }
}
func testSyntaxError() {
let config = Config()
do {
try config.setup(string:"ss-1s: xx \nsds" )
assert(false)
}catch ConfigError.SyntaxError {
}catch {
assert(false)
}
}
// MARK - Proxy
func testInvalidProxy() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let config = Config()
do {
try config.setup(string: [
"proxies:\n",
"- name: vultr",
" type: shadowsocks",
" host: 10.0.0.0",
" port: 9000",
" encryption: rc4-md5"].joinWithSeparator("\n"))
assert(false)
}catch ProxyError.InvalidPassword {
}catch {
assert(false)
}
}
func testSingle() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let config = Config()
do {
try config.setup(string: [
"proxies:\n",
"- name: vultr",
" type: shadowsocks",
" host: 10.0.0.0",
" port: 9000",
" encryption: rc4-md5",
" password: 12345"].joinWithSeparator("\n"))
assert(config.proxies.count == 1)
let proxy = config.proxies[0]
assert(proxy.name == "vultr")
assert(proxy.type == .Shadowsocks)
assert(proxy.host == "10.0.0.0")
assert(proxy.port == 9000)
assert(proxy.authscheme == "rc4-md5")
assert(proxy.password == "12345")
}catch {
assert(false)
}
}
func testMultiple() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let config = Config()
do {
try config.setup(string: [
"proxies:\n",
"- name: vultr",
" type: shadowsocks",
" host: 10.0.0.0",
" port: 9000",
" encryption: rc4-md5",
" password: 12345",
"- name: vultr2",
" type: shadowsocks",
" host: 10.0.0.0",
" port: 9000",
" encryption: rc4-md5",
" password: 12345"].joinWithSeparator("\n"))
assert(config.proxies.count == 2)
}catch {
assert(false)
}
}
func testMultipleSameName() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let config = Config()
do {
try config.setup(string: [
"proxies:\n",
"- name: vultr",
" type: shadowsocks",
" host: 10.0.0.0",
" port: 9000",
" encryption: rc4-md5",
" password: 12345",
"- name: vultr",
" type: shadowsocks",
" host: 10.0.0.0",
" port: 9000",
" encryption: rc4-md5",
" password: 12345"].joinWithSeparator("\n"))
assert(false)
}catch ProxyError.NameAlreadyExists {
}catch {
assert(false)
}
}
func testUri() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let config = Config()
do {
try config.setup(string: [
"proxies:\n",
"- name: vultr",
" uri: ss://salsa20:%%%%$$$:@@10.0.0.0:443"].joinWithSeparator("\n"))
assert(config.proxies.count == 1)
let proxy = config.proxies[0]
assert(proxy.name == "vultr")
assert(proxy.type == .Shadowsocks)
assert(proxy.host == "10.0.0.0")
assert(proxy.port == 443)
assert(proxy.authscheme == "salsa20")
assert(proxy.password == "%%%%$$$:@")
}catch {
assert(false)
}
}
func testInvalidUri() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
let config = Config()
do {
try config.setup(string: [
"proxies:\n",
"- name: vultr",
" uri: ss://salsa20:%%%%$$$:@@10.0.0.0"].joinWithSeparator("\n"))
assert(false)
}catch {
}
}
// MARK: - Rule
func testRule() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
do {
var rule = try Rule(str: "DOMAIN-MATCH, google, DIRECT")
assert(rule.action == .Direct)
assert(rule.type == .DomainMatch)
assert(rule.value == "google")
rule = try Rule(str: "DOMAIN-MATCH, google, PROXY")
assert(rule.action == .Proxy)
rule = try Rule(str: "DOMAIN-MATCH, baidu, REJECT")
assert(rule.action == .Reject)
assert(rule.value == "baidu")
rule = try Rule(str: "DOMAIN-SUFFIX, baidu.com, REJECT")
assert(rule.type == .DomainSuffix)
rule = try Rule(str: "DOMAIN, www.baidu.com, REJECT")
assert(rule.type == .Domain)
rule = try Rule(str: "URL, www.baidu.com, REJECT")
assert(rule.type == .URL)
rule = try Rule(str: "URL-MATCH, ^(https?:\\/\\/)?api\\.xiachufang\\.com\\/v\\d\\/ad\\/show\\.json, REJECT")
assert(rule.type == .URLMatch)
assert(rule.value == "^(https?:\\/\\/)?api\\.xiachufang\\.com\\/v\\d\\/ad\\/show\\.json")
rule = try Rule(str: "IP-CIDR, 17.0.0.0/8, PROXY")
assert(rule.type == .IPCIDR)
rule = try Rule(str: "GEOIP, cn, PROXY")
assert(rule.type == .GeoIP)
}catch {
assert(false)
}
}
}
| mit | 04ea97116d4a34e2e42782c0f5fb4cb0 | 32.486957 | 120 | 0.489873 | 4.416284 | false | true | false | false |
Leo19/swift_begin | test-swift/arraySetDictionary/arraySetDictionary/Enumeration.playground/Contents.swift | 2 | 1375 | //: Playground - noun: a place where people can play
var str = "Hello, playground"
// 没有任何原始类型的枚举
enum PlanetName{
case Earth
case Venus
case Mars
case Jupiter
case Saturn
}
var planet = PlanetName.Earth
planet = .Jupiter
// 有原始类型的枚举,其中Saturn没有给赋值但swift会隐式按顺序赋值Saturn.rawValue=5
enum PlanetIndex: Int{
case Earth = 1
case Venus = 2
case Mars = 3
case Jupiter = 4
case Saturn
}
let saturn = PlanetIndex.Saturn.rawValue
// 通过rawValue也就是原始值来做switch case
let possiblePlanet = 4
if let somePlanet = PlanetIndex(rawValue: possiblePlanet){
switch somePlanet{
case .Earth:
print("a beautiful planet")
case .Mars:
print("not so bad planet")
default:
print("other planets")
}
}else{
print("not one of our galaxy planets")
}
// 关联值,关联值和原始值区别是原始值不能更改
enum Barcode{
case BNRGB(Int,Int,Int)
case OXRGB(String)
}
// 下面这个就会报错
//PlanetIndex.Saturn.rawValue = 90
var greenBarcode = Barcode.BNRGB(32, 32, 64)
greenBarcode = .OXRGB("green")
let colorType = (32,32,64)
switch greenBarcode{
case .BNRGB(let rc,let gc,let bc):
print("\(rc),\(gc),\(bc)")
case .OXRGB(let ffc):
print("this is color string \(ffc)")
}
| gpl-2.0 | 8005869e2d71be99c60cd3b15aaadeaf | 18.140625 | 58 | 0.661224 | 3.365385 | false | false | false | false |
sigito/material-components-ios | components/FlexibleHeader/tests/unit/FlexibleHeaderStatusBarTests.swift | 5 | 1582 | /*
Copyright 2016-present the Material Components for iOS 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 XCTest
import MaterialComponents.MaterialFlexibleHeader
// Testing status bar-related functionality.
class FlexibleHeaderStatusBarTests: XCTestCase {
func testDarkBackgroundColor() {
let controller = MDCFlexibleHeaderViewController()
let view = controller.headerView
view.backgroundColor = UIColor.black
XCTAssertEqual(controller.preferredStatusBarStyle(), UIStatusBarStyle.lightContent)
}
func testLightBackgroundColor() {
let controller = MDCFlexibleHeaderViewController()
let view = controller.headerView
view.backgroundColor = UIColor.white
XCTAssertEqual(controller.preferredStatusBarStyle(), UIStatusBarStyle.default)
}
func testNonOpaqueBackgroundColor() {
let controller = MDCFlexibleHeaderViewController()
let view = controller.headerView
view.backgroundColor = UIColor.init(white: 0, alpha: 0)
XCTAssertEqual(controller.preferredStatusBarStyle(), UIStatusBarStyle.default)
}
}
| apache-2.0 | 56ead3cf31e27843465bbfe54c72778f | 35.790698 | 87 | 0.785714 | 5.186885 | false | true | false | false |
mountainvat/google-maps-ios-utils | samples/SwiftDemoApp/SwiftDemoApp/HeatmapViewController.swift | 1 | 3426 | /* Copyright (c) 2017 Google 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 GoogleMaps
import UIKit
class HeatmapViewController: UIViewController, GMSMapViewDelegate {
private var mapView: GMSMapView!
private var heatmapLayer: GMUHeatmapTileLayer!
private var button: UIButton!
private var gradientColors = [UIColor.green, UIColor.red]
private var gradientStartPoints = [0.2, 1.0] as? [NSNumber]
override func loadView() {
let camera = GMSCameraPosition.camera(withLatitude: -37.848, longitude: 145.001, zoom: 10)
mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
mapView.delegate = self
self.view = mapView
makeButton()
}
override func viewDidLoad() {
// Set heatmap options.
heatmapLayer = GMUHeatmapTileLayer()
heatmapLayer.radius = 80
heatmapLayer.opacity = 0.8
heatmapLayer.gradient = GMUGradient(colors: gradientColors,
startPoints: gradientStartPoints!,
colorMapSize: 256)
addHeatmap()
// Set the heatmap to the mapview.
heatmapLayer.map = mapView
}
// Parse JSON data and add it to the heatmap layer.
func addHeatmap() {
var list = [GMUWeightedLatLng]()
do {
// Get the data: latitude/longitude positions of police stations.
if let path = Bundle.main.url(forResource: "police_stations", withExtension: "json") {
let data = try Data(contentsOf: path)
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let object = json as? [[String: Any]] {
for item in object {
let lat = item["lat"]
let lng = item["lng"]
let coords = GMUWeightedLatLng(coordinate: CLLocationCoordinate2DMake(lat as! CLLocationDegrees, lng as! CLLocationDegrees), intensity: 1.0)
list.append(coords)
}
} else {
print("Could not read the JSON.")
}
}
} catch {
print(error.localizedDescription)
}
// Add the latlngs to the heatmap layer.
heatmapLayer.weightedData = list
}
func removeHeatmap() {
heatmapLayer.map = nil
heatmapLayer = nil
// Disable the button to prevent subsequent calls, since heatmapLayer is now nil.
button.isEnabled = false
}
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")
}
// Add a button to the view.
func makeButton() {
// A button to test removing the heatmap.
button = UIButton(frame: CGRect(x: 5, y: 150, width: 200, height: 35))
button.backgroundColor = .blue
button.alpha = 0.5
button.setTitle("Remove heatmap", for: .normal)
button.addTarget(self, action: #selector(removeHeatmap), for: .touchUpInside)
self.mapView.addSubview(button)
}
}
| apache-2.0 | 789d5187e28a7e86999680799cb6198c | 34.319588 | 152 | 0.670753 | 4.449351 | false | false | false | false |
mapsme/omim | iphone/Maps/Core/DeepLink/DeepLinkHandler.swift | 5 | 3599 | @objc enum DeepLinkProvider: Int {
case native
case appsflyer
var statName: String {
switch self {
case .native:
return kStatNative
case .appsflyer:
return kStatAppsflyer
}
}
}
class DeepLinkURL {
let url: URL
let provider: DeepLinkProvider
init(url: URL, provider: DeepLinkProvider = .native) {
self.url = url
self.provider = provider
}
}
@objc @objcMembers class DeepLinkHandler: NSObject {
static let shared = DeepLinkHandler()
private(set) var isLaunchedByDeeplink = false
private(set) var deeplinkURL: DeepLinkURL?
var needExtraWelcomeScreen: Bool {
guard let host = deeplinkURL?.url.host else { return false }
return host == "catalogue" || host == "guides_page"
}
private var canHandleLink = false
private override init() {
super.init()
}
func applicationDidFinishLaunching(_ options: [UIApplication.LaunchOptionsKey : Any]? = nil) {
if let userActivityOptions = options?[.userActivityDictionary] as? [UIApplication.LaunchOptionsKey : Any],
let userActivityType = userActivityOptions[.userActivityType] as? String,
userActivityType == NSUserActivityTypeBrowsingWeb {
isLaunchedByDeeplink = true
}
if let launchDeeplink = options?[UIApplication.LaunchOptionsKey.url] as? URL {
isLaunchedByDeeplink = true
deeplinkURL = DeepLinkURL(url: launchDeeplink)
}
}
func applicationDidOpenUrl(_ url: URL) -> Bool {
deeplinkURL = DeepLinkURL(url: url)
if canHandleLink {
handleInternal()
}
return true
}
private func setUniversalLink(_ url: URL, provider: DeepLinkProvider) -> Bool {
let dlUrl = convertUniversalLink(url)
guard deeplinkURL == nil else { return false }
deeplinkURL = DeepLinkURL(url: dlUrl)
return true
}
func applicationDidReceiveUniversalLink(_ url: URL) -> Bool {
return applicationDidReceiveUniversalLink(url, provider: .native)
}
func applicationDidReceiveUniversalLink(_ url: URL, provider: DeepLinkProvider) -> Bool {
var result = false
if let host = url.host, host == "mapsme.onelink.me" {
URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.forEach {
if $0.name == "af_dp" {
guard let value = $0.value, let dl = URL(string: value) else { return }
result = setUniversalLink(dl, provider: provider)
}
}
} else {
result = setUniversalLink(url, provider: provider)
}
if canHandleLink {
handleInternal()
}
return result
}
func handleDeeplink() {
canHandleLink = true
if deeplinkURL != nil {
handleInternal()
}
}
func handleDeeplink(_ url: URL) {
deeplinkURL = DeepLinkURL(url: url)
handleDeeplink()
}
func reset() {
isLaunchedByDeeplink = false
deeplinkURL = nil
}
func getBackUrl() -> String {
guard let urlString = deeplinkURL?.url.absoluteString else { return "" }
guard let url = URLComponents(string: urlString) else { return "" }
return (url.queryItems?.first(where: { $0.name == "backurl" })?.value ?? "")
}
private func convertUniversalLink(_ universalLink: URL) -> URL {
let convertedLink = String(format: "mapsme:/%@?%@", universalLink.path, universalLink.query ?? "")
return URL(string: convertedLink)!
}
private func handleInternal() {
guard let url = deeplinkURL else {
assertionFailure()
return
}
LOG(.info, "Handle deeplink: \(url.url)")
let deeplinkHandlerStrategy = DeepLinkStrategyFactory.create(url: url)
deeplinkHandlerStrategy.execute()
}
}
| apache-2.0 | 6741101000b58f8568fb17db6874f00b | 26.899225 | 110 | 0.671575 | 4.394383 | false | false | false | false |
nathantannar4/NTComponents | NTComponents/UI Kit/Controls/NTSwitch.swift | 1 | 17366 | //
// NTSwitch.swift
// NTComponents
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 6/4/17.
// Adapted from https://github.com/JaleelNazir/MJMaterialSwitch to support auto
// layout and NTComponents integration
//
open class NTSwitch: UIControl {
open var isOn: Bool = false {
didSet {
if oldValue != isOn {
self.onSwitchChanged?(self)
}
}
}
open var isBounceEnabled: Bool = false {
didSet {
if isBounceEnabled {
bounceOffset = 3.0
} else {
bounceOffset = 0.0
}
}
}
open var isRippleEnabled: Bool = true
open var sliderOnTintColor: UIColor = Color.Default.Tint.View {
didSet {
rippleColor = sliderOnTintColor.isLight ? sliderOnTintColor.darker(by: 10) : sliderOnTintColor.lighter(by: 10)
}
}
open var trackOnTintColor: UIColor = Color.Default.Tint.View.lighter(by: 20)
open var trackOffTintColor: UIColor = Color.Gray.P500
open var sliderOffTintColor: UIColor = Color.Gray.P300
open var sliderDisabledTintColor: UIColor = Color.Gray.P300
open var trackDisabledTintColor: UIColor = Color.Gray.P300
open var rippleColor: UIColor = Color.Default.Tint.View.isLight ? Color.Default.Tint.View.darker(by: 10) : Color.Default.Tint.View.lighter(by: 10)
open var slider: UIButton = {
let button = UIButton()
button.backgroundColor = .white
button.layer.shadowOpacity = Color.Default.Shadow.Opacity
button.layer.shadowOffset = CGSize(width: 0.0, height: Color.Default.Shadow.Offset.height)
button.layer.shadowColor = Color.Default.Shadow.cgColor
button.layer.shadowRadius = Color.Default.Shadow.Radius
return button
}()
open var track: UIView = {
let view = UIView()
view.backgroundColor = Color.Gray.P500
return view
}()
fileprivate var thumbOnPosition: CGFloat = 0
fileprivate var thumbOffPosition: CGFloat = 0
fileprivate var bounceOffset: CGFloat = 3.0
fileprivate var rippleLayer: CAShapeLayer!
// MARK: - Handlers
open var onSwitchChanged: ((NTSwitch) -> Void)?
@discardableResult
open func onSwitchChanged(_ handler: @escaping ((NTSwitch) -> Void)) -> Self {
onSwitchChanged = handler
return self
}
// MARK: - Initializer
public convenience init() {
self.init(frame: .zero)
}
public override init(frame: CGRect) {
super.init(frame: frame)
addSubview(track)
addSubview(slider)
addGestureRecognizers()
setOn(on: isOn, animated: false)
}
public convenience init(frame: CGRect, isOn: Bool) {
self.init(frame: frame)
setOn(on: isOn, animated: false)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func layoutSubviews() {
super.layoutSubviews()
var trackFrame: CGRect = .zero
var thumbFrame: CGRect = .zero
trackFrame.size.height = frame.height / 2.2
trackFrame.size.width = frame.size.width
trackFrame.origin.x = 0.0
trackFrame.origin.y = (frame.size.height - trackFrame.size.height) / 2
thumbFrame.size.height = frame.width * 5 / 8
thumbFrame.size.width = thumbFrame.size.height
thumbFrame.origin.x = 0.0
thumbFrame.origin.y = (frame.size.height - thumbFrame.size.height) / 2
track.frame = trackFrame
track.layer.cornerRadius = min(track.frame.size.height, track.frame.size.width) / 2
slider.frame = thumbFrame
slider.layer.cornerRadius = slider.frame.size.height / 2
thumbOnPosition = frame.size.width - slider.frame.size.width
thumbOffPosition = slider.frame.origin.x
}
open func addGestureRecognizers() {
slider.addTarget(self, action: #selector(onTouchDown(btn:withEvent:)), for: UIControlEvents.touchDown)
slider.addTarget(self, action: #selector(onTouchUpOutsideOrCanceled(btn:withEvent:)), for: UIControlEvents.touchUpOutside)
slider.addTarget(self, action: #selector(sliderTapped), for: UIControlEvents.touchUpInside)
slider.addTarget(self, action: #selector(onTouchDragInside(btn:withEvent:)), for: UIControlEvents.touchDragInside)
slider.addTarget(self, action: #selector(onTouchUpOutsideOrCanceled(btn:withEvent:)), for: UIControlEvents.touchCancel)
let singleTap = UITapGestureRecognizer(target: self, action: #selector(switchAreaTapped(recognizer:)))
addGestureRecognizer(singleTap)
}
open func setOn(on: Bool, animated: Bool) {
if on {
if animated {
changeThumbStateONwithAnimation()
} else {
changeThumbStateONwithoutAnimation()
}
} else {
if animated {
changeThumbStateOFFwithAnimation()
} else {
changeThumbStateOFFwithoutAnimation()
}
}
}
open func setEnabled(enabled: Bool) {
super.isEnabled = enabled
UIView.animate(withDuration: 0.1) {
if enabled {
if self.isOn {
self.slider.backgroundColor = self.sliderOnTintColor
self.track.backgroundColor = self.trackOnTintColor
} else {
self.slider.backgroundColor = self.sliderOffTintColor
self.track.backgroundColor = self.trackOffTintColor
}
self.isEnabled = true
} else {
self.slider.backgroundColor = self.sliderDisabledTintColor
self.track.backgroundColor = self.trackDisabledTintColor
self.isEnabled = false
}
}
}
@objc open func switchAreaTapped(recognizer: UITapGestureRecognizer) {
changeThumbState()
}
fileprivate func changeThumbState() {
if isOn {
changeThumbStateOFFwithAnimation()
} else {
changeThumbStateONwithAnimation()
}
if isRippleEnabled {
animateRippleEffect()
}
}
fileprivate func changeThumbStateONwithAnimation() {
// switch movement animation
UIView.animate(withDuration: 0.15, delay: 0.05, options: UIViewAnimationOptions.curveEaseInOut, animations: {
var thumbFrame = self.slider.frame
thumbFrame.origin.x = self.thumbOnPosition + self.bounceOffset
self.slider.frame = thumbFrame
if self.isEnabled {
self.slider.hideShadow()
self.slider.backgroundColor = self.sliderOnTintColor
self.track.backgroundColor = self.trackOnTintColor
} else {
self.slider.backgroundColor = self.sliderDisabledTintColor
self.track.backgroundColor = self.trackDisabledTintColor
}
self.isUserInteractionEnabled = false
}) { (finished) in
// change state to ON
if self.isOn {
self.isOn = true // Expressly put this code here to change surely and send action correctly
self.sendActions(for: UIControlEvents.valueChanged)
}
self.isOn = true
UIView.animate(withDuration: 0.15, animations: {
// Bounce to the position
var thumbFrame = self.slider.frame
thumbFrame.origin.x = self.thumbOnPosition
self.slider.frame = thumbFrame
}, completion: { (finished) in
self.isUserInteractionEnabled = true
})
}
}
fileprivate func changeThumbStateOFFwithAnimation() {
// switch movement animation
UIView.animate(withDuration: 0.15, delay: 0.05, options: UIViewAnimationOptions.curveEaseInOut, animations: {
var thumbFrame = self.slider.frame
thumbFrame.origin.x = self.thumbOffPosition - self.bounceOffset
self.slider.frame = thumbFrame
if self.isEnabled {
self.slider.backgroundColor = self.sliderOffTintColor
self.track.backgroundColor = self.trackOffTintColor
} else {
self.slider.setDefaultShadow()
self.slider.backgroundColor = self.sliderDisabledTintColor
self.track.backgroundColor = self.trackDisabledTintColor
}
self.isUserInteractionEnabled = false
}) { (finished) in
// change state to OFF
if self.isOn {
self.isOn = false // Expressly put this code here to change surely and send action correctly
self.sendActions(for: UIControlEvents.valueChanged)
}
self.isOn = false
UIView.animate(withDuration: 0.15, animations: {
// Bounce to the position
var thumbFrame = self.slider.frame
thumbFrame.origin.x = self.thumbOffPosition
self.slider.frame = thumbFrame
}, completion: { (finish) in
self.isUserInteractionEnabled = true
})
}
}
// Without animation
fileprivate func changeThumbStateONwithoutAnimation() {
var thumbFrame = slider.frame
thumbFrame.origin.x = thumbOnPosition
slider.frame = thumbFrame
if isEnabled {
slider.backgroundColor = sliderOnTintColor
track.backgroundColor = trackOnTintColor
} else {
slider.hideShadow()
slider.backgroundColor = sliderDisabledTintColor
track.backgroundColor = trackDisabledTintColor
}
if isOn {
isOn = true
sendActions(for: UIControlEvents.valueChanged)
}
isOn = true
}
// Without animation
fileprivate func changeThumbStateOFFwithoutAnimation() {
var thumbFrame = slider.frame
thumbFrame.origin.x = thumbOffPosition
slider.frame = thumbFrame
if isEnabled {
slider.backgroundColor = sliderOffTintColor
track.backgroundColor = trackOffTintColor
} else {
slider.setDefaultShadow()
slider.backgroundColor = sliderDisabledTintColor
track.backgroundColor = trackDisabledTintColor
}
if isOn {
isOn = false
sendActions(for: UIControlEvents.valueChanged)
}
isOn = false
}
fileprivate func initializeRipple() {
// Ripple size is twice as large as switch thumb
let rippleScale : CGFloat = 2
var rippleFrame = CGRect.zero
rippleFrame.origin.x = -slider.frame.size.width / (rippleScale * 2)
rippleFrame.origin.y = -slider.frame.size.height / (rippleScale * 2)
rippleFrame.size.height = slider.frame.size.height * rippleScale
rippleFrame.size.width = rippleFrame.size.height
let path = UIBezierPath(roundedRect: rippleFrame, cornerRadius: slider.layer.cornerRadius*2)
rippleLayer = CAShapeLayer()
rippleLayer.path = path.cgPath
rippleLayer.frame = rippleFrame
rippleLayer.opacity = 0.2
rippleLayer.strokeColor = UIColor.clear.cgColor
rippleLayer.fillColor = rippleColor.cgColor
rippleLayer.lineWidth = 0
slider.layer.insertSublayer(rippleLayer, below: slider.layer)
}
open func animateRippleEffect() {
if rippleLayer == nil {
initializeRipple()
}
rippleLayer.opacity = 0.0
CATransaction.begin()
CATransaction.setCompletionBlock {
if self.rippleLayer != nil {
self.rippleLayer.removeFromSuperlayer()
self.rippleLayer = nil
}
}
// Scale ripple to the modelate size
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.fromValue = 0.5
scaleAnimation.toValue = 1.25
// Alpha animation for smooth disappearing
let alphaAnimation = CABasicAnimation(keyPath: "opacity")
alphaAnimation.fromValue = 0.4
alphaAnimation.toValue = 0
// Do above animations at the same time with proper duration
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, alphaAnimation]
animation.duration = 0.4
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
rippleLayer.add(animation, forKey: nil)
CATransaction.commit()
}
//MARK: - Event Actions
@objc func onTouchDown(btn: UIButton, withEvent event: UIEvent) {
if isRippleEnabled {
if rippleLayer == nil {
initializeRipple()
}
// Animate for appearing ripple circle when tap and hold the switch thumb
CATransaction.begin()
let scaleAnimation = CABasicAnimation(keyPath: "transform.scale")
scaleAnimation.fromValue = 0.0
scaleAnimation.toValue = 1.0
let alphaAnimation = CABasicAnimation(keyPath:"opacity")
alphaAnimation.fromValue = 0
alphaAnimation.toValue = 0.2
// Do above animations at the same time with proper duration
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, alphaAnimation]
animation.duration = 0.4
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut)
rippleLayer.add(animation, forKey: nil)
CATransaction.commit()
}
}
@objc internal func sliderTapped() {
changeThumbState()
}
// Change thumb state when touchUPOutside action is detected
@objc internal func onTouchUpOutsideOrCanceled(btn: UIButton, withEvent event: UIEvent) {
// print("Touch released at ouside")
if let touch = event.touches(for: btn)?.first {
let prevPos = touch.previousLocation(in: btn)
let pos = touch.location(in: btn)
let dX = pos.x - prevPos.x
//Get the new origin after this motion
let newXOrigin = btn.frame.origin.x + dX
if (newXOrigin > (frame.size.width - slider.frame.size.width)/2) {
changeThumbStateONwithAnimation()
} else {
changeThumbStateOFFwithAnimation()
}
if isRippleEnabled {
animateRippleEffect()
}
}
}
// Drag the switch thumb
@objc internal func onTouchDragInside(btn: UIButton, withEvent event:UIEvent) {
//This code can go awry if there is more than one finger on the screen
if let touch = event.touches(for: btn)?.first {
let prevPos = touch.previousLocation(in: btn)
let pos = touch.location(in: btn)
let dX = pos.x - prevPos.x
//Get the original position of the thumb
var thumbFrame = btn.frame
thumbFrame.origin.x += dX
//Make sure it's within two bounds
thumbFrame.origin.x = min(thumbFrame.origin.x, thumbOnPosition)
thumbFrame.origin.x = max(thumbFrame.origin.x, thumbOffPosition)
//Set the thumb's new frame if need to
if thumbFrame.origin.x != btn.frame.origin.x {
btn.frame = thumbFrame
}
}
}
}
| mit | 5d8f374785972d248df86fb30f8b93c0 | 35.404612 | 150 | 0.598963 | 5.328322 | false | false | false | false |
tomerciucran/TMRCircleTimer | TMRCircleView.swift | 2 | 1594 | //
// CircleView.swift
// ExerciseDemo
//
// Created by Tomer Ciucran on 24/09/15.
// Copyright © 2015 tomerciucran. All rights reserved.
//
import UIKit
class TMRCircleView: UIView {
var circleLayer: CAShapeLayer!
init(frame: CGRect, fillColor: UIColor, strokeColor: UIColor, lineWidth: CGFloat) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
// Draw the circle path with UIBezierPath
let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)
circleLayer = CAShapeLayer()
circleLayer.path = circlePath.CGPath
circleLayer.fillColor = fillColor.CGColor
circleLayer.strokeColor = strokeColor.CGColor
circleLayer.lineWidth = 5.0
circleLayer.strokeEnd = 0.0
layer.addSublayer(circleLayer)
}
func animateCircle(duration: Int) {
// Animate the strokeEnd property of the circleLayer
let animation = CABasicAnimation(keyPath: "strokeEnd")
animation.duration = Double(duration)
animation.fromValue = 0
animation.toValue = 1
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
circleLayer.strokeEnd = 1.0
circleLayer.addAnimation(animation, forKey: "animateCircle")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 8cb9ab949a2010ebbe09df6055e1a354 | 33.630435 | 212 | 0.665411 | 4.551429 | false | false | false | false |
SebastianBoldt/Jelly | Jelly/Classes/private/Extensions/UIView+RoundCorners.swift | 1 | 1023 | import UIKit
extension UIView {
func roundCorners(_ corners: CACornerMask, radius: CGFloat) {
if #available(iOS 11, *) {
self.layer.cornerRadius = radius
self.layer.maskedCorners = corners
} else {
var cornerMask = UIRectCorner()
if(corners.contains(.layerMinXMinYCorner)){
cornerMask.insert(.topLeft)
}
if(corners.contains(.layerMaxXMinYCorner)){
cornerMask.insert(.topRight)
}
if(corners.contains(.layerMinXMaxYCorner)){
cornerMask.insert(.bottomLeft)
}
if(corners.contains(.layerMaxXMaxYCorner)){
cornerMask.insert(.bottomRight)
}
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: cornerMask, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
self.layer.mask = mask
}
}
}
| mit | 168421d12930fe0e2a6412472d6a3c35 | 35.535714 | 144 | 0.56696 | 5.384211 | false | false | false | false |
iOSDevCamp/iOSApp | iOSFunMixerApp/iOSFunMixerApp/ViewController.swift | 1 | 17244 | //
// ViewController.swift
// iOSFunMixerApp
//
// Created by Juncheng Han on 7/23/16.
// Copyright © 2016 iOSDevCamp. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import Social
import Accounts
class ViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate, TableHolderViewControllerDelegate {
@IBOutlet weak var refreashButton: UIButton!
@IBOutlet weak var chooseAgainButton: UIButton!
@IBOutlet weak var mixedImage: UIImageView!
@IBOutlet weak var mixItButton: UIButton!
@IBOutlet weak var chooseImageLabel: UILabel!
@IBOutlet weak var firstButton: UIButton!
@IBOutlet weak var secondButton: UIButton!
@IBOutlet weak var twitterButton: UIButton!
@IBOutlet weak var facebookButton: UIButton!
@IBOutlet weak var moreButton: UIButton!
@IBOutlet weak var imageA: UIImageView!
@IBOutlet weak var imageB: UIImageView!
var ImageTest: UIImageView?
var resultImage: UIImage!
@IBOutlet weak var debuggingLabel: UILabel!
var resultUrl: NSURL?
var isMixIt: Bool? = false
var buttonTag: Int!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//self.navigationItem.
imageA.backgroundColor = UIColor.whiteColor()
imageA.layer.cornerRadius = 8;
imageA.layer.borderWidth = 4;
imageA.layer.borderColor = UIColor.whiteColor().CGColor
imageA.clipsToBounds = true
imageB.backgroundColor = UIColor.whiteColor()
imageB.layer.cornerRadius = 8;
imageB.layer.borderWidth = 4;
imageB.layer.borderColor = UIColor.whiteColor().CGColor
imageB.clipsToBounds = true
firstButton.tag = 1
// firstButton.titleLabel?.font = UIFont.init(name: "IndieFlower", size: 24)
// firstButton.titleLabel?.text = "A"
// firstButton.titleLabel?.textColor = UIColor.blueColor()
secondButton.tag = 2
//chooseAgainButton.hidden = true
chooseAgainButton.alpha = 0.0
refreashButton.alpha = 0.0
mixedImage.backgroundColor = UIColor.whiteColor()
mixedImage.layer.cornerRadius = 8;
mixedImage.layer.borderWidth = 4;
mixedImage.layer.borderColor = UIColor.whiteColor().CGColor
mixedImage.clipsToBounds = true
mixItButton.enabled = false
self.navigationController?.navigationBar.barTintColor = UIColor(red:0.98, green:0.39, blue:0.32, alpha:1.0)
self.navigationController?.navigationBar.titleTextAttributes =
[NSForegroundColorAttributeName: UIColor.whiteColor(),
NSFontAttributeName: UIFont(name: "GiddyupStd", size: 24)!]
facebookButton.alpha = 0
twitterButton.alpha = 0
moreButton.alpha = 0
ImageTest = UIImageView.init()
self.loadImageFromUrl("https://www.rapunzelskincare.com/pic7.jpg", view: ImageTest!, save: true)
self.loadImageFromUrl("https://www.rapunzelskincare.com/pic2.jpg", view: ImageTest!, save: true)
// firstButton.titleLabel!.text = "A"
// secondButton.titleLabel!.text = "B"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func firstButton(sender: UIButton) {
self.buttonAction(sender.tag)
}
@IBAction func secondButton(sender: UIButton) {
self.buttonAction(sender.tag)
}
func buttonAction(tag: Int) {
let myActionSheetC:UIAlertController = UIAlertController(title: "Select Photo From", message: "", preferredStyle:.ActionSheet)
let Camera = UIAlertAction(title: "Camera", style: .Default, handler:{
(action: UIAlertAction!) -> Void in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera;
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
})
let library = UIAlertAction(title: "Library", style: .Default,handler:{
(action:UIAlertAction!) -> Void in
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary;
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
})
let Flicker = UIAlertAction(title: "Flicker", style: .Default, handler: {
(action:UIAlertAction!) -> Void in
let nextView = self.storyboard?.instantiateViewControllerWithIdentifier("PhotoTableView") as? TableHolderViewController
nextView?.myDelegate = self
self.navigationController?.pushViewController(nextView!, animated: true)
})
let cancel = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
myActionSheetC.addAction(library);
myActionSheetC.addAction(Camera);
myActionSheetC.addAction(Flicker);
buttonTag = tag
myActionSheetC.addAction(cancel);self.presentViewController(myActionSheetC, animated: true, completion: nil)
}
@IBAction func mixIt(sender: AnyObject) {
self.firstButton.hidden = true;
self.secondButton.hidden = true;
UIView.animateWithDuration(0.5, delay: 0.0, options: [], animations: {
self.mixItButton.alpha = 0.0
self.imageA.alpha = 0.0
self.imageB.alpha = 0.0
}) { _ in
self.chooseImageLabel.text = "Result"
self.imageA.hidden = true
self.imageB.hidden = true
//self.mixedImage.hidden = false;
//self.mixedImage.hnk_setImageFromURL(NSURL(string: "http://104.198.111.147/mixpx/cartoon.png")!)
//self.loadImageFromUrl("http://104.198.111.147/mixpx/cartoon.png", view: self.mixedImage)
self.resultUrl = NSURL(string: "http://104.198.111.147/mixpx/cartoon.png")
//self.chooseAgainButton.hidden = false
//self.chooseAgainButton.alpha = 1
UIView.animateWithDuration(0.3, animations: {
self.chooseAgainButton.alpha = 1.0
self.refreashButton.alpha = 1.0
})
self.facebookButton.alpha = 1
self.twitterButton.alpha = 1
self.moreButton.alpha = 1
}
self.sendPostRequest()
}
func sendPostRequest()
{
let url1 = "https://www.rapunzelskincare.com/pic7.jpg"
//"https://farm9.staticflickr.com/8561/28218619000_3d827d5c88_m.jpg"
let url2 = "https://www.rapunzelskincare.com/pic2.jpg"
//"https://farm9.staticflickr.com/8404/27886381643_51c6a1b34f_m.jpg"
let url = "http://104.198.111.147:5000/echo?url1=\(url1)&url2=\(url2)"
Alamofire.request(.POST, url, parameters: nil).responseJSON { response in
if let json = response.result.value {
var jsonObj = JSON(json)
print(jsonObj[1])
}
}
let finalURL = "http://104.198.111.147/mixpx/cartoon.png"
self.mixedImage.hidden = false;
self.loadImageFromUrl(finalURL, view: self.mixedImage, save: false)
// let image: UIImage? = UIImage.init(named: "images.jpeg")
//
//
//
//
// let url_1 = NSURL(string: url)
//
// let request = NSMutableURLRequest(URL: url_1!)
// request.HTTPMethod = "POST"
//
// let boundary = generateBoundaryString()
//
// //define the multipart request type
//
// request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
//
// if (image == nil)
// {
// return
// }
//
// let image_data = UIImagePNGRepresentation(image!)
//
// if(image_data == nil)
// {
// return
// }
//
// let body = NSMutableData()
//
// let fname = "test.png"
// let mimetype = "image/png"
//
//
// //define the data post parameter
//
// body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// body.appendData("Content-Disposition:form-data; name=\"test\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// body.appendData("hi\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
//
//
//
// body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// body.appendData("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// body.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// body.appendData(image_data!)
// body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
//
//
// body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
//
//
//
// request.HTTPBody = body
//
// let session = NSURLSession.sharedSession()
//
//
// let task = session.dataTaskWithRequest(request) {
// (
// let data, let response, let error) in
//
// guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
// print("error")
// return
// }
//
// let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
// print(dataString)
//
// }
//
// task.resume()
}
func generateBoundaryString() -> String
{
return "Boundary-\(NSUUID().UUIDString)"
}
func sendUrlToPreviousVC(url: String) {
switch buttonTag! {
case 1:
self.loadImageFromUrl(url, view: imageA, save: false)
//imageA.hnk_setImageFromURL(NSURL(string: url)!)
self.isImagesReady()
firstButton.titleLabel!.text = ""
case 2:
self.loadImageFromUrl(url, view: imageB, save: false)
//imageB.hnk_setImageFromURL(NSURL(string: url)!)
self.isImagesReady()
secondButton.titleLabel!.text = ""
default:
break
}
}
@IBAction func chooseAgainAction(sender: AnyObject) {
mixedImage.image = nil;
mixItButton.setImage(UIImage.init(named: "DisabledMixIt"), forState: .Normal)
UIView.animateWithDuration(0.6 ,animations: {
self.mixItButton.transform = CGAffineTransformMakeScale(0.6, 0.6)
},completion: { finish in
UIView.animateWithDuration(0.6){
self.mixItButton.transform = CGAffineTransformIdentity
}
})
mixItButton.enabled = false
imageA.image = nil
imageB.image = nil
firstButton.titleLabel!.text = "A"
secondButton.titleLabel!.text = "B"
firstButton.hidden = false;
secondButton.hidden = false;
imageA.hidden = false
imageB.hidden = false
chooseImageLabel.text = "Choose your images"
mixedImage.hidden = true;
self.chooseAgainButton.alpha = 0
self.refreashButton.alpha = 0
UIView.animateWithDuration(0.5, delay: 0.0, options: [], animations: {
self.mixItButton.alpha = 1.0
self.imageA.alpha = 1.0
self.imageB.alpha = 1.0
}) { _ in
self.mixedImage.image = UIImage.init()
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let image = info[UIImagePickerControllerOriginalImage] as? UIImage;
switch buttonTag! {
case 1:
imageA.image = image
self.isImagesReady()
firstButton.titleLabel?.text = ""
case 2:
imageB.image = image
self.isImagesReady()
secondButton.titleLabel?.text = ""
default:
break
}
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func shareToFacebook(sender: UIButton) {
let sharetoFacebook : SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
sharetoFacebook.addURL(resultUrl!)
//sharetoFacebook.addImage(image: UIImage!)
self.presentViewController(sharetoFacebook, animated: true, completion: nil)
}
@IBAction func shereToTwitter(sender: UIButton) {
let sharetoTwitter : SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
sharetoTwitter.addURL(resultUrl)
self.presentViewController(sharetoTwitter, animated: true, completion: nil)
}
@IBAction func share(sender: UIButton) {
//let text = "sample text"
//let image = UIImage()
//let items = [text,image]
// UIActivityViewControllerをインスタンス化
if (resultUrl != nil) {
let activityVc = UIActivityViewController(activityItems: [(resultUrl?.absoluteString)! as NSString], applicationActivities: nil)
// UIAcitivityViewControllerを表示
self.presentViewController(activityVc, animated: true, completion: nil)
}
}
func showActivityController(){
let imageToshare = []
let activityController = UIActivityViewController(activityItems: imageToshare as [AnyObject], applicationActivities: nil)
presentViewController(activityController, animated: true, completion: nil)
}
func isImagesReady() {
mixItButton.enabled = true
if imageA.image != nil && imageB.image != nil {
mixItButton.setImage(UIImage.init(named: "MixIt"), forState: .Normal)
UIView.animateWithDuration(0.6 ,animations: {
self.mixItButton.transform = CGAffineTransformMakeScale(0.6, 0.6)
},completion: { finish in
UIView.animateWithDuration(0.6){
self.mixItButton.transform = CGAffineTransformIdentity
}
})
}
}
@IBAction func refreashAction(sender: AnyObject) {
let finalURL = "http://104.198.111.147/mixpx/cartoon.png"
self.mixedImage.hidden = false;
self.loadImageFromUrl(finalURL, view: self.mixedImage, save: false)
}
func loadImageFromUrl(url: String, view: UIImageView, save: Bool){
// Create Url from string
let url = NSURL(string: url)!
// Download task:
// - sharedSession = global NSURLCache, NSHTTPCookieStorage and NSURLCredentialStorage objects.
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (responseData, responseUrl, error) -> Void in
// if responseData is not null...
if let data = responseData{
// execute in UI thread
dispatch_async(dispatch_get_main_queue(), { () -> Void in
//print(UIImage(data: data))
view.image = UIImage(data: data)
if (save) {
UIImageWriteToSavedPhotosAlbum(UIImage(data: data)!, nil, nil, nil)
}
})
}
}
// Run task
task.resume()
}
}
| mit | 03c7b5b215def74e7ba6f617cce6e804 | 34.728216 | 149 | 0.568434 | 5.070966 | false | false | false | false |
dschwartz783/MandelbrotSet | Sources/MandelbrotSet/main.swift | 1 | 6524 | //
// main.swift
// MandelbrotSet
//
// Created by David Schwartz on 6/4/17.
// Copyright © 2017 DDS Programming. All rights reserved.
//
import Cocoa
class MandelbrotDrawClass {
let maxIterations = 50000
var Ox: Float80 = -2 {
willSet {
print("old Ox: \(Ox)")
}
didSet {
print("new Ox: \(Ox)")
}
}
var Oy: Float80 = -2 {
willSet {
print("old Oy: \(Oy)")
}
didSet {
print("new Oy: \(Oy)")
}
}
var Lx: Float80 = 4 {
willSet {
print("old Lx: \(Lx)")
}
didSet {
print("new Lx: \(Lx)")
}
}
var Ly: Float80 = 4 {
willSet {
print("old Ly: \(Ly)")
}
didSet {
print("new Ly: \(Ly)")
}
}
// let height = Int(ProcessInfo.processInfo.arguments[1]) ?? 1000
// let width = Int(ProcessInfo.processInfo.arguments[1]) ?? 1000
let rect: CGRect
var randomColorList: [Int: NSColor] = [:]
let saveThread = DispatchQueue(label: "savethread")
let cgContext = CGDisplayGetDrawingContext(CGMainDisplayID())!
let newContext: NSGraphicsContext
let drawQueue = DispatchQueue(label: "drawQueue")
init() {
for i in 0...maxIterations {
self.randomColorList[i] = NSColor(
calibratedRed: CGFloat(arc4random()) / CGFloat(UInt32.max),
green: CGFloat(arc4random()) / CGFloat(UInt32.max),
blue: CGFloat(arc4random()) / CGFloat(UInt32.max),
alpha: CGFloat(arc4random()) / CGFloat(UInt32.max))
}
newContext = NSGraphicsContext(cgContext: cgContext, flipped: false)
rect = CGDisplayBounds(CGMainDisplayID())
self.Ox = -(Lx / 2) * Float80(rect.width) / Float80(rect.height)
self.Lx = Ly * Float80(rect.width) / Float80(rect.height)
NSGraphicsContext.current = newContext
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "draw"), object: nil, queue: nil) { (aNotification) in
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "zoomDec"), object: nil, queue: nil) { (aNotification) in
self.Ox -= self.Lx / 2
self.Oy -= self.Ly / 2
self.Lx *= 2
self.Ly *= 2
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "zoomInc"), object: nil, queue: nil) { (aNotification) in
self.Ox += self.Lx / 4
self.Oy += self.Ly / 4
self.Lx /= 2
self.Ly /= 2
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "offsetDecX"), object: nil, queue: nil) { (aNotification) in
self.Ox -= self.Lx / 4
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "offsetIncX"), object: nil, queue: nil) { (aNotification) in
self.Ox += self.Lx / 4
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "offsetDecY"), object: nil, queue: nil) { (aNotification) in
self.Oy -= self.Ly / 4
self.draw()
}
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "offsetIncY"), object: nil, queue: nil) { (aNotification) in
self.Oy += self.Ly / 4
self.draw()
}
}
func draw() {
self.drawQueue.async {
autoreleasepool {
let offscreenRep = NSBitmapImageRep(
bitmapDataPlanes:nil,
pixelsWide:Int(self.rect.width),
pixelsHigh:Int(self.rect.height),
bitsPerSample:8,
samplesPerPixel:4,
hasAlpha:true,
isPlanar:false,
colorSpaceName:NSColorSpaceName.deviceRGB,
bitmapFormat:NSBitmapImageRep.Format.alphaFirst,
bytesPerRow:0,
bitsPerPixel:0
)!
let context = NSGraphicsContext(bitmapImageRep: offscreenRep)!
// NSGraphicsContext.current = context
let image = context.cgContext.makeImage()!
let nsImage = NSImage(cgImage: image, size: self.rect.size)
var rawTiff = nsImage.tiffRepresentation!
let bytes = rawTiff.withUnsafeMutableBytes { $0 }
DispatchQueue.concurrentPerform(iterations: Int(self.rect.width)) { (x) in
for y in 0..<Int(self.rect.height) {
let calcX = self.Ox + Float80(x) / Float80(self.rect.width) * self.Lx
let calcY = self.Oy + Float80(y) / Float80(self.rect.height) * self.Ly
let iterations = Mandelbrot.calculate(
x: calcX,
y: calcY,
i: self.maxIterations
)
let color = self.randomColorList[iterations]!
bytes[8 + 4 * (y * Int(self.rect.width) + x)] = UInt8(color.redComponent * CGFloat(UInt8.max))
bytes[9 + 4 * (y * Int(self.rect.width) + x)] = UInt8(color.greenComponent * CGFloat(UInt8.max))
bytes[10 + 4 * (y * Int(self.rect.width) + x)] = UInt8(color.blueComponent * CGFloat(UInt8.max))
bytes[11 + 4 * (y * Int(self.rect.width) + x)] = 0xff
}
}
let resultImage = NSImage(data: rawTiff)
DispatchQueue.main.sync {
resultImage?.draw(in: self.rect)
}
}
}
}
}
CGDisplayCapture(CGMainDisplayID())
let drawObject = MandelbrotDrawClass()
drawObject.draw()
RunLoop.current.add(generateKeyTracker(), forMode: .default)
RunLoop.current.run()
| gpl-3.0 | 6f5298abb431ac657f326acb6cd2d54d | 34.259459 | 146 | 0.503143 | 4.672636 | false | false | false | false |
tkremenek/swift | test/Constraints/members.swift | 2 | 24425 | // RUN: %target-typecheck-verify-swift -swift-version 5
////
// Members of structs
////
struct X {
func f0(_ i: Int) -> X { }
func f1(_ i: Int) { }
mutating func f1(_ f: Float) { }
func f2<T>(_ x: T) -> T { }
}
struct Y<T> {
func f0(_: T) -> T {}
func f1<U>(_ x: U, y: T) -> (T, U) {}
}
var i : Int
var x : X
var yf : Y<Float>
func g0(_: (inout X) -> (Float) -> ()) {}
_ = x.f0(i)
x.f0(i).f1(i)
g0(X.f1) // expected-error{{partial application of 'mutating' method}}
_ = x.f0(x.f2(1))
_ = x.f0(1).f2(i)
_ = yf.f0(1)
_ = yf.f1(i, y: 1)
// Members referenced from inside the struct
struct Z {
var i : Int
func getI() -> Int { return i }
mutating func incI() {}
func curried(_ x: Int) -> (Int) -> Int { return { y in x + y } }
subscript (k : Int) -> Int {
get {
return i + k
}
mutating
set {
i -= k
}
}
}
struct GZ<T> {
var i : T
func getI() -> T { return i }
func f1<U>(_ a: T, b: U) -> (T, U) {
return (a, b)
}
func f2() {
var f : Float
var t = f1(i, b: f)
f = t.1
var zi = Z.i; // expected-error{{instance member 'i' cannot be used on type 'Z'}}
var zj = Z.asdfasdf // expected-error {{type 'Z' has no member 'asdfasdf'}}
}
}
var z = Z(i: 0)
var getI = z.getI
var incI = z.incI // expected-error{{partial application of 'mutating'}}
var zi = z.getI()
var zcurried1 = z.curried
var zcurried2 = z.curried(0)
var zcurriedFull = z.curried(0)(1)
////
// Members of modules
////
// Module
Swift.print(3, terminator: "")
////
// Unqualified references
////
////
// Members of literals
////
// FIXME: Crappy diagnostic
"foo".lower() // expected-error{{value of type 'String' has no member 'lower'}}
var tmp = "foo".debugDescription
////
// Members of enums
////
enum W {
case Omega
func foo(_ x: Int) {}
func curried(_ x: Int) -> (Int) -> () {}
}
var w = W.Omega
var foo = w.foo
var fooFull : () = w.foo(0)
var wcurried1 = w.curried
var wcurried2 = w.curried(0)
var wcurriedFull : () = w.curried(0)(1)
// Member of enum type
func enumMetatypeMember(_ opt: Int?) {
opt.none // expected-error{{enum case 'none' cannot be used as an instance member}}
}
////
// Nested types
////
// Reference a Type member. <rdar://problem/15034920>
class G<T> {
class In {
class func foo() {}
}
}
func goo() {
G<Int>.In.foo()
}
////
// Misc ambiguities
////
// <rdar://problem/15537772>
struct DefaultArgs {
static func f(_ a: Int = 0) -> DefaultArgs {
return DefaultArgs()
}
init() {
self = .f()
}
}
class InstanceOrClassMethod {
func method() -> Bool { return true }
class func method(_ other: InstanceOrClassMethod) -> Bool { return false }
}
func testPreferClassMethodToCurriedInstanceMethod(_ obj: InstanceOrClassMethod) {
let result = InstanceOrClassMethod.method(obj)
let _: Bool = result // no-warning
let _: () -> Bool = InstanceOrClassMethod.method(obj)
}
protocol Numeric {
static func +(x: Self, y: Self) -> Self
}
func acceptBinaryFunc<T>(_ x: T, _ fn: (T, T) -> T) { }
func testNumeric<T : Numeric>(_ x: T) {
acceptBinaryFunc(x, +)
}
/* FIXME: We can't check this directly, but it can happen with
multiple modules.
class PropertyOrMethod {
func member() -> Int { return 0 }
let member = false
class func methodOnClass(_ obj: PropertyOrMethod) -> Int { return 0 }
let methodOnClass = false
}
func testPreferPropertyToMethod(_ obj: PropertyOrMethod) {
let result = obj.member
let resultChecked: Bool = result
let called = obj.member()
let calledChecked: Int = called
let curried = obj.member as () -> Int
let methodOnClass = PropertyOrMethod.methodOnClass
let methodOnClassChecked: (PropertyOrMethod) -> Int = methodOnClass
}
*/
struct Foo { var foo: Int }
protocol ExtendedWithMutatingMethods { }
extension ExtendedWithMutatingMethods {
mutating func mutatingMethod() {}
var mutableProperty: Foo {
get { }
set { }
}
var nonmutatingProperty: Foo {
get { }
nonmutating set { }
}
var mutatingGetProperty: Foo {
mutating get { }
set { }
}
}
class ClassExtendedWithMutatingMethods: ExtendedWithMutatingMethods {}
class SubclassExtendedWithMutatingMethods: ClassExtendedWithMutatingMethods {}
func testClassExtendedWithMutatingMethods(_ c: ClassExtendedWithMutatingMethods, // expected-note* {{}}
sub: SubclassExtendedWithMutatingMethods) { // expected-note* {{}}
c.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'c' is a 'let' constant}}
c.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
c.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
c.nonmutatingProperty = Foo(foo: 0)
c.nonmutatingProperty.foo = 0
c.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
c.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = c.mutableProperty
_ = c.mutableProperty.foo
_ = c.nonmutatingProperty
_ = c.nonmutatingProperty.foo
// FIXME: diagnostic nondeterministically says "member" or "getter"
_ = c.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = c.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
sub.mutatingMethod() // expected-error{{cannot use mutating member on immutable value: 'sub' is a 'let' constant}}
sub.mutableProperty = Foo(foo: 0) // expected-error{{cannot assign to property}}
sub.mutableProperty.foo = 0 // expected-error{{cannot assign to property}}
sub.nonmutatingProperty = Foo(foo: 0)
sub.nonmutatingProperty.foo = 0
sub.mutatingGetProperty = Foo(foo: 0) // expected-error{{cannot use mutating}}
sub.mutatingGetProperty.foo = 0 // expected-error{{cannot use mutating}}
_ = sub.mutableProperty
_ = sub.mutableProperty.foo
_ = sub.nonmutatingProperty
_ = sub.nonmutatingProperty.foo
_ = sub.mutatingGetProperty // expected-error{{cannot use mutating}}
_ = sub.mutatingGetProperty.foo // expected-error{{cannot use mutating}}
var mutableC = c
mutableC.mutatingMethod()
mutableC.mutableProperty = Foo(foo: 0)
mutableC.mutableProperty.foo = 0
mutableC.nonmutatingProperty = Foo(foo: 0)
mutableC.nonmutatingProperty.foo = 0
mutableC.mutatingGetProperty = Foo(foo: 0)
mutableC.mutatingGetProperty.foo = 0
_ = mutableC.mutableProperty
_ = mutableC.mutableProperty.foo
_ = mutableC.nonmutatingProperty
_ = mutableC.nonmutatingProperty.foo
_ = mutableC.mutatingGetProperty
_ = mutableC.mutatingGetProperty.foo
var mutableSub = sub
mutableSub.mutatingMethod()
mutableSub.mutableProperty = Foo(foo: 0)
mutableSub.mutableProperty.foo = 0
mutableSub.nonmutatingProperty = Foo(foo: 0)
mutableSub.nonmutatingProperty.foo = 0
_ = mutableSub.mutableProperty
_ = mutableSub.mutableProperty.foo
_ = mutableSub.nonmutatingProperty
_ = mutableSub.nonmutatingProperty.foo
_ = mutableSub.mutatingGetProperty
_ = mutableSub.mutatingGetProperty.foo
}
// <rdar://problem/18879585> QoI: error message for attempted access to instance properties in static methods are bad.
enum LedModules: Int {
case WS2811_1x_5V
}
extension LedModules {
static var watts: Double {
return [0.30][self.rawValue] // expected-error {{instance member 'rawValue' cannot be used on type 'LedModules'}}
}
}
// <rdar://problem/15117741> QoI: calling a static function on an instance produces a non-helpful diagnostic
class r15117741S {
static func g() {}
}
func test15117741(_ s: r15117741S) {
s.g() // expected-error {{static member 'g' cannot be used on instance of type 'r15117741S'}}
}
// <rdar://problem/22491394> References to unavailable decls sometimes diagnosed as ambiguous
struct UnavailMember {
@available(*, unavailable)
static var XYZ : UnavailMember { get {} } // expected-note {{'XYZ' has been explicitly marked unavailable here}}
}
let _ : [UnavailMember] = [.XYZ] // expected-error {{'XYZ' is unavailable}}
let _ : [UnavailMember] = [.ABC] // expected-error {{type 'UnavailMember' has no member 'ABC'}}
// <rdar://problem/22490787> QoI: Poor error message iterating over property with non-sequence type that defines an Iterator type alias
struct S22490787 {
typealias Iterator = AnyIterator<Int>
}
func f22490787() {
var path: S22490787 = S22490787()
for p in path { // expected-error {{for-in loop requires 'S22490787' to conform to 'Sequence'}}
}
}
// <rdar://problem/23942743> [QoI] Bad diagnostic when errors inside enum constructor
enum r23942743 {
case Tomato(cloud: String)
}
let _ = .Tomato(cloud: .none) // expected-error {{reference to member 'Tomato' cannot be resolved without a contextual type}}
// expected-error@-1 {{cannot infer contextual base in reference to member 'none'}}
// SR-650: REGRESSION: Assertion failed: (baseTy && "Couldn't find appropriate context"), function getMemberSubstitutions
enum SomeErrorType {
case StandaloneError
case UnderlyingError(String)
static func someErrorFromString(_ str: String) -> SomeErrorType? {
if str == "standalone" { return .StandaloneError }
if str == "underlying" { return .UnderlyingError } // expected-error {{member 'UnderlyingError' expects argument of type 'String'}}
return nil
}
}
// SR-2193: QoI: better diagnostic when a decl exists, but is not a type
enum SR_2193_Error: Error {
case Boom
}
do {
throw SR_2193_Error.Boom
} catch let e as SR_2193_Error.Boom { // expected-error {{enum case 'Boom' is not a member type of 'SR_2193_Error'}}
}
// rdar://problem/25341015
extension Sequence {
func r25341015_1() -> Int {
return max(1, 2) // expected-error {{use of 'max' refers to instance method rather than global function 'max' in module 'Swift'}} expected-note {{use 'Swift.' to reference the global function in module 'Swift'}}
}
}
class C_25341015 {
static func baz(_ x: Int, _ y: Int) {}
func baz() {}
func qux() {
baz(1, 2) // expected-error {{static member 'baz' cannot be used on instance of type 'C_25341015'}} {{5-5=C_25341015.}}
}
}
struct S_25341015 {
static func foo(_ x: Int, y: Int) {}
func foo(z: Int) {}
func bar() {
foo(1, y: 2) // expected-error {{static member 'foo' cannot be used on instance of type 'S_25341015'}} {{5-5=S_25341015.}}
}
}
func r25341015() {
func baz(_ x: Int, _ y: Int) {}
class Bar {
func baz() {}
func qux() {
baz(1, 2) // expected-error {{use of 'baz' refers to instance method rather than local function 'baz'}}
}
}
}
func r25341015_local(x: Int, y: Int) {}
func r25341015_inner() {
func r25341015_local() {}
r25341015_local(x: 1, y: 2) // expected-error {{argument passed to call that takes no arguments}}
}
// rdar://problem/32854314 - Emit shadowing diagnostics even if argument types do not much completely
func foo_32854314() -> Double {
return 42
}
func bar_32854314() -> Int {
return 0
}
extension Array where Element == Int {
func foo() {
let _ = min(foo_32854314(), bar_32854314()) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
// expected-error@-1 {{use of 'min' refers to instance method rather than global function 'min' in module 'Swift'}}
}
func foo(_ x: Int, _ y: Double) {
let _ = min(x, y) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
// expected-error@-1 {{use of 'min' refers to instance method rather than global function 'min' in module 'Swift'}}
}
func bar() {
let _ = min(1.0, 2) // expected-note {{use 'Swift.' to reference the global function in module 'Swift'}} {{13-13=Swift.}}
// expected-error@-1 {{use of 'min' refers to instance method rather than global function 'min' in module 'Swift'}}
}
}
// Crash in diagnoseImplicitSelfErrors()
struct Aardvark {
var snout: Int
mutating func burrow() {
dig(&snout, .y) // expected-error {{type 'Int' has no member 'y'}}
}
func dig(_: inout Int, _: Int) {}
}
func rdar33914444() {
struct A {
enum R<E: Error> {
case e(E) // expected-note {{'e' declared here}}
}
struct S {
enum E: Error {
case e1
}
let e: R<E>
}
}
_ = A.S(e: .e1)
// expected-error@-1 {{type 'A.R<A.S.E>' has no member 'e1'; did you mean 'e'?}}
}
// SR-5324: Better diagnostic when instance member of outer type is referenced from nested type
struct Outer {
var outer: Int
struct Inner {
var inner: Int
func sum() -> Int {
return inner + outer
// expected-error@-1 {{instance member 'outer' of type 'Outer' cannot be used on instance of nested type 'Outer.Inner'}}
}
}
}
// rdar://problem/39514009 - don't crash when trying to diagnose members with special names
print("hello")[0] // expected-error {{value of type '()' has no subscripts}}
func rdar40537782() {
class A {}
class B : A {
override init() {}
func foo() -> A { return A() }
}
struct S<T> {
init(_ a: T...) {}
}
func bar<T>(_ t: T) {
_ = S(B(), .foo(), A()) // expected-error {{type 'A' has no member 'foo'}}
}
}
func rdar36989788() {
struct A<T> {
func foo() -> A<T> {
return self
}
}
func bar<T>(_ x: A<T>) -> (A<T>, A<T>) {
return (x.foo(), x.undefined()) // expected-error {{value of type 'A<T>' has no member 'undefined'}}
}
}
func rdar46211109() {
struct MyIntSequenceStruct: Sequence {
struct Iterator: IteratorProtocol {
var current = 0
mutating func next() -> Int? {
return current + 1
}
}
func makeIterator() -> Iterator {
return Iterator()
}
}
func foo<E, S: Sequence>(_ type: E.Type) -> S? where S.Element == E {
return nil
}
let _: MyIntSequenceStruct? = foo(Int.Self)
// expected-error@-1 {{type 'Int' has no member 'Self'}}
}
class A {}
enum B {
static func foo() {
bar(A()) // expected-error {{instance member 'bar' cannot be used on type 'B'}}
}
func bar(_: A) {}
}
class C {
static func foo() {
bar(0) // expected-error {{instance member 'bar' cannot be used on type 'C'}}
}
func bar(_: Int) {}
}
class D {
static func foo() {}
func bar() {
foo() // expected-error {{static member 'foo' cannot be used on instance of type 'D'}}
}
}
func rdar_48114578() {
struct S<T> {
var value: T
static func valueOf<T>(_ v: T) -> S<T> {
return S<T>(value: v)
}
}
typealias A = (a: [String]?, b: Int)
func foo(_ a: [String], _ b: Int) -> S<A> {
let v = (a, b)
return .valueOf(v)
}
func bar(_ a: [String], _ b: Int) -> S<A> {
return .valueOf((a, b)) // Ok
}
}
struct S_Min {
var xmin: Int = 42
}
func xmin(_: Int, _: Float) -> Int { return 0 }
func xmin(_: Float, _: Int) -> Int { return 0 }
extension S_Min : CustomStringConvertible {
public var description: String {
return "\(xmin)" // Ok
}
}
// rdar://problem/50679161
func rdar50679161() {
struct Point {}
struct S {
var w, h: Point
}
struct Q {
init(a: Int, b: Int) {}
init(a: Point, b: Point) {}
}
func foo() {
_ = { () -> Void in
var foo = S
// expected-error@-1 {{expected member name or constructor call after type name}}
// expected-note@-2 {{add arguments after the type to construct a value of the type}}
// expected-note@-3 {{use '.self' to reference the type object}}
if let v = Int?(1) {
var _ = Q(
a: v + foo.w,
// expected-error@-1 {{instance member 'w' cannot be used on type 'S'}}
// expected-error@-2 {{cannot convert value of type 'Point' to expected argument type 'Int'}}
b: v + foo.h
// expected-error@-1 {{instance member 'h' cannot be used on type 'S'}}
// expected-error@-2 {{cannot convert value of type 'Point' to expected argument type 'Int'}}
)
}
}
}
}
func rdar_50467583_and_50909555() {
if #available(macOS 11.3, iOS 14.5, tvOS 14.5, watchOS 7.4, *) {
// rdar://problem/50467583
let _: Set = [Int][] // expected-error {{no 'subscript' candidates produce the expected contextual result type 'Set'}}
// expected-error@-1 {{no exact matches in call to subscript}}
// expected-note@-2 {{found candidate with type '(Int) -> Int'}}
// expected-note@-3 {{found candidate with type '(Range<Int>) -> ArraySlice<Int>'}}
// expected-note@-4 {{found candidate with type '((UnboundedRange_) -> ()) -> ArraySlice<Int>'}}
// expected-note@-5 {{found candidate with type '(Range<Array<Int>.Index>) -> Slice<[Int]>' (aka '(Range<Int>) -> Slice<Array<Int>>')}}
}
// rdar://problem/50909555
struct S {
static subscript(x: Int, y: Int) -> Int { // expected-note {{'subscript(_:_:)' declared here}}
return 1
}
}
func test(_ s: S) {
s[1] // expected-error {{static member 'subscript' cannot be used on instance of type 'S'}} {{5-6=S}}
// expected-error@-1 {{missing argument for parameter #2 in call}} {{8-8=, <#Int#>}}
}
}
// SR-9396 (rdar://problem/46427500) - Nonsensical error message related to constrained extensions
struct SR_9396<A, B> {}
extension SR_9396 where A == Bool { // expected-note {{where 'A' = 'Int'}}
func foo() {}
}
func test_sr_9396(_ s: SR_9396<Int, Double>) {
s.foo() // expected-error {{referencing instance method 'foo()' on 'SR_9396' requires the types 'Int' and 'Bool' be equivalent}}
}
// rdar://problem/34770265 - Better diagnostic needed for constrained extension method call
extension Dictionary where Key == String { // expected-note {{where 'Key' = 'Int'}}
func rdar_34770265_key() {}
}
extension Dictionary where Value == String { // expected-note {{where 'Value' = 'Int'}}
func rdar_34770265_val() {}
}
func test_34770265(_ dict: [Int: Int]) {
dict.rdar_34770265_key()
// expected-error@-1 {{referencing instance method 'rdar_34770265_key()' on 'Dictionary' requires the types 'Int' and 'String' be equivalent}}
dict.rdar_34770265_val()
// expected-error@-1 {{referencing instance method 'rdar_34770265_val()' on 'Dictionary' requires the types 'Int' and 'String' be equivalent}}
}
// SR-12672
_ = [.e] // expected-error {{reference to member 'e' cannot be resolved without a contextual type}}
let _ : [Any] = [.e] // expected-error {{type 'Any' has no member 'e'}}
_ = [1 :.e] // expected-error {{reference to member 'e' cannot be resolved without a contextual type}}
_ = [.e: 1] // expected-error {{reference to member 'e' cannot be resolved without a contextual type}}
let _ : [Int: Any] = [1 : .e] // expected-error {{type 'Any' has no member 'e'}}
let _ : (Int, Any) = (1, .e) // expected-error {{type 'Any' has no member 'e'}}
_ = (1, .e) // expected-error {{cannot infer contextual base in reference to member 'e'}}
// SR-13359
typealias Pair = (Int, Int)
func testSR13359(_ pair: (Int, Int), _ alias: Pair, _ void: Void, labeled: (a: Int, b: Int)) {
_ = pair[0] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; did you mean to use '.0'?}} {{11-14=.0}}
_ = pair[1] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; did you mean to use '.1'?}} {{11-14=.1}}
_ = pair[2] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = pair[100] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = pair["strting"] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = pair[-1] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = pair[1, 1] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = void[0] // expected-error {{value of type 'Void' has no subscripts}}
// Other representations of literals
_ = pair[0x00] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = pair[0b00] // expected-error {{cannot access element using subscript for tuple type '(Int, Int)'; use '.' notation instead}} {{none}}
_ = alias[0] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); did you mean to use '.0'?}} {{12-15=.0}}
_ = alias[1] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); did you mean to use '.1'?}} {{12-15=.1}}
_ = alias[2] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
_ = alias[100] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
_ = alias["strting"] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
_ = alias[-1] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
_ = alias[1, 1] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
_ = alias[0x00] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
_ = alias[0b00] // expected-error {{cannot access element using subscript for tuple type 'Pair' (aka '(Int, Int)'); use '.' notation instead}} {{none}}
// Labeled tuple base
_ = labeled[0] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; did you mean to use '.0'?}} {{14-17=.0}}
_ = labeled[1] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; did you mean to use '.1'?}} {{14-17=.1}}
_ = labeled[2] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled[100] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled["strting"] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled[-1] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled[1, 1] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled[0x00] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled[0b00] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
// Suggesting use label access
_ = labeled["a"] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; did you mean to use '.a'?}} {{14-19=.a}}
_ = labeled["b"] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; did you mean to use '.b'?}} {{14-19=.b}}
_ = labeled["c"] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
_ = labeled[""] // expected-error {{cannot access element using subscript for tuple type '(a: Int, b: Int)'; use '.' notation instead}} {{none}}
}
// rdar://problem/66891544 - incorrect diagnostic ("type is ambiguous") when base type of a reference cannot be determined
func rdar66891544() {
func foo<T>(_: T, defaultT: T? = nil) {}
func foo<U>(_: U, defaultU: U? = nil) {}
foo(.bar) // expected-error {{cannot infer contextual base in reference to member 'bar'}}
}
// rdar://55369704 - extraneous diagnostics produced in combination with missing/misspelled members
func rdar55369704() {
struct S {
}
func test(x: Int, s: S) {
_ = x - Int(s.value) // expected-error {{value of type 'S' has no member 'value'}}
}
}
// SR-14533
struct SR14533 {
var xs: [Int]
}
func fSR14533(_ s: SR14533) {
for (x1, x2) in zip(s.xs, s.ys) {
// expected-error@-1{{value of type 'SR14533' has no member 'ys'}}
}
}
| apache-2.0 | 89e11ef3efb8abdcea96884f4e7f118a | 31.653743 | 215 | 0.641801 | 3.554796 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/GitHubSearchRepositories/GitHubSearchRepositoriesViewController.swift | 8 | 4271 | //
// GitHubSearchRepositoriesViewController.swift
// RxExample
//
// Created by Yoshinori Sano on 9/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
extension UIScrollView {
func isNearBottomEdge(edgeOffset: CGFloat = 20.0) -> Bool {
return self.contentOffset.y + self.frame.size.height + edgeOffset > self.contentSize.height
}
}
class GitHubSearchRepositoriesViewController: ViewController, UITableViewDelegate {
static let startLoadingOffset: CGFloat = 20.0
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Repository>>()
override func viewDidLoad() {
super.viewDidLoad()
dataSource.configureCell = { (_, tv, ip, repository: Repository) in
let cell = tv.dequeueReusableCell(withIdentifier: "Cell")!
cell.textLabel?.text = repository.name
cell.detailTextLabel?.text = repository.url.absoluteString
return cell
}
dataSource.titleForHeaderInSection = { dataSource, sectionIndex in
let section = dataSource[sectionIndex]
return section.items.count > 0 ? "Repositories (\(section.items.count))" : "No repositories found"
}
let tableView: UITableView = self.tableView
let loadNextPageTrigger: (Driver<GitHubSearchRepositoriesState>) -> Driver<()> = { state in
tableView.rx.contentOffset.asDriver()
.withLatestFrom(state)
.flatMap { state in
return tableView.isNearBottomEdge(edgeOffset: 20.0) && !state.shouldLoadNextPage
? Driver.just(())
: Driver.empty()
}
}
let activityIndicator = ActivityIndicator()
let searchBar: UISearchBar = self.searchBar
let state = githubSearchRepositories(
searchText: searchBar.rx.text.orEmpty.changed.asDriver().throttle(0.3),
loadNextPageTrigger: loadNextPageTrigger,
performSearch: { URL in
GitHubSearchRepositoriesAPI.sharedAPI.loadSearchURL(URL)
.trackActivity(activityIndicator)
})
state
.map { $0.isOffline }
.drive(navigationController!.rx.isOffline)
.disposed(by: disposeBag)
state
.map { $0.repositories }
.distinctUntilChanged()
.map { [SectionModel(model: "Repositories", items: $0.value)] }
.drive(tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
tableView.rx.modelSelected(Repository.self)
.subscribe(onNext: { repository in
UIApplication.shared.openURL(repository.url)
})
.disposed(by: disposeBag)
state
.map { $0.isLimitExceeded }
.distinctUntilChanged()
.filter { $0 }
.drive(onNext: { n in
showAlert("Exceeded limit of 10 non authenticated requests per minute for GitHub API. Please wait a minute. :(\nhttps://developer.github.com/v3/#rate-limiting")
})
.disposed(by: disposeBag)
tableView.rx.contentOffset
.subscribe { _ in
if searchBar.isFirstResponder {
_ = searchBar.resignFirstResponder()
}
}
.disposed(by: disposeBag)
// so normal delegate customization can also be used
tableView.rx.setDelegate(self)
.disposed(by: disposeBag)
// activity indicator in status bar
// {
activityIndicator
.drive(UIApplication.shared.rx.isNetworkActivityIndicatorVisible)
.disposed(by: disposeBag)
// }
}
// MARK: Table view delegate
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
deinit {
// I know, I know, this isn't a good place of truth, but it's no
self.navigationController?.navigationBar.backgroundColor = nil
}
}
| mit | 54abe4faf35022e761e982c3c417653d | 33.435484 | 177 | 0.610539 | 5.2457 | false | false | false | false |
parkboo/ios-charts | Charts/Classes/Renderers/CustomBar1ChartRenderer.swift | 1 | 22900 | //
// BarChartRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class CustomBar1ChartRenderer: ChartDataRendererBase
{
public weak var dataProvider: CustomBar1ChartDataProvider?
public init(dataProvider: CustomBar1ChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
public override func drawData(context context: CGContext)
{
guard let dataProvider = dataProvider, barData = dataProvider.customBar1Data else { return }
for (var i = 0; i < barData.dataSetCount; i++)
{
let set = barData.getDataSetByIndex(i)
if set !== nil && set!.isVisible && set.entryCount > 0
{
drawDataSet(context: context, dataSet: set as! CustomBar1ChartDataSet, index: i)
}
}
}
internal func drawDataSet(context context: CGContext, dataSet: CustomBar1ChartDataSet, index: Int)
{
guard let dataProvider = dataProvider, barData = dataProvider.customBar1Data else { return }
CGContextSaveGState(context)
let trans = dataProvider.getTransformer(dataSet.axisDependency)
let drawBarShadowEnabled: Bool = dataProvider.isDrawBarShadowEnabled
let dataSetOffset = (barData.dataSetCount - 1)
let groupSpace = barData.groupSpace
let groupSpaceHalf = groupSpace / 2.0
let barSpace = dataSet.barSpace
let barSpaceHalf = barSpace / 2.0
let containsStacks = dataSet.isStacked
let isInverted = dataProvider.isInverted(dataSet.axisDependency)
var entries = dataSet.yVals as! [BarChartDataEntry]
let barWidth: CGFloat = 0.5
let phaseY = _animator.phaseY
var barRect = CGRect()
var barShadow = CGRect()
var y: Double
// do the drawing
for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++)
{
let e = entries[j]
// calculate the x-position, depending on datasetcount
let x = CGFloat(e.xIndex + e.xIndex * dataSetOffset) + CGFloat(index)
+ groupSpace * CGFloat(e.xIndex) + groupSpaceHalf
var vals = e.values
if (!containsStacks || vals == nil)
{
y = e.value
let left = x - barWidth + barSpaceHalf
let right = x + barWidth - barSpaceHalf
var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0)
var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if (top > 0)
{
top *= phaseY
}
else
{
bottom *= phaseY
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
barShadow.origin.x = barRect.origin.x
barShadow.origin.y = viewPortHandler.contentTop
barShadow.size.width = barRect.size.width
barShadow.size.height = viewPortHandler.contentHeight
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor)
CGContextFillRect(context, barShadow)
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor)
CGContextFillRect(context, barRect)
}
else
{
var posY = 0.0
var negY = -e.negativeSum
var yStart = 0.0
// if drawing the bar shadow is enabled
if (drawBarShadowEnabled)
{
y = e.value
let left = x - barWidth + barSpaceHalf
let right = x + barWidth - barSpaceHalf
var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0)
var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if (top > 0)
{
top *= phaseY
}
else
{
bottom *= phaseY
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
barShadow.origin.x = barRect.origin.x
barShadow.origin.y = viewPortHandler.contentTop
barShadow.size.width = barRect.size.width
barShadow.size.height = viewPortHandler.contentHeight
CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor)
CGContextFillRect(context, barShadow)
}
// fill the stack
for (var k = 0; k < vals!.count; k++)
{
let value = vals![k]
if value >= 0.0
{
y = posY
yStart = posY + value
posY = yStart
}
else
{
y = negY
yStart = negY + abs(value)
negY += abs(value)
}
let left = x - barWidth + barSpaceHalf
let right = x + barWidth - barSpaceHalf
var top: CGFloat, bottom: CGFloat
if isInverted
{
bottom = y >= yStart ? CGFloat(y) : CGFloat(yStart)
top = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
else
{
top = y >= yStart ? CGFloat(y) : CGFloat(yStart)
bottom = y <= yStart ? CGFloat(y) : CGFloat(yStart)
}
// multiply the height of the rect with the phase
top *= phaseY
bottom *= phaseY
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
trans.rectValueToPixel(&barRect)
if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
// Skip to next bar
break
}
// avoid drawing outofbounds values
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor)
CGContextFillRect(context, barRect)
}
}
}
CGContextRestoreGState(context)
}
/// Prepares a bar for being highlighted.
internal func prepareBarHighlight(x x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, inout rect: CGRect)
{
let barWidth: CGFloat = 0.5
let left = x - barWidth + barspacehalf
let right = x + barWidth - barspacehalf
let top = CGFloat(y1)
let bottom = CGFloat(y2)
rect.origin.x = left
rect.origin.y = top
rect.size.width = right - left
rect.size.height = bottom - top
trans.rectValueToPixel(&rect, phaseY: _animator.phaseY)
}
public override func drawValues(context context: CGContext)
{
// if values are drawn
if (passesCheck())
{
guard let dataProvider = dataProvider, barData = dataProvider.customBar1Data else { return }
var dataSets = barData.dataSets
let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled
var posOffset: CGFloat
var negOffset: CGFloat
for (var i = 0, count = barData.dataSetCount; i < count; i++)
{
let dataSet = dataSets[i] as! CustomBar1ChartDataSet
if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0
{
continue
}
let isInverted = dataProvider.isInverted(dataSet.axisDependency)
// calculate the correct offset depending on the draw position of the value
let valueOffsetPlus: CGFloat = 4.5
let valueFont = dataSet.valueFont
let valueTextHeight = valueFont.lineHeight
posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus)
negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus))
if (isInverted)
{
posOffset = -posOffset - valueTextHeight
negOffset = -negOffset - valueTextHeight
}
let valueTextColor = dataSet.valueTextColor
let formatter = dataSet.valueFormatter
let trans = dataProvider.getTransformer(dataSet.axisDependency)
var entries = dataSet.yVals as! [BarChartDataEntry]
var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i)
// if only single values are drawn (sum)
if (!dataSet.isStacked)
{
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
if (!viewPortHandler.isInBoundsRight(valuePoints[j].x))
{
break
}
if (!viewPortHandler.isInBoundsY(valuePoints[j].y)
|| !viewPortHandler.isInBoundsLeft(valuePoints[j].x))
{
continue
}
let val = entries[j].value
drawValue(context: context,
value: formatter!.stringFromNumber(val)!,
xPos: valuePoints[j].x,
yPos: valuePoints[j].y + (val >= 0.0 ? posOffset : negOffset),
font: valueFont,
align: .Center,
color: valueTextColor)
}
}
else
{
// if we have stacks
for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++)
{
let e = entries[j]
let values = e.values
// we still draw stacked bars, but there is one non-stacked in between
if (values == nil)
{
if (!viewPortHandler.isInBoundsRight(valuePoints[j].x))
{
break
}
if (!viewPortHandler.isInBoundsY(valuePoints[j].y)
|| !viewPortHandler.isInBoundsLeft(valuePoints[j].x))
{
continue
}
drawValue(context: context,
value: formatter!.stringFromNumber(e.value)!,
xPos: valuePoints[j].x,
yPos: valuePoints[j].y + (e.value >= 0.0 ? posOffset : negOffset),
font: valueFont,
align: .Center,
color: valueTextColor)
}
else
{
// draw stack values
let vals = values!
var transformed = [CGPoint]()
var posY = 0.0
var negY = -e.negativeSum
for (var k = 0; k < vals.count; k++)
{
let value = vals[k]
var y: Double
if value >= 0.0
{
posY += value
y = posY
}
else
{
y = negY
negY -= value
}
transformed.append(CGPoint(x: 0.0, y: CGFloat(y) * _animator.phaseY))
}
trans.pointValuesToPixel(&transformed)
for (var k = 0; k < transformed.count; k++)
{
let x = valuePoints[j].x
let y = transformed[k].y + (vals[k] >= 0 ? posOffset : negOffset)
if (!viewPortHandler.isInBoundsRight(x))
{
break
}
if (!viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x))
{
continue
}
drawValue(context: context,
value: formatter!.stringFromNumber(vals[k])!,
xPos: x,
yPos: y,
font: valueFont,
align: .Center,
color: valueTextColor)
}
}
}
}
}
}
}
/// Draws a value at the specified x and y position.
internal func drawValue(context context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: UIFont, align: NSTextAlignment, color: UIColor)
{
ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color])
}
public override func drawExtras(context context: CGContext)
{
}
private var _highlightArrowPtsBuffer = [CGPoint](count: 3, repeatedValue: CGPoint())
public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight])
{
guard let dataProvider = dataProvider, barData = dataProvider.customBar1Data else { return }
CGContextSaveGState(context)
let setCount = barData.dataSetCount
let drawHighlightArrowEnabled = dataProvider.isDrawHighlightArrowEnabled
var barRect = CGRect()
for (var i = 0; i < indices.count; i++)
{
let h = indices[i]
let index = h.xIndex
let dataSetIndex = h.dataSetIndex
let set = barData.getDataSetByIndex(dataSetIndex) as! CustomBar1ChartDataSet!
if (set === nil || !set.isHighlightEnabled)
{
continue
}
let barspaceHalf = set.barSpace / 2.0
let trans = dataProvider.getTransformer(set.axisDependency)
CGContextSetFillColorWithColor(context, set.highlightColor.CGColor)
CGContextSetAlpha(context, set.highlightAlpha)
// check outofbounds
if (CGFloat(index) < (CGFloat(dataProvider.chartXMax) * _animator.phaseX) / CGFloat(setCount))
{
let e = set.entryForXIndex(index) as! BarChartDataEntry!
if (e === nil || e.xIndex != index)
{
continue
}
let groupspace = barData.groupSpace
let isStack = h.stackIndex < 0 ? false : true
// calculate the correct x-position
let x = CGFloat(index * setCount + dataSetIndex) + groupspace / 2.0 + groupspace * CGFloat(index)
let y1: Double
let y2: Double
if (isStack)
{
y1 = h.range?.from ?? 0.0
y2 = h.range?.to ?? 0.0
}
else
{
y1 = e.value
y2 = 0.0
}
prepareBarHighlight(x: x, y1: y1, y2: y2, barspacehalf: barspaceHalf, trans: trans, rect: &barRect)
CGContextFillRect(context, barRect)
if (drawHighlightArrowEnabled)
{
CGContextSetAlpha(context, 1.0)
// distance between highlight arrow and bar
let offsetY = _animator.phaseY * 0.07
CGContextSaveGState(context)
let pixelToValueMatrix = trans.pixelToValueMatrix
let xToYRel = abs(sqrt(pixelToValueMatrix.b * pixelToValueMatrix.b + pixelToValueMatrix.d * pixelToValueMatrix.d) / sqrt(pixelToValueMatrix.a * pixelToValueMatrix.a + pixelToValueMatrix.c * pixelToValueMatrix.c))
let arrowWidth = set.barSpace / 2.0
let arrowHeight = arrowWidth * xToYRel
let yArrow = (y1 > -y2 ? y1 : y1) * Double(_animator.phaseY)
_highlightArrowPtsBuffer[0].x = CGFloat(x) + 0.4
_highlightArrowPtsBuffer[0].y = CGFloat(yArrow) + offsetY
_highlightArrowPtsBuffer[1].x = CGFloat(x) + 0.4 + arrowWidth
_highlightArrowPtsBuffer[1].y = CGFloat(yArrow) + offsetY - arrowHeight
_highlightArrowPtsBuffer[2].x = CGFloat(x) + 0.4 + arrowWidth
_highlightArrowPtsBuffer[2].y = CGFloat(yArrow) + offsetY + arrowHeight
trans.pointValuesToPixel(&_highlightArrowPtsBuffer)
CGContextBeginPath(context)
CGContextMoveToPoint(context, _highlightArrowPtsBuffer[0].x, _highlightArrowPtsBuffer[0].y)
CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[1].x, _highlightArrowPtsBuffer[1].y)
CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[2].x, _highlightArrowPtsBuffer[2].y)
CGContextClosePath(context)
CGContextFillPath(context)
CGContextRestoreGState(context)
}
}
}
CGContextRestoreGState(context)
}
public func getTransformedValues(trans trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint]
{
return trans.generateTransformedValuesCustomBar1Chart(entries, dataSet: dataSetIndex, barData: dataProvider!.customBar1Data!, phaseY: _animator.phaseY)
}
internal func passesCheck() -> Bool
{
guard let dataProvider = dataProvider, barData = dataProvider.customBar1Data else { return false }
return CGFloat(barData.yValCount) < CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX
}
} | apache-2.0 | 90b77b5222e12c245201441e1b6c7bdb | 40.487319 | 232 | 0.447031 | 6.425365 | false | false | false | false |
michael-lehew/swift-corelibs-foundation | Foundation/NSURLError.swift | 6 | 5434 | // 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
//
/// `NSURLErrorDomain` indicates an `NSURL` error.
///
/// Constants used by `NSError` to differentiate between "domains" of error codes,
/// serving as a discriminator for error codes that originate from different subsystems or sources.
public let NSURLErrorDomain: String = "NSURLErrorDomain"
/// The `NSError` userInfo dictionary key used to store and retrieve the URL which
/// caused a load to fail.
public let NSURLErrorFailingURLErrorKey: String = "NSErrorFailingURLKey"
/// The `NSError` userInfo dictionary key used to store and retrieve the NSString
/// object for the URL which caused a load to fail.
public let NSURLErrorFailingURLStringErrorKey: String = "NSErrorFailingURLStringKey"
/// The `NSError` userInfo dictionary key used to store and retrieve the
/// SecTrustRef object representing the state of a failed SSL handshake.
public let NSURLErrorFailingURLPeerTrustErrorKey: String = "NSURLErrorFailingURLPeerTrustErrorKey"
/// The `NSError` userInfo dictionary key used to store and retrieve the
/// `NSNumber` corresponding to the reason why a background `NSURLSessionTask`
/// was cancelled
///
/// One of
/// * `NSURLErrorCancelledReasonUserForceQuitApplication`
/// * `NSURLErrorCancelledReasonBackgroundUpdatesDisabled`
/// * `NSURLErrorCancelledReasonInsufficientSystemResources`
public let NSURLErrorBackgroundTaskCancelledReasonKey: String = "NSURLErrorBackgroundTaskCancelledReasonKey"
/// Code associated with `NSURLErrorBackgroundTaskCancelledReasonKey`
public var NSURLErrorCancelledReasonUserForceQuitApplication: Int { return 0 }
/// Code associated with `NSURLErrorBackgroundTaskCancelledReasonKey`
public var NSURLErrorCancelledReasonBackgroundUpdatesDisabled: Int { return 1 }
/// Code associated with `NSURLErrorBackgroundTaskCancelledReasonKey`
public var NSURLErrorCancelledReasonInsufficientSystemResources: Int { return 2 }
//MARK: NSURL-related Error Codes
public var NSURLErrorUnknown: Int { return -1 }
public var NSURLErrorCancelled: Int { return -999 }
public var NSURLErrorBadURL: Int { return -1000 }
public var NSURLErrorTimedOut: Int { return -1001 }
public var NSURLErrorUnsupportedURL: Int { return -1002 }
public var NSURLErrorCannotFindHost: Int { return -1003 }
public var NSURLErrorCannotConnectToHost: Int { return -1004 }
public var NSURLErrorNetworkConnectionLost: Int { return -1005 }
public var NSURLErrorDNSLookupFailed: Int { return -1006 }
public var NSURLErrorHTTPTooManyRedirects: Int { return -1007 }
public var NSURLErrorResourceUnavailable: Int { return -1008 }
public var NSURLErrorNotConnectedToInternet: Int { return -1009 }
public var NSURLErrorRedirectToNonExistentLocation: Int { return -1010 }
public var NSURLErrorBadServerResponse: Int { return -1011 }
public var NSURLErrorUserCancelledAuthentication: Int { return -1012 }
public var NSURLErrorUserAuthenticationRequired: Int { return -1013 }
public var NSURLErrorZeroByteResource: Int { return -1014 }
public var NSURLErrorCannotDecodeRawData: Int { return -1015 }
public var NSURLErrorCannotDecodeContentData: Int { return -1016 }
public var NSURLErrorCannotParseResponse: Int { return -1017 }
public var NSURLErrorAppTransportSecurityRequiresSecureConnection: Int { return -1022 }
public var NSURLErrorFileDoesNotExist: Int { return -1100 }
public var NSURLErrorFileIsDirectory: Int { return -1101 }
public var NSURLErrorNoPermissionsToReadFile: Int { return -1102 }
public var NSURLErrorDataLengthExceedsMaximum: Int { return -1103 }
// SSL errors
public var NSURLErrorSecureConnectionFailed: Int { return -1201 }
public var NSURLErrorServerCertificateHasBadDate: Int { return -1202 }
public var NSURLErrorServerCertificateUntrusted: Int { return -1203 }
public var NSURLErrorServerCertificateHasUnknownRoot: Int { return -1204 }
public var NSURLErrorServerCertificateNotYetValid: Int { return -1205 }
public var NSURLErrorClientCertificateRejected: Int { return -1206 }
public var NSURLErrorClientCertificateRequired: Int { return -1207 }
public var NSURLErrorCannotLoadFromNetwork: Int { return -2000 }
// Download and file I/O errors
public var NSURLErrorCannotCreateFile: Int { return -3000 }
public var NSURLErrorCannotOpenFile: Int { return -3001 }
public var NSURLErrorCannotCloseFile: Int { return -3002 }
public var NSURLErrorCannotWriteToFile: Int { return -3003 }
public var NSURLErrorCannotRemoveFile: Int { return -3004 }
public var NSURLErrorCannotMoveFile: Int { return -3005 }
public var NSURLErrorDownloadDecodingFailedMidStream: Int { return -3006 }
public var NSURLErrorDownloadDecodingFailedToComplete: Int { return -3007 }
public var NSURLErrorInternationalRoamingOff: Int { return -1018 }
public var NSURLErrorCallIsActive: Int { return -1019 }
public var NSURLErrorDataNotAllowed: Int { return -1020 }
public var NSURLErrorRequestBodyStreamExhausted: Int { return -1021 }
public var NSURLErrorBackgroundSessionRequiresSharedContainer: Int { return -995 }
public var NSURLErrorBackgroundSessionInUseByAnotherProcess: Int { return -996 }
public var NSURLErrorBackgroundSessionWasDisconnected: Int { return -997 }
| apache-2.0 | c823ecb41f8bffdf91c9e9f172196722 | 52.27451 | 108 | 0.808244 | 5.155598 | false | false | false | false |
xwu/swift | test/Constraints/casts.swift | 1 | 25884 | // RUN: %target-typecheck-verify-swift -enable-objc-interop
class B {
init() {}
}
class D : B {
override init() { super.init() }
}
var seven : Double = 7
var pair : (Int, Double) = (1, 2)
var closure : (Int, Int) -> Int = { $0 + $1 }
var d_as_b : B = D()
var b_as_d = B() as! D
var bad_b_as_d : D = B() // expected-error{{cannot convert value of type 'B' to specified type 'D'}}
var d = D()
var b = B()
var d_as_b_2 : B = d
var b_as_d_2 = b as! D
var b_is_d:Bool = B() is D
// FIXME: Poor diagnostic below.
var bad_d_is_b:Bool = D() is B // expected-warning{{always true}}
func base_class_archetype_casts<T : B>(_ t: T) {
var _ : B = t
_ = B() as! T
var _ : T = B() // expected-error{{cannot convert value of type 'B' to specified type 'T'}}
let b = B()
_ = b as! T
var _:Bool = B() is T
var _:Bool = b is T
var _:Bool = t is B // expected-warning{{always true}}
_ = t as! D
}
protocol P1 { func p1() }
protocol P2 { func p2() }
struct S1 : P1 {
func p1() {}
}
class C1 : P1 {
func p1() {}
}
class D1 : C1 {}
struct S2 : P2 {
func p2() {}
}
struct S3 {}
struct S12 : P1, P2 {
func p1() {}
func p2() {}
}
func protocol_archetype_casts<T : P1>(_ t: T, p1: P1, p2: P2, p12: P1 & P2) {
// Coercions.
var _ : P1 = t
var _ : P2 = t // expected-error{{value of type 'T' does not conform to specified type 'P2'}}
// Checked unconditional casts.
_ = p1 as! T
_ = p2 as! T
_ = p12 as! T
_ = t as! S1
_ = t as! S12
_ = t as! C1
_ = t as! D1
_ = t as! S2
_ = S1() as! T
_ = S12() as! T
_ = C1() as! T
_ = D1() as! T
_ = S2() as! T
// Type queries.
var _:Bool = p1 is T
var _:Bool = p2 is T
var _:Bool = p12 is T
var _:Bool = t is S1
var _:Bool = t is S12
var _:Bool = t is C1
var _:Bool = t is D1
var _:Bool = t is S2
}
func protocol_concrete_casts(_ p1: P1, p2: P2, p12: P1 & P2) {
// Checked unconditional casts.
_ = p1 as! S1
_ = p1 as! C1
_ = p1 as! D1
_ = p1 as! S12
_ = p1 as! P1 & P2
_ = p2 as! S1 // expected-warning {{cast from 'P2' to unrelated type 'S1' always fails}}
_ = p12 as! S1 // expected-warning {{cast from 'P1 & P2' to unrelated type 'S1' always fails}}
_ = p12 as! S2 // expected-warning {{cast from 'P1 & P2' to unrelated type 'S2' always fails}}
_ = p12 as! S12
_ = p12 as! S3 // expected-warning {{cast from 'P1 & P2' to unrelated type 'S3' always fails}}
// Type queries.
var _:Bool = p1 is S1
var _:Bool = p1 is C1
var _:Bool = p1 is D1
var _:Bool = p1 is S12
var _:Bool = p1 is P1 & P2
var _:Bool = p2 is S1 // expected-warning {{cast from 'P2' to unrelated type 'S1' always fails}}
var _:Bool = p12 is S1 // expected-warning {{cast from 'P1 & P2' to unrelated type 'S1' always fails}}
var _:Bool = p12 is S2 // expected-warning {{cast from 'P1 & P2' to unrelated type 'S2' always fails}}
var _:Bool = p12 is S12
var _:Bool = p12 is S3 // expected-warning {{cast from 'P1 & P2' to unrelated type 'S3' always fails}}
}
func conditional_cast(_ b: B) -> D? {
return b as? D
}
@objc protocol ObjCProto1 {}
@objc protocol ObjCProto2 {}
protocol NonObjCProto : class {}
@objc class ObjCClass {}
class NonObjCClass {}
func objc_protocol_casts(_ op1: ObjCProto1, opn: NonObjCProto) {
_ = ObjCClass() as! ObjCProto1
_ = ObjCClass() as! ObjCProto2
_ = ObjCClass() as! ObjCProto1 & ObjCProto2
_ = ObjCClass() as! NonObjCProto
_ = ObjCClass() as! ObjCProto1 & NonObjCProto
_ = op1 as! ObjCProto1 & ObjCProto2
_ = op1 as! ObjCProto2
_ = op1 as! ObjCProto1 & NonObjCProto
_ = opn as! ObjCProto1
_ = NonObjCClass() as! ObjCProto1
}
func dynamic_lookup_cast(_ dl: AnyObject) {
_ = dl as! ObjCProto1
_ = dl as! ObjCProto2
_ = dl as! ObjCProto1 & ObjCProto2
}
// Cast to subclass with generic parameter inference
class C2<T> : B { }
class C3<T> : C2<[T]> {
func f(_ x: T) { }
}
var c2i : C2<[Int]> = C3()
var c3iOpt = c2i as? C3
c3iOpt?.f(5)
var b1 = c2i is C3
var c2f: C2<Float>? = b as? C2
var c2f2: C2<[Float]>? = b as! C3
// <rdar://problem/15633178>
var f: (Float) -> Float = { $0 as Float }
var f2: (B) -> Bool = { $0 is D }
func metatype_casts<T, U>(_ b: B.Type, t:T.Type, u: U.Type) {
_ = b is D.Type
_ = T.self is U.Type
_ = type(of: T.self) is U.Type.Type
_ = type(of: b) is D.Type // expected-warning{{always fails}}
_ = b is D.Type.Type // expected-warning{{always fails}}
}
// <rdar://problem/17017851>
func forcedDowncastToOptional(_ b: B) {
var dOpt: D? = b as! D // expected-warning{{treating a forced downcast to 'D' as optional will never produce 'nil'}}
// expected-note@-1{{use 'as?' to perform a conditional downcast to 'D'}}{{22-23=?}}
// expected-note@-2{{add parentheses around the cast to silence this warning}}{{18-18=(}}{{25-25=)}}
dOpt = b as! D // expected-warning{{treating a forced downcast to 'D' as optional will never produce 'nil'}}
// expected-note@-1{{use 'as?' to perform a conditional downcast to 'D'}}{{14-15=?}}
// expected-note@-2{{add parentheses around the cast to silence this warning}}{{10-10=(}}{{17-17=)}}
dOpt = (b as! D)
_ = dOpt
}
_ = b1 as Int // expected-error {{cannot convert value of type 'Bool' to type 'Int' in coercion}}
_ = seven as Int // expected-error {{cannot convert value of type 'Double' to type 'Int' in coercion}}
func rdar29894174(v: B?) {
let _ = [v].compactMap { $0 as? D }
}
// When re-typechecking a solution with an 'is' cast applied,
// we would fail to produce a diagnostic.
func process(p: Any?) {
compare(p is String)
// expected-error@-1 {{missing argument for parameter #2 in call}} {{22-22=, <#Bool#>}}
}
func compare<T>(_: T, _: T) {} // expected-note {{'compare' declared here}}
func compare<T>(_: T?, _: T?) {}
_ = nil? as? Int?? // expected-error {{'nil' requires a contextual type}}
func test_tuple_casts_no_warn() {
struct Foo {}
let arr: [(Any, Any)] = [(Foo(), Foo())]
let tup: (Any, Any) = (Foo(), Foo())
_ = arr as! [(Foo, Foo)] // Ok
_ = tup as! (Foo, Foo) // Ok
_ = arr as! [(Foo, Foo, Foo)] // Ok
_ = tup as! (Foo, Foo, Foo) // expected-warning {{cast from '(Any, Any)' to unrelated type '(Foo, Foo, Foo)' always fails}}
_ = arr as! [(a: Foo, Foo)] // Ok
_ = tup as! (a: Foo, Foo) // Ok
}
infix operator ^^^
func ^^^ <T> (lhs: T?, rhs: @autoclosure () -> T) -> T { lhs! }
func ^^^ <T> (lhs: T?, rhs: @autoclosure () -> T?) -> T? { lhs! }
func ohno<T>(_ x: T) -> T? { nil }
// SR-12369: Make sure we don't drop the coercion constraint.
func test_coercions_with_overloaded_operator(str: String, optStr: String?, veryOptString: String????) {
_ = (str ?? "") as String // expected-warning {{left side of nil coalescing operator '??' has non-optional type 'String', so the right side is never used}}
_ = (optStr ?? "") as String
_ = (str ?? "") as Int // expected-error {{cannot convert value of type 'String' to type 'Int' in coercion}}
_ = (optStr ?? "") as Int // expected-error {{cannot convert value of type 'String' to type 'Int' in coercion}}
_ = (optStr ?? "") as Int? // expected-error {{'String' is not convertible to 'Int?'}}
// expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{22-24=as!}}
_ = (str ^^^ "") as Int // expected-error {{cannot convert value of type 'String' to type 'Int' in coercion}}
_ = (optStr ^^^ "") as Int // expected-error {{cannot convert value of type 'String' to type 'Int' in coercion}}
_ = (optStr ^^^ "") as Int? // expected-error {{'String' is not convertible to 'Int?'}}
// expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{23-25=as!}}
_ = ([] ?? []) as String // expected-error {{cannot convert value of type '[Any]' to type 'String' in coercion}}
_ = ([""] ?? []) as [Int: Int] // expected-error {{cannot convert value of type '[String]' to type '[Int : Int]' in coercion}}
_ = (["": ""] ?? [:]) as [Int] // expected-error {{cannot convert value of type '[String : String]' to type '[Int]' in coercion}}
_ = (["": ""] ?? [:]) as Set<Int> // expected-error {{cannot convert value of type '[String : String]' to type 'Set<Int>' in coercion}}
_ = (["": ""] ?? [:]) as Int? // expected-error {{cannot convert value of type '[String : String]' to type 'Int?' in coercion}}
_ = ("" ?? "" ?? "") as String // expected-warning 2{{left side of nil coalescing operator '??' has non-optional type 'String', so the right side is never used}}
_ = ((veryOptString ?? "") ?? "") as String??
_ = ((((veryOptString ?? "") ?? "") ?? "") ?? "") as String
_ = ("" ?? "" ?? "") as Float // expected-error {{cannot convert value of type 'String' to type 'Float' in coercion}}
_ = ((veryOptString ?? "") ?? "") as [String] // expected-error {{cannot convert value of type 'String??' to type '[String]' in coercion}}
_ = ((((veryOptString ?? "") ?? "") ?? "") ?? "") as [String] // expected-error {{cannot convert value of type 'String' to type '[String]' in coercion}}
_ = ohno(ohno(ohno(str))) as String???
_ = ohno(ohno(ohno(str))) as Int // expected-error {{cannot convert value of type 'String???' to type 'Int' in coercion}}
}
func id<T>(_ x: T) -> T { x }
func test_compatibility_coercions(_ arr: [Int], _ optArr: [Int]?, _ dict: [String: Int], _ set: Set<Int>) {
// Successful coercions don't raise a warning.
_ = arr as [Any]?
_ = dict as [String: Int]?
_ = set as Set<Int>
// Don't fix the simple case where no type variable is introduced, that was
// always disallowed.
_ = arr as [String] // expected-error {{cannot convert value of type '[Int]' to type '[String]' in coercion}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}}
_ = dict as [String: String] // expected-error {{cannot convert value of type '[String : Int]' to type '[String : String]' in coercion}}
// expected-note@-1 {{arguments to generic parameter 'Value' ('Int' and 'String') are expected to be equal}}
_ = dict as [String: String]? // expected-error {{'[String : Int]' is not convertible to '[String : String]?'}}
// expected-note@-1 {{did you mean to use 'as!' to force downcast?}} {{12-14=as!}}
_ = (dict as [String: Int]?) as [String: Int] // expected-error {{value of optional type '[String : Int]?' must be unwrapped to a value of type '[String : Int]'}}
// expected-note@-1 {{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-2 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
_ = set as Set<String> // expected-error {{cannot convert value of type 'Set<Int>' to type 'Set<String>' in coercion}}
// expected-note@-1 {{arguments to generic parameter 'Element' ('Int' and 'String') are expected to be equal}}
// Apply the compatibility logic when a type variable is introduced. It's
// unfortunate that this means we'll temporarily accept code we didn't before,
// but it at least means we shouldn't break compatibility with anything.
_ = id(arr) as [String] // expected-warning {{coercion from '[Int]' to '[String]' may fail; use 'as?' or 'as!' instead}}
_ = (arr ?? []) as [String] // expected-warning {{coercion from '[Int]' to '[String]' may fail; use 'as?' or 'as!' instead}}
// expected-warning@-1 {{left side of nil coalescing operator '??' has non-optional type '[Int]', so the right side is never used}}
_ = (arr ?? [] ?? []) as [String] // expected-warning {{coercion from '[Int]' to '[String]' may fail; use 'as?' or 'as!' instead}}
// expected-warning@-1 2{{left side of nil coalescing operator '??' has non-optional type '[Int]', so the right side is never used}}
_ = (optArr ?? []) as [String] // expected-warning {{coercion from '[Int]' to '[String]' may fail; use 'as?' or 'as!' instead}}
// Allow the coercion to increase optionality.
_ = (arr ?? []) as [String]? // expected-warning {{coercion from '[Int]' to '[String]?' may fail; use 'as?' or 'as!' instead}}
// expected-warning@-1 {{left side of nil coalescing operator '??' has non-optional type '[Int]', so the right side is never used}}
_ = (arr ?? []) as [String?]? // expected-warning {{coercion from '[Int]' to '[String?]?' may fail; use 'as?' or 'as!' instead}}
// expected-warning@-1 {{left side of nil coalescing operator '??' has non-optional type '[Int]', so the right side is never used}}
_ = (arr ?? []) as [String??]?? // expected-warning {{coercion from '[Int]' to '[String??]??' may fail; use 'as?' or 'as!' instead}}
// expected-warning@-1 {{left side of nil coalescing operator '??' has non-optional type '[Int]', so the right side is never used}}
_ = (dict ?? [:]) as [String: String?]? // expected-warning {{coercion from '[String : Int]' to '[String : String?]?' may fail; use 'as?' or 'as!' instead}}
// expected-warning@-1 {{left side of nil coalescing operator '??' has non-optional type '[String : Int]', so the right side is never used}}
_ = (set ?? []) as Set<String>?? // expected-warning {{coercion from 'Set<Int>' to 'Set<String>??' may fail; use 'as?' or 'as!' instead}}
// expected-warning@-1 {{left side of nil coalescing operator '??' has non-optional type 'Set<Int>', so the right side is never used}}
// Allow the coercion to decrease optionality.
_ = ohno(ohno(ohno(arr))) as [String] // expected-warning {{coercion from '[Int]???' to '[String]' may fail; use 'as?' or 'as!' instead}}
_ = ohno(ohno(ohno(arr))) as [Int] // expected-warning {{coercion from '[Int]???' to '[Int]' may fail; use 'as?' or 'as!' instead}}
_ = ohno(ohno(ohno(Set<Int>()))) as Set<String> // expected-warning {{coercion from 'Set<Int>???' to 'Set<String>' may fail; use 'as?' or 'as!' instead}}
_ = ohno(ohno(ohno(["": ""]))) as [Int: String] // expected-warning {{coercion from '[String : String]???' to '[Int : String]' may fail; use 'as?' or 'as!' instead}}
_ = ohno(ohno(ohno(dict))) as [String: Int] // expected-warning {{coercion from '[String : Int]???' to '[String : Int]' may fail; use 'as?' or 'as!' instead}}
// In this case the array literal can be inferred to be [String], so totally
// valid.
_ = ([] ?? []) as [String] // expected-warning {{left side of nil coalescing operator '??' has non-optional type '[String]', so the right side is never used}}
_ = (([] as Optional) ?? []) as [String]
// The array can also be inferred to be [Any].
_ = ([] ?? []) as Array // expected-warning {{left side of nil coalescing operator '??' has non-optional type '[Any]', so the right side is never used}}
}
// SR-13088
protocol JSON { }
protocol JSONLeaf: JSON {}
extension Int: JSONLeaf { }
extension Array: JSON where Element: JSON { }
protocol SR13035Error: Error {}
class ChildError: SR13035Error {}
protocol AnyC {
func foo()
}
protocol AnyEvent {}
protocol A {
associatedtype C: AnyC
}
protocol EventA: A {
associatedtype Event
}
typealias Container<Namespace>
= (event: Namespace.Event, c: Namespace.C) where Namespace: EventA
enum ConcreteA: EventA {
struct C: AnyC {
func foo() {}
}
enum Event: AnyEvent {
case test
}
}
protocol ProtocolP1 {}
protocol ProtocolQ1 {}
typealias Composition = ProtocolP1 & ProtocolQ1
protocol ProtocolP {}
protocol ProtocolQ {}
class ConcreteP: ProtocolP {}
class ConcreteQ: ProtocolQ {}
class ConcretePQ: ProtocolP, ProtocolQ {}
class ConcreteCPQ: ConcreteP, ProtocolQ {}
class ConcreteP1: ProtocolP1 {}
class ConcretePQ1: ProtocolP1, ProtocolQ1 {}
class ConcretePPQ1: ProtocolP, ProtocolP1, ProtocolQ1 {}
class NotConforms {}
struct StructNotComforms {}
final class NotConformsFinal {}
func tests_SR13088_false_positive_always_fail_casts() {
// SR-13081
let x: JSON = [4] // [4]
_ = x as? [Any] // Ok
// SR-13035
func SR13035<SomeError: SR13035Error>(_ child: Result<String, ChildError>, _: Result<String, SomeError>) {
let _ = child as? Result<String, SomeError> // Ok
}
func SR13035_1<SomeError: SR13035Error, Child: ChildError>(_ child: Result<String, Child>, parent: Result<String, SomeError>) {
_ = child as? Result<String, SomeError> // Ok
_ = parent as? Result<String, Child> // OK
}
// SR-11434 and SR-12321
func encodable(_ value: Encodable) {
_ = value as! [String : Encodable] // Ok
_ = value as? [String: Encodable] // Ok
}
// SR-13025
func coordinate(_ event: AnyEvent, from c: AnyC) {
switch (event, c) {
case let container as Container<ConcreteA>: // OK
container.c.foo()
default:
break
}
}
// SR-7187
let a: [Any] = [String?.some("hello") as Any, String?.none as Any]
let b: [AnyObject] = [String?.some("hello") as AnyObject, String?.none as AnyObject]
_ = a is [String?] // Ok
_ = a as? [String?] as Any // OK
_ = b is [String?] // Ok
_ = b as? [String?] as AnyObject // OK
// SR-6192
let items = [String]()
let dict = [String: Any]()
let set = Set<String>()
_ = items is [Int] // Ok
_ = items as? [Int] as Any // Ok
_ = items as! [Int] // Ok
_ = dict is [Int: Any] // Ok
_ = dict as? [Int: Any] as Any // Ok
_ = dict as! [Int: Any] as Any // Ok
_ = set is Set<Int> // Ok
_ = set as? Set<Int> as Any // Ok
_ = set as! Set<Int> // Ok
}
// Protocol composition
func protocol_composition(_ c: ProtocolP & ProtocolQ, _ c1: ProtocolP & Composition) {
_ = c as? ConcretePQ // Ok
_ = c as? ConcreteCPQ // Ok
_ = c as? ConcreteP // Ok
_ = c as? NotConforms // Ok
_ = c as? StructNotComforms // expected-warning {{cast from 'ProtocolP & ProtocolQ' to unrelated type 'StructNotComforms' always fails}}
_ = c as? NotConformsFinal // expected-warning {{cast from 'ProtocolP & ProtocolQ' to unrelated type 'NotConformsFinal' always fails}}
_ = c1 as? ConcreteP // Ok
_ = c1 as? ConcreteP1 // OK
_ = c1 as? ConcretePQ1 // OK
_ = c1 as? ConcretePPQ1 // Ok
_ = c1 as? NotConforms // Ok
_ = c1 as? StructNotComforms // expected-warning {{cast from 'ProtocolP & Composition' (aka 'ProtocolP & ProtocolP1 & ProtocolQ1') to unrelated type 'StructNotComforms' always fails}}
_ = c1 as? NotConformsFinal // expected-warning {{cast from 'ProtocolP & Composition' (aka 'ProtocolP & ProtocolP1 & ProtocolQ1') to unrelated type 'NotConformsFinal' always fails}}
}
// SR-13899
class SR13899_Base {}
class SR13899_Derived: SR13899_Base {}
protocol SR13899_P {}
class SR13899_A: SR13899_P {}
typealias DA = SR13899_Derived
typealias BA = SR13899_Base
typealias ClosureType = (SR13899_Derived) -> Void
let blockp = { (_: SR13899_A) in }
let block = { (_: SR13899_Base) in }
let derived = { (_: SR13899_Derived) in }
let blockalias = { (_: BA) in }
let derivedalias = { (_: DA) in }
let _ = block is ClosureType // expected-warning{{runtime conversion from '(SR13899_Base) -> ()' to 'ClosureType' (aka '(SR13899_Derived) -> ()') is not supported; 'is' test always fails}}
// expected-note@-1 {{consider using 'as' coercion instead}} {{15-17=as}}
let _ = blockalias is (SR13899_Derived) -> Void // expected-warning{{runtime conversion from '(BA) -> ()' (aka '(SR13899_Base) -> ()') to '(SR13899_Derived) -> Void' is not supported; 'is' test always fails}}
// expected-note@-1 {{consider using 'as' coercion instead}} {{20-22=as}}
let _ = block is (SR13899_Derived) -> Void // expected-warning{{runtime conversion from '(SR13899_Base) -> ()' to '(SR13899_Derived) -> Void' is not supported; 'is' test always fails}}
// expected-note@-1 {{consider using 'as' coercion instead}} {{15-17=as}}
let _ = block is (SR13899_Derived) -> Void // expected-warning{{runtime conversion from '(SR13899_Base) -> ()' to '(SR13899_Derived) -> Void' is not supported; 'is' test always fails}}
// expected-note@-1 {{consider using 'as' coercion instead}} {{15-17=as}}
let _ = block as! ClosureType // expected-warning{{runtime conversion from '(SR13899_Base) -> ()' to 'ClosureType' (aka '(SR13899_Derived) -> ()') is not supported; cast always fails}}
// expected-note@-1 {{consider using 'as' coercion instead}} {{15-18=as}}
let _ = blockalias as! (SR13899_Derived) -> Void // expected-warning{{runtime conversion from '(BA) -> ()' (aka '(SR13899_Base) -> ()') to '(SR13899_Derived) -> Void' is not supported; cast always fails}}
// expected-note@-1 {{consider using 'as' coercion instead}} {{20-23=as}}
let _ = block as! (SR13899_Derived) -> Void // expected-warning{{runtime conversion from '(SR13899_Base) -> ()' to '(SR13899_Derived) -> Void' is not supported; cast always fails}}
// expected-note@-1 {{consider using 'as' coercion instead}} {{15-18=as}}
let _ = block as! (SR13899_Derived) -> Void // expected-warning{{runtime conversion from '(SR13899_Base) -> ()' to '(SR13899_Derived) -> Void' is not supported; cast always fails}}
// expected-note@-1 {{consider using 'as' coercion instead}} {{15-18=as}}
let _ = block as? ClosureType // expected-warning{{runtime conversion from '(SR13899_Base) -> ()' to 'ClosureType' (aka '(SR13899_Derived) -> ()') is not supported; cast always fails}}
// expected-note@-1 {{consider using 'as' coercion instead}} {{15-18=as}}
let _ = blockalias as? (SR13899_Derived) -> Void // expected-warning{{runtime conversion from '(BA) -> ()' (aka '(SR13899_Base) -> ()') to '(SR13899_Derived) -> Void' is not supported; cast always fails}}
// expected-note@-1 {{consider using 'as' coercion instead}} {{20-23=as}}
let _ = block as? (SR13899_Derived) -> Void // expected-warning{{runtime conversion from '(SR13899_Base) -> ()' to '(SR13899_Derived) -> Void' is not supported; cast always fails}}
// expected-note@-1 {{consider using 'as' coercion instead}} {{15-18=as}}
let _ = block as? (SR13899_Derived) -> Void // expected-warning{{runtime conversion from '(SR13899_Base) -> ()' to '(SR13899_Derived) -> Void' is not supported; cast always fails}}
// expected-note@-1 {{consider using 'as' coercion instead}} {{15-18=as}}
let _ = derived is (SR13899_Base) -> Void // expected-warning{{always fails}}
let _ = blockp is (SR13899_P) -> Void // expected-warning{{always fails}}
// Types are trivially equal.
let _ = block is (SR13899_Base) -> Void // expected-warning{{'is' test is always true}}
let _ = block is (SR13899_Base) throws -> Void // expected-warning{{'is' test is always true}}
let _ = derivedalias is (SR13899_Derived) -> Void // expected-warning{{'is' test is always true}}
let _ = derivedalias is (SR13899_Derived) throws -> Void // expected-warning{{'is' test is always true}}
let _ = derived is (SR13899_Derived) -> Void // expected-warning{{'is' test is always true}}
let _ = derived is (SR13899_Derived) throws -> Void // expected-warning{{'is' test is always true}}
let _ = blockp is (SR13899_A) -> Void //expected-warning{{'is' test is always true}}
let _ = blockp is (SR13899_A) throws -> Void //expected-warning{{'is' test is always true}}
protocol PP1 { }
protocol PP2: PP1 { }
extension Optional: PP1 where Wrapped == PP2 { }
nil is PP1 // expected-error {{'nil' requires a contextual type}}
// SR-15039
enum ChangeType<T> {
case initial(T)
case delta(previous: T, next: T)
case unset
var delta: (previous: T?, next: T)? { nil }
}
extension ChangeType where T == String? {
var foo: String? { return self.delta?.previous as? String } // OK
var bar: String? { self.delta?.next }
}
// SR-15038
protocol ExperimentDeserializable {
static func deserializeExperiment(_ value: Any) -> Self?
}
extension String: ExperimentDeserializable {
static func deserializeExperiment(_ value: Any) -> String? { value as? String }
}
extension Int: ExperimentDeserializable {
static func deserializeExperiment(_ value: Any) -> Int? { value as? Int }
}
class Constant<T> {
private init(getUnderlyingValue: @escaping () -> T) {
print(getUnderlyingValue())
}
}
struct Thing {
let storage: [String: Any]
}
extension Constant where T: Sequence, T.Element: ExperimentDeserializable {
static func foo<U>(thing: Thing, defaultValue: T) -> T where T == [U] {
guard let array = thing.storage["foo"] as? [Any] else {
fatalError()
}
let value = array.map(T.Element.deserializeExperiment) as? [T.Element] ?? defaultValue // OK
return value
}
}
// Array
func decodeStringOrInt<T: FixedWidthInteger>() -> [T] {
let stringWrapped = [String]()
if let values = stringWrapped.map({ $0.isEmpty ? 0 : T($0) }) as? [T] { // OK
return values
} else {
fatalError()
}
}
// Set
func decodeStringOrIntSet<T: FixedWidthInteger>() -> Set<T> {
let stringWrapped = [String]()
if let values = Set(stringWrapped.map({ $0.isEmpty ? 0 : T($0) })) as? Set<T> { // OK
return values
} else {
fatalError()
}
}
// Dictionary
func decodeStringOrIntDictionary<T: FixedWidthInteger>() -> [Int: T] {
let stringWrapped = [String]()
if let values = Dictionary(uniqueKeysWithValues: stringWrapped.map({ $0.isEmpty ? (0, 0) : (0, T($0)) })) as? [Int: T] { // OK
return values
} else {
fatalError()
}
}
// SR-15281
struct SR15281_A { }
struct SR15281_B {
init(a: SR15281_A) { }
}
struct SR15281_S {
var a: SR15281_A? = SR15281_A()
var b: SR15281_B {
a.flatMap(SR15281_B.init(a:)) // expected-error{{cannot convert return expression of type 'SR15281_B?' to return type 'SR15281_B'}} {{34-34=!}}
}
var b1: SR15281_B {
a.flatMap(SR15281_B.init(a:)) as! SR15281_B
// expected-warning@-1 {{forced cast from 'SR15281_B?' to 'SR15281_B' only unwraps optionals; did you mean to use '!'?}} {{34-34=!}} {{34-48=}}
}
}
class SR15281_AC {}
class SR15281_BC {
init(a: SR15281_AC) { }
}
class SR15281_CC: SR15281_BC {}
struct SR15281_SC {
var a: SR15281_AC? = SR15281_AC()
var b: SR15281_BC {
a.flatMap(SR15281_BC.init(a:)) // expected-error{{cannot convert return expression of type 'SR15281_BC?' to return type 'SR15281_BC'}} {{35-35=!}}
}
var c: SR15281_BC {
a.flatMap(SR15281_CC.init(a:)) // expected-error{{cannot convert return expression of type 'SR15281_CC?' to return type 'SR15281_BC'}} {{35-35=!}}
}
}
| apache-2.0 | 6243fc7aa74175942fc7966e8052e081 | 38.638591 | 208 | 0.628303 | 3.304059 | false | false | false | false |
szehnder/Swell | SwellTests/SwellTests.swift | 1 | 13626 | //
// SwellTests.swift
// SwellTests
//
// Created by Hubert Rabago on 6/20/14.
// Copyright (c) 2014 Minute Apps LLC. All rights reserved.
//
import Foundation
import XCTest
import Swell
public class SwellTestLocation: LogLocation {
var logged: Bool = false
var message: String?
func wasLogged() -> Bool {
let result = logged
logged = false
return result
}
public func log(@autoclosure givenMessage: () -> String) {
logged = true
message = givenMessage()
//println(message)
}
public func enable() {}
public func disable() {}
public func description() -> String {
return "SwellTestLocation"
}
}
class SwellTests: XCTestCase {
override func setUp() {
//println("\n\n========================\nHello setUp\n\n")
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testLoggerAndLevel() {
//var d = Swell.dummy
let location = SwellTestLocation()
let logger = Logger(name: "TestLevel", level:.INFO, formatter: QuickFormatter(format: .MessageOnly), logLocation: location)
logger.trace("Hello trace level");
if location.message != nil {
XCTFail("Should not have logged TRACE calls")
}
logger.debug("Hello debug level");
if location.message != nil {
XCTFail("Should not have logged DEBUG calls")
}
logger.info("Hello info level");
if let message = location.message {
XCTAssertEqual(message, "Hello info level", "Pass")
} else {
XCTFail("Should have logged INFO call")
}
logger.warn("Hello warn level");
if let message = location.message {
XCTAssertEqual(message, "Hello warn level", "Pass")
} else {
XCTFail("Should have logged WARN call")
}
logger.error("Hello error level");
if let message = location.message {
XCTAssertEqual(message, "Hello error level", "Pass")
} else {
XCTFail("Should have logged ERROR call")
}
logger.severe("Hello severe level");
if let message = location.message {
XCTAssertEqual(message, "Hello severe level", "Pass")
} else {
XCTFail("Should have logged SEVERE call")
}
logger.error(0);
if let message = location.message {
XCTAssertEqual(message, "0", "Pass")
} else {
XCTFail("Should have logged ERROR call")
}
let date = NSDate()
logger.error(date);
if let message = location.message {
XCTAssertEqual(date.description, message, "Pass")
} else {
XCTFail("Should have logged ERROR call")
}
logger.error(12.234);
if let message = location.message {
XCTAssertEqual(message, "12.234", "Pass")
} else {
XCTFail("Should have logged ERROR call")
}
let customLevel = LogLevel(level: 450, name: "custom", label: "CUSTOM");
logger.log(customLevel, message: [0, 0, 1]);
if let message = location.message {
XCTAssertEqual(message, "[0, 0, 1]", "Pass")
} else {
XCTFail("Should have logged level 450 call")
}
XCTAssert(true, "Pass")
}
// This test doesn't make assertions - I'm just using this to manually test file output
func testFileLogger() {
let location: LogLocation = FileLocation.getInstance("log.txt");
//location = ConsoleLocation();
let logger = Logger(name: "FileTester", level: .TRACE, logLocation: location);
logger.trace("Hello trace level");
logger.debug("Hello debug level");
logger.info("Hello info level");
logger.warn("Hello warn level");
logger.error("Hello error level");
logger.severe("Hello severe level");
logger.error(0);
logger.error(NSDate());
logger.error(12.234);
let customLevel = LogLevel(level: 450, name: "custom", label: "CUSTOM");
logger.log(customLevel, message: [0, 0, 1]);
//XCTAssert(true, "Pass")
}
// This test doesn't make assertions - I'm just using this to manually test Swell log functions
func testSwell() {
Swell.trace("Hello trace level");
Swell.debug("Hello debug level");
Swell.info("Hello info level");
Swell.warn("Hello warn level");
Swell.error("Hello error level");
Swell.severe("Hello severe level");
Swell.error(0);
Swell.error(NSDate());
Swell.error(12.234);
//XCTAssert(true, "Pass")
//Swell.testReadPlist()
}
// This test doesn't make assertions yet
func testSwellGetLogger() {
let logger = Swell.getLogger("SwellTester")
// TODO
logger.trace("Hello trace level");
logger.debug("Hello debug level");
logger.info("Hello info level");
logger.warn("Hello warn level");
logger.error("Hello error level");
logger.severe("Hello severe level");
logger.severe("Hello SwellTester level");
logger.error(0);
logger.error(NSDate());
logger.error(12.234);
let customLevel = LogLevel(level: 450, name: "custom", label: "CUSTOM");
logger.log(customLevel, message: [0, 0, 1]);
//XCTAssert(true, "Pass")
}
func testClosureLogger() {
let logger = Swell.getLogger("Closure")
logger.level = .INFO
var wasLogged: Bool = false
logger.trace {
wasLogged = true
let x = 100
return "This is my \(x) value"
};
XCTAssert(!wasLogged, "Pass")
wasLogged = false
logger.debug {
wasLogged = true
let x = 100
return "This is my \(x) value"
};
XCTAssert(!wasLogged, "Pass")
wasLogged = false
logger.info {
wasLogged = true
let x = 100
return "This is my \(x) value"
};
XCTAssert(wasLogged, "Pass")
}
// This test doesn't make assertions yet
func testSwellGetFileLogger() {
let logger = Swell.getLogger("SwellFileTester")
logger.trace("Hello trace level");
logger.debug("Hello debug level");
logger.info("Hello info level");
logger.warn("Hello warn level");
logger.error("Hello error level");
logger.severe("Hello severe level");
logger.severe("Hello SwellTester level");
logger.error(0);
logger.error(NSDate());
logger.error(12.234);
let customLevel = LogLevel(level: 450, name: "custom", label: "CUSTOM");
logger.log(customLevel, message: [0, 0, 1]);
XCTAssert(true, "Pass")
}
func testLogSelectorParsing() {
let selector = LogSelector()
selector.enableRule = "a,b,c";
XCTAssertEqual(selector.enabled.count, 3, "Pass")
selector.enableRule = ",a,b,c";
XCTAssertEqual(selector.enabled.count, 3, "Pass")
selector.enableRule = "a,b,c,";
XCTAssertEqual(selector.enabled.count, 3, "Pass")
selector.enableRule = "a,,c,";
XCTAssertEqual(selector.enabled.count, 2, "Pass")
}
func testLogSelector() {
let ls = LogSelector()
XCTAssert(ls.shouldEnableLoggerWithName("aaa"))
ls.enableRule = "aaa,bbb"
XCTAssert(ls.shouldEnableLoggerWithName("aaa"))
XCTAssert(ls.shouldEnableLoggerWithName("bbb"))
XCTAssert(!ls.shouldEnableLoggerWithName("ccc"))
ls.disableRule = "aaa"
XCTAssert(!ls.shouldEnableLoggerWithName("aaa"))
XCTAssert(ls.shouldEnableLoggerWithName("bbb"))
XCTAssert(!ls.shouldEnableLoggerWithName("ccc"))
ls.enableRule = "ccc"
ls.disableRule = ""
XCTAssert(!ls.shouldEnableLoggerWithName("aaa"))
XCTAssert(!ls.shouldEnableLoggerWithName("bbb"))
XCTAssert(ls.shouldEnableLoggerWithName("ccc"))
ls.enableRule = ""
ls.disableRule = "bbb"
XCTAssert(ls.shouldEnableLoggerWithName("aaa"))
XCTAssert(!ls.shouldEnableLoggerWithName("bbb"))
XCTAssert(ls.shouldEnableLoggerWithName("ccc"))
}
// This test doesn't make assertions yet
func testObjC() {
let logger = Logger(name: "Tester")
logger.traceMessage("Hello trace level");
logger.debugMessage("Hello debug level");
logger.infoMessage("Hello info level");
logger.warnMessage("Hello warn level");
logger.errorMessage("Hello error level");
logger.severeMessage("Hello severe level");
logger.errorMessage("\(0)");
logger.errorMessage("\(NSDate())");
logger.errorMessage("\(12.234)");
XCTAssert(true, "Pass")
}
class MyClass {
var x = 0
func incX() -> String {
return "x is now \(++x)"
}
}
func testConditionalExecution() {
let logger = Logger(name: "Conditional", level: .INFO)
let myClass = MyClass()
logger.trace(myClass.incX()) // shouldn't trigger incX()
logger.debug(myClass.incX()) // shouldn't trigger incX()
logger.info(myClass.incX())
logger.warn(myClass.incX())
logger.error(myClass.incX())
XCTAssertEqual(myClass.x, 3, "True")
}
func testFlexFormatter() {
let location = SwellTestLocation()
var formatter = FlexFormatter(parts: .NAME, .MESSAGE)
let logger = Logger(name: "TestFlexFormatter", level:.INFO, formatter: formatter, logLocation: location)
logger.info("Log this")
print("Formatter \(formatter.description())")
if let message = location.message {
XCTAssertEqual(message, "TestFlexFormatter: Log this", "Pass")
} else {
XCTFail("Fail")
}
//formatter.format = [.LEVEL, .NAME, .MESSAGE]
formatter = FlexFormatter(parts: .LEVEL, .NAME, .MESSAGE)
logger.formatter = formatter
logger.warn("Warn of this")
if let message = location.message {
XCTAssertEqual(message, " WARN TestFlexFormatter: Warn of this", "Pass")
} else {
XCTFail("Fail")
}
print("Formatter \(formatter.description())")
//formatter.format = [.MESSAGE, .LEVEL, .NAME]
formatter = FlexFormatter(parts: .MESSAGE, .LEVEL, .NAME)
logger.formatter = formatter
logger.warn("Warn of this")
if let message = location.message {
XCTAssertEqual(message, "Warn of this WARN TestFlexFormatter", "Pass")
} else {
XCTFail("Fail")
}
print("Formatter \(formatter.description())")
}
func testFlexPerformance() {
// This is an example of a performance test case.
let location = SwellTestLocation()
let formatter = FlexFormatter(parts: .LEVEL, .NAME, .MESSAGE)
let logger = Logger(name: "TestFlexPerformance", level:.INFO, formatter: formatter, logLocation: location)
self.measureBlock() {
// Put the code you want to measure the time of here.
for _ in 1...5000 {
logger.info("This is my message")
}
}
}
func testFlexSlowestPerformance() {
// This is an example of a performance test case.
let location = SwellTestLocation()
let formatter = FlexFormatter(parts: .DATE, .LEVEL, .NAME, .MESSAGE)
let logger = Logger(name: "TestFlexPerformance", level:.INFO, formatter: formatter, logLocation: location)
self.measureBlock() {
// Put the code you want to measure the time of here.
for _ in 1...5000 {
logger.info("This is my message")
}
}
}
func testQuickPerformance() {
// This is an example of a performance test case.
let location = SwellTestLocation()
let formatter = QuickFormatter(format: .LevelNameMessage)
let logger = Logger(name: "TestQuickPerformance", level:.INFO, formatter: formatter, logLocation: location)
self.measureBlock() {
// Put the code you want to measure the time of here.
for _ in 1...5000 {
logger.info("This is my message")
}
}
}
func testQuickSlowestPerformance() {
// This is an example of a performance test case.
let location = SwellTestLocation()
let formatter = QuickFormatter(format: .All)
let logger = Logger(name: "TestQuickPerformance", level:.INFO, formatter: formatter, logLocation: location)
self.measureBlock() {
// Put the code you want to measure the time of here.
for _ in 1...5000 {
logger.info("This is my message")
}
}
}
}
| apache-2.0 | 9f0938d4017131141e91c0c23c06d3ef | 31.913043 | 131 | 0.565977 | 4.77268 | false | true | false | false |
shorlander/firefox-ios | SyncTests/MetaGlobalTests.swift | 5 | 31833 | /* 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/. */
@testable import Account
import Foundation
import Shared
import Storage
@testable import Sync
import XCGLogger
import Deferred
import XCTest
import SwiftyJSON
private let log = Logger.syncLogger
class MockSyncAuthState: SyncAuthState {
let serverRoot: String
let kB: Data
init(serverRoot: String, kB: Data) {
self.serverRoot = serverRoot
self.kB = kB
}
func invalidate() {
}
func token(_ now: Timestamp, canBeExpired: Bool) -> Deferred<Maybe<(token: TokenServerToken, forKey: Data)>> {
let token = TokenServerToken(id: "id", key: "key", api_endpoint: serverRoot, uid: UInt64(0), hashedFxAUID: "",
durationInSeconds: UInt64(5 * 60), remoteTimestamp: Timestamp(now - 1))
return deferMaybe((token, self.kB))
}
}
class MetaGlobalTests: XCTestCase {
var server: MockSyncServer!
var serverRoot: String!
var kB: Data!
var syncPrefs: Prefs!
var authState: SyncAuthState!
var stateMachine: SyncStateMachine!
override func setUp() {
kB = Data.randomOfLength(32)!
server = MockSyncServer(username: "1234567")
server.start()
serverRoot = server.baseURL
syncPrefs = MockProfilePrefs()
authState = MockSyncAuthState(serverRoot: serverRoot, kB: kB)
stateMachine = SyncStateMachine(prefs: syncPrefs)
}
func storeMetaGlobal(metaGlobal: MetaGlobal) {
let envelope = EnvelopeJSON(JSON(object: [
"id": "global",
"collection": "meta",
"payload": metaGlobal.asPayload().json.stringValue()!,
"modified": Double(Date.now())/1000]))
server.storeRecords(records: [envelope], inCollection: "meta")
}
func storeCryptoKeys(keys: Keys) {
let keyBundle = KeyBundle.fromKB(kB)
let record = Record(id: "keys", payload: keys.asPayload())
let envelope = EnvelopeJSON(keyBundle.serializer({ $0.json })(record)!)
server.storeRecords(records: [envelope], inCollection: "crypto")
}
func assertFreshStart(ready: Ready?, after: Timestamp) {
XCTAssertNotNil(ready)
guard let ready = ready else {
return
}
// We should have wiped.
// We should have uploaded new meta/global and crypto/keys.
XCTAssertGreaterThan(server.collections["meta"]?.records["global"]?.modified ?? 0, after)
XCTAssertGreaterThan(server.collections["meta"]?.modified ?? 0, after)
XCTAssertGreaterThan(server.collections["crypto"]?.records["keys"]?.modified ?? 0, after)
XCTAssertGreaterThan(server.collections["crypto"]?.modified ?? 0, after)
// And we should have downloaded meta/global and crypto/keys.
XCTAssertNotNil(ready.scratchpad.global)
XCTAssertNotNil(ready.scratchpad.keys)
// We should have the default engine configuration.
XCTAssertNotNil(ready.scratchpad.engineConfiguration)
guard let engineConfiguration = ready.scratchpad.engineConfiguration else {
return
}
XCTAssertEqual(engineConfiguration.enabled.sorted(), ["addons", "bookmarks", "clients", "forms", "history", "passwords", "prefs", "tabs"])
XCTAssertEqual(engineConfiguration.declined, [])
// Basic verifications.
XCTAssertEqual(ready.collectionKeys.defaultBundle.encKey.count, 32)
if let clients = ready.scratchpad.global?.value.engines["clients"] {
XCTAssertTrue(clients.syncID.characters.count == 12)
}
}
func testMetaGlobalVersionTooNew() {
// There's no recovery from a meta/global version "in the future": just bail out with an UpgradeRequiredError.
storeMetaGlobal(metaGlobal: MetaGlobal(syncID: "id", storageVersion: 6, engines: [String: EngineMeta](), declined: []))
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "clientUpgradeRequired"])
XCTAssertNotNil(result.failureValue as? ClientUpgradeRequiredError)
XCTAssertNil(result.successValue)
expectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testMetaGlobalVersionTooOld() {
// To recover from a meta/global version "in the past", fresh start.
storeMetaGlobal(metaGlobal: MetaGlobal(syncID: "id", storageVersion: 4, engines: [String: EngineMeta](), declined: []))
let afterStores = Date.now()
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "remoteUpgradeRequired",
"freshStartRequired", "serverConfigurationRequired", "initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
self.assertFreshStart(ready: result.successValue, after: afterStores)
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testMetaGlobalMissing() {
// To recover from a missing meta/global, fresh start.
let afterStores = Date.now()
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "missingMetaGlobal",
"freshStartRequired", "serverConfigurationRequired", "initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
self.assertFreshStart(ready: result.successValue, after: afterStores)
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testCryptoKeysMissing() {
// To recover from a missing crypto/keys, fresh start.
storeMetaGlobal(metaGlobal: createMetaGlobal())
let afterStores = Date.now()
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "missingCryptoKeys", "freshStartRequired", "serverConfigurationRequired", "initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
self.assertFreshStart(ready: result.successValue, after: afterStores)
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testMetaGlobalAndCryptoKeysFresh() {
// When encountering a valid meta/global and crypto/keys, advance smoothly.
let metaGlobal = MetaGlobal(syncID: "id", storageVersion: 5, engines: [String: EngineMeta](), declined: [])
let cryptoKeys = Keys.random()
storeMetaGlobal(metaGlobal: metaGlobal)
storeCryptoKeys(keys: cryptoKeys)
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have downloaded meta/global and crypto/keys.
XCTAssertEqual(ready.scratchpad.global?.value, metaGlobal)
XCTAssertEqual(ready.scratchpad.keys?.value, cryptoKeys)
// We should have marked all local engines for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["bookmarks", "clients", "history", "passwords", "tabs"])
ready.clearLocalCommands()
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
let afterFirstSync = Date.now()
// Now, run through the state machine again. Nothing's changed remotely, so we should advance quickly.
let secondExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "hasMetaGlobal", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have not downloaded a fresh meta/global or crypto/keys.
XCTAssertLessThan(ready.scratchpad.global?.timestamp ?? Timestamp.max, afterFirstSync)
XCTAssertLessThan(ready.scratchpad.keys?.timestamp ?? Timestamp.max, afterFirstSync)
// We should not have marked any local engines for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), [])
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
secondExpectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testFailingOptimisticStateMachine() {
// We test only the optimistic state machine, knowing it will need to go through
// needsFreshMetaGlobal, and fail.
let metaGlobal = MetaGlobal(syncID: "id", storageVersion: 5, engines: [String: EngineMeta](), declined: [])
let cryptoKeys = Keys.random()
storeMetaGlobal(metaGlobal: metaGlobal)
storeCryptoKeys(keys: cryptoKeys)
stateMachine = SyncStateMachine(prefs: syncPrefs, allowingStates: SyncStateMachine.OptimisticStates)
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal"])
XCTAssertNotNil(result.failureValue)
if let failure = result.failureValue as? DisallowedStateError {
XCTAssertEqual(failure.state, SyncStateLabel.NeedsFreshMetaGlobal)
} else {
XCTFail("SyncStatus failed, but with a different error")
}
expectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testHappyOptimisticStateMachine() {
// We should be able to quickly progress through a constrained (a.k.a. optimistic) state machine
let metaGlobal = MetaGlobal(syncID: "id", storageVersion: 5, engines: [String: EngineMeta](), declined: [])
let cryptoKeys = Keys.random()
storeMetaGlobal(metaGlobal: metaGlobal)
storeCryptoKeys(keys: cryptoKeys)
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
expectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
// Now, run through the state machine again. Nothing's changed remotely, so we should advance quickly.
// We should be able to use this 'optimistic' path in an extension.
stateMachine = SyncStateMachine(prefs: syncPrefs, allowingStates: SyncStateMachine.OptimisticStates)
let secondExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "hasMetaGlobal", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
secondExpectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testUpdatedCryptoKeys() {
// When encountering a valid meta/global and crypto/keys, advance smoothly.
let metaGlobal = MetaGlobal(syncID: "id", storageVersion: 5, engines: [String: EngineMeta](), declined: [])
let cryptoKeys = Keys.random()
cryptoKeys.collectionKeys.updateValue(KeyBundle.random(), forKey: "bookmarks")
cryptoKeys.collectionKeys.updateValue(KeyBundle.random(), forKey: "clients")
storeMetaGlobal(metaGlobal: metaGlobal)
storeCryptoKeys(keys: cryptoKeys)
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have downloaded meta/global and crypto/keys.
XCTAssertEqual(ready.scratchpad.global?.value, metaGlobal)
XCTAssertEqual(ready.scratchpad.keys?.value, cryptoKeys)
// We should have marked all local engines for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["bookmarks", "clients", "history", "passwords", "tabs"])
ready.clearLocalCommands()
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
let afterFirstSync = Date.now()
// Store a fresh crypto/keys, with the same default key, one identical collection key, and one changed collection key.
let freshCryptoKeys = Keys(defaultBundle: cryptoKeys.defaultBundle)
freshCryptoKeys.collectionKeys.updateValue(cryptoKeys.forCollection("bookmarks"), forKey: "bookmarks")
freshCryptoKeys.collectionKeys.updateValue(KeyBundle.random(), forKey: "clients")
storeCryptoKeys(keys: freshCryptoKeys)
// Now, run through the state machine again.
let secondExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have not downloaded a fresh meta/global ...
XCTAssertLessThan(ready.scratchpad.global?.timestamp ?? Timestamp.max, afterFirstSync)
// ... but we should have downloaded a fresh crypto/keys.
XCTAssertGreaterThanOrEqual(ready.scratchpad.keys?.timestamp ?? Timestamp.min, afterFirstSync)
// We should have marked only the local engine with a changed key for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["clients"])
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
secondExpectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
let afterSecondSync = Date.now()
// Store a fresh crypto/keys, with a changed default key and one identical collection key, and one changed collection key.
let freshCryptoKeys2 = Keys.random()
freshCryptoKeys2.collectionKeys.updateValue(freshCryptoKeys.forCollection("bookmarks"), forKey: "bookmarks")
freshCryptoKeys2.collectionKeys.updateValue(KeyBundle.random(), forKey: "clients")
storeCryptoKeys(keys: freshCryptoKeys2)
// Now, run through the state machine again.
let thirdExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have not downloaded a fresh meta/global ...
XCTAssertLessThan(ready.scratchpad.global?.timestamp ?? Timestamp.max, afterSecondSync)
// ... but we should have downloaded a fresh crypto/keys.
XCTAssertGreaterThanOrEqual(ready.scratchpad.keys?.timestamp ?? Timestamp.min, afterSecondSync)
// We should have marked all local engines as needing reset, except for the engine whose key remained constant.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["clients", "history", "passwords", "tabs"])
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
thirdExpectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
let afterThirdSync = Date.now()
// Now store a random crypto/keys, with a different default key (and no bulk keys).
let randomCryptoKeys = Keys.random()
storeCryptoKeys(keys: randomCryptoKeys)
// Now, run through the state machine again.
let fourthExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have not downloaded a fresh meta/global ...
XCTAssertLessThan(ready.scratchpad.global?.timestamp ?? Timestamp.max, afterThirdSync)
// ... but we should have downloaded a fresh crypto/keys.
XCTAssertGreaterThanOrEqual(ready.scratchpad.keys?.timestamp ?? Timestamp.min, afterThirdSync)
// We should have marked all local engines for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["bookmarks", "clients", "history", "passwords", "tabs"])
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
fourthExpectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
private func createUnusualMetaGlobal() -> MetaGlobal {
let metaGlobal = MetaGlobal(syncID: "id", storageVersion: 5,
engines: ["bookmarks": EngineMeta(version: 1, syncID: "bookmarks"), "unknownEngine1": EngineMeta(version: 2, syncID: "engineId1")],
declined: ["clients", "forms", "unknownEngine2"])
return metaGlobal
}
func testEngineConfigurations() {
// When encountering a valid meta/global and crypto/keys, advance smoothly. Keep the engine configuration for re-upload.
let metaGlobal = createUnusualMetaGlobal()
let cryptoKeys = Keys.random()
storeMetaGlobal(metaGlobal: metaGlobal)
storeCryptoKeys(keys: cryptoKeys)
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// We should have saved the engine configuration.
XCTAssertNotNil(ready.scratchpad.engineConfiguration)
guard let engineConfiguration = ready.scratchpad.engineConfiguration else {
return
}
XCTAssertEqual(engineConfiguration, metaGlobal.engineConfiguration())
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
// Wipe meta/global.
server.removeAllItemsFromCollection(collection: "meta", atTime: Date.now())
// Now, run through the state machine again. We should produce and upload a meta/global reflecting our engine configuration.
let secondExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "missingMetaGlobal", "freshStartRequired", "serverConfigurationRequired", "initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// The downloaded meta/global should reflect our local engine configuration.
XCTAssertNotNil(ready.scratchpad.global)
guard let global = ready.scratchpad.global?.value else {
return
}
XCTAssertEqual(global.engineConfiguration(), metaGlobal.engineConfiguration())
// We should have the same cached engine configuration.
XCTAssertNotNil(ready.scratchpad.engineConfiguration)
guard let engineConfiguration = ready.scratchpad.engineConfiguration else {
return
}
XCTAssertEqual(engineConfiguration, metaGlobal.engineConfiguration())
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
secondExpectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
func testMetaGlobalModified() {
// When encountering a valid meta/global and crypto/keys, advance smoothly.
let metaGlobal = createUnusualMetaGlobal()
let cryptoKeys = Keys.random()
storeMetaGlobal(metaGlobal: metaGlobal)
storeCryptoKeys(keys: cryptoKeys)
let expectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have downloaded meta/global and crypto/keys.
XCTAssertEqual(ready.scratchpad.global?.value, metaGlobal)
XCTAssertEqual(ready.scratchpad.keys?.value, cryptoKeys)
// We should have marked all local engines for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["bookmarks", "clients", "history", "passwords", "tabs"])
XCTAssertEqual(ready.enginesEnabled(), [])
XCTAssertEqual(ready.enginesDisabled(), [])
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
expectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
let afterFirstSync = Date.now()
// Store a meta/global with a new global syncID.
let newMetaGlobal = metaGlobal.withSyncID("newID")
storeMetaGlobal(metaGlobal: newMetaGlobal)
// Now, run through the state machine again.
let secondExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "needsFreshCryptoKeys", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have downloaded a fresh meta/global ...
XCTAssertGreaterThanOrEqual(ready.scratchpad.global?.timestamp ?? Timestamp.min, afterFirstSync)
// ... and we should have downloaded a fresh crypto/keys -- but its timestamp is identical to the old one!
// Therefore, the "needsFreshCryptoKeys" stage above is our test that we re-downloaded crypto/keys.
// We should have marked all local engines for reset.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["bookmarks", "clients", "history", "passwords", "tabs"])
// And our engine configuration should be unchanged.
XCTAssertNotNil(ready.scratchpad.global)
guard let global = ready.scratchpad.global?.value else {
return
}
XCTAssertEqual(global.engineConfiguration(), metaGlobal.engineConfiguration())
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
secondExpectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
// Now store a meta/global with a changed engine syncID, a new engine, and a new declined entry.
var engines = newMetaGlobal.engines
engines.updateValue(EngineMeta(version: 1, syncID: Bytes.generateGUID()), forKey: "bookmarks")
engines.updateValue(EngineMeta(version: 1, syncID: Bytes.generateGUID()), forKey: "forms")
engines.removeValue(forKey: "unknownEngine1")
var declined = newMetaGlobal.declined.filter({ $0 != "forms" })
declined.append("unknownEngine1")
let secondMetaGlobal = MetaGlobal(syncID: newMetaGlobal.syncID, storageVersion: 5, engines: engines, declined: declined)
storeMetaGlobal(metaGlobal: secondMetaGlobal)
syncPrefs.removeObjectForKey("scratchpad.localCommands")
// Now, run through the state machine again.
let thirdExpectation = self.expectation(description: "Waiting on value.")
stateMachine.toReady(authState).upon { result in
XCTAssertEqual(self.stateMachine.stateLabelSequence.map { $0.rawValue }, ["initialWithLiveToken", "initialWithLiveTokenAndInfo", "needsFreshMetaGlobal", "resolveMetaGlobalVersion", "resolveMetaGlobalContent", "hasMetaGlobal", "hasFreshCryptoKeys", "ready"])
XCTAssertNotNil(result.successValue)
guard let ready = result.successValue else {
return
}
// And we should have downloaded a fresh meta/global ...
XCTAssertGreaterThanOrEqual(ready.scratchpad.global?.timestamp ?? Timestamp.min, afterFirstSync)
// ... and we should have downloaded a fresh crypto/keys -- but its timestamp is identical to the old one!
// Therefore, the "needsFreshCryptoKeys" stage above is our test that we re-downloaded crypto/keys.
// We should have marked the changed engine for local reset, and identified the enabled and disabled engines.
XCTAssertEqual(ready.collectionsThatNeedLocalReset(), ["bookmarks"])
XCTAssertEqual(ready.enginesEnabled(), ["forms"])
XCTAssertEqual(ready.enginesDisabled(), ["unknownEngine1"])
// And our engine configuration should reflect the new meta/global on the server.
XCTAssertNotNil(ready.scratchpad.global)
guard let global = ready.scratchpad.global?.value else {
return
}
XCTAssertEqual(global.engineConfiguration(), secondMetaGlobal.engineConfiguration())
XCTAssertTrue(result.isSuccess)
XCTAssertNil(result.failureValue)
thirdExpectation.fulfill()
}
waitForExpectations(timeout: 2000) { (error) in
XCTAssertNil(error, "Error: \(error ??? "nil")")
}
}
}
| mpl-2.0 | b3de06481299e5c73f92b594d740e495 | 50.343548 | 543 | 0.669211 | 5.572029 | false | true | false | false |
qutheory/vapor | Sources/Vapor/Validation/Validations.swift | 1 | 2422 | public struct Validations {
var storage: [Validation]
public init() {
self.storage = []
}
public mutating func add<T>(
_ key: ValidationKey,
as type: T.Type = T.self,
is validator: Validator<T> = .valid,
required: Bool = true
) {
let validation = Validation(key: key, required: required, validator: validator)
self.storage.append(validation)
}
public mutating func add(
_ key: ValidationKey,
result: ValidatorResult
) {
let validation = Validation(key: key, result: result)
self.storage.append(validation)
}
public mutating func add(
_ key: ValidationKey,
required: Bool = true,
_ nested: (inout Validations) -> ()
) {
var validations = Validations()
nested(&validations)
let validation = Validation(key: key, required: required, nested: validations)
self.storage.append(validation)
}
public func validate(request: Request) throws -> ValidationsResult {
guard let contentType = request.headers.contentType else {
throw Abort(.unprocessableEntity)
}
guard let body = request.body.data else {
throw Abort(.unprocessableEntity)
}
let contentDecoder = try ContentConfiguration.global.requireDecoder(for: contentType)
let decoder = try contentDecoder.decode(DecoderUnwrapper.self, from: body, headers: request.headers)
return try self.validate(decoder.decoder)
}
public func validate(query: URI) throws -> ValidationsResult {
let urlDecoder = try ContentConfiguration.global.requireURLDecoder()
let decoder = try urlDecoder.decode(DecoderUnwrapper.self, from: query)
return try self.validate(decoder.decoder)
}
public func validate(json: String) throws -> ValidationsResult {
let decoder = try JSONDecoder().decode(DecoderUnwrapper.self, from: Data(json.utf8))
return try self.validate(decoder.decoder)
}
public func validate(_ decoder: Decoder) throws -> ValidationsResult {
try self.validate(decoder.container(keyedBy: ValidationKey.self))
}
internal func validate(_ decoder: KeyedDecodingContainer<ValidationKey>) -> ValidationsResult {
.init(results: self.storage.map {
$0.run(decoder)
})
}
}
| mit | 4ec1836374b8dcc6ba7d8fa377113f8e | 33.6 | 108 | 0.637077 | 4.666667 | false | false | false | false |
ldjhust/BeautifulPhotos | BeautifulPhotos/BeautifulPhotos/ShowPhotos/View/MyCollectionViewCell.swift | 1 | 769 | //
// MyCollectionViewCell.swift
// BeautifulPhotos
//
// Created by ldjhust on 15/9/9.
// Copyright (c) 2015年 example. All rights reserved.
//
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
var backgroundImageView: UIImageView?
override init(frame: CGRect) {
super.init(frame: frame)
if backgroundImageView == nil {
self.backgroundImageView = UIImageView()
self.backgroundImageView?.center = CGPoint(x: bounds.width/2, y: bounds.height/2)
self.backgroundImageView?.bounds.size = bounds.size
self.addSubview(self.backgroundImageView!)
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | a46c5c8ad68e29c1f8b433a513aaf3ee | 25.448276 | 93 | 0.634941 | 4.565476 | false | false | false | false |
daisysomus/swift-algorithm-club | Segment Tree/SegmentTree.playground/Contents.swift | 1 | 4987 | //: Playground - noun: a place where people can play
public class SegmentTree<T> {
private var value: T
private var function: (T, T) -> T
private var leftBound: Int
private var rightBound: Int
private var leftChild: SegmentTree<T>?
private var rightChild: SegmentTree<T>?
public init(array: [T], leftBound: Int, rightBound: Int, function: @escaping (T, T) -> T) {
self.leftBound = leftBound
self.rightBound = rightBound
self.function = function
if leftBound == rightBound {
value = array[leftBound]
} else {
let middle = (leftBound + rightBound) / 2
leftChild = SegmentTree<T>(array: array, leftBound: leftBound, rightBound: middle, function: function)
rightChild = SegmentTree<T>(array: array, leftBound: middle+1, rightBound: rightBound, function: function)
value = function(leftChild!.value, rightChild!.value)
}
}
public convenience init(array: [T], function: @escaping (T, T) -> T) {
self.init(array: array, leftBound: 0, rightBound: array.count-1, function: function)
}
public func query(leftBound: Int, rightBound: Int) -> T {
if self.leftBound == leftBound && self.rightBound == rightBound {
return self.value
}
guard let leftChild = leftChild else { fatalError("leftChild should not be nil") }
guard let rightChild = rightChild else { fatalError("rightChild should not be nil") }
if leftChild.rightBound < leftBound {
return rightChild.query(leftBound: leftBound, rightBound: rightBound)
} else if rightChild.leftBound > rightBound {
return leftChild.query(leftBound: leftBound, rightBound: rightBound)
} else {
let leftResult = leftChild.query(leftBound: leftBound, rightBound: leftChild.rightBound)
let rightResult = rightChild.query(leftBound:rightChild.leftBound, rightBound: rightBound)
return function(leftResult, rightResult)
}
}
public func replaceItem(at index: Int, withItem item: T) {
if leftBound == rightBound {
value = item
} else if let leftChild = leftChild, let rightChild = rightChild {
if leftChild.rightBound >= index {
leftChild.replaceItem(at: index, withItem: item)
} else {
rightChild.replaceItem(at: index, withItem: item)
}
value = function(leftChild.value, rightChild.value)
}
}
}
let array = [1, 2, 3, 4]
let sumSegmentTree = SegmentTree(array: array, function: +)
print(sumSegmentTree.query(leftBound: 0, rightBound: 3)) // 1 + 2 + 3 + 4 = 10
print(sumSegmentTree.query(leftBound: 1, rightBound: 2)) // 2 + 3 = 5
print(sumSegmentTree.query(leftBound: 0, rightBound: 0)) // 1 = 1
sumSegmentTree.replaceItem(at: 0, withItem: 2) //our array now is [2, 2, 3, 4]
print(sumSegmentTree.query(leftBound: 0, rightBound: 0)) // 2 = 2
print(sumSegmentTree.query(leftBound: 0, rightBound: 1)) // 2 + 2 = 4
//you can use any associative function (i.e (a+b)+c == a+(b+c)) as function for segment tree
func gcd(_ m: Int, _ n: Int) -> Int {
var a = 0
var b = max(m, n)
var r = min(m, n)
while r != 0 {
a = b
b = r
r = a % b
}
return b
}
let gcdArray = [2, 4, 6, 3, 5]
let gcdSegmentTree = SegmentTree(array: gcdArray, function: gcd)
print(gcdSegmentTree.query(leftBound: 0, rightBound: 1)) // gcd(2, 4) = 2
print(gcdSegmentTree.query(leftBound: 2, rightBound: 3)) // gcd(6, 3) = 3
print(gcdSegmentTree.query(leftBound: 1, rightBound: 3)) // gcd(4, 6, 3) = 1
print(gcdSegmentTree.query(leftBound: 0, rightBound: 4)) // gcd(2, 4, 6, 3, 5) = 1
gcdSegmentTree.replaceItem(at: 3, withItem: 10) //gcdArray now is [2, 4, 6, 10, 5]
print(gcdSegmentTree.query(leftBound: 3, rightBound: 4)) // gcd(10, 5) = 5
//example of segment tree which finds minimum on given range
let minArray = [2, 4, 1, 5, 3]
let minSegmentTree = SegmentTree(array: minArray, function: min)
print(minSegmentTree.query(leftBound: 0, rightBound: 4)) // min(2, 4, 1, 5, 3) = 1
print(minSegmentTree.query(leftBound: 0, rightBound: 1)) // min(2, 4) = 2
minSegmentTree.replaceItem(at: 2, withItem: 10) // minArray now is [2, 4, 10, 5, 3]
print(minSegmentTree.query(leftBound: 0, rightBound: 4)) // min(2, 4, 10, 5, 3) = 2
//type of elements in array can be any type which has some associative function
let stringArray = ["a", "b", "c", "A", "B", "C"]
let stringSegmentTree = SegmentTree(array: stringArray, function: +)
print(stringSegmentTree.query(leftBound: 0, rightBound: 1)) // "a"+"b" = "ab"
print(stringSegmentTree.query(leftBound: 2, rightBound: 3)) // "c"+"A" = "cA"
print(stringSegmentTree.query(leftBound: 1, rightBound: 3)) // "b"+"c"+"A" = "bcA"
print(stringSegmentTree.query(leftBound: 0, rightBound: 5)) // "a"+"b"+"c"+"A"+"B"+"C" = "abcABC"
stringSegmentTree.replaceItem(at: 0, withItem: "I")
stringSegmentTree.replaceItem(at: 1, withItem: " like")
stringSegmentTree.replaceItem(at: 2, withItem: " algorithms")
stringSegmentTree.replaceItem(at: 3, withItem: " and")
stringSegmentTree.replaceItem(at: 4, withItem: " swift")
stringSegmentTree.replaceItem(at: 5, withItem: "!")
print(stringSegmentTree.query(leftBound: 0, rightBound: 5))
| mit | 3d6f0afd630971d37241a5575bcd8003 | 34.877698 | 109 | 0.694205 | 3.369595 | false | false | false | false |
apple/swift-package-manager | Tests/BuildTests/SwiftCompilerOutputParserTests.swift | 2 | 8024 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import XCTest
import Build
class SwiftCompilerOutputParserTests: XCTestCase {
func testParse() throws {
let delegate = MockSwiftCompilerOutputParserDelegate()
let parser = SwiftCompilerOutputParser(targetName: "dummy", delegate: delegate)
parser.parse(bytes: """
338
{
"kind": "began",
"name": "compile",
"inputs": [
"test.swift"
],
"outputs": [
{
"type": "object",
"path": "/var/folders/yc/rgflx8m11p5d71k1ydy0l_pr0000gn/T/test-77d991.o"
}
],
"pid": 22698,
"command_executable": "swift",
"command_arguments" : ["-frontend", "-c", "-primary-file", "test.swift"]
}
117
{
"kind": "finished",
"name": "compile",
"pid": 22698,
"exit-status": 1,
"output": "error: it failed :-("
}
233
{
"kind": "skipped",
"name": "compile",
"inputs": [
"test2.swift"
],
"outputs": [
{
"type": "object",
"path": "/var/folders/yc/rgflx8m11p5d71k1ydy0l_pr0000gn/T/test2-77d991.o"
}
],
"pid": 58776
}
250
{
"kind": "began",
"name": "verify-module-interface",
"inputs": [
"main.swiftinterface"
],
"pid": 31337,
"command_executable": "swift",
"command_arguments" : ["-frontend", "-typecheck-module-from-interface", "main.swiftinterface"]
}
299
{
"kind": "began",
"name": "link",
"inputs": [
"/var/folders/yc/rgflx8m11p5d71k1ydy0l_pr0000gn/T/test-77d991.o"
],
"outputs": [
{
"type": "image",
"path": "test"
}
],
"pid": 22699,
"command_executable": "ld",
"command_arguments" : ["-o", "option", "test"]
}
119
{
"kind": "signalled",
"name": "link",
"pid": 22699,
"error-message": "Segmentation fault: 11",
"signal": 4
}
""".utf8)
delegate.assert(messages: [
SwiftCompilerMessage(
name: "compile",
kind: .began(.init(
pid: 22698,
inputs: ["test.swift"],
outputs: [.init(
type: "object",
path: "/var/folders/yc/rgflx8m11p5d71k1ydy0l_pr0000gn/T/test-77d991.o")],
commandExecutable: "swift",
commandArguments: ["-frontend", "-c", "-primary-file", "test.swift"]))),
SwiftCompilerMessage(
name: "compile",
kind: .finished(.init(
pid: 22698,
output: "error: it failed :-("))),
SwiftCompilerMessage(
name: "compile",
kind: .skipped(.init(
inputs: ["test2.swift"],
outputs: [.init(
type: "object",
path: "/var/folders/yc/rgflx8m11p5d71k1ydy0l_pr0000gn/T/test2-77d991.o")]))),
SwiftCompilerMessage(
name: "verify-module-interface",
kind: .began(.init(
pid: 31337,
inputs: ["main.swiftinterface"],
outputs: nil,
commandExecutable: "swift",
commandArguments: ["-frontend", "-typecheck-module-from-interface", "main.swiftinterface"]))),
SwiftCompilerMessage(
name: "link",
kind: .began(.init(
pid: 22699,
inputs: ["/var/folders/yc/rgflx8m11p5d71k1ydy0l_pr0000gn/T/test-77d991.o"],
outputs: [.init(
type: "image",
path: "test")],
commandExecutable: "ld",
commandArguments: ["-o", "option", "test"]))),
SwiftCompilerMessage(
name: "link",
kind: .signalled(.init(
pid: 22699,
output: nil)))
], errorDescription: nil)
}
func testRawTextTransformsIntoUnknown() {
let delegate = MockSwiftCompilerOutputParserDelegate()
let parser = SwiftCompilerOutputParser(targetName: "dummy", delegate: delegate)
parser.parse(bytes: """
2A
""".utf8)
delegate.assert(messages: [
SwiftCompilerMessage(name: "unknown", kind: .unparsableOutput("2A"))
], errorDescription: nil)
parser.parse(bytes: """
119
{
"kind": "signalled",
"name": "link",
"pid": 22699,
"error-message": "Segmentation fault: 11",
"signal": 4
}
""".utf8)
delegate.assert(messages: [
SwiftCompilerMessage(name: "link", kind: .signalled(.init(pid: 22699, output: nil)))
], errorDescription: nil)
}
func testSignalledStopsParsing() {
let delegate = MockSwiftCompilerOutputParserDelegate()
let parser = SwiftCompilerOutputParser(targetName: "dummy", delegate: delegate)
parser.parse(bytes: """
119
{
"kind": "signalled",
"name": "link",
"pid": 22699,
"error-message": "Segmentation fault: 11",
"signal": 4
}
""".utf8)
delegate.assert(messages: [
SwiftCompilerMessage(name: "link", kind: .signalled(.init(pid: 22699, output: nil)))
], errorDescription: nil)
parser.parse(bytes: """
117
{
"kind": "finished",
"name": "compile",
"pid": 22698,
"exit-status": 1,
"output": "error: it failed :-("
}
""".utf8)
delegate.assert(messages: [], errorDescription: nil)
}
}
class MockSwiftCompilerOutputParserDelegate: SwiftCompilerOutputParserDelegate {
private var messages: [SwiftCompilerMessage] = []
private var error: Error?
func swiftCompilerOutputParser(_ parser: SwiftCompilerOutputParser, didParse message: SwiftCompilerMessage) {
messages.append(message)
}
func swiftCompilerOutputParser(_ parser: SwiftCompilerOutputParser, didFailWith error: Error) {
self.error = error
}
func assert(
messages: [SwiftCompilerMessage],
errorDescription: String?,
file: StaticString = #file,
line: UInt = #line
) {
XCTAssertEqual(messages, self.messages, file: file, line: line)
let errorReason = (self.error as? LocalizedError)?.errorDescription ?? error?.localizedDescription
XCTAssertEqual(errorDescription, errorReason, file: file, line: line)
self.messages = []
self.error = nil
}
}
| apache-2.0 | 08d9ea78a865c2305e49fed6a42ebd52 | 33.290598 | 114 | 0.462238 | 4.877812 | false | true | false | false |
darioalessandro/OAuthClientiOS | OAuthClient/SampleMainController.swift | 1 | 1801 | //
// SampleMainController.swift
// OAuthClient
//
// Created by Dario Lencina on 2/6/16.
// Copyright © 2016 BlackFireApps. All rights reserved.
//
import UIKit
import OAuthClientFramework
class SampleMainController: UITableViewController {
@IBOutlet weak var connectedAs: UITableViewCell!
@IBOutlet weak var login: UITableViewCell!
@IBOutlet weak var logout: UITableViewCell!
override func viewDidLoad() {
super.viewDidLoad()
self.connectedAs.hidden = true
self.logout.hidden = true
self.login.hidden = false
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if(cell == connectedAs) {
} else if(cell == login) {
OAuthClient.sharedInstance.login(self, result : self.loginResult)
} else if(cell == logout) {
OAuthClient.sharedInstance.logout(self.logoutResult)
}
}
lazy var loginResult : (OAuthLoginData?, NSError?) -> Void = {[unowned self](data : OAuthLoginData?, error : NSError?) in
if let loginData = data {
self.connectedAs.hidden = false
self.logout.hidden = false
self.login.hidden = true
self.connectedAs.detailTextLabel!.text = loginData.username
} else {
self.connectedAs.hidden = true
self.logout.hidden = true
self.login.hidden = false
}
}
lazy var logoutResult : (Bool) -> Void = {[unowned self](result : Bool) in
self.connectedAs.hidden = true
self.logout.hidden = true
self.login.hidden = false
}
}
| apache-2.0 | 476152e41c3041ded10e47f0732933a4 | 31.727273 | 125 | 0.635 | 4.774536 | false | false | false | false |
milseman/swift | test/SILOptimizer/specialize_checked_cast_branch.swift | 14 | 12901 | // RUN: %target-swift-frontend -emit-sil -O -sil-inline-threshold 0 %s -o - | %FileCheck %s
class C {}
class D : C {}
class E {}
struct NotUInt8 { var value: UInt8 }
struct NotUInt64 { var value: UInt64 }
var b = NotUInt8(value: 0)
var c = C()
var d = D()
var e = E()
var f = NotUInt64(value: 0)
var o : AnyObject = c
////////////////////////
// Arch to Arch Casts //
////////////////////////
public func ArchetypeToArchetypeCast<T1, T2>(t1 : T1, t2 : T2) -> T2 {
if let x = t1 as? T2 {
return x
}
_preconditionFailure("??? Profit?")
}
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ArchetypeToConcreteCastUInt8AA03NotI0Vx1t_tlFAD_Tg5 : $@convention(thin) (NotUInt8) -> NotUInt8 {
// CHECK: bb0
// CHECK: return %0 : $NotUInt8
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastCAA1CCx1t_tlFAD_Tg5 : $@convention(thin) (@owned C) -> @owned C {
// CHECK: bb0
// CHECK: return %0 : $C
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastCAA1CCx1t_tlFAA1DC_Tg5 : $@convention(thin) (@owned D) -> @owned C {
// CHECK: bb0
// CHECK: [[CAST:%.*]] = upcast %0 : $D to $C
// CHECK: return [[CAST]]
// x -> y where x is a super class of y.
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastDAA1DCx1t_tlFAA1CC_Tg5 : $@convention(thin) (@owned C) -> @owned D {
// CHECK: checked_cast_br %0 : $C to $D,
// CHECK: bb1([[T0:%.*]] : $D):
// CHECK: return [[T0]] : $D
// CHECK: bb2:
// CHECK: integer_literal $Builtin.Int1, -1
// CHECK: cond_fail
// CHECK: unreachable
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA1CC_AA1DCTg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned D
// CHECK: bb0
// CHECK: checked_cast_br %0 : $C to $D, bb1, bb2
// CHECK: bb1(
// CHECK: return
// CHECK: bb2
// CHECK: integer_literal $Builtin.Int1, -1
// CHECK: cond_fail
// CHECK: unreachable
// x -> x where x is a class.
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA1CC_AFTg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned C {
// CHECK: bb0
// CHECK-NOT: bb1
// CHECK: return %0 : $C
// x -> x where x is not a class.
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA8NotUInt8V_AFTg5Tf4nd_n : $@convention(thin) (NotUInt8) -> NotUInt8 {
// CHECK: bb0
// CHECK-NOT: bb1
// CHECK: return %0 : $NotUInt8
// x -> y where x,y are not classes and x is a different type from y.
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA8NotUInt8V_AA0J6UInt64VTg5Tf4dd_n : $@convention(thin) () -> NotUInt64 {
// CHECK: bb0
// CHECK-NOT: bb1
// CHECK: %0 = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail %0 : $Builtin.Int1
// CHECK: unreachable
// x -> y where x is not a class but y is.
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA8NotUInt8V_AA1CCTg5Tf4dd_n : $@convention(thin) () -> @owned C {
// CHECK: bb0
// CHECK-NOT: bb1
// CHECK: %0 = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail %0 : $Builtin.Int1
// CHECK: unreachable
// y -> x where x is a class but y is not.
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA1CC_AA8NotUInt8VTg5Tf4dd_n : $@convention(thin) () -> NotUInt8 {
// CHECK: bb0
// CHECK-NOT: bb1
// CHECK: %0 = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail %0 : $Builtin.Int1
// CHECK: unreachable
// y -> x where x is a super class of y.
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA1DC_AA1CCTg5Tf4nd_n : $@convention(thin) (@owned D) -> @owned C {
// CHECK: [[T1:%.*]] = upcast %0 : $D to $C
// CHECK: return [[T1]] : $C
// x -> y where x and y are unrelated.
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch011ArchetypeToE4Castq_x2t1_q_2t2tr0_lFAA1CC_AA1ECTg5Tf4dd_n : $@convention(thin) () -> @owned E {
// CHECK: bb0
// CHECK-NOT: bb1
// CHECK: %0 = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail %0 : $Builtin.Int1
// CHECK: unreachable
_ = ArchetypeToArchetypeCast(t1: c, t2: d)
_ = ArchetypeToArchetypeCast(t1: c, t2: c)
_ = ArchetypeToArchetypeCast(t1: b, t2: b)
_ = ArchetypeToArchetypeCast(t1: b, t2: f)
_ = ArchetypeToArchetypeCast(t1: b, t2: c)
_ = ArchetypeToArchetypeCast(t1: c, t2: b)
_ = ArchetypeToArchetypeCast(t1: d, t2: c)
_ = ArchetypeToArchetypeCast(t1: c, t2: e)
///////////////////////////
// Archetype To Concrete //
///////////////////////////
func ArchetypeToConcreteCastUInt8<T>(t : T) -> NotUInt8 {
if let x = t as? NotUInt8 {
return x
}
_preconditionFailure("??? Profit?")
}
func ArchetypeToConcreteCastC<T>(t : T) -> C {
if let x = t as? C {
return x
}
_preconditionFailure("??? Profit?")
}
func ArchetypeToConcreteCastD<T>(t : T) -> D {
if let x = t as? D {
return x
}
_preconditionFailure("??? Profit?")
}
func ArchetypeToConcreteCastE<T>(t : T) -> E {
if let x = t as? E {
return x
}
_preconditionFailure("??? Profit?")
}
_ = ArchetypeToConcreteCastUInt8(t: b)
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ArchetypeToConcreteCastUInt8AA03NotI0Vx1t_tlFAA1CC_Tg5Tf4d_n : $@convention(thin) () -> NotUInt8 {
// CHECK: bb0
// CHECK-NOT: checked_cast_br
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail [[TRUE]]
// CHECK: unreachable
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ArchetypeToConcreteCastUInt8AA03NotI0Vx1t_tlFAA0J6UInt64V_Tg5Tf4d_n : $@convention(thin) () -> NotUInt8 {
// CHECK-NEXT: bb0
// CHECK-NOT: checked_cast_br archetype_to_concrete
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail [[TRUE]]
// CHECK: unreachable
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastCAA1CCx1t_tlFAA8NotUInt8V_Tg5Tf4d_n : $@convention(thin) () -> @owned C {
// CHECK: bb0
// CHECK-NOT: checked_cast_br
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail [[TRUE]]
// CHECK: unreachable
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastCAA1CCx1t_tlFAA1EC_Tg5Tf4d_n : $@convention(thin) () -> @owned C {
// CHECK: bb0
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail [[TRUE]]
// CHECK: unreachable
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ArchetypeToConcreteCastEAA1ECx1t_tlFAA1CC_Tg5Tf4d_n : $@convention(thin) () -> @owned E {
// CHECK: bb0
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail [[TRUE]]
// CHECK: unreachable
_ = ArchetypeToConcreteCastUInt8(t: c)
_ = ArchetypeToConcreteCastUInt8(t: f)
_ = ArchetypeToConcreteCastC(t: c)
_ = ArchetypeToConcreteCastC(t: b)
_ = ArchetypeToConcreteCastC(t: d)
_ = ArchetypeToConcreteCastC(t: e)
_ = ArchetypeToConcreteCastD(t: c)
_ = ArchetypeToConcreteCastE(t: c)
///////////////////////////
// Concrete To Archetype //
///////////////////////////
func ConcreteToArchetypeCastUInt8<T>(t: NotUInt8, t2: T) -> T {
if let x = t as? T {
return x
}
_preconditionFailure("??? Profit?")
}
func ConcreteToArchetypeCastC<T>(t: C, t2: T) -> T {
if let x = t as? T {
return x
}
_preconditionFailure("??? Profit?")
}
func ConcreteToArchetypeCastD<T>(t: D, t2: T) -> T {
if let x = t as? T {
return x
}
_preconditionFailure("??? Profit?")
}
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ConcreteToArchetypeCastUInt8xAA03NotI0V1t_x2t2tlFAD_Tg5Tf4nd_n : $@convention(thin) (NotUInt8) -> NotUInt8
// CHECK: bb0
// CHECK: return %0
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ConcreteToArchetypeCastUInt8xAA03NotI0V1t_x2t2tlFAA1CC_Tg5Tf4dd_n : $@convention(thin) () -> @owned C
// CHECK: bb0
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail [[TRUE]]
// CHECK: unreachable
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch28ConcreteToArchetypeCastUInt8xAA03NotI0V1t_x2t2tlFAA0J6UInt64V_Tg5Tf4dd_n : $@convention(thin) () -> NotUInt64
// CHECK: bb0
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail [[TRUE]]
// CHECK: unreachable
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastCxAA1CC1t_x2t2tlFAD_Tg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned C
// CHECK: bb0
// CHECK: return %0
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastCxAA1CC1t_x2t2tlFAA8NotUInt8V_Tg5Tf4dd_n : $@convention(thin) () -> NotUInt8
// CHECK: bb0
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail [[TRUE]]
// CHECK: unreachable
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastCxAA1CC1t_x2t2tlFAA1DC_Tg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned D
// CHECK: bb0
// CHECK: checked_cast_br %0 : $C to $D
// CHECK: bb1
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastCxAA1CC1t_x2t2tlFAA1EC_Tg5Tf4dd_n : $@convention(thin) () -> @owned E
// CHECK: bb0
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail [[TRUE]]
// CHECK: unreachable
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch24ConcreteToArchetypeCastDxAA1DC1t_x2t2tlFAA1CC_Tg5Tf4nd_n : $@convention(thin) (@owned D) -> @owned C
// CHECK: bb0
// CHECK: [[T0:%.*]] = upcast %0 : $D to $C
// CHECK: return [[T0]]
_ = ConcreteToArchetypeCastUInt8(t: b, t2: b)
_ = ConcreteToArchetypeCastUInt8(t: b, t2: c)
_ = ConcreteToArchetypeCastUInt8(t: b, t2: f)
_ = ConcreteToArchetypeCastC(t: c, t2: c)
_ = ConcreteToArchetypeCastC(t: c, t2: b)
_ = ConcreteToArchetypeCastC(t: c, t2: d)
_ = ConcreteToArchetypeCastC(t: c, t2: e)
_ = ConcreteToArchetypeCastD(t: d, t2: c)
////////////////////////
// Super To Archetype //
////////////////////////
func SuperToArchetypeCastC<T>(c : C, t : T) -> T {
if let x = c as? T {
return x
}
_preconditionFailure("??? Profit?")
}
func SuperToArchetypeCastD<T>(d : D, t : T) -> T {
if let x = d as? T {
return x
}
_preconditionFailure("??? Profit?")
}
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastCxAA1CC1c_x1ttlFAD_Tg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned C
// CHECK: bb0
// CHECK: return %0 : $C
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastCxAA1CC1c_x1ttlFAA1DC_Tg5Tf4nd_n : $@convention(thin) (@owned C) -> @owned D
// CHECK: bb0
// CHECK: checked_cast_br %0 : $C to $D
// CHECK: bb1
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastCxAA1CC1c_x1ttlFAA8NotUInt8V_Tg5Tf4dd_n : $@convention(thin) () -> NotUInt8
// CHECK: bb0
// CHECK: [[TRUE:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK: cond_fail [[TRUE]]
// CHECK: unreachable
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastDxAA1DC1d_x1ttlFAA1CC_Tg5Tf4nd_n : $@convention(thin) (@owned D) -> @owned C
// CHECK: bb0
// CHECK: [[T0:%.*]] = upcast %0 : $D to $C
// CHECK: return [[T0]]
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch21SuperToArchetypeCastDxAA1DC1d_x1ttlFAD_Tg5Tf4nd_n : $@convention(thin) (@owned D) -> @owned D
// CHECK: bb0
// CHECK: return %0 : $D
_ = SuperToArchetypeCastC(c: c, t: c)
_ = SuperToArchetypeCastC(c: c, t: d)
_ = SuperToArchetypeCastC(c: c, t: b)
_ = SuperToArchetypeCastD(d: d, t: c)
_ = SuperToArchetypeCastD(d: d, t: d)
//////////////////////////////
// Existential To Archetype //
//////////////////////////////
func ExistentialToArchetypeCast<T>(o : AnyObject, t : T) -> T {
if let x = o as? T {
return x
}
_preconditionFailure("??? Profit?")
}
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch26ExistentialToArchetypeCastxyXl1o_x1ttlFAA1CC_Tg5Tf4nd_n : $@convention(thin) (@owned AnyObject) -> @owned C
// CHECK: bb0
// CHECK: checked_cast_br %0 : $AnyObject to $C
// CHECK: bb1
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch26ExistentialToArchetypeCastxyXl1o_x1ttlFAA8NotUInt8V_Tg5Tf4gd_n : $@convention(thin) (@guaranteed AnyObject) -> NotUInt8
// CHECK: bb0
// CHECK: checked_cast_addr_br take_always AnyObject in {{%.*}} : $*AnyObject to NotUInt8 in {{%.*}} : $*NotUInt8,
// CHECK: bb1
// CHECK-LABEL: sil shared @_T030specialize_checked_cast_branch26ExistentialToArchetypeCastxyXl1o_x1ttlFyXl_Tg5Tf4nd_n : $@convention(thin) (@owned AnyObject) -> @owned AnyObject
// CHECK: bb0
// CHECK-NOT: checked_cast_br %
// CHECK: return %0 : $AnyObject
// CHECK-NOT: checked_cast_br %
_ = ExistentialToArchetypeCast(o: o, t: c)
_ = ExistentialToArchetypeCast(o: o, t: b)
_ = ExistentialToArchetypeCast(o: o, t: o)
| apache-2.0 | d7af8c86fb9d09cca9bbc2a6d3afc842 | 36.286127 | 184 | 0.676072 | 2.98289 | false | false | false | false |
damboscolo/SwiftToast | SwiftToast/Classes/SwiftToastView.swift | 1 | 2240 | //
// SwiftToast.swift
// Daniele Boscolo
//
// Created by damboscolo on 04/04/17.
// Copyright © 2017 Daniele Boscolo. All rights reserved.
//
import UIKit
public protocol SwiftToastViewProtocol: class {
func nib() -> SwiftToastViewProtocol?
func configure(with toast: SwiftToastProtocol)
}
class SwiftToastView: UIView, SwiftToastViewProtocol {
// MARK:- Outlets
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var viewTopConstraint: NSLayoutConstraint!
@IBOutlet weak var viewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var viewMinimumHeightConstraint: NSLayoutConstraint!
// MARK:- Initializers
func nib() -> SwiftToastViewProtocol? {
let podBundle = Bundle(for: SwiftToastView.self)
guard let bundleURL = podBundle.url(forResource: "SwiftToast", withExtension: "bundle"), let bundle = Bundle(url: bundleURL) else {
return nil
}
return bundle.loadNibNamed("SwiftToastView", owner: self, options: nil)?.first as? SwiftToastView
}
// MARK:- Configure
func configure(with toast: SwiftToastProtocol) {
guard let toast = toast as? SwiftToast else {
return
}
titleLabel.text = toast.text
titleLabel.textAlignment = toast.textAlignment
titleLabel.textColor = toast.textColor
titleLabel.font = toast.font
backgroundColor = toast.backgroundColor
isUserInteractionEnabled = toast.isUserInteractionEnabled
// Setup minimum height if needed
if let minimumHeight = toast.minimumHeight {
viewMinimumHeightConstraint.constant = minimumHeight
}
if let image = toast.image {
imageView.image = image
imageView.isHidden = false
} else {
imageView.isHidden = true
}
switch toast.style {
case .statusBar, .belowNavigationBar:
viewTopConstraint.constant = 2.0
viewBottomConstraint.constant = 2.0
default:
viewTopConstraint.constant = 25.0
viewBottomConstraint.constant = 16.0
}
}
}
| mit | 191d730c1426897e7d5d0981490043bb | 30.985714 | 139 | 0.646271 | 5.293144 | false | false | false | false |
mileswd/mac2imgur | mac2imgur/NSMenuExtension.swift | 1 | 2098 | /* This file is part of mac2imgur.
*
* mac2imgur 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.
* mac2imgur 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 mac2imgur. If not, see <http://www.gnu.org/licenses/>.
*/
import Cocoa
extension NSMenu {
/// Adds a menu item with the specified options.
func addItem(withTitle title: String,
action: Selector? = nil,
target: AnyObject? = nil,
representedObject: AnyObject? = nil,
state: Int = NSOffState,
submenu: NSMenu? = nil) {
let menuItem = NSMenuItem()
menuItem.title = title
menuItem.action = action
menuItem.target = target
menuItem.representedObject = representedObject
menuItem.state = state
menuItem.submenu = submenu
addItem(menuItem)
}
/// Creates a section title, which is a title in system small font size
/// surrounded by two separator items.
func addItem(withSectionTitle title: String) {
addItem(.separator())
let menuItem = NSMenuItem()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = NSTextAlignment.center
menuItem.attributedTitle = NSAttributedString(
string: title,
attributes: [
NSFontAttributeName: NSFont.systemFont(
ofSize: NSFont.smallSystemFontSize()),
NSParagraphStyleAttributeName: paragraphStyle
])
addItem(menuItem)
addItem(.separator())
}
}
| gpl-3.0 | 38956657ba47dc2e8572209d035450b2 | 32.83871 | 75 | 0.627264 | 5.324873 | false | false | false | false |
ifLab/WeCenterMobile-iOS | WeCenterMobile/Model/DataObject/User.swift | 3 | 42154 | //
// User.swift
// WeCenterMobile
//
// Created by Darren Liu on 14/11/26.
// Copyright (c) 2014年 Beijing Information Science and Technology University. All rights reserved.
//
import AFNetworking
import CoreData
import UIKit
let UserDefaultsCookiesKey = "WeCenterMobile_DefaultCookies"
let UserDefaultsUserIDKey = "WeCenterMobile_DefaultUserID"
let CurrentUserDidChangeNotificationName = "CurrentUserDidChangeNotification"
let CurrentUserPropertyDidChangeNotificationName = "CurrentUserPropertyDidChangeNotification"
let KeyUserInfoKey = "KeyPathUserInfo"
class User: DataObject {
static var currentUser: User? = nil {
didSet {
NSNotificationCenter.defaultCenter().postNotificationName(CurrentUserDidChangeNotificationName, object: nil)
}
}
var isCurrentUser: Bool {
return id == User.currentUser?.id
}
@NSManaged var agreementCount: NSNumber?
@NSManaged var answerCount: NSNumber?
@NSManaged var answerFavoriteCount: NSNumber?
@NSManaged var articleCount: NSNumber?
@NSManaged var avatarData: NSData?
@NSManaged var avatarURI: String?
@NSManaged var birthday: NSDate?
@NSManaged var followerCount: NSNumber?
@NSManaged var followingCount: NSNumber?
@NSManaged var genderValue: NSNumber?
@NSManaged var jobID: NSNumber?
@NSManaged var markCount: NSNumber?
@NSManaged var name: String?
@NSManaged var questionCount: NSNumber?
@NSManaged var signature: String?
@NSManaged var thankCount: NSNumber?
@NSManaged var topicFocusCount: NSNumber?
@NSManaged var actions: Set<Action>
@NSManaged var answers: Set<Answer>
@NSManaged var articles: Set<Article>
@NSManaged var answerComments: Set<AnswerComment>
@NSManaged var answerCommentsMentioned: Set<AnswerComment>
@NSManaged var featuredQuestionAnswers: Set<FeaturedQuestionAnswer>
@NSManaged var followers: Set<User>
@NSManaged var followings: Set<User>
@NSManaged var questions: Set<Question>
@NSManaged var topics: Set<Topic>
@NSManaged var articleComments: Set<ArticleComment>
@NSManaged var articleCommentsMentioned: Set<ArticleComment>
enum Gender: Int {
case Male = 1
case Female = 2
case Secret = 3
}
var gender: Gender? {
get {
return (genderValue == nil) ? nil : Gender(rawValue: genderValue!.integerValue)
}
set {
genderValue = newValue?.rawValue
}
}
var avatar: UIImage? {
get {
if avatarData != nil {
return UIImage(data: avatarData!)
} else {
return nil
}
}
set {
avatarData = newValue == nil ? nil : UIImagePNGRepresentation(newValue!)
}
}
var following: Bool? = nil
var avatarURL: String? {
get {
return (avatarURI == nil) ? nil : NetworkManager.defaultManager!.website + NetworkManager.defaultManager!.paths["User Avatar"]! + avatarURI!
}
set {
if let replacedString = newValue?.stringByReplacingOccurrencesOfString(NetworkManager.defaultManager!.website + NetworkManager.defaultManager!.paths["User Avatar"]!, withString: "") {
if replacedString != newValue {
avatarURI = replacedString
} else {
avatarURI = nil
}
} else {
avatarURI = nil
}
}
}
class func fetch(ID ID: NSNumber, success: ((User) -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.GET("User Extra Information",
parameters: [
"uid": ID
],
success: {
data in
let data = data as! NSDictionary
let user = User.cachedObjectWithID(ID)
user.id = ID
user.name = data["user_name"] as? String
user.avatarURL = data["avatar_file"] as? String
user.followerCount = Int(msr_object: data["fans_count"])
user.followingCount = Int(msr_object: data["friend_count"])
user.questionCount = Int(msr_object: data["question_count"])
user.answerCount = Int(msr_object: data["answer_count"])
user.articleCount = Int(msr_object: data["article_count"])
user.topicFocusCount = Int(msr_object: data["topic_focus_count"])
user.agreementCount = Int(msr_object: data["agree_count"])
user.thankCount = Int(msr_object: data["thanks_count"])
user.answerFavoriteCount = Int(msr_object: data["answer_favorite_count"])
user.following = (data["has_focus"] as! NSNumber == 1)
_ = try? DataManager.defaultManager.saveChanges()
success?(user)
},
failure: failure)
}
func fetchFollowings(page page: Int, count: Int, success: (([User]) -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.GET("User Following List",
parameters: [
"uid": id,
"type": "follows",
"page": page,
"per_page": count
],
success: {
[weak self] data in
if let self_ = self {
if Int(msr_object: data["total_rows"]!!) > 0 && data["rows"] is [NSDictionary] {
var users = [User]()
for value in data["rows"] as! [NSDictionary] {
let userID = Int(msr_object: value["uid"])
let user = User.cachedObjectWithID(userID!)
user.name = value["user_name"] as? String
user.avatarURL = value["avatar_file"] as? String
user.signature = value["signature"] as? String
self_.followings.insert(user)
users.append(user)
}
_ = try? DataManager.defaultManager.saveChanges()
success?(users)
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
func fetchFollowers(page page: Int, count: Int, success: (([User]) -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.GET("User Follower List",
parameters: [
"uid": id,
"type": "fans",
"page": page,
"per_page": count
],
success: {
[weak self] data in
if let self_ = self {
if Int(msr_object: data["total_rows"]!!) > 0 {
var users = [User]()
for value in data["rows"] as! [NSDictionary] {
let userID = Int(msr_object: value["uid"])!
let user = User.cachedObjectWithID(userID)
user.name = value["user_name"] as? String
user.avatarURL = value["avatar_file"] as? String
user.signature = value["signature"] as? String
self_.followers.insert(user)
users.append(user)
}
_ = try? DataManager.defaultManager.saveChanges()
success?(users)
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
func fetchTopics(page page: Int, count: Int, success: (([Topic]) -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.GET("User Topic List",
parameters: [
"uid": id,
"page": page
],
success: {
[weak self] data in
if let self_ = self {
if Int(msr_object: data["total_rows"]!!) > 0 {
var topics = [Topic]()
for value in data["rows"] as! [NSDictionary] {
let topicID = Int(msr_object: value["topic_id"])!
let topic = Topic.cachedObjectWithID(topicID)
topic.title = value["topic_title"] as? String
topic.introduction = value["topic_description"] as? String
topic.imageURL = value["topic_pic"] as? String
self_.topics.insert(topic)
topics.append(topic)
}
_ = try? DataManager.defaultManager.saveChanges()
success?(topics)
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
func fetchQuestions(page page: Int, count: Int, success: (([Question]) -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.GET("User Question List",
parameters: [
"actions":101,
"uid": id,
"page": page,
"per_page": count
],
success: {
[weak self] data in
if let self_ = self {
if !MSRIsNilOrNull(data["rows"]) && Int(msr_object: data["total_rows"]) > 0 {
let questionsData: [NSDictionary]
if data["rows"] is NSArray {
questionsData = data["rows"] as! [NSDictionary]
} else {
questionsData = [data["rows"] as! NSDictionary]
}
var questions = [Question]()
for questionData in questionsData {
let questionInfo = questionData["question_info"] as! NSDictionary
let questionID = Int(msr_object: questionInfo["question_id"])!
let question = Question.cachedObjectWithID(questionID)
question.user = self
question.title = (questionInfo["question_content"] as! String)
question.body = (questionInfo["message"] as? String)
question.date = NSDate(timeIntervalSince1970: NSTimeInterval(msr_object: questionInfo["add_time"])!)
self_.questions.insert(question)
questions.append(question)
}
_ = try? DataManager.defaultManager.saveChanges()
success?(questions)
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
func fetchAnswers(page page: Int, count: Int, success: (([Answer]) -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.GET("User Answer List",
parameters: [
"actions":201,
"uid": id,
"page": page,
"per_page": count
],
success: {
[weak self] data in
if let self_ = self {
if !MSRIsNilOrNull(data["rows"]) && Int(msr_object: data["total_rows"]) > 0 {
let answersData: [NSDictionary]
if data["rows"] is NSDictionary {
answersData = [data["rows"] as! NSDictionary]
} else {
answersData = data["rows"] as! [NSDictionary]
}
var answers = [Answer]()
for answerData in answersData {
let answerInfo = answerData["answer_info"] as! NSDictionary
let questionInfo = answerData["question_info"] as! NSDictionary
let answerID = Int(msr_object: answerInfo["answer_id"])!
let questionID = Int(msr_object: questionInfo["question_id"])!
let answer = Answer.cachedObjectWithID(answerID)
answer.question = Question.cachedObjectWithID(questionID)
answer.user = self
answer.user?.avatarURL = answerData["avatar_file"] as? String
answer.body = (answerInfo["answer_content"] as! String)
answer.agreementCount = Int(msr_object: answerInfo["agree_count"])
answer.question!.title = (questionInfo["question_content"] as! String)
self_.answers.insert(answer)
answers.append(answer)
}
_ = try? DataManager.defaultManager.saveChanges()
success?(answers)
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
func fetchArticles(page page: Int, count: Int, success: (([Article]) -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.GET("User Article List",
parameters: [
"actions":501,
"uid": id,
"page": page,
"per_page": count
],
success: {
[weak self] data in
if let self_ = self {
if !MSRIsNilOrNull(data["rows"]) && Int(msr_object: data["total_rows"]) > 0 {
let articlesData: [NSDictionary]
if data["rows"] is NSDictionary {
articlesData = [data["rows"] as! NSDictionary]
} else {
articlesData = data["rows"] as! [NSDictionary]
}
var articles = [Article]()
for articleData in articlesData {
let articleInfo = articleData["article_info"] as! NSDictionary
let articleID = Int(msr_object: articleInfo["id"])!
let article: Article = Article.cachedObjectWithID(articleID)
article.user = self
article.title = (articleInfo["title"] as! String)
article.body = (articleInfo["message"] as! String)
article.date = NSDate(timeIntervalSince1970: NSTimeInterval(msr_object: articleData["add_time"])!)
self_.articles.insert(article)
articles.append(article)
}
_ = try? DataManager.defaultManager.saveChanges()
success?(articles)
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
class func registerWithEmail(email: String, name: String, password: String, success: ((User) -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.POST("User Registration",
parameters: [
"user_name": name,
"email": email,
"password": password
],
success: {
data in
let userID = Int(msr_object: data["uid"])!
let user = User.cachedObjectWithID(userID)
user.name = name
let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!
let cookiesData = NSKeyedArchiver.archivedDataWithRootObject(cookies)
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(cookiesData, forKey: UserDefaultsCookiesKey)
defaults.setObject(user.id, forKey: UserDefaultsUserIDKey)
defaults.synchronize()
_ = try? DataManager.defaultManager.saveChanges()
self.loginWithCookiesAndCacheInStorage(success: success, failure: failure)
},
failure: failure)
}
class func loginWithCookiesAndCacheInStorage(success success: ((User) -> Void)?, failure: ((NSError) -> Void)?) {
let defaults = NSUserDefaults.standardUserDefaults()
let data = defaults.objectForKey(UserDefaultsCookiesKey) as? NSData
let userID = defaults.objectForKey(UserDefaultsUserIDKey) as? NSNumber
if data == nil || userID == nil {
let userInfo = [
NSLocalizedDescriptionKey: "Could not find any cookies or cache in storage.",
NSLocalizedFailureReasonErrorKey: "You've never logged in before or cookies and cache have been cleared."
]
failure?(NSError(
domain: NetworkManager.defaultManager!.website,
code: NetworkManager.defaultManager!.internalErrorCode.integerValue,
userInfo: userInfo)) // Needs specification
} else {
let cookies = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! [NSHTTPCookie]
let storage = NSHTTPCookieStorage.sharedHTTPCookieStorage()
for cookie in cookies {
storage.setCookie(cookie)
}
do {
let user = try DataManager.defaultManager?.fetch("User", ID: userID!) as! User
success?(user)
} catch let error as NSError {
let userInfo = [
NSLocalizedDescriptionKey: "Cookies and user ID were found, but no such user in cache.",
NSLocalizedFailureReasonErrorKey: "Caches have been cleared before.",
NSLocalizedRecoverySuggestionErrorKey: "By accessing \"User Basic Information\" with cookies in header, you can get the basic infomation of current user. Cookies have been set into header.",
NSUnderlyingErrorKey: error
]
failure?(NSError(
domain: NetworkManager.defaultManager!.website,
code: NetworkManager.defaultManager!.internalErrorCode.integerValue,
userInfo: userInfo))
}
}
}
class func loginWithName(name: String, password: String, success: ((User) -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.clearCookies()
NetworkManager.defaultManager!.POST("User Login",
parameters: [
"user_name": name.stringByRemovingPercentEncoding!,
"password": password.stringByRemovingPercentEncoding!
],
success: {
data in
let cookies = NSHTTPCookieStorage.sharedHTTPCookieStorage().cookies!
let cookiesData = NSKeyedArchiver.archivedDataWithRootObject(cookies)
let user = User.cachedObjectWithID(Int(msr_object: (data as! NSDictionary)["uid"])!)
user.name = data["user_name"] as? String
user.avatarURL = data["avatar_file"] as? String
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(cookiesData, forKey: UserDefaultsCookiesKey)
defaults.setObject(user.id, forKey: UserDefaultsUserIDKey)
defaults.synchronize()
_ = try? DataManager.defaultManager.saveChanges()
self.loginWithCookiesAndCacheInStorage(success: success, failure: failure)
},
failure: failure)
}
// Needs to be modified
func fetchProfile(success success: (() -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.GET("User Basic Information",
parameters: [
"uid": id
],
success: {
[weak self] data in
let value = data[0] as! NSDictionary
if let self_ = self {
self_.name = value["user_name"] as? String
self_.genderValue = value["sex"] is NSNull ? Gender.Secret.rawValue : Int(msr_object: value["sex"])
let timeInterval = NSTimeInterval(msr_object: value["birthday"])
if timeInterval != nil {
self_.birthday = NSDate(timeIntervalSince1970: timeInterval!)
}
self_.jobID = Int(msr_object: value["job_id"])
self_.signature = value["signature"] as? String
_ = try? DataManager.defaultManager.saveChanges()
success?()
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
func updateProfileForCurrentUser(success success: (() -> Void)?, failure: ((NSError) -> Void)?) {
let id = self.id
let name = self.name
let gender = self.gender!
let signature = self.signature
let birthday = self.birthday
let fmt = NSDateFormatter()
fmt.locale = NSLocale(localeIdentifier: "zh_CN")
fmt.dateFormat = "yyyy"
let birthdayY = Int(msr_object: fmt.stringFromDate(birthday!))!
fmt.dateFormat = "MM"
let birthdayM = Int(msr_object: fmt.stringFromDate(birthday!))!
fmt.dateFormat = "dd"
let birthdayD = Int(msr_object: fmt.stringFromDate(birthday!))!
var parameters: [String: AnyObject] = ["user_name": name!]
parameters["sex"] = gender.rawValue
parameters["signature"] = signature
parameters["birthday_y"] = birthdayY
parameters["birthday_m"] = birthdayM
parameters["birthday_d"] = birthdayD
NetworkManager.defaultManager!.POST("Update Profile",
parameters: parameters,
success: {
data in
if data as! String == "个人资料保存成功" {
User.currentUser!.id = id
User.currentUser!.name = name
User.currentUser!.gender = gender
User.currentUser!.signature = signature
User.currentUser!.birthday = birthday
_ = try? DataManager.defaultManager.saveChanges()
success?()
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
private static var avatarUploadingOperation: AFHTTPRequestOperation?
class func uploadAvatar(avatar: UIImage, success: (() -> Void)?, failure: ((NSError) -> Void)?) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let maxLength: CGFloat = 256
let scale = min(1, max(maxLength / avatar.size.width, maxLength / avatar.size.height))
var image = avatar.msr_imageOfSize(CGSize(width: avatar.size.width * scale, height: avatar.size.height * scale))
image = image.msr_imageByClippingToRect(CGRect(x: (image.size.width - maxLength) / 2, y: (image.size.height - maxLength), width: maxLength, height: maxLength))
let jpeg = UIImageJPEGRepresentation(image, 1)
dispatch_async(dispatch_get_main_queue()) {
self.avatarUploadingOperation = NetworkManager.defaultManager!.request("Upload User Avatar",
GETParameters: [:],
POSTParameters: [:],
constructingBodyWithBlock: {
data in
data?.appendPartWithFileData(jpeg, name: "user_avatar", fileName: "avatar.jpg", mimeType: "image/png")
return
},
success: {
data in
User.avatarUploadingOperation = nil
User.currentUser?.avatar = image
User.currentUser?.avatarURL = (data["preview"] as! String)
_ = try? DataManager.defaultManager.saveChanges()
success?()
},
failure: {
error in
User.avatarUploadingOperation = nil
failure?(error)
})
}
}
}
class func cancleAvatarUploadingOperation() {
avatarUploadingOperation?.cancel()
}
func toggleFollow(success success: (() -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.POST("Follow User",
parameters: [
"uid": id
],
success: {
[weak self] data in
if let self_ = self {
self_.following = (data["type"] as! String == "add")
_ = try? DataManager.defaultManager.saveChanges()
success?()
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
private let imageView = UIImageView()
func fetchAvatar(forced forced: Bool, success: (() -> Void)?, failure: ((NSError) -> Void)?) {
if avatarURL != nil {
let request = NSMutableURLRequest(URL: NSURL(string: avatarURL!)!)
request.addValue("image/*", forHTTPHeaderField:"Accept")
if forced {
(UIImageView.sharedImageCache() as! NSCache).removeObjectForKey(request.URL!.absoluteString)
}
imageView.setImageWithURLRequest(request,
placeholderImage: nil,
success: {
[weak self] request, response, image in
if let self_ = self {
if self_.avatar == nil || response != nil {
self_.avatar = image
_ = try? DataManager.defaultManager.saveChanges()
success?()
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: {
_, _, error in
failure?(error)
return
})
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
}
func fetchRelatedActions(page page: Int, count: Int, success: (([Action]) -> Void)?, failure: ((NSError) -> Void)?) {
NetworkManager.defaultManager!.GET("Home List",
parameters: [
"page": page - 1,
"per_page": count
],
success: {
data in
let rows = data["total_rows"] as! Int
if rows > 0 {
var actions = [Action]()
let objects = data["rows"] as! [[String: AnyObject]]
for object in objects {
let typeID = ActionTypeID(rawValue: Int(msr_object: object["associate_action"])!)
if typeID == nil { print("ActionTypeID got a nil"); continue }
var action_: Action!
switch typeID! {
case .AnswerAgreement:
let action = AnswerAgreementAction.cachedObjectWithID(Int(msr_object: object["history_id"]!)!)
action_ = action
action.date = NSDate(timeIntervalSince1970: (object["add_time"] as! NSNumber).doubleValue)
if let userInfo = object["user_info"] as? [String: AnyObject] {
action.user = User.cachedObjectWithID(Int(msr_object: userInfo["uid"])!)
action.user!.name = (userInfo["user_name"] as! String)
action.user!.avatarURL = userInfo["avatar_file"] as? String
} else {
action.user = nil
}
let answerInfo = object["answer_info"] as! NSDictionary
action.answer = Answer.cachedObjectWithID(Int(msr_object: answerInfo["answer_id"])!)
action.answer!.body = (answerInfo["answer_content"] as! String)
action.answer!.agreementCount = (answerInfo["agree_count"] as! NSNumber)
/// @TODO: [Bug][Back-End] object["question_info"] is NSNull
if let questionInfo = object["question_info"] as? NSDictionary {
action.answer!.question = Question.cachedObjectWithID(Int(msr_object: questionInfo["question_id"])!)
action.answer!.question!.title = (questionInfo["question_content"] as! String)
} else {
action.answer!.question = Question.cachedObjectWithID(Int(msr_object: answerInfo["question_id"])!)
action.answer!.question!.title = "[问题已被删除]"
}
break
case .QuestionFocusing:
let action = QuestionFocusingAction.cachedObjectWithID(Int(msr_object: object["history_id"])!)
action_ = action
action.date = NSDate(timeIntervalSince1970: (object["add_time"] as! NSNumber).doubleValue)
if let userInfo = object["user_info"] as? NSDictionary {
action.user = User.cachedObjectWithID(Int(msr_object: userInfo["uid"])!)
action.user!.name = (userInfo["user_name"] as! String)
action.user!.avatarURL = userInfo["avatar_file"] as? String
} else {
action.user = nil
}
let questionInfo = object["question_info"] as! NSDictionary
action.question = Question.cachedObjectWithID(Int(msr_object: questionInfo["question_id"])!)
action.question!.title = (questionInfo["question_content"] as! String)
break
case .QuestionPublishment:
let action = QuestionPublishmentAction.cachedObjectWithID(Int(msr_object: object["history_id"])!)
action_ = action
action.date = NSDate(timeIntervalSince1970: (object["add_time"] as! NSNumber).doubleValue)
if let userInfo = object["user_info"] as? NSDictionary {
action.user = User.cachedObjectWithID(Int(msr_object: userInfo["uid"])!)
action.user!.name = (userInfo["user_name"] as! String)
action.user!.avatarURL = userInfo["avatar_file"] as? String
} else {
action.user = nil
}
let questionInfo = object["question_info"] as! NSDictionary
action.question = Question.cachedObjectWithID(Int(msr_object: questionInfo["question_id"])!)
action.question!.title = (questionInfo["question_content"] as! String)
action.question!.user = action.user
break
case .ArticleAgreement:
let action = ArticleAgreementAction.cachedObjectWithID(Int(msr_object: object["history_id"])!)
action_ = action
action.date = NSDate(timeIntervalSince1970: (object["add_time"] as! NSNumber).doubleValue)
if let userInfo = object["user_info"] as? NSDictionary {
action.user = User.cachedObjectWithID(Int(msr_object: userInfo["uid"])!)
action.user!.name = (userInfo["user_name"] as! String)
action.user!.avatarURL = userInfo["avatar_file"] as? String
} else {
action.user = nil
}
let articleInfo = object["article_info"] as! NSDictionary
action.article = Article.cachedObjectWithID(Int(msr_object: articleInfo["id"])!)
action.article!.title = (articleInfo["title"] as! String)
break
case .Answer:
let action = AnswerAction.cachedObjectWithID(Int(msr_object: object["history_id"])!)
action_ = action
action.date = NSDate(timeIntervalSince1970: (object["add_time"] as! NSNumber).doubleValue)
if let userInfo = object["user_info"] as? NSDictionary {
action.user = User.cachedObjectWithID(Int(msr_object: userInfo["uid"])!)
action.user!.name = (userInfo["user_name"] as! String)
action.user!.avatarURL = userInfo["avatar_file"] as? String
} else {
action.user = nil
}
let answerInfo = object["answer_info"] as! NSDictionary
action.answer = Answer.cachedObjectWithID(Int(msr_object: answerInfo["answer_id"])!)
action.answer!.body = (answerInfo["answer_content"] as! String)
action.answer!.agreementCount = (answerInfo["agree_count"] as! NSNumber)
let questionInfo = object["question_info"] as! NSDictionary
action.answer!.question = Question.cachedObjectWithID(Int(msr_object: questionInfo["question_id"])!)
action.answer!.question!.title = (questionInfo["question_content"] as! String)
action.answer!.user = action.user
break
case .ArticlePublishment:
let action = ArticlePublishmentAction.cachedObjectWithID(Int(msr_object: object["history_id"])!)
action_ = action
action.date = NSDate(timeIntervalSince1970: (object["add_time"] as! NSNumber).doubleValue)
if let userInfo = object["user_info"] as? NSDictionary {
action.user = User.cachedObjectWithID(Int(msr_object: userInfo["uid"])!)
action.user!.name = (userInfo["user_name"] as! String)
action.user!.avatarURL = userInfo["avatar_file"] as? String
} else {
action.user = nil
}
let articleInfo = object["article_info"] as! NSDictionary
action.article = Article.cachedObjectWithID(Int(msr_object: articleInfo["id"])!)
action.article!.title = (articleInfo["title"] as! String)
action.article!.user = action.user
break
case .ArticleCommentary:
let action = ArticleCommentaryAction.cachedObjectWithID(Int(msr_object: object["history_id"]!)!)
action_ = action
action.date = NSDate(timeIntervalSince1970: (object["add_time"] as! NSNumber).doubleValue)
if let userInfo = object["user_info"] as? [String: AnyObject] {
action.user = User.cachedObjectWithID(Int(msr_object: userInfo["uid"])!)
action.user!.id = Int(msr_object: userInfo["uid"])!
action.user!.name = (userInfo["user_name"] as! String)
action.user!.avatarURL = userInfo["avatar_file"] as? String
} else {
action.user = nil
}
let commentInfo = object["comment_info"] as! [String: AnyObject]
action.comment = ArticleComment.cachedObjectWithID(Int(msr_object: commentInfo["id"]!)!)
action.comment!.body = commentInfo["message"] as? String
action.comment!.agreementCount = Int(msr_object: commentInfo["votes"]!)
if let atID = Int(msr_object: commentInfo["at_uid"]) {
if atID != 0 {
action.comment!.atUser = User.cachedObjectWithID(atID)
}
}
let articleInfo = object["article_info"] as! [String: AnyObject]
action.comment!.article = Article.cachedObjectWithID(Int(msr_object: articleInfo["id"])!)
action.comment!.article!.title = (articleInfo["title"] as! String)
action.comment!.article!.body = (articleInfo["message"] as! String)
break
}
actions.append(action_)
}
_ = try? DataManager.defaultManager.saveChanges()
success?(actions)
} else {
failure?(NSError(domain: NetworkManager.defaultManager!.website, code: NetworkManager.defaultManager!.internalErrorCode.integerValue, userInfo: nil)) // Needs specification
}
},
failure: failure)
}
override func didChangeValueForKey(key: String) {
super.didChangeValueForKey(key)
if isCurrentUser {
NSNotificationCenter.defaultCenter().postNotificationName(CurrentUserPropertyDidChangeNotificationName, object: nil, userInfo: [KeyUserInfoKey: key])
}
}
}
| gpl-2.0 | 6d8c1f8922ddcb101227bf426e7d9496 | 53.143959 | 210 | 0.517971 | 5.730377 | false | false | false | false |
phr85/Shopy | Shopy/SYShopTableViewController.swift | 1 | 5870 | //
// SYShopTableViewController.swift
// Shopy
//
// Created by Philippe H. Regenass on 31.03.17.
// Copyright © 2017 treeinspired GmbH. All rights reserved.
//
import UIKit
import CoreData
import DATAStack
import DATASource
import Sync
import SwiftyJSON
import EZLoadingActivity
import GMStepper
class SYShopTableViewController: UITableViewController {
// MARK: - Properties
let dataStack = (UIApplication.shared.delegate as! AppDelegate).dataStack
let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
// MARK: - Initialization
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
override func viewWillAppear(_ animated: Bool) {
self.reloadData()
}
// MARK: - Setup
private func setup() {
setupShopTableViewCell()
setupTableView()
setupImportData()
}
private func setupImportData() {
EZLoadingActivity.show(NSLocalizedString("Loading Products", comment: ""), disableUI: true)
let urlString = "https://api.treeinspired.com/shopy/index.json"
if let url = URL(string: urlString) {
if let data = try? Data(contentsOf: url, options: []) {
let appDelegate =
UIApplication.shared.delegate as! AppDelegate
let jsonRoot = JSON(data: data)
let json = try! JSONSerialization.jsonObject(with: jsonRoot.rawData(), options: [])
as! [[String: Any]]
Sync.changes(json, inEntityNamed: "SMProducts", dataStack: appDelegate.dataStack) { error in
if let errorDes = error?.localizedDescription {
print(errorDes)
}
}
}
}
EZLoadingActivity.hide()
}
private func setupShopTableViewCell() {
tableView.register(UINib(nibName: "SYShopTableViewCell", bundle: nil),
forCellReuseIdentifier: SYShopTableViewCell.reuseIdentifier)
}
private func setupTableView() {
self.tableView.dataSource = self.dataSource
}
// MARK: - Actions
@IBAction func addProductToBasket(sender: GMStepper) {
let stepperIndexPath = IndexPath.init(row: sender.tag, section: 0)
let item: SMProducts = self.dataSource.object(stepperIndexPath) as! SMProducts
self.dataStack.performInNewBackgroundContext { backgroundContext in
let request:NSFetchRequest<SMBasketArticle> = NSFetchRequest(entityName: "SMBasketArticle")
request.predicate = NSPredicate(format: "id ==[c] %@", item.id)
var resultItem = try! backgroundContext.fetch(request)
if resultItem.count > 0 {
if (sender.value == 0) {
backgroundContext.delete(resultItem[0])
} else {
resultItem[0].setValue(sender.value, forKey: "itemCount")
}
} else if(sender.value > 0) {
let entity = NSEntityDescription.entity(forEntityName: "SMBasketArticle", in: backgroundContext)!
let object = NSManagedObject(entity: entity, insertInto: backgroundContext)
object.setValue(item.title, forKey: "title")
object.setValue(item.price, forKey: "price")
object.setValue(sender.value, forKey: "itemCount")
object.setValue(item.unit, forKey: "unit")
object.setValue(item.id, forKey: "id")
}
try! backgroundContext.save()
DispatchQueue.main.async {
self.appDelegate.updateBasketBadge()
}
}
}
// MARK: - Helpers
private func reloadData() {
self.tableView.reloadData()
}
func stepperValueFromBasketItem(_ prodId: String) -> Double {
let request:NSFetchRequest<SMBasketArticle> = NSFetchRequest(entityName: "SMBasketArticle")
request.predicate = NSPredicate(format: "id ==[c] %@", prodId)
var resultItem = try! self.dataStack.viewContext.fetch(request)
if resultItem.count > 0 {
let item:SMBasketArticle = resultItem[0]
return Double(item.itemCount)
}
return 0
}
// MARK: - Table view data source / DATASource
lazy var dataSource: DATASource = {
let request: NSFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "SMProducts")
request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)]
let dataSource = DATASource(tableView: self.tableView, cellIdentifier: SYShopTableViewCell.reuseIdentifier,
fetchRequest: request, mainContext: self.dataStack.mainContext,
configuration: { cell, item, indexPath in
let shopCell: SYShopTableViewCell = cell as! SYShopTableViewCell
let productItem: SMProducts = item as! SMProducts
shopCell.stepperButton.tag = indexPath.row
shopCell.stepperButton.value = self.stepperValueFromBasketItem(productItem.id)
shopCell.productTitel?.text = productItem.title
shopCell.priceLabel?.text =
String(format: "USD %.2f per %@",
productItem.price,
productItem.unit!)
})
return dataSource
}()
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 68
}
}
| mit | eeae4804b2875b16e18f4ebb6d33631c | 38.389262 | 118 | 0.579997 | 5.404236 | false | false | false | false |
michalkonturek/MKUnits | Example/Tests/VolumeUnitTests.swift | 1 | 2459 | //
// VolumeUnitTests.swift
// MKUnits
//
// Copyright (c) 2016 Michal Konturek <[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 XCTest
import MKUnits
class VolumeUnitTests: XCTestCase {
func test_correctness() {
XCTAssertTrue(1.hectolitre() == 100.litre())
XCTAssertTrue(1.litre() == 10.decilitre())
XCTAssertTrue(1.decilitre() == 10.centilitre())
XCTAssertTrue(1.centilitre() == 10.millilitre())
XCTAssertTrue(1.millilitre() == 1000.microlitre())
XCTAssertTrue(1.microlitre() == 0.000001.litre())
}
func test_extension() {
self.assert(1.hectolitre(), expectedAmount: 1, expectedUnit: VolumeUnit.hectolitre)
self.assert(1.5.litre(), expectedAmount: 1.5, expectedUnit: VolumeUnit.litre)
self.assert(0.00001.decilitre(), expectedAmount: 0.00001, expectedUnit: VolumeUnit.decilitre)
self.assert(1.centilitre(), expectedAmount: 1, expectedUnit: VolumeUnit.centilitre)
self.assert(1.millilitre(), expectedAmount: 1, expectedUnit: VolumeUnit.millilitre)
self.assert(1.microlitre(), expectedAmount: 1, expectedUnit: VolumeUnit.microlitre)
}
func assert(_ item: Quantity, expectedAmount: NSNumber, expectedUnit: MKUnits.Unit) {
XCTAssertEqual(item.amount, expectedAmount)
XCTAssertEqual(item.unit, expectedUnit)
}
}
| mit | bcad87382ab2413bede7b9a180750eaa | 42.910714 | 101 | 0.710858 | 4.239655 | false | true | false | false |
AlicJ/CPUSimulator | CPUSimulator/RegisterBlockView.swift | 1 | 1657 | //
// RegisterBlockView.swift
// CPUSimulator
//
// Created by Eric Xiao on 2016-08-28.
// Copyright © 2016 4ZC3. All rights reserved.
//
import UIKit
class RegisterBlockView: UIView {
fileprivate let margin = Sizes.margin
fileprivate let regWidth = Sizes.register.width
fileprivate let regHeight = Sizes.register.height
internal var registers = [RegisterView]()
override init(frame: CGRect) {
super.init(frame: frame)
initRegisters()
self.backgroundColor = Sizes.debugColor
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initRegisters()
}
fileprivate func initRegisters() {
for i in 0..<9 {
let register = RegisterView(frame: Sizes.register.frame)
register.frame.origin.x += CGFloat(i % 3 * Int(regWidth + margin))
register.label = "Register " + String(i)
register.value = "0"
let row = floor(Double(i) / 3.0)
register.frame.origin.y += CGFloat(row * (regHeight + margin))
if i == 8 {
register.label = "Compare"
register.value = " "
}
registers += [register]
addSubview(register)
}
}
internal func setRegValue(regNum n: Int, regValue v: String){
registers[n].value = v
}
internal func getRegValue(regNum n: Int) -> String {
return registers[n].label
}
internal func getRegView(regNum n: Int) -> UIViewWrapper {
return registers[n]
}
}
| mit | 65bdf2ea281a6e1b426be0ec093ead61 | 25.285714 | 78 | 0.559783 | 4.32376 | false | false | false | false |
edekhayser/KBKit | KBKit/UITableView+RowConvenience.swift | 1 | 1085 | //
// UITableView+RowConvenience.swift
// KBKit
//
// Created by Evan Dekhayser on 12/27/15.
// Copyright © 2015 Evan Dekhayser. All rights reserved.
//
import UIKit
public extension UITableView{
public func indexPathForAbsoluteRow(absoluteRow: Int) -> NSIndexPath?{
var currentRow = 0
for section in 0..<numberOfSections{
for row in 0..<numberOfRowsInSection(section){
if currentRow == absoluteRow{
return NSIndexPath(forRow: row, inSection: section)
}
currentRow += 1
}
}
return nil
}
public func absoluteRowForIndexPath(indexPath: NSIndexPath) -> Int?{
guard indexPath.section < self.numberOfSections else { return nil }
var rowNumber = 0
for section in 0..<indexPath.section{
rowNumber += numberOfRowsInSection(section)
}
guard indexPath.row < numberOfRowsInSection(indexPath.section) else { return nil }
rowNumber += indexPath.row
return rowNumber
}
public func numberOfTotalRows() -> Int{
var total = 0
for section in 0..<numberOfSections{
total += numberOfRowsInSection(section)
}
return total
}
}
| mit | 3ee8016d924980f1b1ab258a8b37e415 | 23.088889 | 84 | 0.712177 | 3.871429 | false | false | false | false |
aojet/Aojet | Sources/Aojet/actors/ActorSupervisor.swift | 1 | 815 | //
// ActorSupervisor.swift
// Aojet
//
// Created by Qihe Bian on 6/6/16.
// Copyright © 2016 Qihe Bian. All rights reserved.
//
import Foundation
public protocol ActorSupervisor: Identifiable {
func onActorStopped(ref: ActorRef)
}
public final class AnyActorSupervisor: ActorSupervisor, IdentifierHashable {
private let _base: Any?
public let objectId: Identifier
private let _onActorStopped: (_ ref: ActorRef) -> ()
public init<T: ActorSupervisor>(_ base: T) {
_base = base
objectId = base.objectId
_onActorStopped = base.onActorStopped
}
public init(_ closure: @escaping (_ ref: ActorRef) -> ()) {
_base = nil
objectId = type(of: self).generateObjectId()
_onActorStopped = closure
}
public func onActorStopped(ref: ActorRef) {
_onActorStopped(ref)
}
}
| mit | 19853c7d25a8c7b8382deb6213303c54 | 22.257143 | 76 | 0.686732 | 3.803738 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | GoDToolOSX/View Controllers/GoDMessageViewController.swift | 1 | 5224 | //
// GoDMessageViewController.swift
// GoD Tool
//
// Created by The Steez on 14/04/2019.
//
import Cocoa
class GoDMessageViewController: GoDTableViewController {
@IBOutlet var filesPopup: GoDPopUpButton!
@IBOutlet var stringIDLabel: NSTextField!
@IBOutlet var stringIDField: NSTextField!
@IBOutlet var messageField: NSTextView!
@IBOutlet var saveButton: NSButton!
@IBOutlet var messageScrollView: NSScrollView!
var singleTable: XGStringTable?
var stringIDs = [Int]()
var currentString: XGString?
var currentTable : XGStringTable? {
didSet {
setUpForFile()
}
}
init(singleTable: XGStringTable) {
self.singleTable = singleTable
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func viewDidLoad() {
super.viewDidLoad()
if let table = singleTable {
self.filesPopup.setTitles(values: [table.file.fileName])
self.filesPopup.isEnabled = false
currentTable = table
} else {
loadAllStrings(refresh: true)
let tables = allStringTables.sorted { $0.file.fileName.simplified < $1.file.fileName.simplified }
self.filesPopup.setTitles(values: ["-"] + tables.map {
$0.file.folder.name + "/" + $0.file.fileName
})
}
self.hideInterface()
}
func hideInterface() {
stringIDField.isEnabled = false
messageField.isEditable = false
saveButton.isEnabled = false
}
func showInterface() {
stringIDField.isEnabled = true
messageField.isEditable = true
stringIDField.isEditable = game != .PBR
saveButton.isEnabled = true
}
func setUpForFile() {
currentString = nil
stringIDs = currentTable?.stringIDs ?? []
stringIDField.stringValue = ""
messageField.string = ""
hideInterface()
table.reloadData()
table.scrollToTop()
}
@IBAction func setFile(_ sender: GoDPopUpButton) {
guard sender.indexOfSelectedItem > 0 else {
currentTable = nil
return
}
currentTable = allStringTables.sorted { $0.file.fileName.simplified < $1.file.fileName.simplified }[sender.indexOfSelectedItem - 1]
}
@IBAction func save(_ sender: Any) {
guard let table = currentTable else {
GoDAlertViewController.displayAlert(title: "Error", text: "No File selected")
return
}
var sid: Int?
if game == .PBR {
sid = currentString?.id
} else {
sid = stringIDField.stringValue.integerValue
}
if let stringID = sid {
let message = messageField.string == "" ? "-" : messageField.string
let string = XGString(string: message, file: table.file, sid: stringID)
let operation = table.containsStringWithId(stringID) ? "replacing" : "adding"
let success = table.addString(string, increaseSize: XGSettings.current.increaseFileSizes, save: true)
let successMessage = success ? "Completed" : "Failed"
let successTitle = success ? "Success" : "Failure"
GoDAlertViewController.displayAlert(title: successTitle, text: "\(successMessage) \(operation) id: \(stringID) message: \(message) to \(table.file.path)")
self.table.reloadData()
} else {
GoDAlertViewController.displayAlert(title: "Error", text: "Please enter a valid string ID")
}
}
override func numberOfRows(in tableView: NSTableView) -> Int {
return stringIDs.count
}
override func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
return 50
}
override func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell = (tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "cell"), owner: self) ?? GoDTableCellView(title: "", colour: GoDDesign.colourBlack(), fontSize: 12, width: widthForTable())) as! GoDTableCellView
guard let currentTable = currentTable else {
return cell
}
let id = stringIDs[row]
let string = currentTable.stringSafelyWithID(id)
cell.setTitle(string.id.hexString() + ": " + string.unformattedString)
cell.titleField.maximumNumberOfLines = 3
cell.addBorder(colour: GoDDesign.colourBlack(), width: 1)
if self.table.selectedRow == row {
cell.setBackgroundColour(GoDDesign.colourLightBlue())
} else {
cell.setBackgroundColour(GoDDesign.colourWhite())
}
return cell
}
override func tableView(_ tableView: GoDTableView, didSelectRow row: Int) {
super.tableView(tableView, didSelectRow: row)
if row >= 0 {
guard let table = currentTable else {
return
}
let id = stringIDs[row]
let string = table.stringSafelyWithID(id)
currentString = string
stringIDField.stringValue = string.id.hexString()
messageField.string = string.string
showInterface()
}
}
override func searchBarBehaviourForTableView(_ tableView: GoDTableView) -> GoDSearchBarBehaviour {
.onEndEditing
}
override func tableView(_ tableView: GoDTableView, didSearchForText text: String) {
defer {
tableView.reloadData()
}
guard !text.isEmpty else {
stringIDs = currentTable?.stringIDs ?? []
return
}
stringIDs = currentTable?.allStrings().filter({ (s) -> Bool in
s.string.simplified.contains(text.simplified)
|| (text.integerValue != nil && text.integerValue == s.id)
|| ((text.integerValue ?? -1) == s.id)
}).map({ (s) -> Int in
s.id
}) ?? []
}
}
| gpl-2.0 | 531a74d03982a29e6604e8aca0c69f34 | 25.927835 | 234 | 0.705207 | 3.72345 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | Revolution Tool CL/objects/PBRConstant.swift | 1 | 3298 | //
// XDSConstant.swift
// Revolution Tool CL
//
// Created by The Steez on 26/12/2018.
//
import Foundation
enum XDSConstantTypes {
// same as classes in script class info
case void
case integer
case float
case string
case vector
case array
case codePointer
case unknown(Int)
var string : String {
get {
switch self {
case .void : return "Void"
case .integer : return "Int"
case .float : return "Float"
case .string : return "String"
case .vector : return "Vector"
case .array : return "Array"
case .codePointer : return "Pointer"
case .unknown(let val) : return "Class\(val)"
}
}
}
var index : Int {
switch self {
case .void : return 0
case .integer : return 1
case .float : return 2
case .string : return 3
case .vector : return 4
case .array : return 7
case .codePointer : return 8
case .unknown(let val) : return val
}
}
static func typeWithIndex(_ id: Int) -> XDSConstantTypes {
switch id {
case 0 : return .void
case 1 : return .integer
case 2 : return .float
case 3 : return .string
case 4 : return .vector
case 7 : return .array
case 8 : return .codePointer
default : return .unknown(id)
}
}
static func typeWithName(_ name: String) -> XDSConstantTypes? {
// not sure of actual number of types but should be fewer than 100
for i in 0 ..< 100 {
let type = XDSConstantTypes.typeWithIndex(i)
if type.string == name {
return type
}
}
return nil
}
}
class XDSConstant: NSObject {
var type: XDSConstantTypes = .void
var value: UInt32 = 0
override var description: String {
return self.rawValueString
}
var asFloat: Float {
return value.hexToSignedFloat()
}
var asInt: Int {
return value.int32
}
var rawValueString: String {
switch self.type {
case .float:
var text = String(format: "%.4f", self.asFloat)
if !text.contains(".") {
text += ".0"
}
while text.last == "0" {
text.removeLast()
}
if text.last == "." {
text += "0"
}
return text
case .string:
return "String(\(self.asInt))"
case .vector:
return "vector_" + String(format: "%02d", self.asInt)
case .integer:
return self.asInt >= 0x200 ? self.asInt.hexString() : "\(self.asInt)"
case .void:
return "Null"
case .array:
return "array_" + String(format: "%02d", self.asInt)
case .codePointer:
return XDSExpr.locationIndex(self.asInt).text[0]
case .unknown(let i):
return XGScriptClass.classes(i).name + "(\(self.asInt))"
}
}
init(type: Int, rawValue: UInt32) {
super.init()
self.type = XDSConstantTypes.typeWithIndex(type)
self.value = rawValue
}
convenience init(type: XDSConstantTypes, rawValue: Int) {
self.init(type: type.index, rawValue: rawValue.unsigned)
}
class var null: XDSConstant {
return XDSConstant(type: 0, rawValue: 0)
}
class func integer(_ val: Int) -> XDSConstant {
return XDSConstant(type: XDSConstantTypes.integer.index, rawValue: val.unsigned)
}
class func integer(_ val: UInt32) -> XDSConstant {
return XDSConstant(type: XDSConstantTypes.integer.index, rawValue: val)
}
class func float(_ val: Float) -> XDSConstant {
return XDSConstant(type: XDSConstantTypes.float.index, rawValue: val.floatToHex())
}
}
| gpl-2.0 | f702ee1160e8f4c8c12bbc1860b3d865 | 20.697368 | 84 | 0.649788 | 3.134981 | false | false | false | false |
bshyong/tasty-board | Keyboard/KeyboardConnector.swift | 1 | 7919 | //
// KeyboardConnector.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/19/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
protocol Connectable {
func attachmentPoints(direction: Direction) -> (CGPoint, CGPoint)
func attachmentDirection() -> Direction?
func attach(direction: Direction?) // call with nil to detach
}
// TODO: Xcode crashes -- as of 2014-10-9, still crashes if implemented
// <ConnectableView: UIView where ConnectableView: Connectable>
class KeyboardConnector: KeyboardKeyBackground {
var start: UIView
var end: UIView
var startDir: Direction
var endDir: Direction
var startConnectable: Connectable
var endConnectable: Connectable
var convertedStartPoints: (CGPoint, CGPoint)!
var convertedEndPoints: (CGPoint, CGPoint)!
var offset: CGPoint
// TODO: until bug is fixed, make sure start/end and startConnectable/endConnectable are the same object
init(blur: Bool, cornerRadius: CGFloat, underOffset: CGFloat, start s: UIView, end e: UIView, startConnectable sC: Connectable, endConnectable eC: Connectable, startDirection: Direction, endDirection: Direction) {
start = s
end = e
startDir = startDirection
endDir = endDirection
startConnectable = sC
endConnectable = eC
offset = CGPointZero
super.init(blur: blur, cornerRadius: cornerRadius, underOffset: underOffset)
}
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
self.setNeedsLayout()
}
override func layoutSubviews() {
self.resizeFrame()
super.layoutSubviews()
}
func generateConvertedPoints() {
if let superview = self.superview {
let startPoints = self.startConnectable.attachmentPoints(self.startDir)
let endPoints = self.endConnectable.attachmentPoints(self.endDir)
self.convertedStartPoints = (
superview.convertPoint(startPoints.0, fromView: self.start),
superview.convertPoint(startPoints.1, fromView: self.start))
self.convertedEndPoints = (
superview.convertPoint(endPoints.0, fromView: self.end),
superview.convertPoint(endPoints.1, fromView: self.end))
}
}
func resizeFrame() {
generateConvertedPoints()
let buffer: CGFloat = 32
self.offset = CGPointMake(buffer/2, buffer/2)
let minX = min(convertedStartPoints.0.x, convertedStartPoints.1.x, convertedEndPoints.0.x, convertedEndPoints.1.x)
let minY = min(convertedStartPoints.0.y, convertedStartPoints.1.y, convertedEndPoints.0.y, convertedEndPoints.1.y)
let maxX = max(convertedStartPoints.0.x, convertedStartPoints.1.x, convertedEndPoints.0.x, convertedEndPoints.1.x)
let maxY = max(convertedStartPoints.0.y, convertedStartPoints.1.y, convertedEndPoints.0.y, convertedEndPoints.1.y)
let width = maxX - minX
let height = maxY - minY
self.frame = CGRectMake(minX - buffer/2, minY - buffer/2, width + buffer, height + buffer)
}
override func generatePointsForDrawing(bounds: CGRect) {
//////////////////
// prepare data //
//////////////////
let startPoints = self.startConnectable.attachmentPoints(self.startDir)
let endPoints = self.endConnectable.attachmentPoints(self.endDir)
var myConvertedStartPoints = (
self.convertPoint(startPoints.0, fromView: self.start),
self.convertPoint(startPoints.1, fromView: self.start))
let myConvertedEndPoints = (
self.convertPoint(endPoints.0, fromView: self.end),
self.convertPoint(endPoints.1, fromView: self.end))
if self.startDir == self.endDir {
let tempPoint = myConvertedStartPoints.0
myConvertedStartPoints.0 = myConvertedStartPoints.1
myConvertedStartPoints.1 = tempPoint
}
var path = CGPathCreateMutable();
CGPathMoveToPoint(path, nil, myConvertedStartPoints.0.x, myConvertedStartPoints.0.y)
CGPathAddLineToPoint(path, nil, myConvertedEndPoints.1.x, myConvertedEndPoints.1.y)
CGPathAddLineToPoint(path, nil, myConvertedEndPoints.0.x, myConvertedEndPoints.0.y)
CGPathAddLineToPoint(path, nil, myConvertedStartPoints.1.x, myConvertedStartPoints.1.y)
CGPathCloseSubpath(path)
// for now, assuming axis-aligned attachment points
let isVertical = (self.startDir == Direction.Up || self.startDir == Direction.Down) && (self.endDir == Direction.Up || self.endDir == Direction.Down)
var midpoint: CGFloat
if isVertical {
midpoint = myConvertedStartPoints.0.y + (myConvertedEndPoints.1.y - myConvertedStartPoints.0.y) / 2
}
else {
midpoint = myConvertedStartPoints.0.x + (myConvertedEndPoints.1.x - myConvertedStartPoints.0.x) / 2
}
var bezierPath = UIBezierPath()
var currentEdgePath = UIBezierPath()
var edgePaths = [UIBezierPath]()
bezierPath.moveToPoint(myConvertedStartPoints.0)
bezierPath.addCurveToPoint(
myConvertedEndPoints.1,
controlPoint1: (isVertical ?
CGPointMake(myConvertedStartPoints.0.x, midpoint) :
CGPointMake(midpoint, myConvertedStartPoints.0.y)),
controlPoint2: (isVertical ?
CGPointMake(myConvertedEndPoints.1.x, midpoint) :
CGPointMake(midpoint, myConvertedEndPoints.1.y)))
currentEdgePath = UIBezierPath()
currentEdgePath.moveToPoint(myConvertedStartPoints.0)
currentEdgePath.addCurveToPoint(
myConvertedEndPoints.1,
controlPoint1: (isVertical ?
CGPointMake(myConvertedStartPoints.0.x, midpoint) :
CGPointMake(midpoint, myConvertedStartPoints.0.y)),
controlPoint2: (isVertical ?
CGPointMake(myConvertedEndPoints.1.x, midpoint) :
CGPointMake(midpoint, myConvertedEndPoints.1.y)))
currentEdgePath.applyTransform(CGAffineTransformMakeTranslation(0, -self.underOffset))
edgePaths.append(currentEdgePath)
bezierPath.addLineToPoint(myConvertedEndPoints.0)
bezierPath.addCurveToPoint(
myConvertedStartPoints.1,
controlPoint1: (isVertical ?
CGPointMake(myConvertedEndPoints.0.x, midpoint) :
CGPointMake(midpoint, myConvertedEndPoints.0.y)),
controlPoint2: (isVertical ?
CGPointMake(myConvertedStartPoints.1.x, midpoint) :
CGPointMake(midpoint, myConvertedStartPoints.1.y)))
bezierPath.addLineToPoint(myConvertedStartPoints.0)
currentEdgePath = UIBezierPath()
currentEdgePath.moveToPoint(myConvertedEndPoints.0)
currentEdgePath.addCurveToPoint(
myConvertedStartPoints.1,
controlPoint1: (isVertical ?
CGPointMake(myConvertedEndPoints.0.x, midpoint) :
CGPointMake(midpoint, myConvertedEndPoints.0.y)),
controlPoint2: (isVertical ?
CGPointMake(myConvertedStartPoints.1.x, midpoint) :
CGPointMake(midpoint, myConvertedStartPoints.1.y)))
currentEdgePath.applyTransform(CGAffineTransformMakeTranslation(0, -self.underOffset))
edgePaths.append(currentEdgePath)
bezierPath.addLineToPoint(myConvertedStartPoints.0)
bezierPath.closePath()
bezierPath.applyTransform(CGAffineTransformMakeTranslation(0, -self.underOffset))
self.fillPath = bezierPath
self.edgePaths = edgePaths
}
}
| bsd-3-clause | 500ebe0fd2e09c7a0ca5d038b6200780 | 39.819588 | 217 | 0.661068 | 5.244371 | false | false | false | false |
soppysonny/wikipedia-ios | Carthage/Checkouts/PromiseKit/Tests/CorePromise/bridging.test.swift | 3 | 2939 | import Foundation
import PromiseKit
import XCTest
class BridgingTestCase_Swift: XCTestCase {
func testCanBridgeAnyObject() {
let sentinel = NSURLRequest()
let p = Promise(sentinel)
let ap = AnyPromise(bound: p)
XCTAssertEqual(ap.valueForKey("value") as? NSURLRequest, sentinel)
}
func testCanBridgeOptional() {
let sentinel = Optional.Some(NSURLRequest())
let p = Promise(sentinel)
let ap = AnyPromise(bound: p)
XCTAssertEqual(ap.valueForKey("value") as? NSURLRequest, sentinel!)
}
func testCanBridgeSwiftArray() {
let sentinel = [NSString(),NSString(),NSString()]
let p = Promise(sentinel)
let ap = AnyPromise(bound: p)
XCTAssertEqual(ap.valueForKey("value") as! [NSString], sentinel)
}
func testCanBridgeSwiftDictionary() {
let sentinel = [NSString():NSString()]
let p = Promise(sentinel)
let ap = AnyPromise(bound: p)
XCTAssertEqual(ap.valueForKey("value") as! [NSString:NSString], sentinel)
}
func testCanBridgeInt() {
let sentinel = 3
let p = Promise(sentinel)
let ap = AnyPromise(bound: p)
XCTAssertEqual(ap.valueForKey("value") as? Int, sentinel)
}
func testCanBridgeString() {
let sentinel = "a" as NSString
let p = Promise(sentinel)
let ap = AnyPromise(bound: p)
XCTAssertEqual(ap.valueForKey("value") as? NSString, sentinel)
}
func testCanChainOffAnyPromiseReturn() {
let ex = expectationWithDescription("")
firstly {
Promise(1)
}.then { _ -> AnyPromise in
return PromiseBridgeHelper().valueForKey("bridge2") as! AnyPromise
}.then { value -> Void in
XCTAssertEqual(123, value as? Int)
ex.fulfill()
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func testCanThenOffAnyPromise() {
let ex = expectationWithDescription("")
let ap = PMKDummyAnyPromise_YES() as! AnyPromise
ap.then { obj -> Void in
if let value = obj as? NSNumber {
XCTAssertEqual(value, NSNumber(bool: true))
ex.fulfill()
}
}
waitForExpectationsWithTimeout(1, handler: nil)
}
func testCanThenOffManifoldAnyPromise() {
let ex = expectationWithDescription("")
let ap = PMKDummyAnyPromise_Manifold() as! AnyPromise
ap.then { obj -> Void in
if let value = obj as? NSNumber {
XCTAssertEqual(value, NSNumber(bool: true))
ex.fulfill()
}
}
waitForExpectationsWithTimeout(1, handler: nil)
}
}
// for bridging.test.m
@objc(PMKPromiseBridgeHelper) class PromiseBridgeHelper: NSObject {
@objc func bridge1() -> AnyPromise {
let p = after(0.01)
return AnyPromise(bound: p)
}
}
| mit | 4c4187f4adfdb269c84298c29fc4e142 | 27.259615 | 81 | 0.601565 | 4.747981 | false | true | false | false |
bvankuik/Spinner | Spinner/VIStatusBaseView.swift | 1 | 3280 | //
// VIBaseView.swift
// Spinner
//
// Created by Bart van Kuik on 29/05/2017.
// Copyright © 2017 DutchVirtual. All rights reserved.
//
enum VIStatusBaseViewState {
case disappeared
case disappearing
case appearing
case appeared
}
public class VIStatusBaseView: UIView {
internal var state: VIStatusBaseViewState = .disappeared
internal var disappearTask: DispatchWorkItem?
internal let animationDuration = 0.33
private let visibleDuration = 2.5
// MARK: - Public functions
public static func showBaseView(baseView: VIStatusBaseView, in containingView: UIView) {
baseView.centerView(in: containingView)
switch baseView.state {
case .disappeared:
baseView.appear()
case .disappearing:
baseView.layer.removeAllAnimations()
baseView.disappearTask?.cancel()
baseView.alpha = 1.0
baseView.scheduleDisappear()
case .appearing:
baseView.layer.removeAllAnimations()
baseView.scheduleDisappear()
case .appeared:
baseView.scheduleDisappear()
}
}
// MARK: - Internal functions
internal func centerView(in containingView: UIView) {
if containingView != self.superview {
self.removeFromSuperview()
containingView.addSubview(self)
let constraints = [
self.centerXAnchor.constraint(equalTo: containingView.centerXAnchor),
self.centerYAnchor.constraint(equalTo: containingView.centerYAnchor),
self.widthAnchor.constraint(lessThanOrEqualTo: containingView.widthAnchor, multiplier: 1.0, constant: -10)
]
containingView.addConstraints(constraints)
}
containingView.bringSubviewToFront(self)
}
internal func appear() {
self.state = .appearing
UIView.animate(withDuration: self.animationDuration, animations: {
self.alpha = 1.0
}) { (finished) in
self.alpha = 1.0
if finished {
self.state = .appeared
self.scheduleDisappear()
}
}
}
internal func scheduleDisappear() {
self.disappearTask?.cancel()
self.disappearTask = DispatchWorkItem {
self.disappear()
}
if let task = self.disappearTask {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + self.visibleDuration, execute: task)
}
}
internal func disappear() {
self.state = .disappearing
UIView.animate(withDuration: self.animationDuration, animations: {
self.alpha = 0.0
}, completion: { (finished) in
if finished {
self.alpha = 0.0
self.state = .disappeared
self.removeFromSuperview()
}
})
}
// MARK: - Life cycle
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.gray
self.translatesAutoresizingMaskIntoConstraints = false
self.alpha = 0.0
self.layer.cornerRadius = 5.0
}
required public init?(coder aDecoder: NSCoder) {
fatalError("Unsupported")
}
}
| mit | 10ab96e7c61b05fe1678014843471f37 | 27.763158 | 122 | 0.608112 | 5.115445 | false | false | false | false |
cactis/SwiftEasyKit | Source/Extensions/UIButtonClosureAdditions.swift | 1 | 1111 | //
// UIButtonClosureAdditions.swift
import UIKit
import ObjectiveC
class ClosureWrapper: NSObject { //, NSCopying {
var closure: (() -> Void)?
convenience init(closure: (() -> Void)?) {
self.init()
self.closure = closure
}
func copyWithZone(zone: NSZone) -> AnyObject {
let wrapper: ClosureWrapper = ClosureWrapper()
wrapper.closure = closure
return wrapper
}
}
extension UIButton {
private struct AssociatedKeys {
static var SNGLSActionHandlerTapKey = "sngls_ActionHandlerTapKey"
}
func handleControlEvent(event: UIControlEvents, handler:(() -> Void)?) {
let aBlockClassWrapper = ClosureWrapper(closure: handler)
objc_setAssociatedObject(self, &AssociatedKeys.SNGLSActionHandlerTapKey, aBlockClassWrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC);
self.addTarget(self, action: #selector(UIButton.callActionBlock(_:)), for: event)
}
@objc func callActionBlock(_ sender: AnyObject) {
let actionBlockAnyObject = objc_getAssociatedObject(self, &AssociatedKeys.SNGLSActionHandlerTapKey) as? ClosureWrapper
actionBlockAnyObject?.closure?()
}
}
| mit | b39a518c165f15586100bd2f73a5e623 | 29.861111 | 154 | 0.749775 | 4.40873 | false | false | false | false |
cactis/SwiftEasyKit | Source/Classes/AppMappable.swift | 1 | 1592 | //
// AppMappable.swift
// SwiftEasyKit
//
// Created by ctslin on 04/01/2018.
//
import ObjectMapper
open class AppMappable: Mappable {
public var id: Int?
public var createdAt: Date?
public var updatedAt: Date?
public var state: String?
// public var status: String?
public var token: String?
public var alert: String?
public var priButton: String?
public var subButton: String?
public var nextEvent: String?
public var css: String?
public var expired: Bool?
static var TIMEFORMAT = K.Api.timeFormat
open func mapping(map: Map) {
id <- map["id"]
state <- map["state"]
// state <- map["state"]
// status <- map["status"]
token <- map["token"]
createdAt <- (map["created_at"], DateTransform(timeFormat: AppMappable.TIMEFORMAT))
updatedAt <- (map["updated_at"], DateTransform(timeFormat: AppMappable.TIMEFORMAT))
alert <- map["alert"]
priButton <- map["pri_button"]
subButton <- map["sub_button"]
nextEvent <- map["next_event"]
css <- map["css"]
expired <- map["expired"]
}
required public init?(map: Map) {}
}
class DateTransform: TransformType {
public typealias Object = Date
public typealias JSON = String
public var timeFormat: String?
public init(timeFormat: String? = AppMappable.TIMEFORMAT) {
self.timeFormat = timeFormat
}
public func transformFromJSON(_ value: Any?) -> Date? {
if value == nil { return nil }
return (value as? String)!.toDate(timeFormat!)
}
public func transformToJSON(_ value: Date?) -> String? {
return value?.toString()
}
}
| mit | 83e934af5c1b03cdc151e1f0192b83a9 | 23.121212 | 88 | 0.658291 | 3.940594 | false | false | false | false |
freshOS/Komponents | Source/UIKitRenderer.swift | 1 | 2775 | //
// UIKitRenderer.swift
// Komponents
//
// Created by Sacha Durand Saint Omer on 30/03/2017.
// Copyright © 2017 freshOS. All rights reserved.
//
import UIKit
import MapKit
class UIKitRenderer {
weak var engine: KomponentsEngine!
var nodeIdViewMap = [Int: UIView]()
var componentIdNodeIdViewMap = [String: Int]()
var storedSubComponents: [IsComponent] = [IsComponent]()
func render(tree: Tree, in view: UIView) {
storedSubComponents = [IsComponent]()
privateRender(tree: tree, in: view)
for sc in storedSubComponents {
sc.didRender()
}
}
func privateRender(tree: Tree, in view: UIView) {
var tree = tree
if let subComponenet = tree as? IsStatefulComponent {
let cId = subComponenet.uniqueComponentIdentifier
componentIdNodeIdViewMap[cId] = tree.uniqueIdentifier
// Create new engine for subcompoenent
subComponenet.reactEngine = KomponentsEngine() // link new engine
} else if let subComponenet = tree as? Renderable {
tree = subComponenet.render()
}
// Create a UIKIt view form a node
let newView = (tree as? UIKitRenderable)?.uiKitView() ?? UIView()
// Link references
linkReference(of: tree, to: newView)
nodeIdViewMap[tree.uniqueIdentifier] = newView
for c in tree.children {
if let subComponenet = c as? IsStatefulComponent {
subComponenet.reactEngine = KomponentsEngine()
subComponenet.reactEngine?.rootView = newView
subComponenet.reactEngine?.render(component: subComponenet, in: newView)
storedSubComponents.append(subComponenet)
} else if let subComponenet = c as? IsComponent {
storedSubComponents.append(subComponenet)
privateRender(tree: c, in: newView)
} else {
privateRender(tree: c, in: newView)
}
}
// View Hierarchy (Use autolayout)
add(newView, asSubviewOf: view)
// Layout
layout(newView, withLayout: tree.layout, inView: view)
// Plug events
plugEvents(from: tree, to: newView)
}
func add(_ newView: UIView, asSubviewOf view: UIView) {
newView.translatesAutoresizingMaskIntoConstraints = false
if let stackView = view as? UIStackView {
stackView.addArrangedSubview(newView)
} else if let cell = view as? UITableViewCell {
cell.contentView.addSubview(newView)
} else {
view.addSubview(newView)
}
}
}
| mit | f41a43bbe0d5393194b55d1f9d5bcc60 | 31.255814 | 88 | 0.590483 | 5.025362 | false | false | false | false |
AndreyAntipov/yota-modem-menubar-battery | Yota Many Dashboard/DataProvider.swift | 2 | 3345 | //
// DataProvider.swift
// Yota Many Dashboard
//
// Created by Andrey Antipov on 28/08/14.
// Copyright (c) 2014 Andrey Antipov. All rights reserved.
//
import Cocoa
// crop string between range
extension String
{
subscript (r: Range<Int>) -> String
{
get
{
let startIndex = advance(self.startIndex, r.startIndex)
let endIndex = advance(startIndex, countElements(self) - r.startIndex - r.endIndex)
return self[Range(start: startIndex, end: endIndex)]
}
}
}
class DataProvider: NSObject {
class var sharedInstance:DataProvider
{
struct Singleton { static let instance = DataProvider() }
return Singleton.instance
}
func headers(request: NSMutableURLRequest) -> NSMutableURLRequest
{
request.HTTPMethod = "GET"
request.addValue("gzip", forHTTPHeaderField: "Accept-Encoding")
request.addValue("*/*", forHTTPHeaderField: "Accept")
request.addValue("http://10.0.0.1", forHTTPHeaderField: "Referer")
request.addValue("Connection", forHTTPHeaderField: "Keep-alive")
return request
}
func HTTPsendRequest(request: NSMutableURLRequest, callback: (String, String?) -> Void)
{
let customHeaders = headers(request)
let task = NSURLSession.sharedSession().dataTaskWithRequest(customHeaders)
{
(data, response, error) -> Void in
if (error != nil)
{
callback("", error.localizedDescription)
}
else
{
callback(NSString(data: data,
encoding: NSUTF8StringEncoding), nil)
}
}
task.resume()
}
func HTTPGet(url: String, callback: (String, String?) -> Void)
{
let request = NSMutableURLRequest(URL: NSURL(string: url))
HTTPsendRequest(request, callback)
}
func get(section : NSString, callback: (Dictionary<String, AnyObject>, String?) -> Void)
{
HTTPGet("http://10.0.0.1/devcontrol?callback=?&command=\(section)")
{
(raw: String, error: String?) -> Void in
if (error != nil) {
let err : [String: String] = ["result" : "error"]
callback(err, error)
}
else
{
// remove unnecessary symbols which are impede to convert data to json
let data = raw[3...3]
let not_authorized = "null, \"not authorized"
if (data == not_authorized)
{
let err : [String: String] = ["result" : "not_authorized"]
callback(err, nil)
}
else
{
let jsonData = data.dataUsingEncoding(NSUTF8StringEncoding)
var error: NSError?
let dictionary = NSJSONSerialization.JSONObjectWithData(jsonData! , options: nil, error: &error) as Dictionary<String, AnyObject>
callback(dictionary, nil)
}
}
}
}
} | mit | b1207af54b80292eb60dbb8f2597fc58 | 29.418182 | 150 | 0.515695 | 5.114679 | false | false | false | false |
ming1016/smck | smck/Lib/RxSwift/Debounce.swift | 47 | 2771 | //
// Debounce.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/11/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
final class DebounceSink<O: ObserverType>
: Sink<O>
, ObserverType
, LockOwnerType
, SynchronizedOnType {
typealias Element = O.E
typealias ParentType = Debounce<Element>
private let _parent: ParentType
let _lock = RecursiveLock()
// state
private var _id = 0 as UInt64
private var _value: Element? = nil
let cancellable = SerialDisposable()
init(parent: ParentType, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let subscription = _parent._source.subscribe(self)
return Disposables.create(subscription, cancellable)
}
func on(_ event: Event<Element>) {
synchronizedOn(event)
}
func _synchronized_on(_ event: Event<Element>) {
switch event {
case .next(let element):
_id = _id &+ 1
let currentId = _id
_value = element
let scheduler = _parent._scheduler
let dueTime = _parent._dueTime
let d = SingleAssignmentDisposable()
self.cancellable.disposable = d
d.setDisposable(scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate))
case .error:
_value = nil
forwardOn(event)
dispose()
case .completed:
if let value = _value {
_value = nil
forwardOn(.next(value))
}
forwardOn(.completed)
dispose()
}
}
func propagate(_ currentId: UInt64) -> Disposable {
_lock.lock(); defer { _lock.unlock() } // {
let originalValue = _value
if let value = originalValue, _id == currentId {
_value = nil
forwardOn(.next(value))
}
// }
return Disposables.create()
}
}
final class Debounce<Element> : Producer<Element> {
fileprivate let _source: Observable<Element>
fileprivate let _dueTime: RxTimeInterval
fileprivate let _scheduler: SchedulerType
init(source: Observable<Element>, dueTime: RxTimeInterval, scheduler: SchedulerType) {
_source = source
_dueTime = dueTime
_scheduler = scheduler
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = DebounceSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| apache-2.0 | 0fba0bd3ade2f7d54e6ba0417b9c6d52 | 26.156863 | 144 | 0.592419 | 4.710884 | false | false | false | false |
yoichitgy/Swinject | Sources/Container.swift | 1 | 13516 | //
// Copyright © 2019 Swinject Contributors. All rights reserved.
//
import Foundation
/// The ``Container`` class represents a dependency injection container, which stores registrations of services
/// and retrieves registered services with dependencies injected.
///
/// **Example to register:**
///
/// let container = Container()
/// container.register(A.self) { _ in B() }
/// container.register(X.self) { r in Y(a: r.resolve(A.self)!) }
///
/// **Example to retrieve:**
///
/// let x = container.resolve(X.self)!
///
/// where `A` and `X` are protocols, `B` is a type conforming `A`, and `Y` is a type conforming `X`
/// and depending on `A`.
public final class Container {
internal var services = [ServiceKey: ServiceEntryProtocol]()
private let parent: Container? // Used by HierarchyObjectScope
private var resolutionDepth = 0
private let debugHelper: DebugHelper
private let defaultObjectScope: ObjectScope
internal var currentObjectGraph: GraphIdentifier?
internal let lock: RecursiveLock // Used by SynchronizedResolver.
internal var behaviors = [Behavior]()
internal init(
parent: Container? = nil,
debugHelper: DebugHelper,
defaultObjectScope: ObjectScope = .graph
) {
self.parent = parent
self.debugHelper = debugHelper
lock = parent.map { $0.lock } ?? RecursiveLock()
self.defaultObjectScope = defaultObjectScope
}
/// Instantiates a ``Container``
///
/// - Parameters
/// - parent: The optional parent ``Container``.
/// - defaultObjectScope: Default object scope (graph if no scope is injected)
/// - behaviors: List of behaviors to be added to the container
/// - registeringClosure: The closure registering services to the new container instance.
///
/// - Remark: Compile time may be long if you pass a long closure to this initializer.
/// Use `init()` or `init(parent:)` instead.
public convenience init(
parent: Container? = nil,
defaultObjectScope: ObjectScope = .graph,
behaviors: [Behavior] = [],
registeringClosure: (Container) -> Void = { _ in }
) {
self.init(parent: parent, debugHelper: LoggingDebugHelper(), defaultObjectScope: defaultObjectScope)
behaviors.forEach(addBehavior)
registeringClosure(self)
}
/// Removes all registrations in the container.
public func removeAll() {
services.removeAll()
}
/// Discards instances for services registered in the given `ObjectsScopeProtocol`.
///
/// **Example usage:**
/// container.resetObjectScope(ObjectScope.container)
///
/// - Parameters:
/// - objectScope: All instances registered in given `ObjectsScopeProtocol` will be discarded.
public func resetObjectScope(_ objectScope: ObjectScopeProtocol) {
services.values
.filter { $0.objectScope === objectScope }
.forEach { $0.storage.instance = nil }
parent?.resetObjectScope(objectScope)
}
/// Discards instances for services registered in the given `ObjectsScope`. It performs the same operation
/// as `resetObjectScope(_:ObjectScopeProtocol)`, but provides more convenient usage syntax.
///
/// **Example usage:**
/// container.resetObjectScope(.container)
///
/// - Parameters:
/// - objectScope: All instances registered in given `ObjectsScope` will be discarded.
public func resetObjectScope(_ objectScope: ObjectScope) {
resetObjectScope(objectScope as ObjectScopeProtocol)
}
/// Adds a registration for the specified service with the factory closure to specify how the service is
/// resolved with dependencies.
///
/// - Parameters:
/// - serviceType: The service type to register.
/// - name: A registration name, which is used to differentiate from other registrations
/// that have the same service and factory types.
/// - factory: The closure to specify how the service type is resolved with the dependencies of the type.
/// It is invoked when the ``Container`` needs to instantiate the instance.
/// It takes a ``Resolver`` to inject dependencies to the instance,
/// and returns the instance of the component type for the service.
///
/// - Returns: A registered ``ServiceEntry`` to configure more settings with method chaining.
@discardableResult
public func register<Service>(
_ serviceType: Service.Type,
name: String? = nil,
factory: @escaping (Resolver) -> Service
) -> ServiceEntry<Service> {
return _register(serviceType, factory: factory, name: name)
}
/// This method is designed for the use to extend Swinject functionality.
/// Do NOT use this method unless you intend to write an extension or plugin to Swinject framework.
///
/// - Parameters:
/// - serviceType: The service type to register.
/// - factory: The closure to specify how the service type is resolved with the dependencies of the type.
/// It is invoked when the ``Container`` needs to instantiate the instance.
/// It takes a ``Resolver`` to inject dependencies to the instance,
/// and returns the instance of the component type for the service.
/// - name: A registration name.
/// - option: A service key option for an extension/plugin.
///
/// - Returns: A registered ``ServiceEntry`` to configure more settings with method chaining.
@discardableResult
// swiftlint:disable:next identifier_name
public func _register<Service, Arguments>(
_ serviceType: Service.Type,
factory: @escaping (Arguments) -> Any,
name: String? = nil,
option: ServiceKeyOption? = nil
) -> ServiceEntry<Service> {
let key = ServiceKey(serviceType: Service.self, argumentsType: Arguments.self, name: name, option: option)
let entry = ServiceEntry(
serviceType: serviceType,
argumentsType: Arguments.self,
factory: factory,
objectScope: defaultObjectScope
)
entry.container = self
services[key] = entry
behaviors.forEach { $0.container(self, didRegisterType: serviceType, toService: entry, withName: name) }
return entry
}
/// Returns a synchronized view of the container for thread safety.
/// The returned container is ``Resolver`` type. Call this method after you finish all service registrations
/// to the original container.
///
/// - Returns: A synchronized container as ``Resolver``.
public func synchronize() -> Resolver {
return SynchronizedResolver(container: self)
}
/// Adds behavior to the container. `Behavior.container(_:didRegisterService:withName:)` will be invoked for
/// each service registered to the `container` **after** the behavior has been added.
///
/// - Parameters:
/// - behavior: Behavior to be added to the container
public func addBehavior(_ behavior: Behavior) {
behaviors.append(behavior)
}
internal func restoreObjectGraph(_ identifier: GraphIdentifier) {
currentObjectGraph = identifier
}
}
// MARK: - _Resolver
extension Container: _Resolver {
// swiftlint:disable:next identifier_name
public func _resolve<Service, Arguments>(
name: String?,
option: ServiceKeyOption? = nil,
invoker: @escaping ((Arguments) -> Any) -> Any
) -> Service? {
var resolvedInstance: Service?
let key = ServiceKey(serviceType: Service.self, argumentsType: Arguments.self, name: name, option: option)
if let entry = getEntry(for: key) {
resolvedInstance = resolve(entry: entry, invoker: invoker)
}
if resolvedInstance == nil {
resolvedInstance = resolveAsWrapper(name: name, option: option, invoker: invoker)
}
if resolvedInstance == nil {
debugHelper.resolutionFailed(
serviceType: Service.self,
key: key,
availableRegistrations: getRegistrations()
)
}
return resolvedInstance
}
fileprivate func resolveAsWrapper<Wrapper, Arguments>(
name: String?,
option: ServiceKeyOption?,
invoker: @escaping ((Arguments) -> Any) -> Any
) -> Wrapper? {
guard let wrapper = Wrapper.self as? InstanceWrapper.Type else { return nil }
let key = ServiceKey(
serviceType: wrapper.wrappedType, argumentsType: Arguments.self, name: name, option: option
)
if let entry = getEntry(for: key) {
let factory = { [weak self] in self?.resolve(entry: entry, invoker: invoker) as Any? }
return wrapper.init(inContainer: self, withInstanceFactory: factory) as? Wrapper
} else {
return wrapper.init(inContainer: self, withInstanceFactory: nil) as? Wrapper
}
}
fileprivate func getRegistrations() -> [ServiceKey: ServiceEntryProtocol] {
var registrations = parent?.getRegistrations() ?? [:]
services.forEach { key, value in registrations[key] = value }
return registrations
}
fileprivate var maxResolutionDepth: Int { return 200 }
fileprivate func incrementResolutionDepth() {
parent?.incrementResolutionDepth()
if resolutionDepth == 0, currentObjectGraph == nil {
currentObjectGraph = GraphIdentifier()
}
guard resolutionDepth < maxResolutionDepth else {
fatalError("Infinite recursive call for circular dependency has been detected. " +
"To avoid the infinite call, 'initCompleted' handler should be used to inject circular dependency.")
}
resolutionDepth += 1
}
fileprivate func decrementResolutionDepth() {
parent?.decrementResolutionDepth()
assert(resolutionDepth > 0, "The depth cannot be negative.")
resolutionDepth -= 1
if resolutionDepth == 0 { graphResolutionCompleted() }
}
fileprivate func graphResolutionCompleted() {
services.values.forEach { $0.storage.graphResolutionCompleted() }
currentObjectGraph = nil
}
}
// MARK: - Resolver
extension Container: Resolver {
/// Retrieves the instance with the specified service type.
///
/// - Parameter serviceType: The service type to resolve.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type
/// is found in the ``Container``.
public func resolve<Service>(_ serviceType: Service.Type) -> Service? {
return resolve(serviceType, name: nil)
}
/// Retrieves the instance with the specified service type and registration name.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - name: The registration name.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type and name
/// is found in the ``Container``.
public func resolve<Service>(_: Service.Type, name: String?) -> Service? {
return _resolve(name: name) { (factory: (Resolver) -> Any) in factory(self) }
}
fileprivate func getEntry(for key: ServiceKey) -> ServiceEntryProtocol? {
if let entry = services[key] {
return entry
} else {
return parent?.getEntry(for: key)
}
}
fileprivate func resolve<Service, Factory>(
entry: ServiceEntryProtocol,
invoker: (Factory) -> Any
) -> Service? {
incrementResolutionDepth()
defer { decrementResolutionDepth() }
guard let currentObjectGraph = currentObjectGraph else {
fatalError("If accessing container from multiple threads, make sure to use a synchronized resolver.")
}
if let persistedInstance = persistedInstance(Service.self, from: entry, in: currentObjectGraph) {
return persistedInstance
}
let resolvedInstance = invoker(entry.factory as! Factory)
if let persistedInstance = persistedInstance(Service.self, from: entry, in: currentObjectGraph) {
// An instance for the key might be added by the factory invocation.
return persistedInstance
}
entry.storage.setInstance(resolvedInstance as Any, inGraph: currentObjectGraph)
if let completed = entry.initCompleted as? (Resolver, Any) -> Void,
let resolvedInstance = resolvedInstance as? Service {
completed(self, resolvedInstance)
}
return resolvedInstance as? Service
}
private func persistedInstance<Service>(
_: Service.Type, from entry: ServiceEntryProtocol, in graph: GraphIdentifier
) -> Service? {
if let instance = entry.storage.instance(inGraph: graph), let service = instance as? Service {
return service
} else {
return nil
}
}
}
// MARK: CustomStringConvertible
extension Container: CustomStringConvertible {
public var description: String {
return "["
+ services.map { "\n { \($1.describeWithKey($0)) }" }.sorted().joined(separator: ",")
+ "\n]"
}
}
| mit | 87d39331e762471d0b91743f870962e0 | 38.402332 | 116 | 0.638328 | 5.022297 | false | false | false | false |
shial4/api-loltracker | Sources/App/Controllers/UserController.swift | 1 | 2330 | //
// UserController.swift
// lolTracker-API
//
// Created by Shial on 16/01/2017.
//
//
import Foundation
import Vapor
import HTTP
final class UserController: RoutesAccessible {
convenience init(drop: Droplet) {
self.init()
let user = drop.grouped("user")
user.get(handler: index)
user.get(String.self, handler: getUserSummoner)
user.patch(String.self, handler: update)
user.patch("add", String.self, handler: addSummoner)
user.patch("remove", String.self, handler: removeSummoner)
}
func index(request: Request) throws -> ResponseRepresentable {
return try User.all().makeNode().converted(to: JSON.self)
}
func getUserSummoner(request: Request, facebook: String) throws -> ResponseRepresentable {
guard let user = try User.query().filter("facebook", .equals, facebook).first() else {
throw Abort.notFound
}
guard let summoners = try user.summoners() else { throw Abort.notFound }
return try summoners.makeNode().converted(to: JSON.self)
}
func update(request: Request, facebook: String) throws -> ResponseRepresentable {
guard var user = try User.query().filter("facebook", .equals, facebook).first() else {
var new = User(facebook: facebook)
try new.save()
return new
}
user.facebook = facebook
try user.save()
return user
}
func addSummoner(request: Request, facebook: String) throws -> ResponseRepresentable {
let summoner = try request.summonerUpdateIfNeeded()
guard var user = try User.query().filter("facebook", .equals, facebook).first() else {
throw Abort.notFound
}
user.summonerId = summoner.id
try user.save()
return user
}
func removeSummoner(request: Request, facebook: String) throws -> ResponseRepresentable {
guard var user = try User.query().filter("facebook", .equals, facebook).first() else {
throw Abort.notFound
}
user.summonerId = nil
try user.save()
return JSON([:])
}
}
extension Request {
func user() throws -> User {
guard let json = json else { throw Abort.badRequest }
return try User(node: json)
}
}
| mit | 85886f27fba87f93c472d80f714efe98 | 31.361111 | 94 | 0.620172 | 4.463602 | false | false | false | false |
voz-living/vozliving-ios | VozLiving/Extensions/StringExt.swift | 1 | 3305 | //
// StringExt.swift
// VozLiving
//
// Created by Hung Nguyen Thanh on 7/3/17.
// Copyright © 2017 VozLiving. All rights reserved.
//
import Foundation
extension Character {
func isEmoji() -> Bool {
return Character(UnicodeScalar(UInt32(0x1d000))!) <= self && self <= Character(UnicodeScalar(UInt32(0x1f77f))!)
|| Character(UnicodeScalar(UInt32(0x2100))!) <= self && self <= Character(UnicodeScalar(UInt32(0x26ff))!)
}
}
extension String {
// MARK: - Localized
var localized : String {
return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "");
}
func stringByRemovingEmoji() -> String {
// return String(filter(self, {(c: Character) in !c.isEmoji()}))
let nStr = String(self.characters.filter { (char: Character) -> Bool in
!char.isEmoji()
})
return nStr
}
var urlEncode: String {
return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
}
var urlDecode: String {
return self.removingPercentEncoding!
}
static func localized(key : String) -> String {
return key.localized
}
// MARK: - Validate String
// MARK: - trimString
func trimString() -> String {
return self.trimmingCharacters(in: NSCharacterSet.whitespacesAndNewlines)
}
// MARK: - isEmptyString
func isEmptyString() -> Bool{
if self.trimString().isEmpty {
return true
}
return false
}
// MARK: - String path component helper
var lastPathComponent: String {
get {
return (self as NSString).lastPathComponent
}
}
var pathExtension: String {
get {
return (self as NSString).pathExtension
}
}
var stringByDeletingLastPathComponent: String {
get {
return (self as NSString).deletingLastPathComponent
}
}
var stringByDeletingPathExtension: String {
get {
return (self as NSString).deletingPathExtension
}
}
var pathComponents: [String] {
get {
return (self as NSString).pathComponents
}
}
func stringByAppendingPathComponent(path: String) -> String {
let nsSt = self as NSString
return nsSt.appendingPathComponent(path)
}
func stringByAppendingPathExtension(ext: String) -> String? {
let nsSt = self as NSString
return nsSt.appendingPathExtension(ext)
}
var length: Int {
get {
return self.characters.count
}
}
func filterOnlyNumber() -> String {
let nStr = String(self.characters.filter { (char: Character) -> Bool in
char >= "0" && char <= "9"
})
return nStr
}
func validateEmail() -> Bool {
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self)
}
}
| apache-2.0 | 0960c59d9632d147daf8c996ce3af2c2 | 23.294118 | 119 | 0.543281 | 4.968421 | false | false | false | false |
caoimghgin/HexKit | Pod/Classes/Scene.swift | 1 | 10253 | //
// Scene.swift
// https://github.com/caoimghgin/HexKit
//
// Copyright © 2015 Kevin Muldoon.
//
// This code is distributed under the terms and conditions of the MIT license.
//
// 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 protocol HexKitSceneDelegate {
func tileWasTapped(tile : Tile)
}
public class Scene: UIScrollView, UIScrollViewDelegate, UIGestureRecognizerDelegate {
var board : Board
var sceneDelegate = HexKitSceneDelegate?()
/**
Creates a HexKit scene.
- parameter controller: UIViewController which presents the scene
- parameter parameters: pList file parameters
- returns: Scene
*/
public convenience init(controller:UIViewController, parameters: String) {
HexKit.sharedInstance.start(parameters)
self.init(frame:controller.view.frame)
self.sceneDelegate = controller as? HexKitSceneDelegate
self.board.sceneDelegate = self.sceneDelegate
}
public override init(frame: CGRect) {
self.board = Board()
super.init(frame: frame)
contentSize = CGSize(width: board.frame.width/2, height: board.frame.height/2)
showsHorizontalScrollIndicator = true;
showsVerticalScrollIndicator = true;
autoresizingMask = [UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleLeftMargin, UIViewAutoresizing.FlexibleBottomMargin, UIViewAutoresizing.FlexibleTopMargin, UIViewAutoresizing.FlexibleHeight, UIViewAutoresizing.FlexibleWidth]
minimumZoomScale = 0.5
maximumZoomScale = 1.0
zoomScale = 1.0
delegate = self
addSubview(board)
let tapGesture = UITapGestureRecognizer(target: self, action: "tapGestureRecognizerAction:")
tapGesture.numberOfTapsRequired = 1
self.addGestureRecognizer(tapGesture)
}
// + (UIImage *) imageWithView:(UIView *)view
// {
// UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0f);
// [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:NO];
// UIImage * snapshotImage = UIGraphicsGetImageFromCurrentImageContext();
// UIGraphicsEndImageContext();
// return snapshotImage;
// }
public func getGridAsImage() -> UIImage {
return Scene.imageWithView(self.board.grid)
}
class func imageWithView(view : UIView) -> UIImage {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, true, 2.0)
view.drawViewHierarchyInRect(view.bounds, afterScreenUpdates: false)
let snapshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return snapshot
}
func tapGestureRecognizerAction(gesture : UITapGestureRecognizer) {
self.sceneDelegate?.tileWasTapped(Touch.tile(gesture))
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func createUnit() -> Unit {
return Unit(frame: CGRectMake(0, 0, 44, 44))
}
func createInfantry() -> Unit {
return Infantry(frame: CGRectMake(0, 0, 44, 44))
}
func createGerman() -> Unit {
return GermanTank(frame: CGRectMake(0, 0, 44, 44))
}
func placeUnit(unit: Unit, tile:Tile) {
unit.center = Point.CG(tile.center)
tile.units.append(unit)
board.arena.addSubview(unit)
}
public func placeUnit(tile:Tile) {
let unit = self.createUnit()
self.placeUnit(unit, tile: tile)
}
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return board
}
public func scrollViewDidZoom(scrollView: UIScrollView) {
print("zoom zoom -> \(scrollView.zoomScale)")
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false;
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
// return false; /* uncomment to disable UIScrollView scrolling **/
var result:Bool
let tile = self.tile(touch.locationInView(self));
if ( tile.units.count > 0 ) {
let unit = tile.units.first
if (unit?.alliance == HexKit.sharedInstance.turn) {
return false
} else {
return true
}
} else {
result = true
}
return result
}
public func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
// scrollView.contentSize = CGSize(width: self.frame.width / 2, height: self.frame.height / 2)
scrollView.contentSize = CGSizeMake(board.frame.size.width * scale, board.frame.size.height * scale)
}
// override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//
// let touch = touches.first
// let point = touch!.locationInView(self)
// let tile = self.tile(point);
//
//// print("expected = \(tile.hex)")
//// print("actual = Touch.hex(CGPointMake\(point))")
//// print("XCTAssertEqual(actual.r, expected.r, \"\")")
//// print("XCTAssertEqual(actual.q, expected.q, \"\")")
//// print("\r")
//
//// print(tile.hex)
// }
public func tile(q q:Int, r:Int) -> Tile {
print("q;\(q)r:\(r)");
let tile = HexKit.sharedInstance.tile(q: q, r : r)!
return tile
}
public func tile(point:CGPoint) -> Tile {
let hex = Touch.hex(point)
let tile = HexKit.sharedInstance.tile(hex)!
return tile
}
}
class Touch {
class func hex(point:CGPoint) -> Hex {
switch (HexKit.sharedInstance.gridTileShape) {
case HexKit.GridTileShape.OddFlat:
return Touch.pointToAxial_Odd_Q(point)
case HexKit.GridTileShape.OddPoint:
return Touch.pointToAxial_Odd_R(point)
case HexKit.GridTileShape.EvenFlat:
return Touch.pointToAxial_Even_Q(point)
case HexKit.GridTileShape.EvenPoint:
return Touch.pointToAxial_Even_R(point)
}
}
class func tile(point: CGPoint) -> Tile {
return HexKit.sharedInstance.tile(Touch.hex(point))!
}
class func tile(gesture:UIGestureRecognizer) -> Tile {
return Touch.tile(gesture.locationInView(gesture.view))
}
class func tile(touch:UITouch) -> Tile {
return Touch.tile(touch.locationInView(touch.view))
}
class func pointToAxial_Odd_R(point:CGPoint) -> Hex {
let tile = HexKit.sharedInstance.tile()
let x = (Double(point.x) - (tile!.ø / 2)) / tile!.ø;
let y = Double(point.y) / (tile!.Ø / 2)
let r = floor((floor(y - x) + floor(x + y)) / 3);
let q = floor((floor(2 * x + 1) + floor(x + y)) / 3) - r;
return Hex.Convert(q:q, r:r)
}
class func pointToAxial_Even_R(point:CGPoint) -> Hex {
let tile = HexKit.sharedInstance.tile()
let x = (Double(point.x) - tile!.ø) / tile!.ø;
let y = Double(point.y) / (tile!.Ø / 2)
let r = floor((floor(y - x) + floor(x + y)) / 3);
var q = floor((floor(2 * x + 1) + floor(x + y)) / 3) - r;
if ( (r+1) % 2 == 0) { q = q + 1 }
return Hex.Convert(q:q, r:r)
}
class func pointToAxial_Odd_Q(point:CGPoint) -> Hex {
let tile = HexKit.sharedInstance.tile()
let q = Double(point.x - CGFloat(tile!.Ø/8)) / (tile!.Ø * 0.75)
let yx = Int(-floor(Double(q)/2))
let yy = Double(floor(point.y)) / tile!.ø
let r = Int(floor(yy)) + yx
let coord = Hex(q: Int(r), r: Int(q))
let result = closeAndHaveACigar(coord, point: point)
return result;
}
class func pointToAxial_Even_Q(point:CGPoint) -> Hex {
// TODO -
return Hex(q: 0, r: 0)
}
class func closeAndHaveACigar(coord: Hex, point:CGPoint) -> Hex {
let guess = HexKit.sharedInstance.tile(q:coord.r, r: coord.q)
if (guess == nil) {return Hex(q:0, r:0)}
var neighbors : [Tile] = HexKit.sharedInstance.neighbors(guess!)
neighbors.append(guess!)
for tile in neighbors {
let dX = Double(point.x) - tile.center.x;
let dY = Double(point.y) - tile.center.y;
tile.delta = (dX * dX) + (dY * dY);
}
neighbors.sortInPlace{ $0.delta < $1.delta }
return neighbors[0].hex
}
} | mit | c12b77fa8a180dadce57fda48bc57b22 | 32.152104 | 255 | 0.599922 | 4.498463 | false | false | false | false |
dasdom/DHTweak | Tweaks/Tweaks/ShakeableWindow.swift | 2 | 1622 | //
// ShakeableWindow.swift
// TweaksDemo
//
// Created by dasdom on 29.09.14.
// Copyright (c) 2014 Dominik Hauser. All rights reserved.
//
import UIKit
public class ShakeableWindow: UIWindow {
var isShaking = false
override public func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent) {
if motion == UIEventSubtype.MotionShake {
isShaking = true
let sec = 0.4 * Float(NSEC_PER_SEC)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(sec)), dispatch_get_main_queue(), {
if self.shouldPresentTweaksController() {
self.presentTweaks()
}
})
}
}
override public func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent) {
isShaking = false
}
func shouldPresentTweaksController() -> Bool {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return true
#else
return self.isShaking && UIApplication.sharedApplication().applicationState == .Active
#endif
}
func presentTweaks() {
var visibleViewController = self.rootViewController
while let presentingViewController = visibleViewController?.presentingViewController {
visibleViewController = presentingViewController
}
if (visibleViewController is CategoriesTableViewController) == false {
visibleViewController?.presentViewController(UINavigationController(rootViewController: CategoriesTableViewController()), animated: true, completion: nil)
}
}
}
| mit | 087e1f4ca3d864880b4d397e0577ea18 | 32.102041 | 166 | 0.636868 | 5.215434 | false | false | false | false |
alfredcc/SwiftPlayground | 😈/TypeErasureExample.playground/Contents.swift | 1 | 1037 | //: Playground - noun: a place where people can play
import UIKit
protocol Pokemon {
typealias SuperPower
func attact(power: SuperPower)
}
struct Electricity {
var charge: Int
func spark() {
print("spark:", Array(count: charge, repeatedValue: "⚡️").joinWithSeparator(""))
}
}
struct Fire {
var level: Int
func blast() {
print("Blast:", Array(count: level, repeatedValue: "🔥").joinWithSeparator(""))
}
}
struct Pikachu: Pokemon {
func attact(power: Electricity) {
power.spark()
}
}
struct Charmander: Pokemon {
func attact(power: Fire) {
power.blast()
}
}
struct anyPokemon<SuperPower>: Pokemon {
let method: SuperPower -> Void
init<U: Pokemon where U.SuperPower == SuperPower>(_ pokemon: U) {
method = pokemon.attact
}
func attact(power: SuperPower) {
method(power)
}
}
let pika = anyPokemon(Pikachu())
let hito = anyPokemon(Charmander())
pika.attact(Electricity(charge: 16))
hito.attact(Fire(level: 10))
| mit | 826772ee9352250d29fb3a9dad92f39e | 19.6 | 88 | 0.633981 | 3.705036 | false | false | false | false |
seandavidmcgee/HumanKontact | keyboardTest/ProfileViewController.swift | 1 | 5581 | //
// ProfileViewController.swift
// keyboardTest
//
// Created by Sean McGee on 4/26/15.
// Copyright (c) 2015 3 Callistos Services. All rights reserved.
//
import UIKit
import QuartzCore
import CoreGraphics
let offset_HeaderStop:CGFloat = 103.0 // At this offset the Header stops its transformations
let offset_B_LabelHeader:CGFloat = 158.0 // At this offset the Black label reaches the Header
let distance_W_LabelHeader:CGFloat = 35.0 // The distance between the bottom of the Header and the top of the White Label
class ProfileViewController: UIViewController, UIScrollViewDelegate {
var image:UIImage? = nil
var nameLabel:String? = nil
@IBOutlet var scrollView:UIScrollView!
@IBOutlet var bgView: UIView!
@IBOutlet var avatarImage:UIImageView!
@IBOutlet var header:UIView!
@IBOutlet var baseLabel: UILabel!
@IBOutlet var headerLabel:UILabel!
@IBOutlet var headerImageView:UIImageView!
@IBOutlet var headerBlurImageView:UIImageView!
var blurredHeaderImageView:UIImageView?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(gradientStyle: UIGradientStyle.TopToBottom, withFrame: self.view.frame, andColors: [FlatHKDark(), FlatHKLight()])
scrollView.delegate = self
}
override func viewWillAppear(animated: Bool) {
// Header - Image
headerImageView = UIImageView(frame: CGRectMake(0, 0, view.frame.width, 170))
headerImageView.image = image?.blurredImageWithRadius(20, iterations: 20, tintColor: UIColor.flatHKDarkColor())
headerImageView.contentMode = UIViewContentMode.ScaleAspectFill
header.insertSubview(headerImageView!, belowSubview: headerLabel)
// Header - Blurred Image
headerBlurImageView = UIImageView(frame: CGRectMake(0, 0, view.frame.width, 170))
headerBlurImageView.image = image?.blurredImageWithRadius(14, iterations: 20, tintColor: UIColor.flatHKDarkColor())
headerBlurImageView.contentMode = UIViewContentMode.ScaleAspectFill
headerBlurImageView.alpha = 0.0
header.insertSubview(headerBlurImageView!, belowSubview: headerLabel)
header.clipsToBounds = true
var profileImageView: UIImageView! = UIImageView(frame: avatarImage.bounds)
profileImageView.image = image!
profileImageView.contentMode = UIViewContentMode.ScaleAspectFill
avatarImage.insertSubview(profileImageView!, atIndex: 0)
headerLabel.text = nameLabel
baseLabel.text = nameLabel
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func scrollViewDidScroll(scrollView: UIScrollView) {
var offset = scrollView.contentOffset.y
var avatarTransform = CATransform3DIdentity
var headerTransform = CATransform3DIdentity
// PULL DOWN -----------------
if offset < 0 {
let headerScaleFactor:CGFloat = -(offset) / header.bounds.height
let headerSizevariation = ((header.bounds.height * (1.0 + headerScaleFactor)) - header.bounds.height)/2.0
headerTransform = CATransform3DTranslate(headerTransform, 0, headerSizevariation, 0)
headerTransform = CATransform3DScale(headerTransform, 1.0 + headerScaleFactor, 1.0 + headerScaleFactor, 0)
header.layer.transform = headerTransform
}
// SCROLL UP/DOWN ------------
else {
// Header -----------
headerTransform = CATransform3DTranslate(headerTransform, 0, max(-offset_HeaderStop, -offset), 0)
// ------------ Label
let labelTransform = CATransform3DMakeTranslation(0, max(-distance_W_LabelHeader, offset_B_LabelHeader - (offset) ), 0)
headerLabel.layer.transform = labelTransform
// ------------ Blur
headerBlurImageView?.alpha = min (1.0, (offset - offset_B_LabelHeader)/distance_W_LabelHeader)
// Avatar -----------
let avatarScaleFactor = (min(offset_HeaderStop, offset)) / avatarImage.bounds.height / 3.5 // Slow down the animation
let avatarSizeVariation = ((avatarImage.bounds.height * (1.0 + avatarScaleFactor)) - avatarImage.bounds.height) / 2.0
avatarTransform = CATransform3DTranslate(avatarTransform, 0, avatarSizeVariation, 0)
avatarTransform = CATransform3DScale(avatarTransform, 1.0 - avatarScaleFactor, 1.0 - avatarScaleFactor, 0)
if offset <= offset_HeaderStop {
if avatarImage.layer.zPosition < header.layer.zPosition{
header.layer.zPosition = 0
}
}else {
if avatarImage.layer.zPosition >= header.layer.zPosition{
header.layer.zPosition = 2
}
}
}
// Apply Transformations
header.layer.transform = headerTransform
avatarImage.layer.transform = avatarTransform
}
@IBAction func shamelessActionThatBringsYouToMyTwitterProfile() {
if !UIApplication.sharedApplication().openURL(NSURL(string:"twitter://user?screen_name=bitwaker")!){
UIApplication.sharedApplication().openURL(NSURL(string:"https://twitter.com/bitwaker")!)
}
}
}
| mit | c03b947a970da9e2f44cddf74a7b1b22 | 40.649254 | 157 | 0.638058 | 5.439571 | false | false | false | false |
rebeloper/SwiftyPlistManager | SwiftyPlistManager/SwiftyPlistManager.swift | 1 | 12392 | /**
MIT License
Copyright (c) 2017 Alex Nagy
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
struct Plist {
let name:String
var sourcePath:String? {
guard let path = Bundle.main.path(forResource: name, ofType: "plist") else { return .none }
return path
}
var destPath:String? {
guard sourcePath != .none else { return .none }
let dir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
return (dir as NSString).appendingPathComponent("\(name).plist")
}
init?(name:String) {
self.name = name
let fileManager = FileManager.default
guard let source = sourcePath else {
plistManagerPrint("WARNING: The \(name).plist could not be initialized because it does not exist in the main bundle. Unable to copy file into the Document Directory of the app. Please add a plist file named \(name).plist into the main bundle (your project).")
return nil }
guard let destination = destPath else { return nil }
guard fileManager.fileExists(atPath: source) else {
plistManagerPrint("The \(name).plist already exist.")
return nil }
if !fileManager.fileExists(atPath: destination) {
do {
try fileManager.copyItem(atPath: source, toPath: destination)
} catch let error as NSError {
plistManagerPrint("Unable to copy file. ERROR: \(error.localizedDescription)")
return nil
}
}
}
func getValuesInPlistFile() throws -> NSDictionary? {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: destPath!) {
guard let dict = NSDictionary(contentsOfFile: destPath!) else { return .none }
return dict
} else {
throw SwiftyPlistManagerError.fileDoesNotExist
}
}
func getMutablePlistFile() -> NSMutableDictionary? {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: destPath!) {
guard let dict = NSMutableDictionary(contentsOfFile: destPath!) else { return .none }
return dict
} else {
return .none
}
}
func addValuesToPlistFile(dictionary:NSDictionary) throws {
let fileManager = FileManager.default
if fileManager.fileExists(atPath: destPath!) {
if !dictionary.write(toFile: destPath!, atomically: false) {
plistManagerPrint("File not written successfully")
throw SwiftyPlistManagerError.fileNotWritten
}
} else {
plistManagerPrint("File does not exist")
throw SwiftyPlistManagerError.fileDoesNotExist
}
}
}
public enum SwiftyPlistManagerError: Error {
case fileNotWritten
case fileDoesNotExist
case fileUnavailable
case fileAlreadyEmpty
case keyValuePairAlreadyExists
case keyValuePairDoesNotExist
}
public class SwiftyPlistManager {
public static let shared = SwiftyPlistManager()
private init() {} //This prevents others from using the default '()' initializer for this class.
var logPlistManager: Bool = false
public func start(plistNames: [String], logging: Bool) {
logPlistManager = logging
plistManagerPrint("Starting SwiftyPlistManager . . .")
var itemCount = 0
for plistName in plistNames {
itemCount += 1
if let _ = Plist(name: plistName) {
plistManagerPrint("Initialized '\(plistName).plist'")
}
}
if itemCount == plistNames.count {
plistManagerPrint("Initialization complete.")
}
}
public func addNew(_ value: Any, key: String, toPlistWithName: String, completion:(_ error :SwiftyPlistManagerError?) -> ()) {
plistManagerPrint("Starting to add value '\(value)' for key '\(key)' to '\(toPlistWithName).plist' . . .")
if !keyAlreadyExists(key: key, inPlistWithName: toPlistWithName) {
if let plist = Plist(name: toPlistWithName) {
guard let dict = plist.getMutablePlistFile() else {
plistManagerPrint("Unable to get '\(toPlistWithName).plist'")
completion(.fileUnavailable)
return
}
dict[key] = value
do {
try plist.addValuesToPlistFile(dictionary: dict)
completion(nil)
} catch {
plistManagerPrint(error)
completion(error as? SwiftyPlistManagerError)
}
logAction(for: plist, withPlistName: toPlistWithName)
} else {
plistManagerPrint("Unable to get '\(toPlistWithName).plist'")
completion(.fileUnavailable)
}
} else {
plistManagerPrint("Value for key '\(key)' already exists. Not saving value. Not overwriting value.")
completion(.keyValuePairAlreadyExists)
}
}
public func removeKeyValuePair(for key: String, fromPlistWithName: String, completion:(_ error :SwiftyPlistManagerError?) -> ()) {
plistManagerPrint("Starting to remove Key-Value pair for '\(key)' from '\(fromPlistWithName).plist' . . .")
if keyAlreadyExists(key: key, inPlistWithName: fromPlistWithName) {
if let plist = Plist(name: fromPlistWithName) {
guard let dict = plist.getMutablePlistFile() else {
plistManagerPrint("Unable to get '\(fromPlistWithName).plist'")
completion(.fileUnavailable)
return
}
dict.removeObject(forKey: key)
do {
try plist.addValuesToPlistFile(dictionary: dict)
completion(nil)
} catch {
plistManagerPrint(error)
completion(error as? SwiftyPlistManagerError)
}
logAction(for: plist, withPlistName: fromPlistWithName)
} else {
plistManagerPrint("Unable to get '\(fromPlistWithName).plist'")
completion(.fileUnavailable)
}
} else {
plistManagerPrint("Key-Value pair for key '\(key)' does not exists. Remove canceled.")
completion(.keyValuePairDoesNotExist)
}
}
public func removeAllKeyValuePairs(fromPlistWithName: String, completion:(_ error :SwiftyPlistManagerError?) -> ()) {
if let plist = Plist(name: fromPlistWithName) {
guard let dict = plist.getMutablePlistFile() else {
plistManagerPrint("Unable to get '\(fromPlistWithName).plist'")
completion(.fileUnavailable)
return
}
let keys = Array(dict.allKeys)
if keys.count != 0 {
dict.removeAllObjects()
} else {
plistManagerPrint("'\(fromPlistWithName).plist' is already empty. Removal of all key-value pairs canceled.")
completion(.fileAlreadyEmpty)
return
}
do {
try plist.addValuesToPlistFile(dictionary: dict)
completion(nil)
} catch {
plistManagerPrint(error)
completion(error as? SwiftyPlistManagerError)
}
logAction(for: plist, withPlistName: fromPlistWithName)
} else {
plistManagerPrint("Unable to get '\(fromPlistWithName).plist'")
completion(.fileUnavailable)
}
}
public func addNewOrSave(_ value: Any, forKey: String, toPlistWithName: String, completion:(_ error :SwiftyPlistManagerError?) -> ()) {
if keyAlreadyExists(key: forKey, inPlistWithName: toPlistWithName){
save(value, forKey: forKey, toPlistWithName: toPlistWithName, completion: completion)
}else{
addNew(value, key: forKey, toPlistWithName: toPlistWithName, completion: completion)
}
}
public func save(_ value: Any, forKey: String, toPlistWithName: String, completion:(_ error :SwiftyPlistManagerError?) -> ()) {
if let plist = Plist(name: toPlistWithName) {
guard let dict = plist.getMutablePlistFile() else {
plistManagerPrint("Unable to get '\(toPlistWithName).plist'")
completion(.fileUnavailable)
return
}
if let dictValue = dict[forKey] {
if type(of: value) != type(of: dictValue){
plistManagerPrint("WARNING: You are saving a '\(type(of: value))' typed value into a '\(type(of: dictValue))' typed value. Best practice is to save Int values to Int fields, String values to String fields etc. (For example: '_NSContiguousString' to '__NSCFString' is ok too; they are both String types) If you believe that this mismatch in the types of the values is ok and will not break your code than disregard this message.")
}
dict[forKey] = value
}
do {
try plist.addValuesToPlistFile(dictionary: dict)
completion(nil)
} catch {
plistManagerPrint(error)
completion(error as? SwiftyPlistManagerError)
}
logAction(for: plist, withPlistName: toPlistWithName)
} else {
plistManagerPrint("Unable to get '\(toPlistWithName).plist'")
completion(.fileUnavailable)
}
}
public func fetchValue(for key: String, fromPlistWithName: String) -> Any? {
guard let plist = Plist(name: fromPlistWithName),
let dict = plist.getMutablePlistFile() else {
plistManagerPrint("Unable to get '\(fromPlistWithName).plist'")
return nil
}
guard let value = dict[key] else {
plistManagerPrint("WARNING: The Value for key '\(key)' does not exist in '\(fromPlistWithName).plist'! Please, check your spelling.")
return nil
}
plistManagerPrint("Sending value to completion handler: \(value)")
return value
}
public func getValue(for key: String, fromPlistWithName: String, completion:(_ result : Any?, _ error :SwiftyPlistManagerError?) -> ()) {
guard let plist = Plist(name: fromPlistWithName),
let dict = plist.getMutablePlistFile() else {
plistManagerPrint("Unable to get '\(fromPlistWithName).plist'")
completion(nil, .fileUnavailable)
return
}
guard let value = dict[key] else {
plistManagerPrint("WARNING: The Value for key '\(key)' does not exist in '\(fromPlistWithName).plist'! Please, check your spelling.")
completion(nil, .keyValuePairDoesNotExist)
return
}
plistManagerPrint("Sending value to completion handler: \(value)")
completion(value, nil)
}
func keyAlreadyExists(key: String, inPlistWithName: String) -> Bool {
guard let plist = Plist(name: inPlistWithName),
let dict = plist.getMutablePlistFile() else { return false }
let keys = dict.allKeys
return keys.contains { $0 as? String == key }
}
func logAction(for plist:Plist, withPlistName: String) {
if logPlistManager {
plistManagerPrint("An Action has been performed. You can check if it went ok by taking a look at the current content of the '\(withPlistName).plist' file: ")
do {
let plistValues = try plist.getValuesInPlistFile()
plistManagerPrint("\(plistValues ?? [:])")
} catch {
plistManagerPrint("Could not retreive '\(withPlistName).plist' values.")
plistManagerPrint(error)
}
}
}
}
func plistManagerPrint(_ text: Any) {
if SwiftyPlistManager.shared.logPlistManager {
print("[SwiftyPlistManager]", text)
}
}
| mit | f6f244c80761adf7a8dffb5fa1b2597a | 33.614525 | 439 | 0.649935 | 5.300257 | false | false | false | false |
itsbriany/Sudoku | Sudoku/Sudoku.swift | 1 | 2670 | //
// Sudoku.swift
// Sudoku
//
// Created by Brian Yip on 2016-01-20.
// Copyright © 2016 Brian Yip. All rights reserved.
//
import Foundation
public class Sudoku: NSCopying {
// MARK: Properties
var format: SudokuFormat
var cells: [[Int]]
var selectableCells: [[Bool]]
// Copy constructor
init(sudoku: Sudoku) {
self.format = sudoku.format
self.cells = sudoku.cells
self.selectableCells = sudoku.selectableCells
}
init!(sudoku: String, format: SudokuFormat) {
self.format = format
self.cells = [[Int]](count: format.rows, repeatedValue: [Int](count: format.columns, repeatedValue: 0))
self.selectableCells = [[Bool]](count: format.rows, repeatedValue: [Bool](count: format.columns, repeatedValue: true))
mapValues(sudoku)
}
// MARK: NSCopying Implementation
@objc public func copyWithZone(zone: NSZone) -> AnyObject {
return Sudoku(sudoku: self)
}
// MARK: Public Interface
/*
Returns true if this sudoku is solved correctly
*/
func isSolved() -> Bool {
for row in self.cells {
if (!self.checkColumn(row)) {
return false
}
if (!self.checkRow(row)) {
return false
}
}
return true
}
// MARK: Private Interface
private func mapValues(sudoku: String) {
var localRows = 0
var localColumns = 0
for char in sudoku.characters {
if let number = Int(String(char)) {
cells[localRows][localColumns] = number
}
localColumns++
localColumns %= format.columns
if (localColumns == 0) {
localRows++
}
}
}
private func sortIntegers(value1: Int, value2: Int) -> Bool {
return value1 < value2
}
private func checkColumn(row: [Int]) -> Bool {
var current: Int = 0
var unsortedColumn: [Int] = [Int]()
for value in row {
unsortedColumn.append(value)
}
let sortedColumn = unsortedColumn.sort(sortIntegers)
for value in sortedColumn {
if (value != current + 1) {
return false
}
current++
}
return true
}
private func checkRow(row: [Int]) -> Bool {
var current = 0
let sortedRow = row.sort(sortIntegers)
for value in sortedRow {
if (value != current + 1) {
return false
}
current++
}
return true
}
} | apache-2.0 | 1b18c88bfca681b449022b7afe8c3809 | 25.7 | 126 | 0.534283 | 4.546848 | false | false | false | false |
MikeEmery/Swift-iOS-Rotten-Tomatoes | SwiftTomatoes/MovieDetailViewController.swift | 1 | 1759 | //
// MovieDetailViewController.swift
// SwiftTomatoes
//
// Created by Michael Emery on 6/11/14.
// Copyright (c) 2014 Michael Emery. All rights reserved.
//
import UIKit
class MovieDetailViewController: UIViewController {
@IBOutlet var largePosterImageView : UIImageView
@IBOutlet var synopsisTextView : UITextView
var movie: Movie
init(movie: Movie) {
self.movie = movie;
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
println("Movie: \(self.movie.title)")
self.title = self.movie.title
self.synopsisTextView.text = self.movie.synopsis
let request = NSURLRequest(URL: movie.largeUrl)
let operationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: operationQueue, completionHandler: {(response, data, error) in
let downloadedImage = UIImage(data: data)
dispatch_async(dispatch_get_main_queue(), {
self.largePosterImageView.image = downloadedImage
})
println("downloaded large image")
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// #pragma 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 | 9d5f6b264a59d5fe1081645e9a5aa020 | 28.316667 | 126 | 0.640136 | 5.12828 | false | false | false | false |
nbrady-techempower/FrameworkBenchmarks | frameworks/Swift/swift-nio/Sources/swift-nio-tfb-default/main.swift | 3 | 4650 |
import Foundation
import NIO
import NIOHTTP1
struct JSONTestResponse: Encodable {
let message = "Hello, World!"
}
enum Constants {
static let httpVersion = HTTPVersion(major: 1, minor: 1)
static let serverName = "SwiftNIO"
static let plainTextResponse: StaticString = "Hello, World!"
static let plainTextResponseLength = plainTextResponse.count
static let plainTextResponseLengthString = String(plainTextResponseLength)
static let jsonResponseLength = try! JSONEncoder().encode(JSONTestResponse()).count
static let jsonResponseLengthString = String(jsonResponseLength)
}
private final class HTTPHandler: ChannelInboundHandler {
public typealias InboundIn = HTTPServerRequestPart
public typealias OutboundOut = HTTPServerResponsePart
let dateFormatter = RFC1123DateFormatter()
let jsonEncoder = JSONEncoder()
var plaintextBuffer: ByteBuffer!
var jsonBuffer: ByteBuffer!
init() {
let allocator = ByteBufferAllocator()
plaintextBuffer = allocator.buffer(capacity: Constants.plainTextResponseLength)
plaintextBuffer.write(staticString: Constants.plainTextResponse)
jsonBuffer = allocator.buffer(capacity: Constants.jsonResponseLength)
}
func channelRead(ctx: ChannelHandlerContext, data: NIOAny) {
let reqPart = self.unwrapInboundIn(data)
switch reqPart {
case .head(let request):
switch request.uri {
case "/plaintext":
processPlaintext(ctx: ctx)
case "/json":
processJSON(ctx: ctx)
default:
_ = ctx.close()
}
case .body:
break
case .end:
_ = ctx.write(self.wrapOutboundOut(.end(nil)))
}
}
func channelReadComplete(ctx: ChannelHandlerContext) {
ctx.flush()
ctx.fireChannelReadComplete()
}
private func processPlaintext(ctx: ChannelHandlerContext) {
let responseHead = plainTextResponseHead(contentLength: Constants.plainTextResponseLengthString)
ctx.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
ctx.write(self.wrapOutboundOut(.body(.byteBuffer(plaintextBuffer))), promise: nil)
}
private func processJSON(ctx: ChannelHandlerContext) {
let responseHead = jsonResponseHead(contentLength: Constants.jsonResponseLengthString)
ctx.write(self.wrapOutboundOut(.head(responseHead)), promise: nil)
let responseData = try! jsonEncoder.encode(JSONTestResponse())
jsonBuffer.clear()
jsonBuffer.write(bytes: responseData)
ctx.write(self.wrapOutboundOut(.body(.byteBuffer(jsonBuffer))), promise: nil)
}
private func jsonResponseHead(contentLength: String) -> HTTPResponseHead {
return responseHead(contentType: "application/json", contentLength: contentLength)
}
private func plainTextResponseHead(contentLength: String) -> HTTPResponseHead {
return responseHead(contentType: "text/plain", contentLength: contentLength)
}
private func responseHead(contentType: String, contentLength: String) -> HTTPResponseHead {
var headers = HTTPHeaders()
headers.add(name: "content-type", value: contentType)
headers.add(name: "content-length", value: contentLength)
headers.add(name: "server", value: Constants.serverName)
headers.add(name: "date", value: dateFormatter.getDate())
return HTTPResponseHead(version: Constants.httpVersion,
status: .ok,
headers: headers)
}
}
let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
let bootstrap = ServerBootstrap(group: group)
.serverChannelOption(ChannelOptions.backlog, value: 8192)
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_TCP), TCP_NODELAY), value: 1)
.childChannelInitializer { channel in
channel.pipeline.configureHTTPServerPipeline(withPipeliningAssistance: false).then {
channel.pipeline.add(handler: HTTPHandler())
}
}
.childChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.childChannelOption(ChannelOptions.maxMessagesPerRead, value: 16)
.childChannelOption(ChannelOptions.recvAllocator, value: AdaptiveRecvByteBufferAllocator())
defer {
try! group.syncShutdownGracefully()
}
let channel = try! bootstrap.bind(host: "0.0.0.0", port: 8080).wait()
try! channel.closeFuture.wait()
| bsd-3-clause | 1bf7b5257ce66df15769e3cac14b5868 | 35.904762 | 104 | 0.700215 | 5.121145 | false | false | false | false |
hooman/swift | test/IRGen/associated_types.swift | 4 | 4647 | // RUN: %target-swift-frontend -emit-ir -primary-file %s | %FileCheck %s -DINT=i%target-ptrsize
// REQUIRES: CPU=i386 || CPU=x86_64
protocol Runcer {
associatedtype Runcee
}
protocol Runcible {
associatedtype RuncerType : Runcer
associatedtype AltRuncerType : Runcer
}
struct Mince {}
struct Quince : Runcer {
typealias Runcee = Mince
}
struct Spoon : Runcible {
typealias RuncerType = Quince
typealias AltRuncerType = Quince
}
struct Owl<T : Runcible, U> {
// CHECK: define hidden swiftcc void @"$s16associated_types3OwlV3eat{{[_0-9a-zA-Z]*}}F"(%swift.opaque*
func eat(_ what: T.RuncerType.Runcee, and: T.RuncerType, with: T) { }
}
class Pussycat<T : Runcible, U> {
init() {}
// CHECK: define hidden swiftcc void @"$s16associated_types8PussycatC3eat{{[_0-9a-zA-Z]*}}F"(%swift.opaque* noalias nocapture %0, %swift.opaque* noalias nocapture %1, %swift.opaque* noalias nocapture %2, %T16associated_types8PussycatC* swiftself %3)
func eat(_ what: T.RuncerType.Runcee, and: T.RuncerType, with: T) { }
}
func owl() -> Owl<Spoon, Int> {
return Owl()
}
func owl2() {
Owl<Spoon, Int>().eat(Mince(), and: Quince(), with: Spoon())
}
func pussycat() -> Pussycat<Spoon, Int> {
return Pussycat()
}
func pussycat2() {
Pussycat<Spoon, Int>().eat(Mince(), and: Quince(), with: Spoon())
}
protocol Speedy {
static func accelerate()
}
protocol FastRuncer {
associatedtype Runcee : Speedy
}
protocol FastRuncible {
associatedtype RuncerType : FastRuncer
}
// This is a complex example demonstrating the need to pull conformance
// information for archetypes from all paths to that archetype, not just
// its parent relationships.
func testFastRuncible<T: Runcible, U: FastRuncible>(_ t: T, u: U)
where T.RuncerType == U.RuncerType {
U.RuncerType.Runcee.accelerate()
}
// CHECK: define hidden swiftcc void @"$s16associated_types16testFastRuncible_1uyx_q_tAA0E0RzAA0dE0R_10RuncerTypeQy_AFRtzr0_lF"(%swift.opaque* noalias nocapture %0, %swift.opaque* noalias nocapture %1, %swift.type* %T, %swift.type* %U, i8** %T.Runcible, i8** %U.FastRuncible) {{.*}} {
// 1. Get the type metadata for U.RuncerType.Runcee.
// 1a. Get the type metadata for U.RuncerType.
// Note that we actually look things up in T, which is going to prove unfortunate.
// CHECK: [[T2:%.*]] = call swiftcc %swift.metadata_response @swift_getAssociatedTypeWitness([[INT]] 255, i8** %T.Runcible, %swift.type* %T, %swift.protocol_requirement* getelementptr{{.*}}i32 12), i32 -1), %swift.protocol_requirement* getelementptr inbounds (<{{.*}}>, <{{.*}}>* @"$s16associated_types8RuncibleMp", i32 0, i32 14)) [[NOUNWIND_READNONE:#.*]]
// CHECK-NEXT: %T.RuncerType = extractvalue %swift.metadata_response [[T2]], 0
// CHECK-NEXT: extractvalue %swift.metadata_response [[T2]], 1
// 2. Get the witness table for U.RuncerType.Runcee : Speedy
// 2a. Get the protocol witness table for U.RuncerType : FastRuncer.
// CHECK-NEXT: %T.RuncerType.FastRuncer = call swiftcc i8** @swift_getAssociatedConformanceWitness(i8** %U.FastRuncible, %swift.type* %U, %swift.type* %T.RuncerType
// 1c. Get the type metadata for U.RuncerType.Runcee.
// CHECK-NEXT: [[T2:%.*]] = call swiftcc %swift.metadata_response @swift_getAssociatedTypeWitness([[INT]] 0, i8** %T.RuncerType.FastRuncer, %swift.type* %T.RuncerType, {{.*}}, %swift.protocol_requirement* getelementptr inbounds (<{{.*}}>, <{{.*}}>* @"$s16associated_types10FastRuncerMp", i32 0, i32 10))
// CHECK-NEXT: %T.RuncerType.Runcee = extractvalue %swift.metadata_response [[T2]], 0
// 2b. Get the witness table for U.RuncerType.Runcee : Speedy.
// CHECK-NEXT: %T.RuncerType.Runcee.Speedy = call swiftcc i8** @swift_getAssociatedConformanceWitness(i8** %T.RuncerType.FastRuncer, %swift.type* %T.RuncerType, %swift.type* %T.RuncerType.Runcee
// 3. Perform the actual call.
// CHECK-NEXT: [[T0_GEP:%.*]] = getelementptr inbounds i8*, i8** %T.RuncerType.Runcee.Speedy, i32 1
// CHECK-NEXT: [[T0:%.*]] = load i8*, i8** [[T0_GEP]]
// CHECK-NEXT: [[T1:%.*]] = bitcast i8* [[T0]] to void (%swift.type*, %swift.type*, i8**)*
// CHECK-NEXT: call swiftcc void [[T1]](%swift.type* swiftself %T.RuncerType.Runcee, %swift.type* %T.RuncerType.Runcee, i8** %T.RuncerType.Runcee.Speedy)
public protocol P0 {
associatedtype ErrorType : Swift.Error
}
public struct P0Impl : P0 {
public typealias ErrorType = Swift.Error
}
// CHECK: define{{.*}} swiftcc i8** @"$s16associated_types6P0ImplVAA0C0AA9ErrorTypeAaDP_s0E0PWT"(%swift.type* %P0Impl.ErrorType, %swift.type* %P0Impl, i8** %P0Impl.P0)
// CHECK: ret i8** @"$ss5ErrorWS"
// CHECK: attributes [[NOUNWIND_READNONE]] = { nounwind readnone }
| apache-2.0 | c5eeb823e70e775519a6dcdf09adb4f1 | 42.429907 | 357 | 0.697224 | 3.345572 | false | false | false | false |
johntmcintosh/BarricadeKit | BarricadeKit/Core/ResponseSet/ResponseSet.swift | 1 | 1300 | //
// ResponseSet.swift
// Barricade
//
// Created by John McIntosh on 5/5/17.
// Copyright © 2017 John T McIntosh. All rights reserved.
//
import Foundation
public struct ResponseSet {
public var requestName: String
public private(set) var allResponses: [Response]
private var evaluation: ResponseSetEvaluation
public init(requestName: String, evaluation: ResponseSetEvaluation) {
self.requestName = requestName
self.allResponses = []
self.evaluation = evaluation
}
public mutating func add(response: Response) {
allResponses.append(response)
}
public mutating func add(response: NetworkResponse) {
allResponses.append(.network(response))
}
public mutating func add(response: ErrorResponse) {
allResponses.append(.error(response))
}
public func response(named: String) -> Response? {
return allResponses.first(where: { response -> Bool in
return response.name == named
})
}
public func responds(to request: URLRequest, components: URLComponents) -> Bool {
return evaluation.evaluate(request: request, components: components)
}
public var defaultResponse: Response? {
return allResponses.first
}
}
| mit | 2cfb5bfb74ef6243ae6438661692d445 | 24.470588 | 85 | 0.658968 | 4.639286 | false | false | false | false |
blackandgreystudios/BGAccessoryArrow | BGAccessoryArrow/BGAccessoryArrow.swift | 1 | 1861 | //
// BGAccessoryArrow.swift
// BGAccessoryArrow
//
// Created by Black & Grey Studios on 4/29/16.
//
// MARK: Properties & Initializers
public class BGAccessoryArrow: UIControl
{
// MARK: Properties
private let color: UIColor!
// MARK: Initializers
public required init?(coder aDecoder: NSCoder)
{
return nil
}
public init(frame: CGRect, color: UIColor)
{
self.color = color
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
public convenience init(color: UIColor)
{
let frame = CGRectMake(0, 0, 11.5, 15.0)
self.init(frame: frame, color: color)
}
}
// MARK: - Drawing
public extension BGAccessoryArrow
{
// MARK: Draw Rect
override public func drawRect(rect: CGRect)
{
// Set x and y coordinates of arrow tip
let x = CGRectGetMaxX(self.bounds) - 3.0
let y = CGRectGetMidY(self.bounds)
// Set arrow length
let arrowLength: CGFloat = 4.5
// Get current context
let context = UIGraphicsGetCurrentContext()
// Move context to top left
CGContextMoveToPoint(context, x - arrowLength, y - arrowLength)
// Add line from context to arrow tip
CGContextAddLineToPoint(context, x, y)
// Add line from arrow tip to bottom left
CGContextAddLineToPoint(context, x - arrowLength, y + arrowLength)
// Set line properties
CGContextSetLineCap(context, CGLineCap.Square)
CGContextSetLineJoin(context, CGLineJoin.Miter)
CGContextSetLineWidth(context, 2)
// Set arrow color
self.color.setStroke()
// Draw arrow
CGContextStrokePath(context)
}
}
| mit | 2ba6c2559380ee219a9d2686a1fea1ed | 22.858974 | 74 | 0.588931 | 4.833766 | false | false | false | false |
zyrx/eidolon | Kiosk/App/Models/BuyersPremium.swift | 7 | 441 | import UIKit
import SwiftyJSON
class BuyersPremium: JSONAble {
let id: String
let name: String
init(id: String, name: String) {
self.id = id
self.name = name
}
override class func fromJSON(json: [String: AnyObject]) -> JSONAble {
let json = JSON(json)
let id = json["id"].stringValue
let name = json["name"].stringValue
return BuyersPremium(id: id, name: name)
}
}
| mit | 2b17443a61f84f5c28f42ab7bf2218df | 21.05 | 73 | 0.600907 | 4.045872 | false | false | false | false |
vincenzorm117/Perceptron-Visualization | Perceptron/Perceptron/Graph.swift | 1 | 6793 | //
// Graph.swift
// Perceptron
//
// Created by Vincenzo on 2/14/15.
// Copyright (c) 2015 Vincenzo. All rights reserved.
//
import AppKit
import Foundation
import Cocoa
class Graph: NSView {
var teamRed: [(CGFloat,CGFloat)] = []
var teamBlue: [(CGFloat,CGFloat)] = []
var hasSelectedExample: Bool = false
var clearCanvas: Bool = false
var lineDrawn: Bool = false
let line: CGFloat = 4
let offset: CGFloat = 20
var drawBoundary = false
// var w0: CGFloat = 0.0
// var w1: CGFloat = 0.0
// var w2: CGFloat = 0.0
var w0: [CGFloat] = []
var w1: [CGFloat] = []
var w2: [CGFloat] = []
var lastw0: CGFloat = 0.0
var lastw1: CGFloat = 0.0
var lastw2: CGFloat = 0.0
func clearHistory(){
w0 = []
w1 = []
w2 = []
}
func clearWeights(){
teamRed = []
teamBlue = []
}
func clear(){
clearWeights()
clearCanvas = true
needsDisplay = true
}
func updateBoundary() -> Int {
return w0.count
}
func setGrid(){
// Fill Background with white
NSColor.whiteColor().set()
NSRectFill(self.bounds)
// Draw Y-Axis
NSColor.grayColor().set()
let yAxis = NSBezierPath()
yAxis.moveToPoint(NSMakePoint(self.bounds.width/2, 0))
yAxis.lineToPoint(NSPoint(x: self.bounds.width/2, y: self.bounds.height))
yAxis.lineWidth = 1
yAxis.stroke()
// Draw X-Axis
NSColor.grayColor().set()
let xAxis = NSBezierPath()
xAxis.moveToPoint(NSMakePoint(0, self.bounds.height/2))
xAxis.lineToPoint(NSPoint(x: self.bounds.width, y: self.bounds.height/2))
xAxis.lineWidth = 1
xAxis.stroke()
let width = Double(self.bounds.width)
let height = Double(self.bounds.height)
let numBars = 20
let bar = NSBezierPath()
NSColor.blackColor().set()
bar.lineWidth = 1;
// // Draw Horizontal bars
// for(var i = 1; i <= numBars; i++){
// var x = CGFloat(Double(i)*width / Double(numBars))
// var y = CGFloat(height/2)
// bar.moveToPoint(NSMakePoint(x,y-2))
// bar.lineToPoint(NSMakePoint(x, y+2))
// bar.stroke()
// }
//
// // Draw Vertical bars
// for(var i = 1; i <= numBars; i++){
// var x = CGFloat(width/2)
// var y = CGFloat(Double(i)*height / Double(numBars))
// bar.moveToPoint(NSMakePoint(x-2, y))
// bar.lineToPoint(NSMakePoint(x+2, y))
// bar.stroke()
// }
}
override func mouseDown(theEvent: NSEvent) {
super.mouseDown(theEvent)
let x: CGFloat = theEvent.locationInWindow.x - offset
let y: CGFloat = theEvent.locationInWindow.y - offset
teamRed.append((x,y))
needsDisplay = true
}
override func rightMouseDown(theEvent: NSEvent) {
super.rightMouseDown(theEvent)
let x: CGFloat = theEvent.locationInWindow.x - offset
let y: CGFloat = theEvent.locationInWindow.y - offset
teamBlue.append((x,y))
needsDisplay = true
}
func drawBoundary(w0: CGFloat, w1: CGFloat, w2: CGFloat){
self.w0.append(w0)
self.w1.append(w1)
self.w2.append(w2)
drawBoundary = true
needsDisplay = true
}
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
setGrid()
if clearCanvas {
w0 = []
w1 = []
w2 = []
lastw0 = 0.0
lastw1 = 0.0
lastw2 = 0.0
clearCanvas = false
return
}
// Draw boundary line
var cross: NSBezierPath
if 0 < w0.count {
lineDrawn = true
let w0 = self.w0.removeAtIndex(0)
let w1 = self.w1.removeAtIndex(0)
let w2 = self.w2.removeAtIndex(0)
lastw0 = w0
lastw1 = w1
lastw2 = w2
NSColor.greenColor().set()
cross = NSBezierPath()
cross.lineWidth = 1
let source: CGFloat = -w0 * bounds.height / w2
let dest: CGFloat = -w0 * bounds.height / w2 - w1 * bounds.height / w2
// let dest: CGFloat = -w0 * bounds.height / w2 - bounds.width * w1 * bounds.height / w2 / bounds.width
cross.moveToPoint(NSMakePoint(CGFloat(0.0), source))
cross.lineToPoint(NSMakePoint(CGFloat(bounds.width), dest))
cross.stroke()
cross.closePath()
} else if lineDrawn && lastw0 != 0.0 && lastw1 != 0.0 && lastw2 != 0.0 {
let w0 = lastw0
let w1 = lastw1
let w2 = lastw2
NSColor.greenColor().set()
cross = NSBezierPath()
cross.lineWidth = 1
let source: CGFloat = -w0 * bounds.height / w2
let dest: CGFloat = -w0 * bounds.height / w2 - w1 * bounds.height / w2
// let dest: CGFloat = -w0 * bounds.height / w2 - bounds.width * w1 * bounds.height / w2 / bounds.width
cross.moveToPoint(NSMakePoint(CGFloat(0.0), source))
cross.lineToPoint(NSMakePoint(CGFloat(bounds.width), dest))
cross.stroke()
cross.closePath()
}
// Draw Points
NSColor.redColor().setStroke()
for (x,y) in teamRed {
cross = NSBezierPath()
cross.lineWidth = 3
cross.moveToPoint(NSMakePoint(x-line, y))
cross.lineToPoint(NSMakePoint(x+line, y))
cross.stroke()
cross.moveToPoint(NSMakePoint(x, y-line))
cross.lineToPoint(NSMakePoint(x, y+line))
cross.stroke()
cross.closePath()
}
NSColor.blueColor().setStroke()
for (x,y) in teamBlue {
cross = NSBezierPath()
cross.lineWidth = 3
cross.moveToPoint(NSMakePoint(x-line, y))
cross.lineToPoint(NSMakePoint(x+line, y))
cross.stroke()
cross.moveToPoint(NSMakePoint(x, y-line))
cross.lineToPoint(NSMakePoint(x, y+line))
cross.stroke()
cross.closePath()
}
}
}
| mit | bfe9ca5cf866a6db9c24204ebc44b744 | 25.02682 | 128 | 0.500957 | 4.253601 | false | false | false | false |
wireapp/wire-ios | Wire-iOS Tests/Utils/XCTestCase+ImageFromBundle.swift | 1 | 1985 | //
// Wire
// Copyright (C) 2018 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 XCTest
extension XCTestCase {
func dataInTestBundleNamed(_ name: String) -> Data {
return try! Data(contentsOf: urlForResource(inTestBundleNamed: name))
}
func image(inTestBundleNamed name: String) -> UIImage {
return UIImage(contentsOfFile: urlForResource(inTestBundleNamed: name).path)!
}
func urlForResource(inTestBundleNamed name: String) -> URL {
let bundle = Bundle(for: type(of: self))
let url = bundle.url(forResource: name, withExtension: "")
if let isFileURL = url?.isFileURL {
XCTAssert(isFileURL)
} else {
XCTFail("\(name) does not exist")
}
return url!
}
var mockImageData: Data {
return image(inTestBundleNamed: "unsplash_matterhorn.jpg").jpegData(compressionQuality: 0.9)!
}
}
extension UIImage {
public convenience init?(inTestBundleNamed name: String,
for aClass: AnyClass) {
let bundle = Bundle(for: aClass)
let url = bundle.url(forResource: name, withExtension: "")
if let isFileURL = url?.isFileURL {
XCTAssert(isFileURL)
} else {
XCTFail("\(name) does not exist")
}
self.init(contentsOfFile: url!.path)!
}
}
| gpl-3.0 | affe96485f995ab5fdc9662832f91873 | 28.626866 | 101 | 0.653904 | 4.605568 | false | true | false | false |
frootloops/swift | stdlib/public/SDK/Foundation/NSRange.swift | 2 | 7638 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
extension NSRange : Hashable {
public var hashValue: Int {
#if arch(i386) || arch(arm)
return Int(bitPattern: (UInt(bitPattern: location) | (UInt(bitPattern: length) << 16)))
#elseif arch(x86_64) || arch(arm64)
return Int(bitPattern: (UInt(bitPattern: location) | (UInt(bitPattern: length) << 32)))
#endif
}
public static func==(_ lhs: NSRange, _ rhs: NSRange) -> Bool {
return lhs.location == rhs.location && lhs.length == rhs.length
}
}
extension NSRange : CustomStringConvertible, CustomDebugStringConvertible {
public var description: String { return "{\(location), \(length)}" }
public var debugDescription: String {
guard location != NSNotFound else {
return "{NSNotFound, \(length)}"
}
return "{\(location), \(length)}"
}
}
extension NSRange {
public init?(_ string: String) {
var savedLocation = 0
if string.isEmpty {
// fail early if the string is empty
return nil
}
let scanner = Scanner(string: string)
let digitSet = CharacterSet.decimalDigits
let _ = scanner.scanUpToCharacters(from: digitSet, into: nil)
if scanner.isAtEnd {
// fail early if there are no decimal digits
return nil
}
var location = 0
savedLocation = scanner.scanLocation
guard scanner.scanInt(&location) else {
return nil
}
if scanner.isAtEnd {
// return early if there are no more characters after the first int in the string
return nil
}
if scanner.scanString(".", into: nil) {
scanner.scanLocation = savedLocation
var double = 0.0
guard scanner.scanDouble(&double) else {
return nil
}
guard let integral = Int(exactly: double) else {
return nil
}
location = integral
}
let _ = scanner.scanUpToCharacters(from: digitSet, into: nil)
if scanner.isAtEnd {
// return early if there are no integer characters after the first int in the string
return nil
}
var length = 0
savedLocation = scanner.scanLocation
guard scanner.scanInt(&length) else {
return nil
}
if !scanner.isAtEnd {
if scanner.scanString(".", into: nil) {
scanner.scanLocation = savedLocation
var double = 0.0
guard scanner.scanDouble(&double) else {
return nil
}
guard let integral = Int(exactly: double) else {
return nil
}
length = integral
}
}
self.init(location: location, length: length)
}
}
extension NSRange {
public var lowerBound: Int { return location }
public var upperBound: Int { return location + length }
public func contains(_ index: Int) -> Bool { return (!(index < location) && (index - location) < length) }
public mutating func formUnion(_ other: NSRange) {
self = union(other)
}
public func union(_ other: NSRange) -> NSRange {
let max1 = location + length
let max2 = other.location + other.length
let maxend = (max1 < max2) ? max2 : max1
let minloc = location < other.location ? location : other.location
return NSRange(location: minloc, length: maxend - minloc)
}
public func intersection(_ other: NSRange) -> NSRange? {
let max1 = location + length
let max2 = other.location + other.length
let minend = (max1 < max2) ? max1 : max2
if other.location <= location && location < max2 {
return NSRange(location: location, length: minend - location)
} else if location <= other.location && other.location < max1 {
return NSRange(location: other.location, length: minend - other.location);
}
return nil
}
}
//===----------------------------------------------------------------------===//
// Ranges
//===----------------------------------------------------------------------===//
extension NSRange {
public init<R: RangeExpression>(_ region: R)
where R.Bound: FixedWidthInteger, R.Bound.Stride : SignedInteger {
let r = region.relative(to: 0..<R.Bound.max)
self.init(location: numericCast(r.lowerBound), length: numericCast(r.count))
}
public init<R: RangeExpression, S: StringProtocol>(_ region: R, in target: S)
where R.Bound == S.Index, S.Index == String.Index {
let r = region.relative(to: target)
self = NSRange(
location: r.lowerBound.encodedOffset - target.startIndex.encodedOffset,
length: r.upperBound.encodedOffset - r.lowerBound.encodedOffset
)
}
@available(swift, deprecated: 4, renamed: "Range.init(_:)")
public func toRange() -> Range<Int>? {
if location == NSNotFound { return nil }
return location..<(location+length)
}
}
extension Range where Bound: BinaryInteger {
public init?(_ range: NSRange) {
guard range.location != NSNotFound else { return nil }
self.init(uncheckedBounds: (numericCast(range.lowerBound), numericCast(range.upperBound)))
}
}
// This additional overload will mean Range.init(_:) defaults to Range<Int> when
// no additional type context is provided:
extension Range where Bound == Int {
public init?(_ range: NSRange) {
guard range.location != NSNotFound else { return nil }
self.init(uncheckedBounds: (range.lowerBound, range.upperBound))
}
}
extension Range where Bound == String.Index {
public init?(_ range: NSRange, in string: String) {
let u = string.utf16
guard range.location != NSNotFound,
let start = u.index(u.startIndex, offsetBy: range.location, limitedBy: u.endIndex),
let end = u.index(u.startIndex, offsetBy: range.location + range.length, limitedBy: u.endIndex),
let lowerBound = String.Index(start, within: string),
let upperBound = String.Index(end, within: string)
else { return nil }
self = lowerBound..<upperBound
}
}
extension NSRange : CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: ["location": location, "length": length])
}
}
extension NSRange : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .range(Int64(location), Int64(length))
}
}
extension NSRange : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
let location = try container.decode(Int.self)
let length = try container.decode(Int.self)
self.init(location: location, length: length)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try container.encode(self.location)
try container.encode(self.length)
}
}
| apache-2.0 | 66957291e585e2e1ff29d48c5f9a47fe | 33.876712 | 110 | 0.593873 | 4.738213 | false | false | false | false |
YaoJuan/YJDouYu | YJDouYu/YJDouYu/Classes/Tool/UIBarButtonItem + Extension.swift | 1 | 751 | //
// UIBarButtonItem + Extension.swift
// YJDouYu
//
// Created by 赵思 on 2017/7/29.
// Copyright © 2017年 赵思. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
convenience init(normalImage: UIImage, highlightImage: UIImage?, size: CGSize = CGSize.zero) {
// 1. 设置按钮内容
let btn = UIButton()
btn.setImage(normalImage, for: .normal)
if let hImage = highlightImage {
btn.setImage(hImage, for: .highlighted)
}
// 2. 设置按钮尺寸
if size == CGSize.zero {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
self.init(customView: btn)
}
}
| mit | 9dc116f959c8ba360bce9791a9df7aa5 | 23.689655 | 98 | 0.565642 | 4 | false | false | false | false |
donmichael41/helloVapor | Sources/App/Controllers/TimeKeeper.swift | 1 | 401 | import Foundation
var dateFormater: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm:ssss a z 'on' EEEE, MMMM dd, y"
formatter.timeZone = TimeZone(abbreviation: "ICT")
return formatter
}()
final class TimeKeeper {
var systemTime: () -> String = {
let current = Date()
return dateFormater.string(from: current)
}
}
| mit | b5dff58c7fc4aae7a2b7c196d4612aab | 22.588235 | 65 | 0.633416 | 4.265957 | false | false | false | false |
tempodox/ComposedParsing | ComposedParsing/main.swift | 1 | 2080 | /* ———————————————————————————————————————————————————————————————————————— *
*
* main.swift
* ~~~~~~~~~~
*
* Demo for ComposedParsing
*
* Project: ComposedParsing
*
* File encoding: UTF-8
*
* Created 2014·06·26: Ulrich Singer
*/
import Foundation
let arithmetic = Parser(terminals:["+", "-", "*", "/", "%", "Num", "(", ")"])
arithmetic.rule("expr", parses: "sum")
arithmetic.rule("sum", parses: "mul" &> "sumTail")
arithmetic.rule("sumTail", parses:
"+" &> "mul"
&> { $ in ($(0) as! NSNumber).doubleValue + ($(2) as! NSNumber).doubleValue }
&> "sumTail"
|> "-" &> "mul"
&> { $ in ($(0) as! NSNumber).doubleValue - ($(2) as! NSNumber).doubleValue }
&> "sumTail"
|> { $ in $(0) })
arithmetic.rule("mul", parses: "sgn" &> "mulTail")
arithmetic.rule("mulTail", parses:
"*" &> "sgn"
&> { $ in ($(0) as! NSNumber).doubleValue * ($(2) as! NSNumber).doubleValue }
&> "mulTail"
|> "/" &> "sgn"
&> { $ in ($(0) as! NSNumber).doubleValue / ($(2) as! NSNumber).doubleValue }
&> "mulTail"
|> "%" &> "sgn"
&> { $ in ($(0) as! NSNumber).doubleValue % ($(2) as! NSNumber).doubleValue }
&> "mulTail"
|> { $ in $(0) })
arithmetic.rule("sgn", parses:
"-" &> "sgn" &> { $ in -($(2) as! NSNumber).doubleValue }
|> "+" &> "sgn" &> { $ in +($(2) as! NSNumber).doubleValue }
|> "term")
arithmetic.rule("term", parses:
"(" &> "expr" &> ")" &> { $ in $(2) }
|> "Num")
let tokenSource = ArrayLexer(tokens:[("(",""),("Num",6),("-",""),("Num",1),(")",""), ("/",""), ("+",""),("Num",2), ("/",""), ("-",""),("Num",2)])
var rule = "expr"<!
var val: Parser.Result
let t0 = NSDate()
for _ in 1...1000
{
val = arithmetic.start(rule, tokenSource)
tokenSource.reset()
}
let t1 = NSDate()
let dt = t1.timeIntervalSinceDate(t0)
print("∆t = \(dt) s\n\(val!)")
/* ~ main.swift ~ */ | mit | 59700768b65aab6ae80d21bdccdf373d | 24.434211 | 145 | 0.465321 | 3.274576 | false | false | false | false |
thankmelater23/relliK | relliK/GlobalsAndConstants.swift | 1 | 6708 | //
// GlobalsAndConstants.swift
// Color Wars
//
// Created by Andre Villanueva on 6/3/15.
// Copyright (c) 2015 BangBangStudios. All rights reserved.
//
import Foundation
import SpriteKit
/// Amount of seconds in a day 86,400
let SecondsInADay = 86400
enum entityDirection {
case left
case right
case up
case down
case unSelected
}
enum blockPlace: Int {
case home = 1
case first = 2
case second = 3
case third = 4
case fourth = 5
case fifth = 6
case unSelected = 7
}
enum blockLabel: Int {
case empty
case enemy
case player
case bullet
}
struct PhysicsCategory {
static let All: UInt32 = 0x1 << 0
static let Player: UInt32 = 0x1 << 1
static let Enemy: UInt32 = 0x1 << 2
static let Bullet: UInt32 = 0x1 << 3
static let dead: UInt32 = 0x1 << 30
static let None: UInt32 = 0x1 << 29
}
struct BitMaskOfLighting {
static let None: UInt32 = 0x1 << 0
static let right: UInt32 = 0x1 << 1
static let left: UInt32 = 0x1 << 2
static let down: UInt32 = 0x1 << 3
static let up: UInt32 = 0x1 << 4
}
let GAME_MIN_SPEED: TimeInterval = TimeInterval(1.0)
let GAME_MAX_SPEED: TimeInterval = TimeInterval(0.5)
let enemyWaitMinSpeed: TimeInterval = TimeInterval(1.0)
let enemyWaitMaxSpeed: TimeInterval = TimeInterval(0.1)
//Scales
let playerScale: CGFloat = 0.35
let enemyScale: CGFloat = 0.20
let playerBlockScale: CGFloat = 0.35
let enemyBlockScale: CGFloat = 0.25
let bulletScale: CGFloat = 0.40
//Sizes
///Space between blocks and character
var spaceBetweenEnemyBlock: CGFloat = 85.00
///Space between each block
var incrementalSpaceBetweenBlocks: CGFloat = 55.00
var spaceToLastBox: CGFloat = incrementalSpaceBetweenBlocks * 4
var gameSpeed: TimeInterval = GAME_MIN_SPEED
let gameIncrementalSpeed: TimeInterval = (GAME_MIN_SPEED - GAME_MAX_SPEED) * 0.10 //GAME_MIN_SPEED / NSTimeInterval(4.0)
//Time Vars
let enemyWaitIncrementalSpeed: TimeInterval = (enemyWaitMinSpeed - enemyWaitMaxSpeed) * 0.10 //gameIncrementalSpeed * 2 //enemyWaitMinSpeed / NSTimeInterval(4.0)
var enemyWaitTime: TimeInterval = enemyWaitMinSpeed
var bulletCoolDownTime: TimeInterval = 0.1 //GAME_MAX_SPEED
var bulletCurrentCoolDownTime: TimeInterval = bulletCoolDownTime
var lastShot: TimeInterval = TimeInterval(0.0)
var gameTotalSpeed: TimeInterval = gameSpeed + enemyWaitTime
/// String thats used for sharing feature
let ShareLink = """
**************************************
Check out relliK #App for your Apple Device. Download it #FREE today!***CLICK THE LINK***
**************************************
#2DGame #Shooter #Arcade #2018 #IOSApp #BangBangStudios #relliK
**************************************
http://BangBangStudios.com/relliK
"""
// MARK: - GCD
/// First, the system provides you with a special serial queue known as the main queue. Like any serial queue, tasks in this queue execute one at a time. However, it’s guaranteed that all tasks will execute on the main thread, which is the only thread allowed to update your UI. This queue is the one to use for sending messages to UIView objects or posting notifications.
let GlobalMainQueue = DispatchQueue.main
/// QOS_CLASS_USER_INTERACTIVE: The user interactive class represents tasks that need to be done immediately in order to provide a nice user experience. Use it for UI updates, event handling and small workloads that require low latency. The total amount of work done in this class during the execution of your app should be small.
let GlobalUserInteractiveQueue = DispatchQueue(label: "com.userInteractive", qos: .userInteractive, attributes: DispatchQueue.Attributes.concurrent)
/// QOS_CLASS_USER_INITIATED: The user initiated class represents tasks that are initiated from the UI and can be performed asynchronously. It should be used when the user is waiting for immediate results, and for tasks required to continue user interaction.
let GlobalUserInitiatedQueue = DispatchQueue(label: "com.userInitiated", qos: .userInitiated, attributes: .concurrent)
/// QOS_CLASS_UTILITY: The utility class represents long-running tasks, typically with a user-visible progress indicator. Use it for computations, I/O, networking, continous data feeds and similar tasks. This class is designed to be energy efficient.
let GlobalUtilityQueue = DispatchQueue(label: "com.Utility", qos: .utility, attributes: .concurrent)
/// QOS_CLASS_BACKGROUND: The background class represents tasks that the user is not directly aware of. Use it for prefetching, maintenance, and other tasks that don’t require user interaction and aren’t time-sensitive.
let GlobalBackgroundQueue = DispatchQueue(label: "com.background", qos: .background, attributes: .concurrent)
/// Custom concurrent Belize Lottery Background Queue
let GlobalRellikConcurrent = DispatchQueue(label: "com.Rellik.Concurrent", attributes: .concurrent)
/// Custom serial Belize Lottery Background Queue
let GlobalRellikSerial = DispatchQueue(label: "com.Rellik.Serial")
/// Custom Serial Belize Lottery Background DataTransform Queue
let GlobalRellikDataTransformSerial = DispatchQueue(label: "com.Rellik.Serial.DataTransform")
/// Custom Serial Belize Lottery Background Database Queue
let GlobalRellikDataBaseSerial = DispatchQueue(label: "com.Rellik.Serial.DataBase")
/// Custom Serial Belize Lottery Background Network Queue
let GlobalRellikNetworkSerial = DispatchQueue(label: "com.Rellik.Serial.Network")
/// Custom Serial Belize Lottery Background Network Queue
let GlobalRellikSFXConcurrent = DispatchQueue(label: "com.Rellik.Concurrent.Network", qos: .userInitiated, attributes: .concurrent)
let GlobalRellikGameLoopConcurrent = DispatchQueue(label: "com.Rellik.Concurrent.GameLoop", qos: .userInitiated, attributes: .concurrent)
let GlobalRellikGameLoopSerial = DispatchQueue(label: "com.Rellik.Serial.GameLoop")
let GlobalRellikBulletConcurrent = DispatchQueue(label: "com.Rellik.Concurrent.Bullet", qos: .userInitiated, attributes: .concurrent)
let GlobalRellikBulletSerial = DispatchQueue(label: "com.Rellik.Serial.Bullet")
let GlobalRellikEnemyConcurrent = DispatchQueue(label: "com.Rellik.Concurrent.Enemy", qos: .userInitiated, attributes: .concurrent)
let GlobalRellikEnemySerial = DispatchQueue(label: "com.Rellik.Serial.Enemy")
let GlobalRellikPlayerConcurrent = DispatchQueue(label: "com.Rellik.Concurrent.Player", qos: .userInitiated, attributes: .concurrent)
let GlobalRellikPlayerSerial = DispatchQueue(label: "com.Rellik.Serial.Player")
///MARK: - Dispatch Groups
let GameLoadGroup = DispatchGroup()
| unlicense | 499eb46cf01201cacc07807e9e512742 | 50.160305 | 374 | 0.740674 | 4.293402 | false | false | false | false |
apple/swift-driver | Sources/SwiftDriver/Driver/ToolExecutionDelegate.swift | 1 | 13125 | //===--------------- ToolExecutionDelegate.swift - Tool Execution Delegate ===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if canImport(Darwin)
import Darwin.C
#elseif os(Windows)
import ucrt
import WinSDK
#elseif canImport(Glibc)
import Glibc
#else
#error("Missing libc or equivalent")
#endif
import TSCBasic // <<<
import class TSCBasic.DiagnosticsEngine
import struct TSCBasic.Diagnostic
import struct TSCBasic.ProcessResult
import var TSCBasic.stderrStream
import var TSCBasic.stdoutStream
/// Delegate for printing execution information on the command-line.
@_spi(Testing) public final class ToolExecutionDelegate: JobExecutionDelegate {
/// Quasi-PIDs are _negative_ PID-like unique keys used to
/// masquerade batch job constituents as (quasi)processes, when writing
/// parseable output to consumers that don't understand the idea of a batch
/// job. They are negative in order to avoid possibly colliding with real
/// PIDs (which are always positive). We start at -1000 here as a crude but
/// harmless hedge against colliding with an errno value that might slip
/// into the stream of real PIDs.
static let QUASI_PID_START = -1000
public enum Mode {
case verbose
case parsableOutput
case regular
case silent
}
public let mode: Mode
public let buildRecordInfo: BuildRecordInfo?
public let showJobLifecycle: Bool
public let diagnosticEngine: DiagnosticsEngine
public var anyJobHadAbnormalExit: Bool = false
private var nextBatchQuasiPID: Int
private let argsResolver: ArgsResolver
private var batchJobInputQuasiPIDMap = TwoLevelMap<Job, TypedVirtualPath, Int>()
@_spi(Testing) public init(mode: ToolExecutionDelegate.Mode,
buildRecordInfo: BuildRecordInfo?,
showJobLifecycle: Bool,
argsResolver: ArgsResolver,
diagnosticEngine: DiagnosticsEngine) {
self.mode = mode
self.buildRecordInfo = buildRecordInfo
self.showJobLifecycle = showJobLifecycle
self.diagnosticEngine = diagnosticEngine
self.argsResolver = argsResolver
self.nextBatchQuasiPID = ToolExecutionDelegate.QUASI_PID_START
}
public func jobStarted(job: Job, arguments: [String], pid: Int) {
if showJobLifecycle {
diagnosticEngine.emit(.remark_job_lifecycle("Starting", job))
}
switch mode {
case .regular, .silent:
break
case .verbose:
stdoutStream <<< arguments.map { $0.spm_shellEscaped() }.joined(separator: " ") <<< "\n"
stdoutStream.flush()
case .parsableOutput:
let messages = constructJobBeganMessages(job: job, arguments: arguments, pid: pid)
for beganMessage in messages {
emit(ParsableMessage(name: job.kind.rawValue, kind: .began(beganMessage)))
}
}
}
public func jobFinished(job: Job, result: ProcessResult, pid: Int) {
if showJobLifecycle {
diagnosticEngine.emit(.remark_job_lifecycle("Finished", job))
}
buildRecordInfo?.jobFinished(job: job, result: result)
#if os(Windows)
if case .abnormal = result.exitStatus {
anyJobHadAbnormalExit = true
}
#else
if case .signalled = result.exitStatus {
anyJobHadAbnormalExit = true
}
#endif
switch mode {
case .silent:
break
case .regular, .verbose:
let output = (try? result.utf8Output() + result.utf8stderrOutput()) ?? ""
if !output.isEmpty {
Driver.stdErrQueue.sync {
stderrStream <<< output
stderrStream.flush()
}
}
case .parsableOutput:
let output = (try? result.utf8Output() + result.utf8stderrOutput()).flatMap { $0.isEmpty ? nil : $0 }
let messages: [ParsableMessage]
switch result.exitStatus {
case .terminated(let code):
messages = constructJobFinishedMessages(job: job, exitCode: code, output: output,
pid: pid).map {
ParsableMessage(name: job.kind.rawValue, kind: .finished($0))
}
#if os(Windows)
case .abnormal(let exception):
messages = constructAbnormalExitMessage(job: job, output: output,
exception: exception, pid: pid).map {
ParsableMessage(name: job.kind.rawValue, kind: .abnormal($0))
}
#else
case .signalled(let signal):
let errorMessage = strsignal(signal).map { String(cString: $0) } ?? ""
messages = constructJobSignalledMessages(job: job, error: errorMessage, output: output,
signal: signal, pid: pid).map {
ParsableMessage(name: job.kind.rawValue, kind: .signalled($0))
}
#endif
}
for message in messages {
emit(message)
}
}
}
public func jobSkipped(job: Job) {
if showJobLifecycle {
diagnosticEngine.emit(.remark_job_lifecycle("Skipped", job))
}
switch mode {
case .regular, .verbose, .silent:
break
case .parsableOutput:
let skippedMessage = SkippedMessage(inputs: job.displayInputs.map{ $0.file.name })
let message = ParsableMessage(name: job.kind.rawValue, kind: .skipped(skippedMessage))
emit(message)
}
}
private func emit(_ message: ParsableMessage) {
// FIXME: Do we need to do error handling here? Can this even fail?
guard let json = try? message.toJSON() else { return }
Driver.stdErrQueue.sync {
stderrStream <<< json.count <<< "\n"
stderrStream <<< String(data: json, encoding: .utf8)! <<< "\n"
stderrStream.flush()
}
}
}
// MARK: - Message Construction
/// Generation of messages from jobs, including breaking down batch compile jobs into constituent messages.
private extension ToolExecutionDelegate {
// MARK: - Job Began
func constructJobBeganMessages(job: Job, arguments: [String], pid: Int) -> [BeganMessage] {
let result : [BeganMessage]
if job.kind == .compile,
job.primaryInputs.count > 1 {
// Batched compile jobs need to be broken up into multiple messages, one per constituent.
result = constructBatchCompileBeginMessages(job: job, arguments: arguments, pid: pid,
quasiPIDBase: nextBatchQuasiPID)
// Today, parseable-output messages are constructed and emitted synchronously
// on `MultiJobExecutor`'s `delegateQueue`. This is why the below operation is safe.
nextBatchQuasiPID -= result.count
} else {
result = [constructSingleBeganMessage(inputs: job.displayInputs,
outputs: job.outputs,
arguments: arguments,
pid: pid,
realPid: pid)]
}
return result
}
func constructBatchCompileBeginMessages(job: Job, arguments: [String], pid: Int,
quasiPIDBase: Int) -> [BeganMessage] {
precondition(job.kind == .compile && job.primaryInputs.count > 1)
var quasiPID = quasiPIDBase
var result : [BeganMessage] = []
for input in job.primaryInputs {
let outputs = job.getCompileInputOutputs(for: input) ?? []
let outputPaths = outputs.map {
TypedVirtualPath(file: try! VirtualPath.intern(path: argsResolver.resolve(.path($0.file))),
type: $0.type)
}
result.append(
constructSingleBeganMessage(inputs: [input],
outputs: outputPaths,
arguments: arguments,
pid: quasiPID,
realPid: pid))
// Save the quasiPID of this job/input combination in order to generate the correct
// `finished` message
batchJobInputQuasiPIDMap[(job, input)] = quasiPID
quasiPID -= 1
}
return result
}
func constructSingleBeganMessage(inputs: [TypedVirtualPath], outputs: [TypedVirtualPath],
arguments: [String], pid: Int, realPid: Int) -> BeganMessage {
let outputs: [BeganMessage.Output] = outputs.map {
.init(path: $0.file.name, type: $0.type.description)
}
return BeganMessage(
pid: pid,
realPid: realPid,
inputs: inputs.map{ $0.file.name },
outputs: outputs,
commandExecutable: arguments[0],
commandArguments: arguments[1...].map { String($0) }
)
}
// MARK: - Job Finished
func constructJobFinishedMessages(job: Job, exitCode: Int32, output: String?, pid: Int)
-> [FinishedMessage] {
let result : [FinishedMessage]
if job.kind == .compile,
job.primaryInputs.count > 1 {
result = constructBatchCompileFinishedMessages(job: job, exitCode: exitCode,
output: output, pid: pid)
} else {
result = [constructSingleFinishedMessage(exitCode: exitCode, output: output,
pid: pid, realPid: pid)]
}
return result
}
func constructBatchCompileFinishedMessages(job: Job, exitCode: Int32, output: String?, pid: Int)
-> [FinishedMessage] {
precondition(job.kind == .compile && job.primaryInputs.count > 1)
var result : [FinishedMessage] = []
for input in job.primaryInputs {
guard let quasiPid = batchJobInputQuasiPIDMap[(job, input)] else {
fatalError("Parsable-Output batch sub-job finished with no matching started message: \(job.description) : \(input.file.description)")
}
result.append(
constructSingleFinishedMessage(exitCode: exitCode, output: output,
pid: quasiPid, realPid: pid))
}
return result
}
func constructSingleFinishedMessage(exitCode: Int32, output: String?, pid: Int, realPid: Int)
-> FinishedMessage {
return FinishedMessage(exitStatus: Int(exitCode), output: output, pid: pid, realPid: realPid)
}
// MARK: - Abnormal Exit
func constructAbnormalExitMessage(job: Job, output: String?, exception: UInt32, pid: Int) -> [AbnormalExitMessage] {
let result: [AbnormalExitMessage]
if job.kind == .compile, job.primaryInputs.count > 1 {
result = job.primaryInputs.map {
guard let quasiPid = batchJobInputQuasiPIDMap[(job, $0)] else {
fatalError("Parsable-Output batch sub-job abnormal exit with no matching started message: \(job.description): \($0.file.description)")
}
return AbnormalExitMessage(pid: quasiPid, realPid: pid, output: output, exception: exception)
}
} else {
result = [AbnormalExitMessage(pid: pid, realPid: pid, output: output, exception: exception)]
}
return result
}
// MARK: - Job Signalled
func constructJobSignalledMessages(job: Job, error: String, output: String?,
signal: Int32, pid: Int) -> [SignalledMessage] {
let result : [SignalledMessage]
if job.kind == .compile,
job.primaryInputs.count > 1 {
result = constructBatchCompileSignalledMessages(job: job, error: error, output: output,
signal: signal, pid: pid)
} else {
result = [constructSingleSignalledMessage(error: error, output: output, signal: signal,
pid: pid, realPid: pid)]
}
return result
}
func constructBatchCompileSignalledMessages(job: Job, error: String, output: String?,
signal: Int32, pid: Int)
-> [SignalledMessage] {
precondition(job.kind == .compile && job.primaryInputs.count > 1)
var result : [SignalledMessage] = []
for input in job.primaryInputs {
guard let quasiPid = batchJobInputQuasiPIDMap[(job, input)] else {
fatalError("Parsable-Output batch sub-job signalled with no matching started message: \(job.description) : \(input.file.description)")
}
result.append(
constructSingleSignalledMessage(error: error, output: output, signal: signal,
pid: quasiPid, realPid: pid))
}
return result
}
func constructSingleSignalledMessage(error: String, output: String?, signal: Int32,
pid: Int, realPid: Int)
-> SignalledMessage {
return SignalledMessage(pid: pid, realPid: realPid, output: output,
errorMessage: error, signal: Int(signal))
}
}
fileprivate extension Diagnostic.Message {
static func remark_job_lifecycle(_ what: String, _ job: Job
) -> Diagnostic.Message {
.remark("\(what) \(job.descriptionForLifecycle)")
}
}
| apache-2.0 | d2a8d1fb38dae57372b4a115ce460a25 | 37.716814 | 144 | 0.625067 | 4.704301 | false | false | false | false |
mlpqaz/V2ex | ZZV2ex/ZZV2ex/View/Control/NotificationMenuButton.swift | 1 | 1128 | //
// NotificationMenuButton.swift
// ZZV2ex
//
// Created by ios on 2017/4/29.
// Copyright © 2017年 张璋. All rights reserved.
//
import UIKit
import SnapKit
class NotificationMenuButton: UIButton {
var aPointImageView:UIImageView?
required init() {
super.init(frame: CGRect.zero)
self.contentMode = .center
self.imageEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0)
self.setImage(UIImage.imageUserdTemplateMode("ic_menu_36pt"), for: UIControlState())
self.aPointImageView = UIImageView()
self.aPointImageView!.backgroundColor = UIColor.blue
self.aPointImageView!.layer.cornerRadius = 4
self.aPointImageView!.layer.masksToBounds = true
self.addSubview(self.aPointImageView!)
self.aPointImageView!.snp.makeConstraints{ (make) -> Void in
make.width.height.equalTo(8)
make.top.equalTo(self).offset(3)
make.right.equalTo(self).offset(-6)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 93098e7bc1be4ce58cc8c5336bae25a0 | 27.025 | 92 | 0.642284 | 4.278626 | false | false | false | false |
jatinpandey/Tweeter | tweeter/ComposeViewController.swift | 1 | 2662 | //
// ComposeViewController.swift
// tweeter
//
// Created by Jatin Pandey on 9/25/14.
// Copyright (c) 2014 Jatin Pandey. All rights reserved.
//
import UIKit
class ComposeViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var posterName: UILabel!
@IBOutlet weak var chars: UILabel!
@IBOutlet weak var tView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
posterName.text = "@\(User.currentUser!.screenName)"
tView.delegate = self
tView.layer.borderColor = UIColor.blueColor().CGColor
tView.layer.borderWidth = 2
}
func textViewDidChange(textView: UITextView) {
var tweetVal = tView.text as NSString
var currentLength = tweetVal.length
let charsLeft = 40 - currentLength
chars.text = "\(charsLeft)"
}
func textViewDidBeginEditing(textView: UITextView) {
tView.text = ""
tView.textColor = UIColor.blackColor()
}
@IBAction func onTapGoKeyboard(sender: AnyObject) {
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onClickCancel(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func onTweet(sender: AnyObject) {
if chars.text?.toInt() >= 0 {
var status = tView.text.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
println(status)
TwitterClient.sharedInstance.POST("1.1/statuses/update.json?status=\(status!)", parameters: nil, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
println(response)
self.dismissViewControllerAnimated(true, completion: nil)
}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
println("Error posting tweet")
})
}
else {
println("Too long")
let alert = UIAlertView(title: "Unable to post", message: "Make sure tweet is within 40 chars", delegate: self, cancelButtonTitle: "OK")
alert.show()
}
}
/*
// 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 | e6a66e32b7dff2142decf615d3dc0322 | 32.275 | 189 | 0.646131 | 4.957169 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/Lambda/Lambda_Shapes.swift | 1 | 178787 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import Foundation
import SotoCore
extension Lambda {
// MARK: Enums
public enum EventSourcePosition: String, CustomStringConvertible, Codable {
case atTimestamp = "AT_TIMESTAMP"
case latest = "LATEST"
case trimHorizon = "TRIM_HORIZON"
public var description: String { return self.rawValue }
}
public enum FunctionVersion: String, CustomStringConvertible, Codable {
case all = "ALL"
public var description: String { return self.rawValue }
}
public enum InvocationType: String, CustomStringConvertible, Codable {
case dryrun = "DryRun"
case event = "Event"
case requestresponse = "RequestResponse"
public var description: String { return self.rawValue }
}
public enum LastUpdateStatus: String, CustomStringConvertible, Codable {
case failed = "Failed"
case inprogress = "InProgress"
case successful = "Successful"
public var description: String { return self.rawValue }
}
public enum LastUpdateStatusReasonCode: String, CustomStringConvertible, Codable {
case enilimitexceeded = "EniLimitExceeded"
case insufficientrolepermissions = "InsufficientRolePermissions"
case internalerror = "InternalError"
case invalidconfiguration = "InvalidConfiguration"
case invalidsecuritygroup = "InvalidSecurityGroup"
case invalidsubnet = "InvalidSubnet"
case subnetoutofipaddresses = "SubnetOutOfIPAddresses"
public var description: String { return self.rawValue }
}
public enum LogType: String, CustomStringConvertible, Codable {
case none = "None"
case tail = "Tail"
public var description: String { return self.rawValue }
}
public enum ProvisionedConcurrencyStatusEnum: String, CustomStringConvertible, Codable {
case failed = "FAILED"
case inProgress = "IN_PROGRESS"
case ready = "READY"
public var description: String { return self.rawValue }
}
public enum Runtime: String, CustomStringConvertible, Codable {
case dotnetcore10 = "dotnetcore1.0"
case dotnetcore20 = "dotnetcore2.0"
case dotnetcore21 = "dotnetcore2.1"
case dotnetcore31 = "dotnetcore3.1"
case go1X = "go1.x"
case java11
case java8
case java8Al2 = "java8.al2"
case nodejs
case nodejs10X = "nodejs10.x"
case nodejs12X = "nodejs12.x"
case nodejs43 = "nodejs4.3"
case nodejs43Edge = "nodejs4.3-edge"
case nodejs610 = "nodejs6.10"
case nodejs810 = "nodejs8.10"
case provided
case providedAl2 = "provided.al2"
case python27 = "python2.7"
case python36 = "python3.6"
case python37 = "python3.7"
case python38 = "python3.8"
case ruby25 = "ruby2.5"
case ruby27 = "ruby2.7"
public var description: String { return self.rawValue }
}
public enum State: String, CustomStringConvertible, Codable {
case active = "Active"
case failed = "Failed"
case inactive = "Inactive"
case pending = "Pending"
public var description: String { return self.rawValue }
}
public enum StateReasonCode: String, CustomStringConvertible, Codable {
case creating = "Creating"
case enilimitexceeded = "EniLimitExceeded"
case idle = "Idle"
case insufficientrolepermissions = "InsufficientRolePermissions"
case internalerror = "InternalError"
case invalidconfiguration = "InvalidConfiguration"
case invalidsecuritygroup = "InvalidSecurityGroup"
case invalidsubnet = "InvalidSubnet"
case restoring = "Restoring"
case subnetoutofipaddresses = "SubnetOutOfIPAddresses"
public var description: String { return self.rawValue }
}
public enum TracingMode: String, CustomStringConvertible, Codable {
case active = "Active"
case passthrough = "PassThrough"
public var description: String { return self.rawValue }
}
// MARK: Shapes
public struct AccountLimit: AWSDecodableShape {
/// The maximum size of a function's deployment package and layers when they're extracted.
public let codeSizeUnzipped: Int64?
/// The maximum size of a deployment package when it's uploaded directly to AWS Lambda. Use Amazon S3 for larger files.
public let codeSizeZipped: Int64?
/// The maximum number of simultaneous function executions.
public let concurrentExecutions: Int?
/// The amount of storage space that you can use for all deployment packages and layer archives.
public let totalCodeSize: Int64?
/// The maximum number of simultaneous function executions, minus the capacity that's reserved for individual functions with PutFunctionConcurrency.
public let unreservedConcurrentExecutions: Int?
public init(codeSizeUnzipped: Int64? = nil, codeSizeZipped: Int64? = nil, concurrentExecutions: Int? = nil, totalCodeSize: Int64? = nil, unreservedConcurrentExecutions: Int? = nil) {
self.codeSizeUnzipped = codeSizeUnzipped
self.codeSizeZipped = codeSizeZipped
self.concurrentExecutions = concurrentExecutions
self.totalCodeSize = totalCodeSize
self.unreservedConcurrentExecutions = unreservedConcurrentExecutions
}
private enum CodingKeys: String, CodingKey {
case codeSizeUnzipped = "CodeSizeUnzipped"
case codeSizeZipped = "CodeSizeZipped"
case concurrentExecutions = "ConcurrentExecutions"
case totalCodeSize = "TotalCodeSize"
case unreservedConcurrentExecutions = "UnreservedConcurrentExecutions"
}
}
public struct AccountUsage: AWSDecodableShape {
/// The number of Lambda functions.
public let functionCount: Int64?
/// The amount of storage space, in bytes, that's being used by deployment packages and layer archives.
public let totalCodeSize: Int64?
public init(functionCount: Int64? = nil, totalCodeSize: Int64? = nil) {
self.functionCount = functionCount
self.totalCodeSize = totalCodeSize
}
private enum CodingKeys: String, CodingKey {
case functionCount = "FunctionCount"
case totalCodeSize = "TotalCodeSize"
}
}
public struct AddLayerVersionPermissionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "layerName", location: .uri(locationName: "LayerName")),
AWSMemberEncoding(label: "revisionId", location: .querystring(locationName: "RevisionId")),
AWSMemberEncoding(label: "versionNumber", location: .uri(locationName: "VersionNumber"))
]
/// The API action that grants access to the layer. For example, lambda:GetLayerVersion.
public let action: String
/// The name or Amazon Resource Name (ARN) of the layer.
public let layerName: String
/// With the principal set to *, grant permission to all accounts in the specified organization.
public let organizationId: String?
/// An account ID, or * to grant permission to all AWS accounts.
public let principal: String
/// Only update the policy if the revision ID matches the ID specified. Use this option to avoid modifying a policy that has changed since you last read it.
public let revisionId: String?
/// An identifier that distinguishes the policy from others on the same layer version.
public let statementId: String
/// The version number.
public let versionNumber: Int64
public init(action: String, layerName: String, organizationId: String? = nil, principal: String, revisionId: String? = nil, statementId: String, versionNumber: Int64) {
self.action = action
self.layerName = layerName
self.organizationId = organizationId
self.principal = principal
self.revisionId = revisionId
self.statementId = statementId
self.versionNumber = versionNumber
}
public func validate(name: String) throws {
try self.validate(self.action, name: "action", parent: name, pattern: "lambda:GetLayerVersion")
try self.validate(self.layerName, name: "layerName", parent: name, max: 140)
try self.validate(self.layerName, name: "layerName", parent: name, min: 1)
try self.validate(self.layerName, name: "layerName", parent: name, pattern: "(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+")
try self.validate(self.organizationId, name: "organizationId", parent: name, pattern: "o-[a-z0-9]{10,32}")
try self.validate(self.principal, name: "principal", parent: name, pattern: "\\d{12}|\\*|arn:(aws[a-zA-Z-]*):iam::\\d{12}:root")
try self.validate(self.statementId, name: "statementId", parent: name, max: 100)
try self.validate(self.statementId, name: "statementId", parent: name, min: 1)
try self.validate(self.statementId, name: "statementId", parent: name, pattern: "([a-zA-Z0-9-_]+)")
}
private enum CodingKeys: String, CodingKey {
case action = "Action"
case organizationId = "OrganizationId"
case principal = "Principal"
case statementId = "StatementId"
}
}
public struct AddLayerVersionPermissionResponse: AWSDecodableShape {
/// A unique identifier for the current revision of the policy.
public let revisionId: String?
/// The permission statement.
public let statement: String?
public init(revisionId: String? = nil, statement: String? = nil) {
self.revisionId = revisionId
self.statement = statement
}
private enum CodingKeys: String, CodingKey {
case revisionId = "RevisionId"
case statement = "Statement"
}
}
public struct AddPermissionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier"))
]
/// The action that the principal can use on the function. For example, lambda:InvokeFunction or lambda:GetFunction.
public let action: String
/// For Alexa Smart Home functions, a token that must be supplied by the invoker.
public let eventSourceToken: String?
/// The name of the Lambda function, version, or alias. Name formats Function name - my-function (name-only), my-function:v1 (with alias). Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The AWS service or account that invokes the function. If you specify a service, use SourceArn or SourceAccount to limit who can invoke the function through that service.
public let principal: String
/// Specify a version or alias to add permissions to a published version of the function.
public let qualifier: String?
/// Only update the policy if the revision ID matches the ID that's specified. Use this option to avoid modifying a policy that has changed since you last read it.
public let revisionId: String?
/// For Amazon S3, the ID of the account that owns the resource. Use this together with SourceArn to ensure that the resource is owned by the specified account. It is possible for an Amazon S3 bucket to be deleted by its owner and recreated by another account.
public let sourceAccount: String?
/// For AWS services, the ARN of the AWS resource that invokes the function. For example, an Amazon S3 bucket or Amazon SNS topic.
public let sourceArn: String?
/// A statement identifier that differentiates the statement from others in the same policy.
public let statementId: String
public init(action: String, eventSourceToken: String? = nil, functionName: String, principal: String, qualifier: String? = nil, revisionId: String? = nil, sourceAccount: String? = nil, sourceArn: String? = nil, statementId: String) {
self.action = action
self.eventSourceToken = eventSourceToken
self.functionName = functionName
self.principal = principal
self.qualifier = qualifier
self.revisionId = revisionId
self.sourceAccount = sourceAccount
self.sourceArn = sourceArn
self.statementId = statementId
}
public func validate(name: String) throws {
try self.validate(self.action, name: "action", parent: name, pattern: "(lambda:[*]|lambda:[a-zA-Z]+|[*])")
try self.validate(self.eventSourceToken, name: "eventSourceToken", parent: name, max: 256)
try self.validate(self.eventSourceToken, name: "eventSourceToken", parent: name, min: 0)
try self.validate(self.eventSourceToken, name: "eventSourceToken", parent: name, pattern: "[a-zA-Z0-9._\\-]+")
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.principal, name: "principal", parent: name, pattern: ".*")
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
try self.validate(self.sourceAccount, name: "sourceAccount", parent: name, pattern: "\\d{12}")
try self.validate(self.sourceArn, name: "sourceArn", parent: name, pattern: "arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\\-])+:([a-z]{2}(-gov)?-[a-z]+-\\d{1})?:(\\d{12})?:(.*)")
try self.validate(self.statementId, name: "statementId", parent: name, max: 100)
try self.validate(self.statementId, name: "statementId", parent: name, min: 1)
try self.validate(self.statementId, name: "statementId", parent: name, pattern: "([a-zA-Z0-9-_]+)")
}
private enum CodingKeys: String, CodingKey {
case action = "Action"
case eventSourceToken = "EventSourceToken"
case principal = "Principal"
case revisionId = "RevisionId"
case sourceAccount = "SourceAccount"
case sourceArn = "SourceArn"
case statementId = "StatementId"
}
}
public struct AddPermissionResponse: AWSDecodableShape {
/// The permission statement that's added to the function policy.
public let statement: String?
public init(statement: String? = nil) {
self.statement = statement
}
private enum CodingKeys: String, CodingKey {
case statement = "Statement"
}
}
public struct AliasConfiguration: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the alias.
public let aliasArn: String?
/// A description of the alias.
public let description: String?
/// The function version that the alias invokes.
public let functionVersion: String?
/// The name of the alias.
public let name: String?
/// A unique identifier that changes when you update the alias.
public let revisionId: String?
/// The routing configuration of the alias.
public let routingConfig: AliasRoutingConfiguration?
public init(aliasArn: String? = nil, description: String? = nil, functionVersion: String? = nil, name: String? = nil, revisionId: String? = nil, routingConfig: AliasRoutingConfiguration? = nil) {
self.aliasArn = aliasArn
self.description = description
self.functionVersion = functionVersion
self.name = name
self.revisionId = revisionId
self.routingConfig = routingConfig
}
private enum CodingKeys: String, CodingKey {
case aliasArn = "AliasArn"
case description = "Description"
case functionVersion = "FunctionVersion"
case name = "Name"
case revisionId = "RevisionId"
case routingConfig = "RoutingConfig"
}
}
public struct AliasRoutingConfiguration: AWSEncodableShape & AWSDecodableShape {
/// The second version, and the percentage of traffic that's routed to it.
public let additionalVersionWeights: [String: Double]?
public init(additionalVersionWeights: [String: Double]? = nil) {
self.additionalVersionWeights = additionalVersionWeights
}
public func validate(name: String) throws {
try self.additionalVersionWeights?.forEach {
try validate($0.key, name: "additionalVersionWeights.key", parent: name, max: 1024)
try validate($0.key, name: "additionalVersionWeights.key", parent: name, min: 1)
try validate($0.key, name: "additionalVersionWeights.key", parent: name, pattern: "[0-9]+")
try validate($0.value, name: "additionalVersionWeights[\"\($0.key)\"]", parent: name, max: 1)
try validate($0.value, name: "additionalVersionWeights[\"\($0.key)\"]", parent: name, min: 0)
}
}
private enum CodingKeys: String, CodingKey {
case additionalVersionWeights = "AdditionalVersionWeights"
}
}
public struct Concurrency: AWSDecodableShape {
/// The number of concurrent executions that are reserved for this function. For more information, see Managing Concurrency.
public let reservedConcurrentExecutions: Int?
public init(reservedConcurrentExecutions: Int? = nil) {
self.reservedConcurrentExecutions = reservedConcurrentExecutions
}
private enum CodingKeys: String, CodingKey {
case reservedConcurrentExecutions = "ReservedConcurrentExecutions"
}
}
public struct CreateAliasRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName"))
]
/// A description of the alias.
public let description: String?
/// The name of the Lambda function. Name formats Function name - MyFunction. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction. Partial ARN - 123456789012:function:MyFunction. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The function version that the alias invokes.
public let functionVersion: String
/// The name of the alias.
public let name: String
/// The routing configuration of the alias.
public let routingConfig: AliasRoutingConfiguration?
public init(description: String? = nil, functionName: String, functionVersion: String, name: String, routingConfig: AliasRoutingConfiguration? = nil) {
self.description = description
self.functionName = functionName
self.functionVersion = functionVersion
self.name = name
self.routingConfig = routingConfig
}
public func validate(name: String) throws {
try self.validate(self.description, name: "description", parent: name, max: 256)
try self.validate(self.description, name: "description", parent: name, min: 0)
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.functionVersion, name: "functionVersion", parent: name, max: 1024)
try self.validate(self.functionVersion, name: "functionVersion", parent: name, min: 1)
try self.validate(self.functionVersion, name: "functionVersion", parent: name, pattern: "(\\$LATEST|[0-9]+)")
try self.validate(self.name, name: "name", parent: name, max: 128)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "(?!^[0-9]+$)([a-zA-Z0-9-_]+)")
try self.routingConfig?.validate(name: "\(name).routingConfig")
}
private enum CodingKeys: String, CodingKey {
case description = "Description"
case functionVersion = "FunctionVersion"
case name = "Name"
case routingConfig = "RoutingConfig"
}
}
public struct CreateEventSourceMappingRequest: AWSEncodableShape {
/// The maximum number of items to retrieve in a single batch. Amazon Kinesis - Default 100. Max 10,000. Amazon DynamoDB Streams - Default 100. Max 1,000. Amazon Simple Queue Service - Default 10. Max 10. Amazon Managed Streaming for Apache Kafka - Default 100. Max 10,000.
public let batchSize: Int?
/// (Streams) If the function returns an error, split the batch in two and retry.
public let bisectBatchOnFunctionError: Bool?
/// (Streams) An Amazon SQS queue or Amazon SNS topic destination for discarded records.
public let destinationConfig: DestinationConfig?
/// If true, the event source mapping is active. Set to false to pause polling and invocation.
public let enabled: Bool?
/// The Amazon Resource Name (ARN) of the event source. Amazon Kinesis - The ARN of the data stream or a stream consumer. Amazon DynamoDB Streams - The ARN of the stream. Amazon Simple Queue Service - The ARN of the queue. Amazon Managed Streaming for Apache Kafka - The ARN of the cluster.
public let eventSourceArn: String
/// The name of the Lambda function. Name formats Function name - MyFunction. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction. Version or Alias ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction:PROD. Partial ARN - 123456789012:function:MyFunction. The length constraint applies only to the full ARN. If you specify only the function name, it's limited to 64 characters in length.
public let functionName: String
/// (Streams) The maximum amount of time to gather records before invoking the function, in seconds.
public let maximumBatchingWindowInSeconds: Int?
/// (Streams) Discard records older than the specified age. The default value is infinite (-1).
public let maximumRecordAgeInSeconds: Int?
/// (Streams) Discard records after the specified number of retries. The default value is infinite (-1). When set to infinite (-1), failed records will be retried until the record expires.
public let maximumRetryAttempts: Int?
/// (Streams) The number of batches to process from each shard concurrently.
public let parallelizationFactor: Int?
/// The position in a stream from which to start reading. Required for Amazon Kinesis, Amazon DynamoDB, and Amazon MSK Streams sources. AT_TIMESTAMP is only supported for Amazon Kinesis streams.
public let startingPosition: EventSourcePosition?
/// With StartingPosition set to AT_TIMESTAMP, the time from which to start reading.
public let startingPositionTimestamp: Date?
/// (MSK) The name of the Kafka topic.
public let topics: [String]?
public init(batchSize: Int? = nil, bisectBatchOnFunctionError: Bool? = nil, destinationConfig: DestinationConfig? = nil, enabled: Bool? = nil, eventSourceArn: String, functionName: String, maximumBatchingWindowInSeconds: Int? = nil, maximumRecordAgeInSeconds: Int? = nil, maximumRetryAttempts: Int? = nil, parallelizationFactor: Int? = nil, startingPosition: EventSourcePosition? = nil, startingPositionTimestamp: Date? = nil, topics: [String]? = nil) {
self.batchSize = batchSize
self.bisectBatchOnFunctionError = bisectBatchOnFunctionError
self.destinationConfig = destinationConfig
self.enabled = enabled
self.eventSourceArn = eventSourceArn
self.functionName = functionName
self.maximumBatchingWindowInSeconds = maximumBatchingWindowInSeconds
self.maximumRecordAgeInSeconds = maximumRecordAgeInSeconds
self.maximumRetryAttempts = maximumRetryAttempts
self.parallelizationFactor = parallelizationFactor
self.startingPosition = startingPosition
self.startingPositionTimestamp = startingPositionTimestamp
self.topics = topics
}
public func validate(name: String) throws {
try self.validate(self.batchSize, name: "batchSize", parent: name, max: 10000)
try self.validate(self.batchSize, name: "batchSize", parent: name, min: 1)
try self.destinationConfig?.validate(name: "\(name).destinationConfig")
try self.validate(self.eventSourceArn, name: "eventSourceArn", parent: name, pattern: "arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\\-])+:([a-z]{2}(-gov)?-[a-z]+-\\d{1})?:(\\d{12})?:(.*)")
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.maximumBatchingWindowInSeconds, name: "maximumBatchingWindowInSeconds", parent: name, max: 300)
try self.validate(self.maximumBatchingWindowInSeconds, name: "maximumBatchingWindowInSeconds", parent: name, min: 0)
try self.validate(self.maximumRecordAgeInSeconds, name: "maximumRecordAgeInSeconds", parent: name, max: 604_800)
try self.validate(self.maximumRecordAgeInSeconds, name: "maximumRecordAgeInSeconds", parent: name, min: -1)
try self.validate(self.maximumRetryAttempts, name: "maximumRetryAttempts", parent: name, max: 10000)
try self.validate(self.maximumRetryAttempts, name: "maximumRetryAttempts", parent: name, min: -1)
try self.validate(self.parallelizationFactor, name: "parallelizationFactor", parent: name, max: 10)
try self.validate(self.parallelizationFactor, name: "parallelizationFactor", parent: name, min: 1)
try self.topics?.forEach {
try validate($0, name: "topics[]", parent: name, max: 249)
try validate($0, name: "topics[]", parent: name, min: 1)
try validate($0, name: "topics[]", parent: name, pattern: "^[^.]([a-zA-Z0-9\\-_.]+)")
}
try self.validate(self.topics, name: "topics", parent: name, max: 1)
try self.validate(self.topics, name: "topics", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case batchSize = "BatchSize"
case bisectBatchOnFunctionError = "BisectBatchOnFunctionError"
case destinationConfig = "DestinationConfig"
case enabled = "Enabled"
case eventSourceArn = "EventSourceArn"
case functionName = "FunctionName"
case maximumBatchingWindowInSeconds = "MaximumBatchingWindowInSeconds"
case maximumRecordAgeInSeconds = "MaximumRecordAgeInSeconds"
case maximumRetryAttempts = "MaximumRetryAttempts"
case parallelizationFactor = "ParallelizationFactor"
case startingPosition = "StartingPosition"
case startingPositionTimestamp = "StartingPositionTimestamp"
case topics = "Topics"
}
}
public struct CreateFunctionRequest: AWSEncodableShape {
/// The code for the function.
public let code: FunctionCode
/// A dead letter queue configuration that specifies the queue or topic where Lambda sends asynchronous events when they fail processing. For more information, see Dead Letter Queues.
public let deadLetterConfig: DeadLetterConfig?
/// A description of the function.
public let description: String?
/// Environment variables that are accessible from function code during execution.
public let environment: Environment?
/// Connection settings for an Amazon EFS file system.
public let fileSystemConfigs: [FileSystemConfig]?
/// The name of the Lambda function. Name formats Function name - my-function. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The name of the method within your code that Lambda calls to execute your function. The format includes the file name. It can also include namespaces and other qualifiers, depending on the runtime. For more information, see Programming Model.
public let handler: String
/// The ARN of the AWS Key Management Service (AWS KMS) key that's used to encrypt your function's environment variables. If it's not provided, AWS Lambda uses a default service key.
public let kMSKeyArn: String?
/// A list of function layers to add to the function's execution environment. Specify each layer by its ARN, including the version.
public let layers: [String]?
/// The amount of memory that your function has access to. Increasing the function's memory also increases its CPU allocation. The default value is 128 MB. The value must be a multiple of 64 MB.
public let memorySize: Int?
/// Set to true to publish the first version of the function during creation.
public let publish: Bool?
/// The Amazon Resource Name (ARN) of the function's execution role.
public let role: String
/// The identifier of the function's runtime.
public let runtime: Runtime
/// A list of tags to apply to the function.
public let tags: [String: String]?
/// The amount of time that Lambda allows a function to run before stopping it. The default is 3 seconds. The maximum allowed value is 900 seconds.
public let timeout: Int?
/// Set Mode to Active to sample and trace a subset of incoming requests with AWS X-Ray.
public let tracingConfig: TracingConfig?
/// For network connectivity to AWS resources in a VPC, specify a list of security groups and subnets in the VPC. When you connect a function to a VPC, it can only access resources and the internet through that VPC. For more information, see VPC Settings.
public let vpcConfig: VpcConfig?
public init(code: FunctionCode, deadLetterConfig: DeadLetterConfig? = nil, description: String? = nil, environment: Environment? = nil, fileSystemConfigs: [FileSystemConfig]? = nil, functionName: String, handler: String, kMSKeyArn: String? = nil, layers: [String]? = nil, memorySize: Int? = nil, publish: Bool? = nil, role: String, runtime: Runtime, tags: [String: String]? = nil, timeout: Int? = nil, tracingConfig: TracingConfig? = nil, vpcConfig: VpcConfig? = nil) {
self.code = code
self.deadLetterConfig = deadLetterConfig
self.description = description
self.environment = environment
self.fileSystemConfigs = fileSystemConfigs
self.functionName = functionName
self.handler = handler
self.kMSKeyArn = kMSKeyArn
self.layers = layers
self.memorySize = memorySize
self.publish = publish
self.role = role
self.runtime = runtime
self.tags = tags
self.timeout = timeout
self.tracingConfig = tracingConfig
self.vpcConfig = vpcConfig
}
public func validate(name: String) throws {
try self.code.validate(name: "\(name).code")
try self.deadLetterConfig?.validate(name: "\(name).deadLetterConfig")
try self.validate(self.description, name: "description", parent: name, max: 256)
try self.validate(self.description, name: "description", parent: name, min: 0)
try self.environment?.validate(name: "\(name).environment")
try self.fileSystemConfigs?.forEach {
try $0.validate(name: "\(name).fileSystemConfigs[]")
}
try self.validate(self.fileSystemConfigs, name: "fileSystemConfigs", parent: name, max: 1)
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.handler, name: "handler", parent: name, max: 128)
try self.validate(self.handler, name: "handler", parent: name, pattern: "[^\\s]+")
try self.validate(self.kMSKeyArn, name: "kMSKeyArn", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()")
try self.layers?.forEach {
try validate($0, name: "layers[]", parent: name, max: 140)
try validate($0, name: "layers[]", parent: name, min: 1)
try validate($0, name: "layers[]", parent: name, pattern: "arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+")
}
try self.validate(self.memorySize, name: "memorySize", parent: name, max: 3008)
try self.validate(self.memorySize, name: "memorySize", parent: name, min: 128)
try self.validate(self.role, name: "role", parent: name, pattern: "arn:(aws[a-zA-Z-]*)?:iam::\\d{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+")
try self.validate(self.timeout, name: "timeout", parent: name, min: 1)
try self.vpcConfig?.validate(name: "\(name).vpcConfig")
}
private enum CodingKeys: String, CodingKey {
case code = "Code"
case deadLetterConfig = "DeadLetterConfig"
case description = "Description"
case environment = "Environment"
case fileSystemConfigs = "FileSystemConfigs"
case functionName = "FunctionName"
case handler = "Handler"
case kMSKeyArn = "KMSKeyArn"
case layers = "Layers"
case memorySize = "MemorySize"
case publish = "Publish"
case role = "Role"
case runtime = "Runtime"
case tags = "Tags"
case timeout = "Timeout"
case tracingConfig = "TracingConfig"
case vpcConfig = "VpcConfig"
}
}
public struct DeadLetterConfig: AWSEncodableShape & AWSDecodableShape {
/// The Amazon Resource Name (ARN) of an Amazon SQS queue or Amazon SNS topic.
public let targetArn: String?
public init(targetArn: String? = nil) {
self.targetArn = targetArn
}
public func validate(name: String) throws {
try self.validate(self.targetArn, name: "targetArn", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()")
}
private enum CodingKeys: String, CodingKey {
case targetArn = "TargetArn"
}
}
public struct DeleteAliasRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "name", location: .uri(locationName: "Name"))
]
/// The name of the Lambda function. Name formats Function name - MyFunction. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction. Partial ARN - 123456789012:function:MyFunction. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The name of the alias.
public let name: String
public init(functionName: String, name: String) {
self.functionName = functionName
self.name = name
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.name, name: "name", parent: name, max: 128)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "(?!^[0-9]+$)([a-zA-Z0-9-_]+)")
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteEventSourceMappingRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "uuid", location: .uri(locationName: "UUID"))
]
/// The identifier of the event source mapping.
public let uuid: String
public init(uuid: String) {
self.uuid = uuid
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteFunctionConcurrencyRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName"))
]
/// The name of the Lambda function. Name formats Function name - my-function. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
public init(functionName: String) {
self.functionName = functionName
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteFunctionEventInvokeConfigRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier"))
]
/// The name of the Lambda function, version, or alias. Name formats Function name - my-function (name-only), my-function:v1 (with alias). Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// A version number or alias name.
public let qualifier: String?
public init(functionName: String, qualifier: String? = nil) {
self.functionName = functionName
self.qualifier = qualifier
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteFunctionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier"))
]
/// The name of the Lambda function or version. Name formats Function name - my-function (name-only), my-function:1 (with version). Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// Specify a version to delete. You can't delete a version that's referenced by an alias.
public let qualifier: String?
public init(functionName: String, qualifier: String? = nil) {
self.functionName = functionName
self.qualifier = qualifier
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteLayerVersionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "layerName", location: .uri(locationName: "LayerName")),
AWSMemberEncoding(label: "versionNumber", location: .uri(locationName: "VersionNumber"))
]
/// The name or Amazon Resource Name (ARN) of the layer.
public let layerName: String
/// The version number.
public let versionNumber: Int64
public init(layerName: String, versionNumber: Int64) {
self.layerName = layerName
self.versionNumber = versionNumber
}
public func validate(name: String) throws {
try self.validate(self.layerName, name: "layerName", parent: name, max: 140)
try self.validate(self.layerName, name: "layerName", parent: name, min: 1)
try self.validate(self.layerName, name: "layerName", parent: name, pattern: "(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+")
}
private enum CodingKeys: CodingKey {}
}
public struct DeleteProvisionedConcurrencyConfigRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier"))
]
/// The name of the Lambda function. Name formats Function name - my-function. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The version number or alias name.
public let qualifier: String
public init(functionName: String, qualifier: String) {
self.functionName = functionName
self.qualifier = qualifier
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
}
private enum CodingKeys: CodingKey {}
}
public struct DestinationConfig: AWSEncodableShape & AWSDecodableShape {
/// The destination configuration for failed invocations.
public let onFailure: OnFailure?
/// The destination configuration for successful invocations.
public let onSuccess: OnSuccess?
public init(onFailure: OnFailure? = nil, onSuccess: OnSuccess? = nil) {
self.onFailure = onFailure
self.onSuccess = onSuccess
}
public func validate(name: String) throws {
try self.onFailure?.validate(name: "\(name).onFailure")
try self.onSuccess?.validate(name: "\(name).onSuccess")
}
private enum CodingKeys: String, CodingKey {
case onFailure = "OnFailure"
case onSuccess = "OnSuccess"
}
}
public struct Environment: AWSEncodableShape {
/// Environment variable key-value pairs.
public let variables: [String: String]?
public init(variables: [String: String]? = nil) {
self.variables = variables
}
public func validate(name: String) throws {
try self.variables?.forEach {
try validate($0.key, name: "variables.key", parent: name, pattern: "[a-zA-Z]([a-zA-Z0-9_])+")
}
}
private enum CodingKeys: String, CodingKey {
case variables = "Variables"
}
}
public struct EnvironmentError: AWSDecodableShape {
/// The error code.
public let errorCode: String?
/// The error message.
public let message: String?
public init(errorCode: String? = nil, message: String? = nil) {
self.errorCode = errorCode
self.message = message
}
private enum CodingKeys: String, CodingKey {
case errorCode = "ErrorCode"
case message = "Message"
}
}
public struct EnvironmentResponse: AWSDecodableShape {
/// Error messages for environment variables that couldn't be applied.
public let error: EnvironmentError?
/// Environment variable key-value pairs.
public let variables: [String: String]?
public init(error: EnvironmentError? = nil, variables: [String: String]? = nil) {
self.error = error
self.variables = variables
}
private enum CodingKeys: String, CodingKey {
case error = "Error"
case variables = "Variables"
}
}
public struct EventSourceMappingConfiguration: AWSDecodableShape {
/// The maximum number of items to retrieve in a single batch.
public let batchSize: Int?
/// (Streams) If the function returns an error, split the batch in two and retry.
public let bisectBatchOnFunctionError: Bool?
/// (Streams) An Amazon SQS queue or Amazon SNS topic destination for discarded records.
public let destinationConfig: DestinationConfig?
/// The Amazon Resource Name (ARN) of the event source.
public let eventSourceArn: String?
/// The ARN of the Lambda function.
public let functionArn: String?
/// The date that the event source mapping was last updated, or its state changed.
public let lastModified: Date?
/// The result of the last AWS Lambda invocation of your Lambda function.
public let lastProcessingResult: String?
/// (Streams) The maximum amount of time to gather records before invoking the function, in seconds.
public let maximumBatchingWindowInSeconds: Int?
/// (Streams) The maximum age of a record that Lambda sends to a function for processing.
public let maximumRecordAgeInSeconds: Int?
/// (Streams) The maximum number of times to retry when the function returns an error.
public let maximumRetryAttempts: Int?
/// (Streams) The number of batches to process from each shard concurrently.
public let parallelizationFactor: Int?
/// The state of the event source mapping. It can be one of the following: Creating, Enabling, Enabled, Disabling, Disabled, Updating, or Deleting.
public let state: String?
/// Indicates whether the last change to the event source mapping was made by a user, or by the Lambda service.
public let stateTransitionReason: String?
/// (MSK) The name of the Kafka topic.
public let topics: [String]?
/// The identifier of the event source mapping.
public let uuid: String?
public init(batchSize: Int? = nil, bisectBatchOnFunctionError: Bool? = nil, destinationConfig: DestinationConfig? = nil, eventSourceArn: String? = nil, functionArn: String? = nil, lastModified: Date? = nil, lastProcessingResult: String? = nil, maximumBatchingWindowInSeconds: Int? = nil, maximumRecordAgeInSeconds: Int? = nil, maximumRetryAttempts: Int? = nil, parallelizationFactor: Int? = nil, state: String? = nil, stateTransitionReason: String? = nil, topics: [String]? = nil, uuid: String? = nil) {
self.batchSize = batchSize
self.bisectBatchOnFunctionError = bisectBatchOnFunctionError
self.destinationConfig = destinationConfig
self.eventSourceArn = eventSourceArn
self.functionArn = functionArn
self.lastModified = lastModified
self.lastProcessingResult = lastProcessingResult
self.maximumBatchingWindowInSeconds = maximumBatchingWindowInSeconds
self.maximumRecordAgeInSeconds = maximumRecordAgeInSeconds
self.maximumRetryAttempts = maximumRetryAttempts
self.parallelizationFactor = parallelizationFactor
self.state = state
self.stateTransitionReason = stateTransitionReason
self.topics = topics
self.uuid = uuid
}
private enum CodingKeys: String, CodingKey {
case batchSize = "BatchSize"
case bisectBatchOnFunctionError = "BisectBatchOnFunctionError"
case destinationConfig = "DestinationConfig"
case eventSourceArn = "EventSourceArn"
case functionArn = "FunctionArn"
case lastModified = "LastModified"
case lastProcessingResult = "LastProcessingResult"
case maximumBatchingWindowInSeconds = "MaximumBatchingWindowInSeconds"
case maximumRecordAgeInSeconds = "MaximumRecordAgeInSeconds"
case maximumRetryAttempts = "MaximumRetryAttempts"
case parallelizationFactor = "ParallelizationFactor"
case state = "State"
case stateTransitionReason = "StateTransitionReason"
case topics = "Topics"
case uuid = "UUID"
}
}
public struct FileSystemConfig: AWSEncodableShape & AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the Amazon EFS access point that provides access to the file system.
public let arn: String
/// The path where the function can access the file system, starting with /mnt/.
public let localMountPath: String
public init(arn: String, localMountPath: String) {
self.arn = arn
self.localMountPath = localMountPath
}
public func validate(name: String) throws {
try self.validate(self.arn, name: "arn", parent: name, max: 200)
try self.validate(self.arn, name: "arn", parent: name, pattern: "arn:aws[a-zA-Z-]*:elasticfilesystem:[a-z]{2}((-gov)|(-iso(b?)))?-[a-z]+-\\d{1}:\\d{12}:access-point/fsap-[a-f0-9]{17}")
try self.validate(self.localMountPath, name: "localMountPath", parent: name, max: 160)
try self.validate(self.localMountPath, name: "localMountPath", parent: name, pattern: "^/mnt/[a-zA-Z0-9-_.]+$")
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case localMountPath = "LocalMountPath"
}
}
public struct FunctionCode: AWSEncodableShape {
/// An Amazon S3 bucket in the same AWS Region as your function. The bucket can be in a different AWS account.
public let s3Bucket: String?
/// The Amazon S3 key of the deployment package.
public let s3Key: String?
/// For versioned objects, the version of the deployment package object to use.
public let s3ObjectVersion: String?
/// The base64-encoded contents of the deployment package. AWS SDK and AWS CLI clients handle the encoding for you.
public let zipFile: Data?
public init(s3Bucket: String? = nil, s3Key: String? = nil, s3ObjectVersion: String? = nil, zipFile: Data? = nil) {
self.s3Bucket = s3Bucket
self.s3Key = s3Key
self.s3ObjectVersion = s3ObjectVersion
self.zipFile = zipFile
}
public func validate(name: String) throws {
try self.validate(self.s3Bucket, name: "s3Bucket", parent: name, max: 63)
try self.validate(self.s3Bucket, name: "s3Bucket", parent: name, min: 3)
try self.validate(self.s3Bucket, name: "s3Bucket", parent: name, pattern: "^[0-9A-Za-z\\.\\-_]*(?<!\\.)$")
try self.validate(self.s3Key, name: "s3Key", parent: name, max: 1024)
try self.validate(self.s3Key, name: "s3Key", parent: name, min: 1)
try self.validate(self.s3ObjectVersion, name: "s3ObjectVersion", parent: name, max: 1024)
try self.validate(self.s3ObjectVersion, name: "s3ObjectVersion", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case s3Bucket = "S3Bucket"
case s3Key = "S3Key"
case s3ObjectVersion = "S3ObjectVersion"
case zipFile = "ZipFile"
}
}
public struct FunctionCodeLocation: AWSDecodableShape {
/// A presigned URL that you can use to download the deployment package.
public let location: String?
/// The service that's hosting the file.
public let repositoryType: String?
public init(location: String? = nil, repositoryType: String? = nil) {
self.location = location
self.repositoryType = repositoryType
}
private enum CodingKeys: String, CodingKey {
case location = "Location"
case repositoryType = "RepositoryType"
}
}
public struct FunctionConfiguration: AWSDecodableShape {
/// The SHA256 hash of the function's deployment package.
public let codeSha256: String?
/// The size of the function's deployment package, in bytes.
public let codeSize: Int64?
/// The function's dead letter queue.
public let deadLetterConfig: DeadLetterConfig?
/// The function's description.
public let description: String?
/// The function's environment variables.
public let environment: EnvironmentResponse?
/// Connection settings for an Amazon EFS file system.
public let fileSystemConfigs: [FileSystemConfig]?
/// The function's Amazon Resource Name (ARN).
public let functionArn: String?
/// The name of the function.
public let functionName: String?
/// The function that Lambda calls to begin executing your function.
public let handler: String?
/// The KMS key that's used to encrypt the function's environment variables. This key is only returned if you've configured a customer managed CMK.
public let kMSKeyArn: String?
/// The date and time that the function was last updated, in ISO-8601 format (YYYY-MM-DDThh:mm:ss.sTZD).
public let lastModified: String?
/// The status of the last update that was performed on the function. This is first set to Successful after function creation completes.
public let lastUpdateStatus: LastUpdateStatus?
/// The reason for the last update that was performed on the function.
public let lastUpdateStatusReason: String?
/// The reason code for the last update that was performed on the function.
public let lastUpdateStatusReasonCode: LastUpdateStatusReasonCode?
/// The function's layers.
public let layers: [Layer]?
/// For Lambda@Edge functions, the ARN of the master function.
public let masterArn: String?
/// The memory that's allocated to the function.
public let memorySize: Int?
/// The latest updated revision of the function or alias.
public let revisionId: String?
/// The function's execution role.
public let role: String?
/// The runtime environment for the Lambda function.
public let runtime: Runtime?
/// The current state of the function. When the state is Inactive, you can reactivate the function by invoking it.
public let state: State?
/// The reason for the function's current state.
public let stateReason: String?
/// The reason code for the function's current state. When the code is Creating, you can't invoke or modify the function.
public let stateReasonCode: StateReasonCode?
/// The amount of time in seconds that Lambda allows a function to run before stopping it.
public let timeout: Int?
/// The function's AWS X-Ray tracing configuration.
public let tracingConfig: TracingConfigResponse?
/// The version of the Lambda function.
public let version: String?
/// The function's networking configuration.
public let vpcConfig: VpcConfigResponse?
public init(codeSha256: String? = nil, codeSize: Int64? = nil, deadLetterConfig: DeadLetterConfig? = nil, description: String? = nil, environment: EnvironmentResponse? = nil, fileSystemConfigs: [FileSystemConfig]? = nil, functionArn: String? = nil, functionName: String? = nil, handler: String? = nil, kMSKeyArn: String? = nil, lastModified: String? = nil, lastUpdateStatus: LastUpdateStatus? = nil, lastUpdateStatusReason: String? = nil, lastUpdateStatusReasonCode: LastUpdateStatusReasonCode? = nil, layers: [Layer]? = nil, masterArn: String? = nil, memorySize: Int? = nil, revisionId: String? = nil, role: String? = nil, runtime: Runtime? = nil, state: State? = nil, stateReason: String? = nil, stateReasonCode: StateReasonCode? = nil, timeout: Int? = nil, tracingConfig: TracingConfigResponse? = nil, version: String? = nil, vpcConfig: VpcConfigResponse? = nil) {
self.codeSha256 = codeSha256
self.codeSize = codeSize
self.deadLetterConfig = deadLetterConfig
self.description = description
self.environment = environment
self.fileSystemConfigs = fileSystemConfigs
self.functionArn = functionArn
self.functionName = functionName
self.handler = handler
self.kMSKeyArn = kMSKeyArn
self.lastModified = lastModified
self.lastUpdateStatus = lastUpdateStatus
self.lastUpdateStatusReason = lastUpdateStatusReason
self.lastUpdateStatusReasonCode = lastUpdateStatusReasonCode
self.layers = layers
self.masterArn = masterArn
self.memorySize = memorySize
self.revisionId = revisionId
self.role = role
self.runtime = runtime
self.state = state
self.stateReason = stateReason
self.stateReasonCode = stateReasonCode
self.timeout = timeout
self.tracingConfig = tracingConfig
self.version = version
self.vpcConfig = vpcConfig
}
private enum CodingKeys: String, CodingKey {
case codeSha256 = "CodeSha256"
case codeSize = "CodeSize"
case deadLetterConfig = "DeadLetterConfig"
case description = "Description"
case environment = "Environment"
case fileSystemConfigs = "FileSystemConfigs"
case functionArn = "FunctionArn"
case functionName = "FunctionName"
case handler = "Handler"
case kMSKeyArn = "KMSKeyArn"
case lastModified = "LastModified"
case lastUpdateStatus = "LastUpdateStatus"
case lastUpdateStatusReason = "LastUpdateStatusReason"
case lastUpdateStatusReasonCode = "LastUpdateStatusReasonCode"
case layers = "Layers"
case masterArn = "MasterArn"
case memorySize = "MemorySize"
case revisionId = "RevisionId"
case role = "Role"
case runtime = "Runtime"
case state = "State"
case stateReason = "StateReason"
case stateReasonCode = "StateReasonCode"
case timeout = "Timeout"
case tracingConfig = "TracingConfig"
case version = "Version"
case vpcConfig = "VpcConfig"
}
}
public struct FunctionEventInvokeConfig: AWSDecodableShape {
/// A destination for events after they have been sent to a function for processing. Destinations Function - The Amazon Resource Name (ARN) of a Lambda function. Queue - The ARN of an SQS queue. Topic - The ARN of an SNS topic. Event Bus - The ARN of an Amazon EventBridge event bus.
public let destinationConfig: DestinationConfig?
/// The Amazon Resource Name (ARN) of the function.
public let functionArn: String?
/// The date and time that the configuration was last updated.
public let lastModified: Date?
/// The maximum age of a request that Lambda sends to a function for processing.
public let maximumEventAgeInSeconds: Int?
/// The maximum number of times to retry when the function returns an error.
public let maximumRetryAttempts: Int?
public init(destinationConfig: DestinationConfig? = nil, functionArn: String? = nil, lastModified: Date? = nil, maximumEventAgeInSeconds: Int? = nil, maximumRetryAttempts: Int? = nil) {
self.destinationConfig = destinationConfig
self.functionArn = functionArn
self.lastModified = lastModified
self.maximumEventAgeInSeconds = maximumEventAgeInSeconds
self.maximumRetryAttempts = maximumRetryAttempts
}
private enum CodingKeys: String, CodingKey {
case destinationConfig = "DestinationConfig"
case functionArn = "FunctionArn"
case lastModified = "LastModified"
case maximumEventAgeInSeconds = "MaximumEventAgeInSeconds"
case maximumRetryAttempts = "MaximumRetryAttempts"
}
}
public struct GetAccountSettingsRequest: AWSEncodableShape {
public init() {}
}
public struct GetAccountSettingsResponse: AWSDecodableShape {
/// Limits that are related to concurrency and code storage.
public let accountLimit: AccountLimit?
/// The number of functions and amount of storage in use.
public let accountUsage: AccountUsage?
public init(accountLimit: AccountLimit? = nil, accountUsage: AccountUsage? = nil) {
self.accountLimit = accountLimit
self.accountUsage = accountUsage
}
private enum CodingKeys: String, CodingKey {
case accountLimit = "AccountLimit"
case accountUsage = "AccountUsage"
}
}
public struct GetAliasRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "name", location: .uri(locationName: "Name"))
]
/// The name of the Lambda function. Name formats Function name - MyFunction. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction. Partial ARN - 123456789012:function:MyFunction. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The name of the alias.
public let name: String
public init(functionName: String, name: String) {
self.functionName = functionName
self.name = name
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.name, name: "name", parent: name, max: 128)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "(?!^[0-9]+$)([a-zA-Z0-9-_]+)")
}
private enum CodingKeys: CodingKey {}
}
public struct GetEventSourceMappingRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "uuid", location: .uri(locationName: "UUID"))
]
/// The identifier of the event source mapping.
public let uuid: String
public init(uuid: String) {
self.uuid = uuid
}
private enum CodingKeys: CodingKey {}
}
public struct GetFunctionConcurrencyRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName"))
]
/// The name of the Lambda function. Name formats Function name - my-function. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
public init(functionName: String) {
self.functionName = functionName
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
}
private enum CodingKeys: CodingKey {}
}
public struct GetFunctionConcurrencyResponse: AWSDecodableShape {
/// The number of simultaneous executions that are reserved for the function.
public let reservedConcurrentExecutions: Int?
public init(reservedConcurrentExecutions: Int? = nil) {
self.reservedConcurrentExecutions = reservedConcurrentExecutions
}
private enum CodingKeys: String, CodingKey {
case reservedConcurrentExecutions = "ReservedConcurrentExecutions"
}
}
public struct GetFunctionConfigurationRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier"))
]
/// The name of the Lambda function, version, or alias. Name formats Function name - my-function (name-only), my-function:v1 (with alias). Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// Specify a version or alias to get details about a published version of the function.
public let qualifier: String?
public init(functionName: String, qualifier: String? = nil) {
self.functionName = functionName
self.qualifier = qualifier
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 170)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_\\.]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
}
private enum CodingKeys: CodingKey {}
}
public struct GetFunctionEventInvokeConfigRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier"))
]
/// The name of the Lambda function, version, or alias. Name formats Function name - my-function (name-only), my-function:v1 (with alias). Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// A version number or alias name.
public let qualifier: String?
public init(functionName: String, qualifier: String? = nil) {
self.functionName = functionName
self.qualifier = qualifier
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
}
private enum CodingKeys: CodingKey {}
}
public struct GetFunctionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier"))
]
/// The name of the Lambda function, version, or alias. Name formats Function name - my-function (name-only), my-function:v1 (with alias). Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// Specify a version or alias to get details about a published version of the function.
public let qualifier: String?
public init(functionName: String, qualifier: String? = nil) {
self.functionName = functionName
self.qualifier = qualifier
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 170)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_\\.]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
}
private enum CodingKeys: CodingKey {}
}
public struct GetFunctionResponse: AWSDecodableShape {
/// The deployment package of the function or version.
public let code: FunctionCodeLocation?
/// The function's reserved concurrency.
public let concurrency: Concurrency?
/// The configuration of the function or version.
public let configuration: FunctionConfiguration?
/// The function's tags.
public let tags: [String: String]?
public init(code: FunctionCodeLocation? = nil, concurrency: Concurrency? = nil, configuration: FunctionConfiguration? = nil, tags: [String: String]? = nil) {
self.code = code
self.concurrency = concurrency
self.configuration = configuration
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case code = "Code"
case concurrency = "Concurrency"
case configuration = "Configuration"
case tags = "Tags"
}
}
public struct GetLayerVersionByArnRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "arn", location: .querystring(locationName: "Arn"))
]
/// The ARN of the layer version.
public let arn: String
public init(arn: String) {
self.arn = arn
}
public func validate(name: String) throws {
try self.validate(self.arn, name: "arn", parent: name, max: 140)
try self.validate(self.arn, name: "arn", parent: name, min: 1)
try self.validate(self.arn, name: "arn", parent: name, pattern: "arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+")
}
private enum CodingKeys: CodingKey {}
}
public struct GetLayerVersionPolicyRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "layerName", location: .uri(locationName: "LayerName")),
AWSMemberEncoding(label: "versionNumber", location: .uri(locationName: "VersionNumber"))
]
/// The name or Amazon Resource Name (ARN) of the layer.
public let layerName: String
/// The version number.
public let versionNumber: Int64
public init(layerName: String, versionNumber: Int64) {
self.layerName = layerName
self.versionNumber = versionNumber
}
public func validate(name: String) throws {
try self.validate(self.layerName, name: "layerName", parent: name, max: 140)
try self.validate(self.layerName, name: "layerName", parent: name, min: 1)
try self.validate(self.layerName, name: "layerName", parent: name, pattern: "(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+")
}
private enum CodingKeys: CodingKey {}
}
public struct GetLayerVersionPolicyResponse: AWSDecodableShape {
/// The policy document.
public let policy: String?
/// A unique identifier for the current revision of the policy.
public let revisionId: String?
public init(policy: String? = nil, revisionId: String? = nil) {
self.policy = policy
self.revisionId = revisionId
}
private enum CodingKeys: String, CodingKey {
case policy = "Policy"
case revisionId = "RevisionId"
}
}
public struct GetLayerVersionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "layerName", location: .uri(locationName: "LayerName")),
AWSMemberEncoding(label: "versionNumber", location: .uri(locationName: "VersionNumber"))
]
/// The name or Amazon Resource Name (ARN) of the layer.
public let layerName: String
/// The version number.
public let versionNumber: Int64
public init(layerName: String, versionNumber: Int64) {
self.layerName = layerName
self.versionNumber = versionNumber
}
public func validate(name: String) throws {
try self.validate(self.layerName, name: "layerName", parent: name, max: 140)
try self.validate(self.layerName, name: "layerName", parent: name, min: 1)
try self.validate(self.layerName, name: "layerName", parent: name, pattern: "(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+")
}
private enum CodingKeys: CodingKey {}
}
public struct GetLayerVersionResponse: AWSDecodableShape {
/// The layer's compatible runtimes.
public let compatibleRuntimes: [Runtime]?
/// Details about the layer version.
public let content: LayerVersionContentOutput?
/// The date that the layer version was created, in ISO-8601 format (YYYY-MM-DDThh:mm:ss.sTZD).
public let createdDate: String?
/// The description of the version.
public let description: String?
/// The ARN of the layer.
public let layerArn: String?
/// The ARN of the layer version.
public let layerVersionArn: String?
/// The layer's software license.
public let licenseInfo: String?
/// The version number.
public let version: Int64?
public init(compatibleRuntimes: [Runtime]? = nil, content: LayerVersionContentOutput? = nil, createdDate: String? = nil, description: String? = nil, layerArn: String? = nil, layerVersionArn: String? = nil, licenseInfo: String? = nil, version: Int64? = nil) {
self.compatibleRuntimes = compatibleRuntimes
self.content = content
self.createdDate = createdDate
self.description = description
self.layerArn = layerArn
self.layerVersionArn = layerVersionArn
self.licenseInfo = licenseInfo
self.version = version
}
private enum CodingKeys: String, CodingKey {
case compatibleRuntimes = "CompatibleRuntimes"
case content = "Content"
case createdDate = "CreatedDate"
case description = "Description"
case layerArn = "LayerArn"
case layerVersionArn = "LayerVersionArn"
case licenseInfo = "LicenseInfo"
case version = "Version"
}
}
public struct GetPolicyRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier"))
]
/// The name of the Lambda function, version, or alias. Name formats Function name - my-function (name-only), my-function:v1 (with alias). Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// Specify a version or alias to get the policy for that resource.
public let qualifier: String?
public init(functionName: String, qualifier: String? = nil) {
self.functionName = functionName
self.qualifier = qualifier
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 170)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_\\.]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
}
private enum CodingKeys: CodingKey {}
}
public struct GetPolicyResponse: AWSDecodableShape {
/// The resource-based policy.
public let policy: String?
/// A unique identifier for the current revision of the policy.
public let revisionId: String?
public init(policy: String? = nil, revisionId: String? = nil) {
self.policy = policy
self.revisionId = revisionId
}
private enum CodingKeys: String, CodingKey {
case policy = "Policy"
case revisionId = "RevisionId"
}
}
public struct GetProvisionedConcurrencyConfigRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier"))
]
/// The name of the Lambda function. Name formats Function name - my-function. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The version number or alias name.
public let qualifier: String
public init(functionName: String, qualifier: String) {
self.functionName = functionName
self.qualifier = qualifier
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
}
private enum CodingKeys: CodingKey {}
}
public struct GetProvisionedConcurrencyConfigResponse: AWSDecodableShape {
/// The amount of provisioned concurrency allocated.
public let allocatedProvisionedConcurrentExecutions: Int?
/// The amount of provisioned concurrency available.
public let availableProvisionedConcurrentExecutions: Int?
/// The date and time that a user last updated the configuration, in ISO 8601 format.
public let lastModified: String?
/// The amount of provisioned concurrency requested.
public let requestedProvisionedConcurrentExecutions: Int?
/// The status of the allocation process.
public let status: ProvisionedConcurrencyStatusEnum?
/// For failed allocations, the reason that provisioned concurrency could not be allocated.
public let statusReason: String?
public init(allocatedProvisionedConcurrentExecutions: Int? = nil, availableProvisionedConcurrentExecutions: Int? = nil, lastModified: String? = nil, requestedProvisionedConcurrentExecutions: Int? = nil, status: ProvisionedConcurrencyStatusEnum? = nil, statusReason: String? = nil) {
self.allocatedProvisionedConcurrentExecutions = allocatedProvisionedConcurrentExecutions
self.availableProvisionedConcurrentExecutions = availableProvisionedConcurrentExecutions
self.lastModified = lastModified
self.requestedProvisionedConcurrentExecutions = requestedProvisionedConcurrentExecutions
self.status = status
self.statusReason = statusReason
}
private enum CodingKeys: String, CodingKey {
case allocatedProvisionedConcurrentExecutions = "AllocatedProvisionedConcurrentExecutions"
case availableProvisionedConcurrentExecutions = "AvailableProvisionedConcurrentExecutions"
case lastModified = "LastModified"
case requestedProvisionedConcurrentExecutions = "RequestedProvisionedConcurrentExecutions"
case status = "Status"
case statusReason = "StatusReason"
}
}
public struct InvocationRequest: AWSEncodableShape & AWSShapeWithPayload {
/// The key for the payload
public static let _payloadPath: String = "payload"
public static let _payloadOptions: AWSShapePayloadOptions = [.raw]
public static var _encoding = [
AWSMemberEncoding(label: "clientContext", location: .header(locationName: "X-Amz-Client-Context")),
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "invocationType", location: .header(locationName: "X-Amz-Invocation-Type")),
AWSMemberEncoding(label: "logType", location: .header(locationName: "X-Amz-Log-Type")),
AWSMemberEncoding(label: "payload", location: .body(locationName: "Payload")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier"))
]
/// Up to 3583 bytes of base64-encoded data about the invoking client to pass to the function in the context object.
public let clientContext: String?
/// The name of the Lambda function, version, or alias. Name formats Function name - my-function (name-only), my-function:v1 (with alias). Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// Choose from the following options. RequestResponse (default) - Invoke the function synchronously. Keep the connection open until the function returns a response or times out. The API response includes the function response and additional data. Event - Invoke the function asynchronously. Send events that fail multiple times to the function's dead-letter queue (if it's configured). The API response only includes a status code. DryRun - Validate parameter values and verify that the user or role has permission to invoke the function.
public let invocationType: InvocationType?
/// Set to Tail to include the execution log in the response.
public let logType: LogType?
/// The JSON that you want to provide to your Lambda function as input.
public let payload: AWSPayload?
/// Specify a version or alias to invoke a published version of the function.
public let qualifier: String?
public init(clientContext: String? = nil, functionName: String, invocationType: InvocationType? = nil, logType: LogType? = nil, payload: AWSPayload? = nil, qualifier: String? = nil) {
self.clientContext = clientContext
self.functionName = functionName
self.invocationType = invocationType
self.logType = logType
self.payload = payload
self.qualifier = qualifier
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 170)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_\\.]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
}
private enum CodingKeys: CodingKey {}
}
public struct InvocationResponse: AWSDecodableShape & AWSShapeWithPayload {
/// The key for the payload
public static let _payloadPath: String = "payload"
public static let _payloadOptions: AWSShapePayloadOptions = [.raw]
public static var _encoding = [
AWSMemberEncoding(label: "executedVersion", location: .header(locationName: "X-Amz-Executed-Version")),
AWSMemberEncoding(label: "functionError", location: .header(locationName: "X-Amz-Function-Error")),
AWSMemberEncoding(label: "logResult", location: .header(locationName: "X-Amz-Log-Result")),
AWSMemberEncoding(label: "payload", location: .body(locationName: "Payload")),
AWSMemberEncoding(label: "statusCode", location: .statusCode)
]
/// The version of the function that executed. When you invoke a function with an alias, this indicates which version the alias resolved to.
public let executedVersion: String?
/// If present, indicates that an error occurred during function execution. Details about the error are included in the response payload.
public let functionError: String?
/// The last 4 KB of the execution log, which is base64 encoded.
public let logResult: String?
/// The response from the function, or an error object.
public let payload: AWSPayload?
/// The HTTP status code is in the 200 range for a successful request. For the RequestResponse invocation type, this status code is 200. For the Event invocation type, this status code is 202. For the DryRun invocation type, the status code is 204.
public let statusCode: Int?
public init(executedVersion: String? = nil, functionError: String? = nil, logResult: String? = nil, payload: AWSPayload? = nil, statusCode: Int? = nil) {
self.executedVersion = executedVersion
self.functionError = functionError
self.logResult = logResult
self.payload = payload
self.statusCode = statusCode
}
private enum CodingKeys: String, CodingKey {
case executedVersion = "X-Amz-Executed-Version"
case functionError = "X-Amz-Function-Error"
case logResult = "X-Amz-Log-Result"
case payload = "Payload"
case statusCode = "StatusCode"
}
}
public struct InvokeAsyncRequest: AWSEncodableShape & AWSShapeWithPayload {
/// The key for the payload
public static let _payloadPath: String = "invokeArgs"
public static let _payloadOptions: AWSShapePayloadOptions = [.raw, .allowStreaming]
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "invokeArgs", location: .body(locationName: "InvokeArgs"))
]
/// The name of the Lambda function. Name formats Function name - my-function. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The JSON that you want to provide to your Lambda function as input.
public let invokeArgs: AWSPayload
public init(functionName: String, invokeArgs: AWSPayload) {
self.functionName = functionName
self.invokeArgs = invokeArgs
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 170)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_\\.]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
}
private enum CodingKeys: CodingKey {}
}
public struct InvokeAsyncResponse: AWSDecodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "status", location: .statusCode)
]
/// The status code.
public let status: Int?
public init(status: Int? = nil) {
self.status = status
}
private enum CodingKeys: String, CodingKey {
case status = "Status"
}
}
public struct Layer: AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the function layer.
public let arn: String?
/// The size of the layer archive in bytes.
public let codeSize: Int64?
public init(arn: String? = nil, codeSize: Int64? = nil) {
self.arn = arn
self.codeSize = codeSize
}
private enum CodingKeys: String, CodingKey {
case arn = "Arn"
case codeSize = "CodeSize"
}
}
public struct LayerVersionContentInput: AWSEncodableShape {
/// The Amazon S3 bucket of the layer archive.
public let s3Bucket: String?
/// The Amazon S3 key of the layer archive.
public let s3Key: String?
/// For versioned objects, the version of the layer archive object to use.
public let s3ObjectVersion: String?
/// The base64-encoded contents of the layer archive. AWS SDK and AWS CLI clients handle the encoding for you.
public let zipFile: Data?
public init(s3Bucket: String? = nil, s3Key: String? = nil, s3ObjectVersion: String? = nil, zipFile: Data? = nil) {
self.s3Bucket = s3Bucket
self.s3Key = s3Key
self.s3ObjectVersion = s3ObjectVersion
self.zipFile = zipFile
}
public func validate(name: String) throws {
try self.validate(self.s3Bucket, name: "s3Bucket", parent: name, max: 63)
try self.validate(self.s3Bucket, name: "s3Bucket", parent: name, min: 3)
try self.validate(self.s3Bucket, name: "s3Bucket", parent: name, pattern: "^[0-9A-Za-z\\.\\-_]*(?<!\\.)$")
try self.validate(self.s3Key, name: "s3Key", parent: name, max: 1024)
try self.validate(self.s3Key, name: "s3Key", parent: name, min: 1)
try self.validate(self.s3ObjectVersion, name: "s3ObjectVersion", parent: name, max: 1024)
try self.validate(self.s3ObjectVersion, name: "s3ObjectVersion", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case s3Bucket = "S3Bucket"
case s3Key = "S3Key"
case s3ObjectVersion = "S3ObjectVersion"
case zipFile = "ZipFile"
}
}
public struct LayerVersionContentOutput: AWSDecodableShape {
/// The SHA-256 hash of the layer archive.
public let codeSha256: String?
/// The size of the layer archive in bytes.
public let codeSize: Int64?
/// A link to the layer archive in Amazon S3 that is valid for 10 minutes.
public let location: String?
public init(codeSha256: String? = nil, codeSize: Int64? = nil, location: String? = nil) {
self.codeSha256 = codeSha256
self.codeSize = codeSize
self.location = location
}
private enum CodingKeys: String, CodingKey {
case codeSha256 = "CodeSha256"
case codeSize = "CodeSize"
case location = "Location"
}
}
public struct LayerVersionsListItem: AWSDecodableShape {
/// The layer's compatible runtimes.
public let compatibleRuntimes: [Runtime]?
/// The date that the version was created, in ISO 8601 format. For example, 2018-11-27T15:10:45.123+0000.
public let createdDate: String?
/// The description of the version.
public let description: String?
/// The ARN of the layer version.
public let layerVersionArn: String?
/// The layer's open-source license.
public let licenseInfo: String?
/// The version number.
public let version: Int64?
public init(compatibleRuntimes: [Runtime]? = nil, createdDate: String? = nil, description: String? = nil, layerVersionArn: String? = nil, licenseInfo: String? = nil, version: Int64? = nil) {
self.compatibleRuntimes = compatibleRuntimes
self.createdDate = createdDate
self.description = description
self.layerVersionArn = layerVersionArn
self.licenseInfo = licenseInfo
self.version = version
}
private enum CodingKeys: String, CodingKey {
case compatibleRuntimes = "CompatibleRuntimes"
case createdDate = "CreatedDate"
case description = "Description"
case layerVersionArn = "LayerVersionArn"
case licenseInfo = "LicenseInfo"
case version = "Version"
}
}
public struct LayersListItem: AWSDecodableShape {
/// The newest version of the layer.
public let latestMatchingVersion: LayerVersionsListItem?
/// The Amazon Resource Name (ARN) of the function layer.
public let layerArn: String?
/// The name of the layer.
public let layerName: String?
public init(latestMatchingVersion: LayerVersionsListItem? = nil, layerArn: String? = nil, layerName: String? = nil) {
self.latestMatchingVersion = latestMatchingVersion
self.layerArn = layerArn
self.layerName = layerName
}
private enum CodingKeys: String, CodingKey {
case latestMatchingVersion = "LatestMatchingVersion"
case layerArn = "LayerArn"
case layerName = "LayerName"
}
}
public struct ListAliasesRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "functionVersion", location: .querystring(locationName: "FunctionVersion")),
AWSMemberEncoding(label: "marker", location: .querystring(locationName: "Marker")),
AWSMemberEncoding(label: "maxItems", location: .querystring(locationName: "MaxItems"))
]
/// The name of the Lambda function. Name formats Function name - MyFunction. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction. Partial ARN - 123456789012:function:MyFunction. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// Specify a function version to only list aliases that invoke that version.
public let functionVersion: String?
/// Specify the pagination token that's returned by a previous request to retrieve the next page of results.
public let marker: String?
/// Limit the number of aliases returned.
public let maxItems: Int?
public init(functionName: String, functionVersion: String? = nil, marker: String? = nil, maxItems: Int? = nil) {
self.functionName = functionName
self.functionVersion = functionVersion
self.marker = marker
self.maxItems = maxItems
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.functionVersion, name: "functionVersion", parent: name, max: 1024)
try self.validate(self.functionVersion, name: "functionVersion", parent: name, min: 1)
try self.validate(self.functionVersion, name: "functionVersion", parent: name, pattern: "(\\$LATEST|[0-9]+)")
try self.validate(self.maxItems, name: "maxItems", parent: name, max: 10000)
try self.validate(self.maxItems, name: "maxItems", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListAliasesResponse: AWSDecodableShape {
/// A list of aliases.
public let aliases: [AliasConfiguration]?
/// The pagination token that's included if more results are available.
public let nextMarker: String?
public init(aliases: [AliasConfiguration]? = nil, nextMarker: String? = nil) {
self.aliases = aliases
self.nextMarker = nextMarker
}
private enum CodingKeys: String, CodingKey {
case aliases = "Aliases"
case nextMarker = "NextMarker"
}
}
public struct ListEventSourceMappingsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "eventSourceArn", location: .querystring(locationName: "EventSourceArn")),
AWSMemberEncoding(label: "functionName", location: .querystring(locationName: "FunctionName")),
AWSMemberEncoding(label: "marker", location: .querystring(locationName: "Marker")),
AWSMemberEncoding(label: "maxItems", location: .querystring(locationName: "MaxItems"))
]
/// The Amazon Resource Name (ARN) of the event source. Amazon Kinesis - The ARN of the data stream or a stream consumer. Amazon DynamoDB Streams - The ARN of the stream. Amazon Simple Queue Service - The ARN of the queue. Amazon Managed Streaming for Apache Kafka - The ARN of the cluster.
public let eventSourceArn: String?
/// The name of the Lambda function. Name formats Function name - MyFunction. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction. Version or Alias ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction:PROD. Partial ARN - 123456789012:function:MyFunction. The length constraint applies only to the full ARN. If you specify only the function name, it's limited to 64 characters in length.
public let functionName: String?
/// A pagination token returned by a previous call.
public let marker: String?
/// The maximum number of event source mappings to return.
public let maxItems: Int?
public init(eventSourceArn: String? = nil, functionName: String? = nil, marker: String? = nil, maxItems: Int? = nil) {
self.eventSourceArn = eventSourceArn
self.functionName = functionName
self.marker = marker
self.maxItems = maxItems
}
public func validate(name: String) throws {
try self.validate(self.eventSourceArn, name: "eventSourceArn", parent: name, pattern: "arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\\-])+:([a-z]{2}(-gov)?-[a-z]+-\\d{1})?:(\\d{12})?:(.*)")
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.maxItems, name: "maxItems", parent: name, max: 10000)
try self.validate(self.maxItems, name: "maxItems", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListEventSourceMappingsResponse: AWSDecodableShape {
/// A list of event source mappings.
public let eventSourceMappings: [EventSourceMappingConfiguration]?
/// A pagination token that's returned when the response doesn't contain all event source mappings.
public let nextMarker: String?
public init(eventSourceMappings: [EventSourceMappingConfiguration]? = nil, nextMarker: String? = nil) {
self.eventSourceMappings = eventSourceMappings
self.nextMarker = nextMarker
}
private enum CodingKeys: String, CodingKey {
case eventSourceMappings = "EventSourceMappings"
case nextMarker = "NextMarker"
}
}
public struct ListFunctionEventInvokeConfigsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "marker", location: .querystring(locationName: "Marker")),
AWSMemberEncoding(label: "maxItems", location: .querystring(locationName: "MaxItems"))
]
/// The name of the Lambda function. Name formats Function name - my-function. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// Specify the pagination token that's returned by a previous request to retrieve the next page of results.
public let marker: String?
/// The maximum number of configurations to return.
public let maxItems: Int?
public init(functionName: String, marker: String? = nil, maxItems: Int? = nil) {
self.functionName = functionName
self.marker = marker
self.maxItems = maxItems
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.maxItems, name: "maxItems", parent: name, max: 50)
try self.validate(self.maxItems, name: "maxItems", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListFunctionEventInvokeConfigsResponse: AWSDecodableShape {
/// A list of configurations.
public let functionEventInvokeConfigs: [FunctionEventInvokeConfig]?
/// The pagination token that's included if more results are available.
public let nextMarker: String?
public init(functionEventInvokeConfigs: [FunctionEventInvokeConfig]? = nil, nextMarker: String? = nil) {
self.functionEventInvokeConfigs = functionEventInvokeConfigs
self.nextMarker = nextMarker
}
private enum CodingKeys: String, CodingKey {
case functionEventInvokeConfigs = "FunctionEventInvokeConfigs"
case nextMarker = "NextMarker"
}
}
public struct ListFunctionsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionVersion", location: .querystring(locationName: "FunctionVersion")),
AWSMemberEncoding(label: "marker", location: .querystring(locationName: "Marker")),
AWSMemberEncoding(label: "masterRegion", location: .querystring(locationName: "MasterRegion")),
AWSMemberEncoding(label: "maxItems", location: .querystring(locationName: "MaxItems"))
]
/// Set to ALL to include entries for all published versions of each function.
public let functionVersion: FunctionVersion?
/// Specify the pagination token that's returned by a previous request to retrieve the next page of results.
public let marker: String?
/// For Lambda@Edge functions, the AWS Region of the master function. For example, us-east-1 filters the list of functions to only include Lambda@Edge functions replicated from a master function in US East (N. Virginia). If specified, you must set FunctionVersion to ALL.
public let masterRegion: SotoCore.Region?
/// The maximum number of functions to return.
public let maxItems: Int?
public init(functionVersion: FunctionVersion? = nil, marker: String? = nil, masterRegion: SotoCore.Region? = nil, maxItems: Int? = nil) {
self.functionVersion = functionVersion
self.marker = marker
self.masterRegion = masterRegion
self.maxItems = maxItems
}
public func validate(name: String) throws {
try self.validate(self.maxItems, name: "maxItems", parent: name, max: 10000)
try self.validate(self.maxItems, name: "maxItems", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListFunctionsResponse: AWSDecodableShape {
/// A list of Lambda functions.
public let functions: [FunctionConfiguration]?
/// The pagination token that's included if more results are available.
public let nextMarker: String?
public init(functions: [FunctionConfiguration]? = nil, nextMarker: String? = nil) {
self.functions = functions
self.nextMarker = nextMarker
}
private enum CodingKeys: String, CodingKey {
case functions = "Functions"
case nextMarker = "NextMarker"
}
}
public struct ListLayerVersionsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "compatibleRuntime", location: .querystring(locationName: "CompatibleRuntime")),
AWSMemberEncoding(label: "layerName", location: .uri(locationName: "LayerName")),
AWSMemberEncoding(label: "marker", location: .querystring(locationName: "Marker")),
AWSMemberEncoding(label: "maxItems", location: .querystring(locationName: "MaxItems"))
]
/// A runtime identifier. For example, go1.x.
public let compatibleRuntime: Runtime?
/// The name or Amazon Resource Name (ARN) of the layer.
public let layerName: String
/// A pagination token returned by a previous call.
public let marker: String?
/// The maximum number of versions to return.
public let maxItems: Int?
public init(compatibleRuntime: Runtime? = nil, layerName: String, marker: String? = nil, maxItems: Int? = nil) {
self.compatibleRuntime = compatibleRuntime
self.layerName = layerName
self.marker = marker
self.maxItems = maxItems
}
public func validate(name: String) throws {
try self.validate(self.layerName, name: "layerName", parent: name, max: 140)
try self.validate(self.layerName, name: "layerName", parent: name, min: 1)
try self.validate(self.layerName, name: "layerName", parent: name, pattern: "(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+")
try self.validate(self.maxItems, name: "maxItems", parent: name, max: 50)
try self.validate(self.maxItems, name: "maxItems", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListLayerVersionsResponse: AWSDecodableShape {
/// A list of versions.
public let layerVersions: [LayerVersionsListItem]?
/// A pagination token returned when the response doesn't contain all versions.
public let nextMarker: String?
public init(layerVersions: [LayerVersionsListItem]? = nil, nextMarker: String? = nil) {
self.layerVersions = layerVersions
self.nextMarker = nextMarker
}
private enum CodingKeys: String, CodingKey {
case layerVersions = "LayerVersions"
case nextMarker = "NextMarker"
}
}
public struct ListLayersRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "compatibleRuntime", location: .querystring(locationName: "CompatibleRuntime")),
AWSMemberEncoding(label: "marker", location: .querystring(locationName: "Marker")),
AWSMemberEncoding(label: "maxItems", location: .querystring(locationName: "MaxItems"))
]
/// A runtime identifier. For example, go1.x.
public let compatibleRuntime: Runtime?
/// A pagination token returned by a previous call.
public let marker: String?
/// The maximum number of layers to return.
public let maxItems: Int?
public init(compatibleRuntime: Runtime? = nil, marker: String? = nil, maxItems: Int? = nil) {
self.compatibleRuntime = compatibleRuntime
self.marker = marker
self.maxItems = maxItems
}
public func validate(name: String) throws {
try self.validate(self.maxItems, name: "maxItems", parent: name, max: 50)
try self.validate(self.maxItems, name: "maxItems", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListLayersResponse: AWSDecodableShape {
/// A list of function layers.
public let layers: [LayersListItem]?
/// A pagination token returned when the response doesn't contain all layers.
public let nextMarker: String?
public init(layers: [LayersListItem]? = nil, nextMarker: String? = nil) {
self.layers = layers
self.nextMarker = nextMarker
}
private enum CodingKeys: String, CodingKey {
case layers = "Layers"
case nextMarker = "NextMarker"
}
}
public struct ListProvisionedConcurrencyConfigsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "marker", location: .querystring(locationName: "Marker")),
AWSMemberEncoding(label: "maxItems", location: .querystring(locationName: "MaxItems"))
]
/// The name of the Lambda function. Name formats Function name - my-function. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// Specify the pagination token that's returned by a previous request to retrieve the next page of results.
public let marker: String?
/// Specify a number to limit the number of configurations returned.
public let maxItems: Int?
public init(functionName: String, marker: String? = nil, maxItems: Int? = nil) {
self.functionName = functionName
self.marker = marker
self.maxItems = maxItems
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.maxItems, name: "maxItems", parent: name, max: 50)
try self.validate(self.maxItems, name: "maxItems", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListProvisionedConcurrencyConfigsResponse: AWSDecodableShape {
/// The pagination token that's included if more results are available.
public let nextMarker: String?
/// A list of provisioned concurrency configurations.
public let provisionedConcurrencyConfigs: [ProvisionedConcurrencyConfigListItem]?
public init(nextMarker: String? = nil, provisionedConcurrencyConfigs: [ProvisionedConcurrencyConfigListItem]? = nil) {
self.nextMarker = nextMarker
self.provisionedConcurrencyConfigs = provisionedConcurrencyConfigs
}
private enum CodingKeys: String, CodingKey {
case nextMarker = "NextMarker"
case provisionedConcurrencyConfigs = "ProvisionedConcurrencyConfigs"
}
}
public struct ListTagsRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resource", location: .uri(locationName: "ARN"))
]
/// The function's Amazon Resource Name (ARN).
public let resource: String
public init(resource: String) {
self.resource = resource
}
public func validate(name: String) throws {
try self.validate(self.resource, name: "resource", parent: name, pattern: "arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\\d{1}:\\d{12}:function:[a-zA-Z0-9-_]+(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
}
private enum CodingKeys: CodingKey {}
}
public struct ListTagsResponse: AWSDecodableShape {
/// The function's tags.
public let tags: [String: String]?
public init(tags: [String: String]? = nil) {
self.tags = tags
}
private enum CodingKeys: String, CodingKey {
case tags = "Tags"
}
}
public struct ListVersionsByFunctionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "marker", location: .querystring(locationName: "Marker")),
AWSMemberEncoding(label: "maxItems", location: .querystring(locationName: "MaxItems"))
]
/// The name of the Lambda function. Name formats Function name - MyFunction. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction. Partial ARN - 123456789012:function:MyFunction. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// Specify the pagination token that's returned by a previous request to retrieve the next page of results.
public let marker: String?
/// The maximum number of versions to return.
public let maxItems: Int?
public init(functionName: String, marker: String? = nil, maxItems: Int? = nil) {
self.functionName = functionName
self.marker = marker
self.maxItems = maxItems
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 170)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_\\.]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.maxItems, name: "maxItems", parent: name, max: 10000)
try self.validate(self.maxItems, name: "maxItems", parent: name, min: 1)
}
private enum CodingKeys: CodingKey {}
}
public struct ListVersionsByFunctionResponse: AWSDecodableShape {
/// The pagination token that's included if more results are available.
public let nextMarker: String?
/// A list of Lambda function versions.
public let versions: [FunctionConfiguration]?
public init(nextMarker: String? = nil, versions: [FunctionConfiguration]? = nil) {
self.nextMarker = nextMarker
self.versions = versions
}
private enum CodingKeys: String, CodingKey {
case nextMarker = "NextMarker"
case versions = "Versions"
}
}
public struct OnFailure: AWSEncodableShape & AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the destination resource.
public let destination: String?
public init(destination: String? = nil) {
self.destination = destination
}
public func validate(name: String) throws {
try self.validate(self.destination, name: "destination", parent: name, max: 350)
try self.validate(self.destination, name: "destination", parent: name, min: 0)
try self.validate(self.destination, name: "destination", parent: name, pattern: "^$|arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\\-])+:([a-z]{2}(-gov)?-[a-z]+-\\d{1})?:(\\d{12})?:(.*)")
}
private enum CodingKeys: String, CodingKey {
case destination = "Destination"
}
}
public struct OnSuccess: AWSEncodableShape & AWSDecodableShape {
/// The Amazon Resource Name (ARN) of the destination resource.
public let destination: String?
public init(destination: String? = nil) {
self.destination = destination
}
public func validate(name: String) throws {
try self.validate(self.destination, name: "destination", parent: name, max: 350)
try self.validate(self.destination, name: "destination", parent: name, min: 0)
try self.validate(self.destination, name: "destination", parent: name, pattern: "^$|arn:(aws[a-zA-Z0-9-]*):([a-zA-Z0-9\\-])+:([a-z]{2}(-gov)?-[a-z]+-\\d{1})?:(\\d{12})?:(.*)")
}
private enum CodingKeys: String, CodingKey {
case destination = "Destination"
}
}
public struct ProvisionedConcurrencyConfigListItem: AWSDecodableShape {
/// The amount of provisioned concurrency allocated.
public let allocatedProvisionedConcurrentExecutions: Int?
/// The amount of provisioned concurrency available.
public let availableProvisionedConcurrentExecutions: Int?
/// The Amazon Resource Name (ARN) of the alias or version.
public let functionArn: String?
/// The date and time that a user last updated the configuration, in ISO 8601 format.
public let lastModified: String?
/// The amount of provisioned concurrency requested.
public let requestedProvisionedConcurrentExecutions: Int?
/// The status of the allocation process.
public let status: ProvisionedConcurrencyStatusEnum?
/// For failed allocations, the reason that provisioned concurrency could not be allocated.
public let statusReason: String?
public init(allocatedProvisionedConcurrentExecutions: Int? = nil, availableProvisionedConcurrentExecutions: Int? = nil, functionArn: String? = nil, lastModified: String? = nil, requestedProvisionedConcurrentExecutions: Int? = nil, status: ProvisionedConcurrencyStatusEnum? = nil, statusReason: String? = nil) {
self.allocatedProvisionedConcurrentExecutions = allocatedProvisionedConcurrentExecutions
self.availableProvisionedConcurrentExecutions = availableProvisionedConcurrentExecutions
self.functionArn = functionArn
self.lastModified = lastModified
self.requestedProvisionedConcurrentExecutions = requestedProvisionedConcurrentExecutions
self.status = status
self.statusReason = statusReason
}
private enum CodingKeys: String, CodingKey {
case allocatedProvisionedConcurrentExecutions = "AllocatedProvisionedConcurrentExecutions"
case availableProvisionedConcurrentExecutions = "AvailableProvisionedConcurrentExecutions"
case functionArn = "FunctionArn"
case lastModified = "LastModified"
case requestedProvisionedConcurrentExecutions = "RequestedProvisionedConcurrentExecutions"
case status = "Status"
case statusReason = "StatusReason"
}
}
public struct PublishLayerVersionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "layerName", location: .uri(locationName: "LayerName"))
]
/// A list of compatible function runtimes. Used for filtering with ListLayers and ListLayerVersions.
public let compatibleRuntimes: [Runtime]?
/// The function layer archive.
public let content: LayerVersionContentInput
/// The description of the version.
public let description: String?
/// The name or Amazon Resource Name (ARN) of the layer.
public let layerName: String
/// The layer's software license. It can be any of the following: An SPDX license identifier. For example, MIT. The URL of a license hosted on the internet. For example, https://opensource.org/licenses/MIT. The full text of the license.
public let licenseInfo: String?
public init(compatibleRuntimes: [Runtime]? = nil, content: LayerVersionContentInput, description: String? = nil, layerName: String, licenseInfo: String? = nil) {
self.compatibleRuntimes = compatibleRuntimes
self.content = content
self.description = description
self.layerName = layerName
self.licenseInfo = licenseInfo
}
public func validate(name: String) throws {
try self.validate(self.compatibleRuntimes, name: "compatibleRuntimes", parent: name, max: 5)
try self.content.validate(name: "\(name).content")
try self.validate(self.description, name: "description", parent: name, max: 256)
try self.validate(self.description, name: "description", parent: name, min: 0)
try self.validate(self.layerName, name: "layerName", parent: name, max: 140)
try self.validate(self.layerName, name: "layerName", parent: name, min: 1)
try self.validate(self.layerName, name: "layerName", parent: name, pattern: "(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+")
try self.validate(self.licenseInfo, name: "licenseInfo", parent: name, max: 512)
}
private enum CodingKeys: String, CodingKey {
case compatibleRuntimes = "CompatibleRuntimes"
case content = "Content"
case description = "Description"
case licenseInfo = "LicenseInfo"
}
}
public struct PublishLayerVersionResponse: AWSDecodableShape {
/// The layer's compatible runtimes.
public let compatibleRuntimes: [Runtime]?
/// Details about the layer version.
public let content: LayerVersionContentOutput?
/// The date that the layer version was created, in ISO-8601 format (YYYY-MM-DDThh:mm:ss.sTZD).
public let createdDate: String?
/// The description of the version.
public let description: String?
/// The ARN of the layer.
public let layerArn: String?
/// The ARN of the layer version.
public let layerVersionArn: String?
/// The layer's software license.
public let licenseInfo: String?
/// The version number.
public let version: Int64?
public init(compatibleRuntimes: [Runtime]? = nil, content: LayerVersionContentOutput? = nil, createdDate: String? = nil, description: String? = nil, layerArn: String? = nil, layerVersionArn: String? = nil, licenseInfo: String? = nil, version: Int64? = nil) {
self.compatibleRuntimes = compatibleRuntimes
self.content = content
self.createdDate = createdDate
self.description = description
self.layerArn = layerArn
self.layerVersionArn = layerVersionArn
self.licenseInfo = licenseInfo
self.version = version
}
private enum CodingKeys: String, CodingKey {
case compatibleRuntimes = "CompatibleRuntimes"
case content = "Content"
case createdDate = "CreatedDate"
case description = "Description"
case layerArn = "LayerArn"
case layerVersionArn = "LayerVersionArn"
case licenseInfo = "LicenseInfo"
case version = "Version"
}
}
public struct PublishVersionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName"))
]
/// Only publish a version if the hash value matches the value that's specified. Use this option to avoid publishing a version if the function code has changed since you last updated it. You can get the hash for the version that you uploaded from the output of UpdateFunctionCode.
public let codeSha256: String?
/// A description for the version to override the description in the function configuration.
public let description: String?
/// The name of the Lambda function. Name formats Function name - MyFunction. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction. Partial ARN - 123456789012:function:MyFunction. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// Only update the function if the revision ID matches the ID that's specified. Use this option to avoid publishing a version if the function configuration has changed since you last updated it.
public let revisionId: String?
public init(codeSha256: String? = nil, description: String? = nil, functionName: String, revisionId: String? = nil) {
self.codeSha256 = codeSha256
self.description = description
self.functionName = functionName
self.revisionId = revisionId
}
public func validate(name: String) throws {
try self.validate(self.description, name: "description", parent: name, max: 256)
try self.validate(self.description, name: "description", parent: name, min: 0)
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
}
private enum CodingKeys: String, CodingKey {
case codeSha256 = "CodeSha256"
case description = "Description"
case revisionId = "RevisionId"
}
}
public struct PutFunctionConcurrencyRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName"))
]
/// The name of the Lambda function. Name formats Function name - my-function. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The number of simultaneous executions to reserve for the function.
public let reservedConcurrentExecutions: Int
public init(functionName: String, reservedConcurrentExecutions: Int) {
self.functionName = functionName
self.reservedConcurrentExecutions = reservedConcurrentExecutions
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.reservedConcurrentExecutions, name: "reservedConcurrentExecutions", parent: name, min: 0)
}
private enum CodingKeys: String, CodingKey {
case reservedConcurrentExecutions = "ReservedConcurrentExecutions"
}
}
public struct PutFunctionEventInvokeConfigRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier"))
]
/// A destination for events after they have been sent to a function for processing. Destinations Function - The Amazon Resource Name (ARN) of a Lambda function. Queue - The ARN of an SQS queue. Topic - The ARN of an SNS topic. Event Bus - The ARN of an Amazon EventBridge event bus.
public let destinationConfig: DestinationConfig?
/// The name of the Lambda function, version, or alias. Name formats Function name - my-function (name-only), my-function:v1 (with alias). Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The maximum age of a request that Lambda sends to a function for processing.
public let maximumEventAgeInSeconds: Int?
/// The maximum number of times to retry when the function returns an error.
public let maximumRetryAttempts: Int?
/// A version number or alias name.
public let qualifier: String?
public init(destinationConfig: DestinationConfig? = nil, functionName: String, maximumEventAgeInSeconds: Int? = nil, maximumRetryAttempts: Int? = nil, qualifier: String? = nil) {
self.destinationConfig = destinationConfig
self.functionName = functionName
self.maximumEventAgeInSeconds = maximumEventAgeInSeconds
self.maximumRetryAttempts = maximumRetryAttempts
self.qualifier = qualifier
}
public func validate(name: String) throws {
try self.destinationConfig?.validate(name: "\(name).destinationConfig")
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.maximumEventAgeInSeconds, name: "maximumEventAgeInSeconds", parent: name, max: 21600)
try self.validate(self.maximumEventAgeInSeconds, name: "maximumEventAgeInSeconds", parent: name, min: 60)
try self.validate(self.maximumRetryAttempts, name: "maximumRetryAttempts", parent: name, max: 2)
try self.validate(self.maximumRetryAttempts, name: "maximumRetryAttempts", parent: name, min: 0)
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
}
private enum CodingKeys: String, CodingKey {
case destinationConfig = "DestinationConfig"
case maximumEventAgeInSeconds = "MaximumEventAgeInSeconds"
case maximumRetryAttempts = "MaximumRetryAttempts"
}
}
public struct PutProvisionedConcurrencyConfigRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier"))
]
/// The name of the Lambda function. Name formats Function name - my-function. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The amount of provisioned concurrency to allocate for the version or alias.
public let provisionedConcurrentExecutions: Int
/// The version number or alias name.
public let qualifier: String
public init(functionName: String, provisionedConcurrentExecutions: Int, qualifier: String) {
self.functionName = functionName
self.provisionedConcurrentExecutions = provisionedConcurrentExecutions
self.qualifier = qualifier
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.provisionedConcurrentExecutions, name: "provisionedConcurrentExecutions", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
}
private enum CodingKeys: String, CodingKey {
case provisionedConcurrentExecutions = "ProvisionedConcurrentExecutions"
}
}
public struct PutProvisionedConcurrencyConfigResponse: AWSDecodableShape {
/// The amount of provisioned concurrency allocated.
public let allocatedProvisionedConcurrentExecutions: Int?
/// The amount of provisioned concurrency available.
public let availableProvisionedConcurrentExecutions: Int?
/// The date and time that a user last updated the configuration, in ISO 8601 format.
public let lastModified: String?
/// The amount of provisioned concurrency requested.
public let requestedProvisionedConcurrentExecutions: Int?
/// The status of the allocation process.
public let status: ProvisionedConcurrencyStatusEnum?
/// For failed allocations, the reason that provisioned concurrency could not be allocated.
public let statusReason: String?
public init(allocatedProvisionedConcurrentExecutions: Int? = nil, availableProvisionedConcurrentExecutions: Int? = nil, lastModified: String? = nil, requestedProvisionedConcurrentExecutions: Int? = nil, status: ProvisionedConcurrencyStatusEnum? = nil, statusReason: String? = nil) {
self.allocatedProvisionedConcurrentExecutions = allocatedProvisionedConcurrentExecutions
self.availableProvisionedConcurrentExecutions = availableProvisionedConcurrentExecutions
self.lastModified = lastModified
self.requestedProvisionedConcurrentExecutions = requestedProvisionedConcurrentExecutions
self.status = status
self.statusReason = statusReason
}
private enum CodingKeys: String, CodingKey {
case allocatedProvisionedConcurrentExecutions = "AllocatedProvisionedConcurrentExecutions"
case availableProvisionedConcurrentExecutions = "AvailableProvisionedConcurrentExecutions"
case lastModified = "LastModified"
case requestedProvisionedConcurrentExecutions = "RequestedProvisionedConcurrentExecutions"
case status = "Status"
case statusReason = "StatusReason"
}
}
public struct RemoveLayerVersionPermissionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "layerName", location: .uri(locationName: "LayerName")),
AWSMemberEncoding(label: "revisionId", location: .querystring(locationName: "RevisionId")),
AWSMemberEncoding(label: "statementId", location: .uri(locationName: "StatementId")),
AWSMemberEncoding(label: "versionNumber", location: .uri(locationName: "VersionNumber"))
]
/// The name or Amazon Resource Name (ARN) of the layer.
public let layerName: String
/// Only update the policy if the revision ID matches the ID specified. Use this option to avoid modifying a policy that has changed since you last read it.
public let revisionId: String?
/// The identifier that was specified when the statement was added.
public let statementId: String
/// The version number.
public let versionNumber: Int64
public init(layerName: String, revisionId: String? = nil, statementId: String, versionNumber: Int64) {
self.layerName = layerName
self.revisionId = revisionId
self.statementId = statementId
self.versionNumber = versionNumber
}
public func validate(name: String) throws {
try self.validate(self.layerName, name: "layerName", parent: name, max: 140)
try self.validate(self.layerName, name: "layerName", parent: name, min: 1)
try self.validate(self.layerName, name: "layerName", parent: name, pattern: "(arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\\d{12}:layer:[a-zA-Z0-9-_]+)|[a-zA-Z0-9-_]+")
try self.validate(self.statementId, name: "statementId", parent: name, max: 100)
try self.validate(self.statementId, name: "statementId", parent: name, min: 1)
try self.validate(self.statementId, name: "statementId", parent: name, pattern: "([a-zA-Z0-9-_]+)")
}
private enum CodingKeys: CodingKey {}
}
public struct RemovePermissionRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier")),
AWSMemberEncoding(label: "revisionId", location: .querystring(locationName: "RevisionId")),
AWSMemberEncoding(label: "statementId", location: .uri(locationName: "StatementId"))
]
/// The name of the Lambda function, version, or alias. Name formats Function name - my-function (name-only), my-function:v1 (with alias). Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// Specify a version or alias to remove permissions from a published version of the function.
public let qualifier: String?
/// Only update the policy if the revision ID matches the ID that's specified. Use this option to avoid modifying a policy that has changed since you last read it.
public let revisionId: String?
/// Statement ID of the permission to remove.
public let statementId: String
public init(functionName: String, qualifier: String? = nil, revisionId: String? = nil, statementId: String) {
self.functionName = functionName
self.qualifier = qualifier
self.revisionId = revisionId
self.statementId = statementId
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
try self.validate(self.statementId, name: "statementId", parent: name, max: 100)
try self.validate(self.statementId, name: "statementId", parent: name, min: 1)
try self.validate(self.statementId, name: "statementId", parent: name, pattern: "([a-zA-Z0-9-_.]+)")
}
private enum CodingKeys: CodingKey {}
}
public struct TagResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resource", location: .uri(locationName: "ARN"))
]
/// The function's Amazon Resource Name (ARN).
public let resource: String
/// A list of tags to apply to the function.
public let tags: [String: String]
public init(resource: String, tags: [String: String]) {
self.resource = resource
self.tags = tags
}
public func validate(name: String) throws {
try self.validate(self.resource, name: "resource", parent: name, pattern: "arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\\d{1}:\\d{12}:function:[a-zA-Z0-9-_]+(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
}
private enum CodingKeys: String, CodingKey {
case tags = "Tags"
}
}
public struct TracingConfig: AWSEncodableShape {
/// The tracing mode.
public let mode: TracingMode?
public init(mode: TracingMode? = nil) {
self.mode = mode
}
private enum CodingKeys: String, CodingKey {
case mode = "Mode"
}
}
public struct TracingConfigResponse: AWSDecodableShape {
/// The tracing mode.
public let mode: TracingMode?
public init(mode: TracingMode? = nil) {
self.mode = mode
}
private enum CodingKeys: String, CodingKey {
case mode = "Mode"
}
}
public struct UntagResourceRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "resource", location: .uri(locationName: "ARN")),
AWSMemberEncoding(label: "tagKeys", location: .querystring(locationName: "tagKeys"))
]
/// The function's Amazon Resource Name (ARN).
public let resource: String
/// A list of tag keys to remove from the function.
public let tagKeys: [String]
public init(resource: String, tagKeys: [String]) {
self.resource = resource
self.tagKeys = tagKeys
}
public func validate(name: String) throws {
try self.validate(self.resource, name: "resource", parent: name, pattern: "arn:(aws[a-zA-Z-]*)?:lambda:[a-z]{2}(-gov)?-[a-z]+-\\d{1}:\\d{12}:function:[a-zA-Z0-9-_]+(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
}
private enum CodingKeys: CodingKey {}
}
public struct UpdateAliasRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "name", location: .uri(locationName: "Name"))
]
/// A description of the alias.
public let description: String?
/// The name of the Lambda function. Name formats Function name - MyFunction. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction. Partial ARN - 123456789012:function:MyFunction. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The function version that the alias invokes.
public let functionVersion: String?
/// The name of the alias.
public let name: String
/// Only update the alias if the revision ID matches the ID that's specified. Use this option to avoid modifying an alias that has changed since you last read it.
public let revisionId: String?
/// The routing configuration of the alias.
public let routingConfig: AliasRoutingConfiguration?
public init(description: String? = nil, functionName: String, functionVersion: String? = nil, name: String, revisionId: String? = nil, routingConfig: AliasRoutingConfiguration? = nil) {
self.description = description
self.functionName = functionName
self.functionVersion = functionVersion
self.name = name
self.revisionId = revisionId
self.routingConfig = routingConfig
}
public func validate(name: String) throws {
try self.validate(self.description, name: "description", parent: name, max: 256)
try self.validate(self.description, name: "description", parent: name, min: 0)
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.functionVersion, name: "functionVersion", parent: name, max: 1024)
try self.validate(self.functionVersion, name: "functionVersion", parent: name, min: 1)
try self.validate(self.functionVersion, name: "functionVersion", parent: name, pattern: "(\\$LATEST|[0-9]+)")
try self.validate(self.name, name: "name", parent: name, max: 128)
try self.validate(self.name, name: "name", parent: name, min: 1)
try self.validate(self.name, name: "name", parent: name, pattern: "(?!^[0-9]+$)([a-zA-Z0-9-_]+)")
try self.routingConfig?.validate(name: "\(name).routingConfig")
}
private enum CodingKeys: String, CodingKey {
case description = "Description"
case functionVersion = "FunctionVersion"
case revisionId = "RevisionId"
case routingConfig = "RoutingConfig"
}
}
public struct UpdateEventSourceMappingRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "uuid", location: .uri(locationName: "UUID"))
]
/// The maximum number of items to retrieve in a single batch. Amazon Kinesis - Default 100. Max 10,000. Amazon DynamoDB Streams - Default 100. Max 1,000. Amazon Simple Queue Service - Default 10. Max 10. Amazon Managed Streaming for Apache Kafka - Default 100. Max 10,000.
public let batchSize: Int?
/// (Streams) If the function returns an error, split the batch in two and retry.
public let bisectBatchOnFunctionError: Bool?
/// (Streams) An Amazon SQS queue or Amazon SNS topic destination for discarded records.
public let destinationConfig: DestinationConfig?
/// If true, the event source mapping is active. Set to false to pause polling and invocation.
public let enabled: Bool?
/// The name of the Lambda function. Name formats Function name - MyFunction. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction. Version or Alias ARN - arn:aws:lambda:us-west-2:123456789012:function:MyFunction:PROD. Partial ARN - 123456789012:function:MyFunction. The length constraint applies only to the full ARN. If you specify only the function name, it's limited to 64 characters in length.
public let functionName: String?
/// (Streams) The maximum amount of time to gather records before invoking the function, in seconds.
public let maximumBatchingWindowInSeconds: Int?
/// (Streams) Discard records older than the specified age. The default value is infinite (-1).
public let maximumRecordAgeInSeconds: Int?
/// (Streams) Discard records after the specified number of retries. The default value is infinite (-1). When set to infinite (-1), failed records will be retried until the record expires.
public let maximumRetryAttempts: Int?
/// (Streams) The number of batches to process from each shard concurrently.
public let parallelizationFactor: Int?
/// The identifier of the event source mapping.
public let uuid: String
public init(batchSize: Int? = nil, bisectBatchOnFunctionError: Bool? = nil, destinationConfig: DestinationConfig? = nil, enabled: Bool? = nil, functionName: String? = nil, maximumBatchingWindowInSeconds: Int? = nil, maximumRecordAgeInSeconds: Int? = nil, maximumRetryAttempts: Int? = nil, parallelizationFactor: Int? = nil, uuid: String) {
self.batchSize = batchSize
self.bisectBatchOnFunctionError = bisectBatchOnFunctionError
self.destinationConfig = destinationConfig
self.enabled = enabled
self.functionName = functionName
self.maximumBatchingWindowInSeconds = maximumBatchingWindowInSeconds
self.maximumRecordAgeInSeconds = maximumRecordAgeInSeconds
self.maximumRetryAttempts = maximumRetryAttempts
self.parallelizationFactor = parallelizationFactor
self.uuid = uuid
}
public func validate(name: String) throws {
try self.validate(self.batchSize, name: "batchSize", parent: name, max: 10000)
try self.validate(self.batchSize, name: "batchSize", parent: name, min: 1)
try self.destinationConfig?.validate(name: "\(name).destinationConfig")
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.maximumBatchingWindowInSeconds, name: "maximumBatchingWindowInSeconds", parent: name, max: 300)
try self.validate(self.maximumBatchingWindowInSeconds, name: "maximumBatchingWindowInSeconds", parent: name, min: 0)
try self.validate(self.maximumRecordAgeInSeconds, name: "maximumRecordAgeInSeconds", parent: name, max: 604_800)
try self.validate(self.maximumRecordAgeInSeconds, name: "maximumRecordAgeInSeconds", parent: name, min: -1)
try self.validate(self.maximumRetryAttempts, name: "maximumRetryAttempts", parent: name, max: 10000)
try self.validate(self.maximumRetryAttempts, name: "maximumRetryAttempts", parent: name, min: -1)
try self.validate(self.parallelizationFactor, name: "parallelizationFactor", parent: name, max: 10)
try self.validate(self.parallelizationFactor, name: "parallelizationFactor", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case batchSize = "BatchSize"
case bisectBatchOnFunctionError = "BisectBatchOnFunctionError"
case destinationConfig = "DestinationConfig"
case enabled = "Enabled"
case functionName = "FunctionName"
case maximumBatchingWindowInSeconds = "MaximumBatchingWindowInSeconds"
case maximumRecordAgeInSeconds = "MaximumRecordAgeInSeconds"
case maximumRetryAttempts = "MaximumRetryAttempts"
case parallelizationFactor = "ParallelizationFactor"
}
}
public struct UpdateFunctionCodeRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName"))
]
/// Set to true to validate the request parameters and access permissions without modifying the function code.
public let dryRun: Bool?
/// The name of the Lambda function. Name formats Function name - my-function. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// Set to true to publish a new version of the function after updating the code. This has the same effect as calling PublishVersion separately.
public let publish: Bool?
/// Only update the function if the revision ID matches the ID that's specified. Use this option to avoid modifying a function that has changed since you last read it.
public let revisionId: String?
/// An Amazon S3 bucket in the same AWS Region as your function. The bucket can be in a different AWS account.
public let s3Bucket: String?
/// The Amazon S3 key of the deployment package.
public let s3Key: String?
/// For versioned objects, the version of the deployment package object to use.
public let s3ObjectVersion: String?
/// The base64-encoded contents of the deployment package. AWS SDK and AWS CLI clients handle the encoding for you.
public let zipFile: Data?
public init(dryRun: Bool? = nil, functionName: String, publish: Bool? = nil, revisionId: String? = nil, s3Bucket: String? = nil, s3Key: String? = nil, s3ObjectVersion: String? = nil, zipFile: Data? = nil) {
self.dryRun = dryRun
self.functionName = functionName
self.publish = publish
self.revisionId = revisionId
self.s3Bucket = s3Bucket
self.s3Key = s3Key
self.s3ObjectVersion = s3ObjectVersion
self.zipFile = zipFile
}
public func validate(name: String) throws {
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.s3Bucket, name: "s3Bucket", parent: name, max: 63)
try self.validate(self.s3Bucket, name: "s3Bucket", parent: name, min: 3)
try self.validate(self.s3Bucket, name: "s3Bucket", parent: name, pattern: "^[0-9A-Za-z\\.\\-_]*(?<!\\.)$")
try self.validate(self.s3Key, name: "s3Key", parent: name, max: 1024)
try self.validate(self.s3Key, name: "s3Key", parent: name, min: 1)
try self.validate(self.s3ObjectVersion, name: "s3ObjectVersion", parent: name, max: 1024)
try self.validate(self.s3ObjectVersion, name: "s3ObjectVersion", parent: name, min: 1)
}
private enum CodingKeys: String, CodingKey {
case dryRun = "DryRun"
case publish = "Publish"
case revisionId = "RevisionId"
case s3Bucket = "S3Bucket"
case s3Key = "S3Key"
case s3ObjectVersion = "S3ObjectVersion"
case zipFile = "ZipFile"
}
}
public struct UpdateFunctionConfigurationRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName"))
]
/// A dead letter queue configuration that specifies the queue or topic where Lambda sends asynchronous events when they fail processing. For more information, see Dead Letter Queues.
public let deadLetterConfig: DeadLetterConfig?
/// A description of the function.
public let description: String?
/// Environment variables that are accessible from function code during execution.
public let environment: Environment?
/// Connection settings for an Amazon EFS file system.
public let fileSystemConfigs: [FileSystemConfig]?
/// The name of the Lambda function. Name formats Function name - my-function. Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The name of the method within your code that Lambda calls to execute your function. The format includes the file name. It can also include namespaces and other qualifiers, depending on the runtime. For more information, see Programming Model.
public let handler: String?
/// The ARN of the AWS Key Management Service (AWS KMS) key that's used to encrypt your function's environment variables. If it's not provided, AWS Lambda uses a default service key.
public let kMSKeyArn: String?
/// A list of function layers to add to the function's execution environment. Specify each layer by its ARN, including the version.
public let layers: [String]?
/// The amount of memory that your function has access to. Increasing the function's memory also increases its CPU allocation. The default value is 128 MB. The value must be a multiple of 64 MB.
public let memorySize: Int?
/// Only update the function if the revision ID matches the ID that's specified. Use this option to avoid modifying a function that has changed since you last read it.
public let revisionId: String?
/// The Amazon Resource Name (ARN) of the function's execution role.
public let role: String?
/// The identifier of the function's runtime.
public let runtime: Runtime?
/// The amount of time that Lambda allows a function to run before stopping it. The default is 3 seconds. The maximum allowed value is 900 seconds.
public let timeout: Int?
/// Set Mode to Active to sample and trace a subset of incoming requests with AWS X-Ray.
public let tracingConfig: TracingConfig?
/// For network connectivity to AWS resources in a VPC, specify a list of security groups and subnets in the VPC. When you connect a function to a VPC, it can only access resources and the internet through that VPC. For more information, see VPC Settings.
public let vpcConfig: VpcConfig?
public init(deadLetterConfig: DeadLetterConfig? = nil, description: String? = nil, environment: Environment? = nil, fileSystemConfigs: [FileSystemConfig]? = nil, functionName: String, handler: String? = nil, kMSKeyArn: String? = nil, layers: [String]? = nil, memorySize: Int? = nil, revisionId: String? = nil, role: String? = nil, runtime: Runtime? = nil, timeout: Int? = nil, tracingConfig: TracingConfig? = nil, vpcConfig: VpcConfig? = nil) {
self.deadLetterConfig = deadLetterConfig
self.description = description
self.environment = environment
self.fileSystemConfigs = fileSystemConfigs
self.functionName = functionName
self.handler = handler
self.kMSKeyArn = kMSKeyArn
self.layers = layers
self.memorySize = memorySize
self.revisionId = revisionId
self.role = role
self.runtime = runtime
self.timeout = timeout
self.tracingConfig = tracingConfig
self.vpcConfig = vpcConfig
}
public func validate(name: String) throws {
try self.deadLetterConfig?.validate(name: "\(name).deadLetterConfig")
try self.validate(self.description, name: "description", parent: name, max: 256)
try self.validate(self.description, name: "description", parent: name, min: 0)
try self.environment?.validate(name: "\(name).environment")
try self.fileSystemConfigs?.forEach {
try $0.validate(name: "\(name).fileSystemConfigs[]")
}
try self.validate(self.fileSystemConfigs, name: "fileSystemConfigs", parent: name, max: 1)
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.handler, name: "handler", parent: name, max: 128)
try self.validate(self.handler, name: "handler", parent: name, pattern: "[^\\s]+")
try self.validate(self.kMSKeyArn, name: "kMSKeyArn", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:[a-z0-9-.]+:.*)|()")
try self.layers?.forEach {
try validate($0, name: "layers[]", parent: name, max: 140)
try validate($0, name: "layers[]", parent: name, min: 1)
try validate($0, name: "layers[]", parent: name, pattern: "arn:[a-zA-Z0-9-]+:lambda:[a-zA-Z0-9-]+:\\d{12}:layer:[a-zA-Z0-9-_]+:[0-9]+")
}
try self.validate(self.memorySize, name: "memorySize", parent: name, max: 3008)
try self.validate(self.memorySize, name: "memorySize", parent: name, min: 128)
try self.validate(self.role, name: "role", parent: name, pattern: "arn:(aws[a-zA-Z-]*)?:iam::\\d{12}:role/?[a-zA-Z_0-9+=,.@\\-_/]+")
try self.validate(self.timeout, name: "timeout", parent: name, min: 1)
try self.vpcConfig?.validate(name: "\(name).vpcConfig")
}
private enum CodingKeys: String, CodingKey {
case deadLetterConfig = "DeadLetterConfig"
case description = "Description"
case environment = "Environment"
case fileSystemConfigs = "FileSystemConfigs"
case handler = "Handler"
case kMSKeyArn = "KMSKeyArn"
case layers = "Layers"
case memorySize = "MemorySize"
case revisionId = "RevisionId"
case role = "Role"
case runtime = "Runtime"
case timeout = "Timeout"
case tracingConfig = "TracingConfig"
case vpcConfig = "VpcConfig"
}
}
public struct UpdateFunctionEventInvokeConfigRequest: AWSEncodableShape {
public static var _encoding = [
AWSMemberEncoding(label: "functionName", location: .uri(locationName: "FunctionName")),
AWSMemberEncoding(label: "qualifier", location: .querystring(locationName: "Qualifier"))
]
/// A destination for events after they have been sent to a function for processing. Destinations Function - The Amazon Resource Name (ARN) of a Lambda function. Queue - The ARN of an SQS queue. Topic - The ARN of an SNS topic. Event Bus - The ARN of an Amazon EventBridge event bus.
public let destinationConfig: DestinationConfig?
/// The name of the Lambda function, version, or alias. Name formats Function name - my-function (name-only), my-function:v1 (with alias). Function ARN - arn:aws:lambda:us-west-2:123456789012:function:my-function. Partial ARN - 123456789012:function:my-function. You can append a version number or alias to any of the formats. The length constraint applies only to the full ARN. If you specify only the function name, it is limited to 64 characters in length.
public let functionName: String
/// The maximum age of a request that Lambda sends to a function for processing.
public let maximumEventAgeInSeconds: Int?
/// The maximum number of times to retry when the function returns an error.
public let maximumRetryAttempts: Int?
/// A version number or alias name.
public let qualifier: String?
public init(destinationConfig: DestinationConfig? = nil, functionName: String, maximumEventAgeInSeconds: Int? = nil, maximumRetryAttempts: Int? = nil, qualifier: String? = nil) {
self.destinationConfig = destinationConfig
self.functionName = functionName
self.maximumEventAgeInSeconds = maximumEventAgeInSeconds
self.maximumRetryAttempts = maximumRetryAttempts
self.qualifier = qualifier
}
public func validate(name: String) throws {
try self.destinationConfig?.validate(name: "\(name).destinationConfig")
try self.validate(self.functionName, name: "functionName", parent: name, max: 140)
try self.validate(self.functionName, name: "functionName", parent: name, min: 1)
try self.validate(self.functionName, name: "functionName", parent: name, pattern: "(arn:(aws[a-zA-Z-]*)?:lambda:)?([a-z]{2}(-gov)?-[a-z]+-\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_]+)(:(\\$LATEST|[a-zA-Z0-9-_]+))?")
try self.validate(self.maximumEventAgeInSeconds, name: "maximumEventAgeInSeconds", parent: name, max: 21600)
try self.validate(self.maximumEventAgeInSeconds, name: "maximumEventAgeInSeconds", parent: name, min: 60)
try self.validate(self.maximumRetryAttempts, name: "maximumRetryAttempts", parent: name, max: 2)
try self.validate(self.maximumRetryAttempts, name: "maximumRetryAttempts", parent: name, min: 0)
try self.validate(self.qualifier, name: "qualifier", parent: name, max: 128)
try self.validate(self.qualifier, name: "qualifier", parent: name, min: 1)
try self.validate(self.qualifier, name: "qualifier", parent: name, pattern: "(|[a-zA-Z0-9$_-]+)")
}
private enum CodingKeys: String, CodingKey {
case destinationConfig = "DestinationConfig"
case maximumEventAgeInSeconds = "MaximumEventAgeInSeconds"
case maximumRetryAttempts = "MaximumRetryAttempts"
}
}
public struct VpcConfig: AWSEncodableShape {
/// A list of VPC security groups IDs.
public let securityGroupIds: [String]?
/// A list of VPC subnet IDs.
public let subnetIds: [String]?
public init(securityGroupIds: [String]? = nil, subnetIds: [String]? = nil) {
self.securityGroupIds = securityGroupIds
self.subnetIds = subnetIds
}
public func validate(name: String) throws {
try self.validate(self.securityGroupIds, name: "securityGroupIds", parent: name, max: 5)
try self.validate(self.subnetIds, name: "subnetIds", parent: name, max: 16)
}
private enum CodingKeys: String, CodingKey {
case securityGroupIds = "SecurityGroupIds"
case subnetIds = "SubnetIds"
}
}
public struct VpcConfigResponse: AWSDecodableShape {
/// A list of VPC security groups IDs.
public let securityGroupIds: [String]?
/// A list of VPC subnet IDs.
public let subnetIds: [String]?
/// The ID of the VPC.
public let vpcId: String?
public init(securityGroupIds: [String]? = nil, subnetIds: [String]? = nil, vpcId: String? = nil) {
self.securityGroupIds = securityGroupIds
self.subnetIds = subnetIds
self.vpcId = vpcId
}
private enum CodingKeys: String, CodingKey {
case securityGroupIds = "SecurityGroupIds"
case subnetIds = "SubnetIds"
case vpcId = "VpcId"
}
}
}
| apache-2.0 | 468f99ea6e2fe34f249f39af01eb7a2e | 55.470941 | 875 | 0.64904 | 4.823087 | false | true | false | false |
devincoughlin/swift | test/Constraints/patterns.swift | 1 | 10779 | // RUN: %target-typecheck-verify-swift
// Leaf expression patterns are matched to corresponding pieces of a switch
// subject (TODO: or ~= expression) using ~= overload resolution.
switch (1, 2.5, "three") {
case (1, _, _):
()
// Double is ExpressibleByIntegerLiteral
case (_, 2, _),
(_, 2.5, _),
(_, _, "three"):
()
// ~= overloaded for (Range<Int>, Int)
case (0..<10, _, _),
(0..<10, 2.5, "three"),
(0...9, _, _),
(0...9, 2.5, "three"):
()
default:
()
}
switch (1, 2) {
case (var a, a): // expected-error {{use of unresolved identifier 'a'}}
()
}
// 'is' patterns can perform the same checks that 'is' expressions do.
protocol P { func p() }
class B : P {
init() {}
func p() {}
func b() {}
}
class D : B {
override init() { super.init() }
func d() {}
}
class E {
init() {}
func e() {}
}
struct S : P {
func p() {}
func s() {}
}
// Existential-to-concrete.
var bp : P = B()
switch bp {
case is B,
is D,
is S:
()
case is E:
()
default:
()
}
switch bp {
case let b as B:
b.b()
case let d as D:
d.b()
d.d()
case let s as S:
s.s()
case let e as E:
e.e()
default:
()
}
// Super-to-subclass.
var db : B = D()
switch db {
case is D:
()
case is E: // expected-warning {{always fails}}
()
default:
()
}
// Raise an error if pattern productions are used in expressions.
var b = var a // expected-error{{expected initial value after '='}} expected-error {{type annotation missing in pattern}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
var c = is Int // expected-error{{expected initial value after '='}} expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
// TODO: Bad recovery in these cases. Although patterns are never valid
// expr-unary productions, it would be good to parse them anyway for recovery.
//var e = 2 + var y
//var e = var y + 2
// 'E.Case' can be used in a dynamic type context as an equivalent to
// '.Case as E'.
protocol HairType {}
enum MacbookHair: HairType {
case HairSupply(S)
}
enum iPadHair<T>: HairType {
case HairForceOne
}
enum Watch {
case Sport, Watch, Edition
}
let hair: HairType = MacbookHair.HairSupply(S())
switch hair {
case MacbookHair.HairSupply(let s):
s.s()
case iPadHair<S>.HairForceOne:
()
case iPadHair<E>.HairForceOne:
()
case iPadHair.HairForceOne: // expected-error{{generic enum type 'iPadHair' is ambiguous without explicit generic parameters when matching value of type 'HairType'}}
()
case Watch.Edition: // expected-warning {{cast from 'HairType' to unrelated type 'Watch' always fails}}
()
case .HairForceOne: // expected-error{{type 'HairType' has no member 'HairForceOne'}}
()
default:
break
}
// <rdar://problem/19382878> Introduce new x? pattern
switch Optional(42) {
case let x?: break // expected-warning{{immutable value 'x' was never used; consider replacing with '_' or removing it}}
case nil: break
}
func SR2066(x: Int?) {
// nil literals should still work when wrapped in parentheses
switch x {
case (nil): break
case _?: break
}
switch x {
case ((nil)): break
case _?: break
}
switch (x, x) {
case ((nil), _): break
case (_?, _): break
}
}
// Test x???? patterns.
switch (nil as Int???) {
case let x???: print(x, terminator: "")
case let x??: print(x as Any, terminator: "")
case let x?: print(x as Any, terminator: "")
case 4???: break
case nil??: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
case nil?: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
default: break
}
switch ("foo" as String?) {
case "what": break
default: break
}
// Test some value patterns.
let x : Int?
extension Int {
func method() -> Int { return 42 }
}
func ~= <T : Equatable>(lhs: T?, rhs: T?) -> Bool {
return lhs == rhs
}
switch 4 as Int? {
case x?.method(): break // match value
default: break
}
switch 4 {
case x ?? 42: break // match value
default: break
}
for (var x) in 0...100 {} // expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}}
for var x in 0...100 {} // rdar://20167543 expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}}
for (let x) in 0...100 { _ = x} // expected-error {{'let' pattern cannot appear nested in an already immutable context}}
var (let y) = 42 // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}}
let (var z) = 42 // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}}
// Crash when re-typechecking EnumElementPattern.
// FIXME: This should actually type-check -- the diagnostics are bogus. But
// at least we don't crash anymore.
protocol PP {
associatedtype E
}
struct A<T> : PP {
typealias E = T
}
extension PP {
func map<T>(_ f: (Self.E) -> T) -> T {}
}
enum EE {
case A
case B
}
func good(_ a: A<EE>) -> Int {
return a.map {
switch $0 {
case .A:
return 1
default:
return 2
}
}
}
func bad(_ a: A<EE>) {
a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{10-10= () -> Int in }}
let _: EE = $0
return 1
}
}
func ugly(_ a: A<EE>) {
a.map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{10-10= () -> Int in }}
switch $0 {
case .A:
return 1
default:
return 2
}
}
}
// SR-2057
enum SR2057 {
case foo
}
let sr2057: SR2057?
if case .foo = sr2057 { } // Ok
// Invalid 'is' pattern
class SomeClass {}
if case let doesNotExist as SomeClass:AlsoDoesNotExist {}
// expected-error@-1 {{use of undeclared type 'AlsoDoesNotExist'}}
// expected-error@-2 {{variable binding in a condition requires an initializer}}
// `.foo` and `.bar(...)` pattern syntax should also be able to match
// static members as expr patterns
struct StaticMembers: Equatable {
init() {}
init(_: Int) {}
init?(opt: Int) {}
static var prop = StaticMembers()
static var optProp: Optional = StaticMembers()
static func method(_: Int) -> StaticMembers { return prop }
static func method(withLabel: Int) -> StaticMembers { return prop }
static func optMethod(_: Int) -> StaticMembers? { return optProp }
static func ==(x: StaticMembers, y: StaticMembers) -> Bool { return true }
}
let staticMembers = StaticMembers()
let optStaticMembers: Optional = StaticMembers()
switch staticMembers {
case .init: break // expected-error{{cannot match values of type 'StaticMembers'}}
case .init(opt:): break // expected-error{{cannot match values of type 'StaticMembers'}}
case .init(): break
case .init(0): break
case .init(_): break // expected-error{{'_' can only appear in a pattern}}
case .init(let x): break // expected-error{{cannot appear in an expression}} expected-error{{variable 'x' is not bound by any pattern}}
case .init(opt: 0): break // expected-error{{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}}
// expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
// expected-note@-2 {{coalesce using '??' to provide a default when the optional value contains 'nil'}}
case .prop: break
// TODO: repeated error message
case .optProp: break // expected-error* {{not unwrapped}}
case .method: break // expected-error{{cannot match}}
case .method(0): break
case .method(_): break // expected-error{{'_' can only appear in a pattern}}
case .method(let x): break // expected-error{{cannot appear in an expression}} expected-error{{variable 'x' is not bound by any pattern}}
case .method(withLabel:): break // expected-error{{cannot match}}
case .method(withLabel: 0): break
case .method(withLabel: _): break // expected-error{{'_' can only appear in a pattern}}
case .method(withLabel: let x): break // expected-error{{cannot appear in an expression}} expected-error{{variable 'x' is not bound by any pattern}}
case .optMethod: break // expected-error{{cannot match}}
case .optMethod(0): break
// expected-error@-1 {{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}}
// expected-note@-2 {{coalesce}}
// expected-note@-3 {{force-unwrap}}
}
_ = 0
// rdar://problem/32241441 - Add fix-it for cases in switch with optional chaining
struct S_32241441 {
enum E_32241441 {
case foo
case bar
}
var type: E_32241441 = E_32241441.foo
}
func rdar32241441() {
let s: S_32241441? = S_32241441()
switch s?.type { // expected-error {{switch must be exhaustive}} expected-note {{add missing case: '.none'}}
case .foo: // Ok
break;
case .bar: // Ok
break;
}
}
// SR-6100
struct One<Two> {
public enum E: Error {
// if you remove associated value, everything works
case SomeError(String)
}
}
func testOne() {
do {
} catch let error { // expected-warning{{'catch' block is unreachable because no errors are thrown in 'do' block}}
if case One.E.SomeError = error {} // expected-error{{generic enum type 'One.E' is ambiguous without explicit generic parameters when matching value of type 'Error'}}
}
}
// SR-8347
// constrain initializer expressions of optional some pattern bindings to be optional
func test8347() -> String {
struct C {
subscript (s: String) -> String? {
return ""
}
subscript (s: String) -> [String] {
return [""]
}
func f() -> String? {
return ""
}
func f() -> Int {
return 3
}
func g() -> String {
return ""
}
func h() -> String { // expected-note {{found this candidate}}
return ""
}
func h() -> Double { // expected-note {{found this candidate}}
return 3.0
}
func h() -> Int? { //expected-note{{found this candidate}}
return 2
}
func h() -> Float? { //expected-note{{found this candidate}}
return nil
}
}
let c = C()
if let s = c[""] {
return s
}
if let s = c.f() {
return s
}
if let s = c.g() { //expected-error{{initializer for conditional binding must have Optional type, not 'String'}}
return s
}
if let s = c.h() { //expected-error{{ambiguous use of 'h()'}}
return s
}
}
enum SR_7799 {
case baz
case bar
}
let sr7799: SR_7799? = .bar
switch sr7799 {
case .bar?: break // Ok
case .baz: break // Ok
default: break
}
let sr7799_1: SR_7799?? = .baz
switch sr7799_1 {
case .bar?: break // Ok
case .baz: break // Ok
default: break
}
if case .baz = sr7799_1 {} // Ok
if case .bar? = sr7799_1 {} // Ok
| apache-2.0 | 67c2b940c86336f356dca80c8c2dbd18 | 23.893764 | 208 | 0.635773 | 3.593 | false | false | false | false |
developerY/Swift2_Playgrounds | Swift2LangRef.playground/Pages/Protocols.xcplaygroundpage/Contents.swift | 1 | 13705 | //: [Previous](@previous)
import Foundation
//: ------------------------------------------------------------------------------------------------
//: Things to know:
//:
//: * Protocols define a required set of functionality (including methods and properties) for a
//: class, structure or enumeration.
//:
//: * Protocols are "adopted" by a class, structure or enumeration to provide the implementation.
//: This is called "conforming" to a protocol.
//:
//: * As you should already be aware, protocols are often used for delegation.
//:
//: * Protcol Syntax looks like this:
//:
//: protocol SomeProtocol
//: {
//: //: protocol definition goes here
//: }
//:
//: * Protocol adoption looks like this:
//:
//: struct SomeStructure: FirstProtocol, AnotherProtocol
//: {
//: //: structure definition goes here
//: }
//:
//: class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol
//: {
//: //: class definition goes here
//: }
//: ------------------------------------------------------------------------------------------------
//: ------------------------------------------------------------------------------------------------
//: Property requirements
//:
//: * A protocol can require the conforming type to provide an instance of a property or type
//: property.
//:
//: * The protocol can also specify if the property must be gettable or gettable and
//: settable. If a protocol only requires a gettable property, the conforming class can use
//: a stored property or a computed property. Also, the conforming class is allowed to add
//: a setter if it needs.
//:
//: * Property requirements are always declared as variable types with the 'var' introducer.
//:
//: Let's take a look at a simple protocol. As you'll see, we only need to define the properties
//: in terms of 'get' and 'set' and do not provide the actual functionality.
protocol someProtocolForProperties
{
// A read/write property
var mustBeSettable: Int { get set }
// A read-only property
var doesNotNeedToBeSettable: Int { get }
// Can only use 'class' inside a class. This is the case even if adopted by a structure or
// enumeration which will use 'static' when conforming to the protocol's property.
static var someTypeProperty: Int { get set }
}
//: Let's create a more practical protocol that we can actually conform to:
protocol FullyNamed
{
var fullName: String { get }
}
//: A structure that conforms to FullyNamed. We won't bother creating an explicit getter or setter
//: for the 'fullName' property because Swift's defaults will suffice.
struct Person: FullyNamed
{
var fullName: String
}
let john = Person(fullName: "John Smith")
//: Let's try a more complex class
class Starship: FullyNamed
{
var prefix: String?
var name: String
init(name: String, prefix: String? = nil)
{
self.name = name
self.prefix = prefix
}
var fullName: String
{
return (prefix != .None ? prefix! + " " : "") + name
}
}
//: In the class above, we use a 'name' and an optional 'prefix' to represent the full name, then
//: provide a computed value to fulfill our 'fullName' requirement.
//:
//: Here it is in action:
var ncc1701 = Starship(name: "Enterprise", prefix: "USS")
ncc1701.fullName
//: ------------------------------------------------------------------------------------------------
//: Method Requirements
//:
//: Similar to property requirements, the protocol only defines the method type, not the
//: implementation.
//:
//: Variadic parameters are allowed, but default values are not.
//:
//: Method requirements can be mutating - simply use the 'mutating' keyword before the function
//: definition. Note that when conforming to the protocol, only classes are required to use the
//: 'mutating' keyword when conforming to the protocol, following the normal procedure.
//:
//: As with property requirements, type methods are always prefixed with the 'class' keyword.
//:
//: Here's a simple example that defines the requirements for a 'random' function which takes
//: no parameters and returns a Double:
protocol RandomNumberGenerator
{
func random() -> Double
}
//: Let's adopt this protocol:
class LinearCongruentialGenerator: RandomNumberGenerator
{
var lastRandom = 42.0
var m = 139956.0
var a = 3877.0
var c = 29573.0
func random() -> Double
{
lastRandom = ((lastRandom * a + c) % m)
return lastRandom / m
}
}
let generator = LinearCongruentialGenerator()
generator.random()
generator.random()
generator.random()
//: ------------------------------------------------------------------------------------------------
//: Protocols as Types
//:
//: Protocols are types, which means they can be used where many other types are allowed,
//: including:
//:
//: * As a parameter to a function, method or initializer
//: * As the type of a constant, variable or property
//: * As the type of items in an Array, Dictionary or other container
//:
//: Here's a protocol used as a type. We'll create a Dice class that stores a RandomNumberGenerator
//: as a constant so that it can be used to customize the randomization of the dice roll:
class Dice
{
let sides: Int
let generator: RandomNumberGenerator
init(sides: Int, generator: RandomNumberGenerator)
{
self.sides = sides
self.generator = generator
}
func roll() -> Int
{
return Int(generator.random() * Double(sides)) + 1
}
}
//: Just for fun, let's roll a few:
let d6 = Dice(sides: 6, generator: generator)
d6.roll()
d6.roll()
d6.roll()
d6.roll()
d6.roll()
d6.roll()
//: ------------------------------------------------------------------------------------------------
//: Adding Protocol Conformance with an Extension
//:
//: Existing classes, structures and enumerations can be extended to conform to a given protocol.
//:
//: Let's start with a simple protocol we'll use for expirimentation:
protocol TextRepresentable
{
func asText() -> String
}
//: We'll extend our Dice class:
extension Dice: TextRepresentable
{
func asText() -> String
{
return "A \(sides)-sided dice"
}
}
//: Existing instances (such as 'd6' will automatically adopt and conform to the new protocol, even
//: though it was declared prior to the extension.
d6.asText()
//: ------------------------------------------------------------------------------------------------
//: Declaring Protocol Adoption with an Extension
//:
//: Some types may already adopt a protocol, but do not state so in their definition. Types do not
//: automatically adopt to protocols whose requirements they satisfy - protocol adoption must
//: always be stated explicitly.
//:
//: This can be resolved with by using an empty extension.
//:
//: To showcase this, let's create a structure that conforms to the TextRepresentable protocol, but
//: doesn't include this as part of the definition:
struct Hamster
{
var name: String
func asText() -> String
{
return "A hamster named \(name)"
}
}
//: Let's verify our work:
let tedTheHamster = Hamster(name: "Ted")
tedTheHamster.asText()
//: We can add TextRepresentable conformance to Hamster by using an empty extension.
//:
//: This works because the requirements are already met, so we don't need to include any additional
//: functionality within the extension definition.
extension Hamster: TextRepresentable
{
}
//: ------------------------------------------------------------------------------------------------
//: Collections of Protocol Types
//:
//: Hamsters and Dice don't have much in common, but in our sample code above, they both conform
//: to the TextRepresentable protocol. Because of this, we can create an array of things that are
//: TextRepresentable which includes each:
let textRepresentableThigns: [TextRepresentable] = [d6, tedTheHamster]
//: We can now loop through each and produce its text representation:
for thing in textRepresentableThigns
{
thing.asText()
}
//: ------------------------------------------------------------------------------------------------
//: Protocol Inheritance
//:
//: Protocols can inherit from other protocols in order to add further requirements. The syntax
//: for this is similar to a class ineriting from its superclass.
//:
//: Let's create a new text representable type, inherited from TextRepresentable:
protocol PrettyTextRepresentable: TextRepresentable
{
func asPrettyText() -> String
}
//: Let's make our Dice a little prettier.
//:
//: Note that the Dice already knows that it conforms to the TextRepresentable, which means we can
//: call asText() inside our asPrettyText() method.
extension Dice: PrettyTextRepresentable
{
func asPrettyText() -> String
{
return "The pretty version of " + asText()
}
}
//: We can test our work:
d6.asPrettyText()
//: ------------------------------------------------------------------------------------------------
//: Protocol Composition
//:
//: Protocols can be combined such that a type conforms to each of them. For example, a person can
//: be an aged person as well as a named person.
//:
//: Protocol Composition is a syntactic method of declaring that an instance conforms to a set
//: of protocols. It takes the form "protocol<SomeProtocol, AnotherProtocol>". There can be as
//: many protocols between the angle brackets as you need.
//:
//: Let's start by creating a couple of protocols for expirimentation:
protocol Named
{
var name: String { get }
}
protocol Aged
{
var age: Int { get }
}
//: Here, we declare an Individual that conforms to both Name and Age protocols:
struct Individual: Named, Aged
{
var name: String
var age: Int
}
//: Here, we can see the protocol composition at work as the parameter into the wishHappyBirthday()
//: function:
func wishHappyBirthday(celebrator: protocol<Named, Aged>) -> String
{
return "Happy Birthday \(celebrator.name) - you're \(celebrator.age)!"
}
//: If we call the member, we can see the celebratory wish for this individual:
wishHappyBirthday(Individual(name: "Bill", age: 31))
//: ------------------------------------------------------------------------------------------------
//: Checking for Protocol Conformance
//:
//: We can use 'is' and 'as' for testing for protocol conformance, just as we've seen in the
//: section on Type Casting.
//:
//: In order for this to work with protocols, they must be marked with an "@objc" attribute. See
//: further down in this playground for a special note about the @objc attribute.
//:
//: Let's create a new protocol with the proper prefix so that we can investigate:
@objc protocol HasArea
{
var area: Double { get }
}
class Circle: HasArea
{
let pi = 3.14159
var radius: Double
@objc var area: Double { return pi * radius * radius }
init(radius: Double) { self.radius = radius }
}
class Country: HasArea
{
@objc var area: Double
init(area: Double) { self.area = area }
}
class Animal
{
var legs: Int
init(legs: Int) { self.legs = legs }
}
//: We can store our objects into an array of type AnyObject[]
let objects: [AnyObject] =
[
Circle(radius: 3.0),
Country(area: 4356947.0),
Animal(legs: 4)
]
//: Then we can test each for conformance to HasArea:
objects[0] is HasArea
objects[1] is HasArea
objects[2] is HasArea
//: ------------------------------------------------------------------------------------------------
//: Optional Protocol Requirements
//:
//: Sometimes it's convenient to declare protocols that have one or more requirements that are
//: optional. This is done by prefixing those requirements with the 'optional' keyword.
//:
//: The term "optional protocol" refers to protocols that are optional in a very similar since to
//: optionals we've seen in the past. However, rather than stored values that can be nil, they
//: can still use optional chaining and optional binding for determining if an optional requirement
//: has been satisfied and if so, using that requirement.
//:
//: As with Protocol Conformance, a protocol that uses optional requirements must also be prefixed
//: with the '@objc' attribute.
//:
//: A special note about @objc attribute:
//:
//: * In order to check if an instance of a class conforms to a given protocol, that protocol must
//: be declared with the @objc attribute.
//:
//: * This is also the case with optional requirements in protocols. In order to use the optional
//: declaration modifier, the protocol must be declared with the @objc attribute.
//:
//: * Additionally, any class, structure or enumeration that owns an instance that conforms to a
//: protocol declared with the @objc attribute must also be declared with the @objc attribute.
//:
//: Here's another simple protocol that uses optional requrements:
@objc protocol CounterDataSource
{
optional func incrementForCount(count: Int) -> Int
optional var fixedIncrement: Int { get }
}
//: In the class below, we'll see that checking to see if an instance conforms to a specific
//: requirement is similar to checking for (and accessing) optionals. We'll use optional chaining
//: for these optional reqirements:
class Counter
{
var count = 0
var dataSource: CounterDataSource?
func increment()
{
//: Does the dataSource conform to the incrementForCount method?
if let amount = dataSource?.incrementForCount?(count)
{
count += amount
}
//: If not, does it conform to the fixedIncrement variable requirement?
else if let amount = dataSource?.fixedIncrement
{
count += amount
}
}
}
//: [Next](@next)
| mit | 687ec6fb53180648808c31020cc1e225 | 32.184019 | 100 | 0.639912 | 4.585146 | false | false | false | false |
developerY/Swift2_Playgrounds | Swift2LangRef.playground/Pages/Inheritance.xcplaygroundpage/Contents.swift | 1 | 4885 | //: [Previous](@previous)
//: ------------------------------------------------------------------------------------------------
//: Things to know:
//:
//: * There is no default base class for Swift objects. Any class that doesn't derive from
//: another class is a base class.
//: ------------------------------------------------------------------------------------------------
//: Let's start with a simple base class:
class Vehicle
{
var numberOfWheels: Int
var maxPassengers: Int
func description() -> String
{
return "\(numberOfWheels) wheels; up to \(maxPassengers) passengers"
}
// Must initialize any properties that do not have a default value
init()
{
numberOfWheels = 0
maxPassengers = 1
}
}
//: ------------------------------------------------------------------------------------------------
//: Subclasses
//:
//: Now let's subclass the Vehicle to create a two-wheeled vehicle called a Bicycle
class Bicycle: Vehicle
{
// We'll make this a 2-wheeled vehicle
override init()
{
super.init()
numberOfWheels = 2
}
}
//: We can call a member from the superclass
let bicycle = Bicycle()
bicycle.description()
//: Subclasses can also be subclassed
class Tandem: Bicycle
{
// This bicycle has 2 passengers
override init()
{
super.init()
maxPassengers = 2
}
}
//: Here, we'll create a car that includes a new description by overriding the superclass' instance
//: method
class Car: Vehicle
{
// Adding a new property
var speed: Double = 0.0
// New initialization, starting with super.init()
override init()
{
super.init()
maxPassengers = 5
numberOfWheels = 4
}
// Using the override keyword to specify that we're overriding a function up the inheritance
// chain. It is a compilation error to leave out 'override' if a method exists up the chain.
override func description() -> String
{
// We start with the default implementation of description then tack our stuff onto it
return super.description() + "; " + "traveling at \(speed) mph"
}
}
//: Here, we'll check our description to see that it does indeed give us something different from
//: the superclass' default description:
let car = Car()
car.speed = 55
car.description()
//: ------------------------------------------------------------------------------------------------
//: Overriding Properties
//:
//: We can override property getters and setters. This applies to any property, including stored and
//: computed properties
//:
//: When we do this, our overridden property must include the name of the property as well as the
//: property's type.
class SpeedLimitedCar: Car
{
//: Make sure to specify the name and type
override var speed: Double
{
get
{
return super.speed
}
// We need a setter since the super's property is read/write
//
// However, if the super was read-only, we wouldn't need this setter unless we wanted to
// add write capability.
set
{
super.speed = min(newValue, 40.0)
}
}
}
//: We can see our override in action
var speedLimitedCar = SpeedLimitedCar()
speedLimitedCar.speed = 60
speedLimitedCar.speed
//: We can also override property observers
class AutomaticCar: Car
{
var gear = 1
override var speed: Double
{
// Set the gear based on changes to speed
didSet { gear = Int(speed / 10.0) + 1 }
// Since we're overriding the property observer, we're not allowed to override the
// getter/setter.
//
// The following lines will not compile:
//
// get { return super.speed }
// set { super.speed = newValue }
}
}
//: Here is our overridden observers in action
var automaticCar = AutomaticCar()
automaticCar.speed = 35.0
automaticCar.gear
//: ------------------------------------------------------------------------------------------------
//: Preenting Overrides
//:
//: We can prevent a subclass from overriding a particular method or property using the 'final'
//: keyword.
//:
//: final can be applied to: class, var, func, class methods and subscripts
//:
//: Here, we'll prevent an entire class from being subclassed by applying the . Because of this,
//: the finals inside the class are not needed, but are present for descriptive purposes. These
//: additional finals may not compile in the future, but they do today:
final class AnotherAutomaticCar: Car
{
// This variable cannot be overridden
final var gear = 1
// We can even prevent overridden functions from being further refined
final override var speed: Double
{
didSet { gear = Int(speed / 10.0) + 1 }
}
}
//: [Next](@next)
| mit | 065978f616ee950008d18c81aed13333 | 28.251497 | 100 | 0.579529 | 4.841427 | false | false | false | false |
el-hoshino/NotAutoLayout | Sources/NotAutoLayout/LayoutMaker/IndividualProperties/3-Element/MiddleRightWidth.Individual.swift | 1 | 1242 | //
// MiddleRightWidth.Individual.swift
// NotAutoLayout
//
// Created by 史翔新 on 2017/06/20.
// Copyright © 2017年 史翔新. All rights reserved.
//
import Foundation
extension IndividualProperty {
public struct MiddleRightWidth {
let middleRight: LayoutElement.Point
let width: LayoutElement.Length
}
}
// MARK: - Make Frame
extension IndividualProperty.MiddleRightWidth {
private func makeFrame(middleRight: Point, width: Float, height: Float) -> Rect {
let x = middleRight.x - width
let y = middleRight.y - height.half
let frame = Rect(x: x, y: y, width: width, height: height)
return frame
}
}
// MARK: - Set A Length -
// MARK: Height
extension IndividualProperty.MiddleRightWidth: LayoutPropertyCanStoreHeightToEvaluateFrameType {
public func evaluateFrame(height: LayoutElement.Length, parameters: IndividualFrameCalculationParameters) -> Rect {
let middleRight = self.middleRight.evaluated(from: parameters)
let width = self.width.evaluated(from: parameters, withTheOtherAxis: .height(0))
let height = height.evaluated(from: parameters, withTheOtherAxis: .width(width))
return self.makeFrame(middleRight: middleRight, width: width, height: height)
}
}
| apache-2.0 | 574f74a6426963ceac08f8ddc83d31ce | 22.596154 | 116 | 0.731051 | 3.907643 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/UI/RewardViewController.swift | 1 | 4986 | //
// RewardViewController.swift
// Habitica
//
// Created by Phillip on 21.08.17.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import UIKit
import Habitica_Models
import ReactiveSwift
class RewardViewController: BaseCollectionViewController, UICollectionViewDelegateFlowLayout {
let userRepository = UserRepository()
let dataSource = RewardViewDataSource()
let refreshControl = UIRefreshControl()
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource.collectionView = self.collectionView
let customRewardNib = UINib.init(nibName: "CustomRewardCell", bundle: .main)
collectionView?.register(customRewardNib, forCellWithReuseIdentifier: "CustomRewardCell")
let inAppRewardNib = UINib.init(nibName: "InAppRewardCell", bundle: .main)
collectionView?.register(inAppRewardNib, forCellWithReuseIdentifier: "InAppRewardCell")
collectionView?.alwaysBounceVertical = true
refreshControl.addTarget(self, action: #selector(refresh), for: .valueChanged)
collectionView?.addSubview(refreshControl)
tutorialIdentifier = "rewards"
navigationItem.title = L10n.Tasks.rewards
refresh()
ThemeService.shared.addThemeable(themable: self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
collectionView.reloadData()
}
override func applyTheme(theme: Theme) {
super.applyTheme(theme: theme)
collectionView.backgroundColor = theme.contentBackgroundColor
}
override func getDefinitonForTutorial(_ tutorialIdentifier: String!) -> [AnyHashable: Any] {
if tutorialIdentifier == "rewards" {
return [
"textList": NSArray.init(array: [L10n.Tutorials.rewards1, L10n.Tutorials.rewards2])
]
}
return [:]
}
@objc
func refresh() {
userRepository.retrieveUser(withTasks: false)
.flatMap(.latest, {[weak self] _ in
return self?.userRepository.retrieveInAppRewards() ?? Signal.empty
})
.observeCompleted {[weak self] in
self?.refreshControl.endRefreshing()
}
}
private var editedReward: TaskProtocol?
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let reward = dataSource.item(at: indexPath) as? TaskProtocol {
editedReward = reward
performSegue(withIdentifier: "FormSegue", sender: self)
} else {
let storyboard = UIStoryboard(name: "BuyModal", bundle: nil)
if let viewController = storyboard.instantiateViewController(withIdentifier: "HRPGBuyItemModalViewController") as? HRPGBuyItemModalViewController {
viewController.modalTransitionStyle = .crossDissolve
viewController.reward = dataSource.item(at: indexPath) as? InAppRewardProtocol
if let tabbarController = self.tabBarController {
tabbarController.present(viewController, animated: true, completion: nil)
} else {
present(viewController, animated: true, completion: nil)
}
}
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return dataSource.collectionView(collectionView, layout: collectionViewLayout, sizeForItemAt: indexPath)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return dataSource.collectionView(collectionView, layout: collectionViewLayout, insetForSectionAt: section)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "FormSegue" {
guard let destinationController = segue.destination as? TaskFormVisualEffectsModalViewController else {
return
}
destinationController.taskType = .reward
if let editedReward = self.editedReward {
destinationController.taskId = editedReward.id
destinationController.isCreating = false
} else {
destinationController.isCreating = true
}
editedReward = nil
}
}
}
| gpl-3.0 | 70e3b2d8800173313d83d79c84db409d | 39.528455 | 175 | 0.667001 | 5.810023 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/Views/HabiticaButton.swift | 1 | 1446 | //
// HabiticaButton.swift
// Habitica
//
// Created by Phillip Thelen on 02.11.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import UIKit
@IBDesignable
class HabiticaButton: UIButton {
@IBInspectable public var buttonColor: UIColor = UIColor.purple200 {
didSet {
backgroundColor = buttonColor
}
}
override open var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? buttonColor.lighter(by: 15) : buttonColor
}
}
override open var isSelected: Bool {
didSet {
backgroundColor = isHighlighted ? buttonColor.lighter(by: 25) : buttonColor
}
}
override open var isEnabled: Bool {
didSet {
backgroundColor = isEnabled ? buttonColor : UIColor.gray400
}
}
override open var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
func setupView() {
cornerRadius = 6
setTitleColor(.white, for: .normal)
setTitleColor(.white, for: .highlighted)
setTitleColor(.white, for: .selected)
}
}
| gpl-3.0 | 33a56bb0cd79b29d73e5e749c6d2d975 | 21.936508 | 87 | 0.574394 | 4.965636 | false | false | false | false |
milseman/swift | test/IDE/coloring.swift | 4 | 23144 | // RUN: %target-swift-ide-test -syntax-coloring -source-filename %s | %FileCheck %s
// RUN: %target-swift-ide-test -syntax-coloring -typecheck -source-filename %s | %FileCheck %s
// XFAIL: broken_std_regex
#line 17 "abc.swift"
// CHECK: <kw>#line</kw> <int>17</int> <str>"abc.swift"</str>
@available(iOS 8.0, OSX 10.10, *)
// CHECK: <attr-builtin>@available</attr-builtin>(<kw>iOS</kw> <float>8.0</float>, <kw>OSX</kw> <float>10.10</float>, *)
func foo() {
// CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> <float>10.10</float>, <kw>iOS</kw> <float>8.01</float>, *) {<kw>let</kw> <kw>_</kw> = <str>"iOS"</str>}
if #available (OSX 10.10, iOS 8.01, *) {let _ = "iOS"}
}
enum List<T> {
case Nil
// rdar://21927124
// CHECK: <attr-builtin>indirect</attr-builtin> <kw>case</kw> Cons(T, List)
indirect case Cons(T, List)
}
// CHECK: <kw>struct</kw> S {
struct S {
// CHECK: <kw>var</kw> x : <type>Int</type>
var x : Int
// CHECK: <kw>var</kw> y : <type>Int</type>.<type>Int</type>
var y : Int.Int
// CHECK: <kw>var</kw> a, b : <type>Int</type>
var a, b : Int
}
enum EnumWithDerivedEquatableConformance : Int {
// CHECK-LABEL: <kw>enum</kw> EnumWithDerivedEquatableConformance : {{(<type>)}}Int{{(</type>)?}} {
case CaseA
// CHECK-NEXT: <kw>case</kw> CaseA
case CaseB, CaseC
// CHECK-NEXT: <kw>case</kw> CaseB, CaseC
case CaseD = 30, CaseE
// CHECK-NEXT: <kw>case</kw> CaseD = <int>30</int>, CaseE
}
// CHECK-NEXT: }
// CHECK: <kw>class</kw> MyCls {
class MyCls {
// CHECK: <kw>var</kw> www : <type>Int</type>
var www : Int
// CHECK: <kw>func</kw> foo(x: <type>Int</type>) {}
func foo(x: Int) {}
// CHECK: <kw>var</kw> aaa : <type>Int</type> {
var aaa : Int {
// CHECK: <kw>get</kw> {}
get {}
// CHECK: <kw>set</kw> {}
set {}
}
// CHECK: <kw>var</kw> bbb : <type>Int</type> {
var bbb : Int {
// CHECK: <kw>set</kw> {
set {
// CHECK: <kw>var</kw> tmp : <type>Int</type>
var tmp : Int
}
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>var</kw> tmp : <type>Int</type>
var tmp : Int
}
}
// CHECK: <kw>subscript</kw> (i : <type>Int</type>, j : <type>Int</type>) -> <type>Int</type> {
subscript (i : Int, j : Int) -> Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>return</kw> i + j
return i + j
}
// CHECK: <kw>set</kw>(v) {
set(v) {
// CHECK: v + i - j
v + i - j
}
}
// CHECK: <kw>func</kw> multi(<kw>_</kw> name: <type>Int</type>, otherpart x: <type>Int</type>) {}
func multi(_ name: Int, otherpart x: Int) {}
}
// CHECK-LABEL: <kw>class</kw> Attributes {
class Attributes {
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> v0: <type>Int</type>
@IBOutlet var v0: Int
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-id>@IBOutlet</attr-id> <kw>var</kw> {{(<attr-builtin>)?}}v1{{(</attr-builtin>)?}}: <type>String</type>
@IBOutlet @IBOutlet var v1: String
// CHECK: <attr-builtin>@objc</attr-builtin> <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v2{{(</attr-builtin>)?}}: <type>String</type>
@objc @IBOutlet var v2: String
// CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-builtin>@objc</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v3{{(</attr-builtin>)?}}: <type>String</type>
@IBOutlet @objc var v3: String
// CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f1() {}
@available(*, unavailable) func f1() {}
// CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <attr-builtin>@IBAction</attr-builtin> <kw>func</kw> f2() {}
@available(*, unavailable) @IBAction func f2() {}
// CHECK: <attr-builtin>@IBAction</attr-builtin> <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f3() {}
@IBAction @available(*, unavailable) func f3() {}
// CHECK: <attr-builtin>mutating</attr-builtin> <kw>func</kw> func_mutating_1() {}
mutating func func_mutating_1() {}
// CHECK: <attr-builtin>nonmutating</attr-builtin> <kw>func</kw> func_mutating_2() {}
nonmutating func func_mutating_2() {}
}
func stringLikeLiterals() {
// CHECK: <kw>var</kw> us1: <type>UnicodeScalar</type> = <str>"a"</str>
var us1: UnicodeScalar = "a"
// CHECK: <kw>var</kw> us2: <type>UnicodeScalar</type> = <str>"ы"</str>
var us2: UnicodeScalar = "ы"
// CHECK: <kw>var</kw> ch1: <type>Character</type> = <str>"a"</str>
var ch1: Character = "a"
// CHECK: <kw>var</kw> ch2: <type>Character</type> = <str>"あ"</str>
var ch2: Character = "あ"
// CHECK: <kw>var</kw> s1 = <str>"abc абвгд あいうえお"</str>
var s1 = "abc абвгд あいうえお"
}
// CHECK: <kw>var</kw> globComp : <type>Int</type>
var globComp : Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>return</kw> <int>0</int>
return 0
}
}
// CHECK: <comment-block>/* foo is the best */</comment-block>
/* foo is the best */
// CHECK: <kw>func</kw> foo(n: <type>Float</type>) -> <type>Int</type> {
func foo(n: Float) -> Int {
// CHECK: <kw>var</kw> fnComp : <type>Int</type>
var fnComp : Int {
// CHECK: <kw>get</kw> {
get {
// CHECK: <kw>var</kw> a: <type>Int</type>
// CHECK: <kw>return</kw> <int>0</int>
var a: Int
return 0
}
}
// CHECK: <kw>var</kw> q = {{(<type>)?}}MyCls{{(</type>)?}}()
var q = MyCls()
// CHECK: <kw>var</kw> ee = <str>"yoo"</str>;
var ee = "yoo";
// CHECK: <kw>return</kw> <int>100009</int>
return 100009
}
///- returns: single-line, no space
// CHECK: ///- <doc-comment-field>returns</doc-comment-field>: single-line, no space
/// - returns: single-line, 1 space
// CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 1 space
/// - returns: single-line, 2 spaces
// CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 2 spaces
/// - returns: single-line, more spaces
// CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, more spaces
// CHECK: <kw>protocol</kw> Prot {
protocol Prot {
// CHECK: <kw>typealias</kw> Blarg
typealias Blarg
// CHECK: <kw>func</kw> protMeth(x: <type>Int</type>)
func protMeth(x: Int)
// CHECK: <kw>var</kw> protocolProperty1: <type>Int</type> { <kw>get</kw> }
var protocolProperty1: Int { get }
// CHECK: <kw>var</kw> protocolProperty2: <type>Int</type> { <kw>get</kw> <kw>set</kw> }
var protocolProperty2: Int { get set }
}
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-* : FunnyPrecedence{{$}}
infix operator *-* : FunnyPrecedence
// CHECK: <kw>precedencegroup</kw> FunnyPrecedence
// CHECK-NEXT: <kw>associativity</kw>: left{{$}}
// CHECK-NEXT: <kw>higherThan</kw>: MultiplicationPrecedence
precedencegroup FunnyPrecedence {
associativity: left
higherThan: MultiplicationPrecedence
}
// CHECK: <kw>func</kw> *-*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *-*(l: Int, r: Int) -> Int { return l }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-+* : FunnyPrecedence
infix operator *-+* : FunnyPrecedence
// CHECK: <kw>func</kw> *-+*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *-+*(l: Int, r: Int) -> Int { return l }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *--*{{$}}
infix operator *--*
// CHECK: <kw>func</kw> *--*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}}
func *--*(l: Int, r: Int) -> Int { return l }
// CHECK: <kw>protocol</kw> Prot2 : <type>Prot</type> {}
protocol Prot2 : Prot {}
// CHECK: <kw>class</kw> SubCls : <type>MyCls</type>, <type>Prot</type> {}
class SubCls : MyCls, Prot {}
// CHECK: <kw>func</kw> genFn<T : <type>Prot</type> <kw>where</kw> <type>T</type>.<type>Blarg</type> : <type>Prot2</type>>(<kw>_</kw>: <type>T</type>) -> <type>Int</type> {}{{$}}
func genFn<T : Prot where T.Blarg : Prot2>(_: T) -> Int {}
func f(x: Int) -> Int {
// CHECK: <comment-line>// string interpolation is the best</comment-line>
// string interpolation is the best
// CHECK: <str>"This is string </str>\<anchor>(</anchor>genFn({(a:<type>Int</type> -> <type>Int</type>) <kw>in</kw> a})<anchor>)</anchor><str> interpolation"</str>
"This is string \(genFn({(a:Int -> Int) in a})) interpolation"
// CHECK: <str>"""
// CHECK-NEXT: This is a multiline string.
// CHECK-NEXT: """</str>
"""
This is a multiline string.
"""
// CHECK: <str>"""
// CHECK-NEXT: This is a multiline</str>\<anchor>(</anchor> <str>"interpolated"</str> <anchor>)</anchor><str>string
// CHECK-NEXT: """</str>
"""
This is a multiline\( "interpolated" )string
"""
// CHECK: <str>"</str>\<anchor>(</anchor><int>1</int><anchor>)</anchor>\<anchor>(</anchor><int>1</int><anchor>)</anchor><str>"</str>
"\(1)\(1)"
}
// CHECK: <kw>func</kw> bar(x: <type>Int</type>) -> (<type>Int</type>, <type>Float</type>) {
func bar(x: Int) -> (Int, Float) {
// CHECK: foo({{(<type>)?}}Float{{(</type>)?}}())
foo(Float())
}
class GenC<T1,T2> {}
func test() {
// CHECK: {{(<type>)?}}GenC{{(</type>)?}}<<type>Int</type>, <type>Float</type>>()
var x = GenC<Int, Float>()
}
// CHECK: <kw>typealias</kw> MyInt = <type>Int</type>
typealias MyInt = Int
func test2(x: Int) {
// CHECK: <str>"</str>\<anchor>(</anchor>x<anchor>)</anchor><str>"</str>
"\(x)"
}
// CHECK: <kw>class</kw> Observers {
class Observers {
// CHECK: <kw>var</kw> p1 : <type>Int</type> {
var p1 : Int {
// CHECK: <kw>willSet</kw>(newValue) {}
willSet(newValue) {}
// CHECK: <kw>didSet</kw> {}
didSet {}
}
// CHECK: <kw>var</kw> p2 : <type>Int</type> {
var p2 : Int {
// CHECK: <kw>didSet</kw> {}
didSet {}
// CHECK: <kw>willSet</kw> {}
willSet {}
}
}
// CHECK: <kw>func</kw> test3(o: <type>AnyObject</type>) {
func test3(o: AnyObject) {
// CHECK: <kw>let</kw> x = o <kw>as</kw>! <type>MyCls</type>
let x = o as! MyCls
}
// CHECK: <kw>func</kw> test4(<kw>inout</kw> a: <type>Int</type>) {{{$}}
func test4(inout a: Int) {
// CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> >= <float>10.10</float>, <kw>iOS</kw> >= <float>8.01</float>) {<kw>let</kw> OSX = <str>"iOS"</str>}}{{$}}
if #available (OSX >= 10.10, iOS >= 8.01) {let OSX = "iOS"}}
// CHECK: <kw>func</kw> test4b(a: <kw>inout</kw> <type>Int</type>) {{{$}}
func test4b(a: inout Int) {
}
// CHECK: <kw>class</kw> MySubClass : <type>MyCls</type> {
class MySubClass : MyCls {
// CHECK: <attr-builtin>override</attr-builtin> <kw>func</kw> foo(x: <type>Int</type>) {}
override func foo(x: Int) {}
// CHECK: <attr-builtin>convenience</attr-builtin> <kw>init</kw>(a: <type>Int</type>) {}
convenience init(a: Int) {}
}
// CHECK: <kw>var</kw> g1 = { (x: <type>Int</type>) -> <type>Int</type> <kw>in</kw> <kw>return</kw> <int>0</int> }
var g1 = { (x: Int) -> Int in return 0 }
// CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> ~~ {
infix operator ~~ {}
// CHECK: <attr-builtin>prefix</attr-builtin> <kw>operator</kw> *~~ {
prefix operator *~~ {}
// CHECK: <attr-builtin>postfix</attr-builtin> <kw>operator</kw> ~~* {
postfix operator ~~* {}
func test_defer() {
defer {
// CHECK: <kw>let</kw> x : <type>Int</type> = <int>0</int>
let x : Int = 0
}
}
// FIXME: blah.
// FIXME: blah blah
// Something something, FIXME: blah
// CHECK: <comment-line>// <comment-marker>FIXME: blah.</comment-marker></comment-line>
// CHECK: <comment-line>// <comment-marker>FIXME: blah blah</comment-marker></comment-line>
// CHECK: <comment-line>// Something something, <comment-marker>FIXME: blah</comment-marker></comment-line>
/* FIXME: blah*/
// CHECK: <comment-block>/* <comment-marker>FIXME: blah*/</comment-marker></comment-block>
/*
* FIXME: blah
* Blah, blah.
*/
// CHECK: <comment-block>/*
// CHECK: * <comment-marker>FIXME: blah</comment-marker>
// CHECK: * Blah, blah.
// CHECK: */</comment-block>
// TODO: blah.
// TTODO: blah.
// MARK: blah.
// CHECK: <comment-line>// <comment-marker>TODO: blah.</comment-marker></comment-line>
// CHECK: <comment-line>// T<comment-marker>TODO: blah.</comment-marker></comment-line>
// CHECK: <comment-line>// <comment-marker>MARK: blah.</comment-marker></comment-line>
// CHECK: <kw>func</kw> test5() -> <type>Int</type> {
func test5() -> Int {
// CHECK: <comment-line>// <comment-marker>TODO: something, something.</comment-marker></comment-line>
// TODO: something, something.
// CHECK: <kw>return</kw> <int>0</int>
return 0
}
func test6<T : Prot>(x: T) {}
// CHECK: <kw>func</kw> test6<T : <type>Prot</type>>(x: <type>T</type>) {}{{$}}
// http://whatever.com?ee=2&yy=1 and radar://123456
/* http://whatever.com FIXME: see in http://whatever.com/fixme
http://whatever.com */
// CHECK: <comment-line>// <comment-url>http://whatever.com?ee=2&yy=1</comment-url> and <comment-url>radar://123456</comment-url></comment-line>
// CHECK: <comment-block>/* <comment-url>http://whatever.com</comment-url> <comment-marker>FIXME: see in <comment-url>http://whatever.com/fixme</comment-url></comment-marker>
// CHECK: <comment-url>http://whatever.com</comment-url> */</comment-block>
// CHECK: <comment-line>// <comment-url>http://whatever.com/what-ever</comment-url></comment-line>
// http://whatever.com/what-ever
// CHECK: <kw>func</kw> <placeholder><#test1#></placeholder> () {}
func <#test1#> () {}
/// Brief.
///
/// Simple case.
///
/// - parameter x: A number
/// - parameter y: Another number
/// - PaRamEteR z-hyphen-q: Another number
/// - parameter : A strange number...
/// - parameternope1: Another number
/// - parameter nope2
/// - parameter: nope3
/// -parameter nope4: Another number
/// * parameter nope5: Another number
/// - parameter nope6: Another number
/// - Parameters: nope7
/// - seealso: yes
/// - seealso: yes
/// - seealso:
/// -seealso: nope
/// - seealso : nope
/// - seealso nope
/// - returns: `x + y`
func foo(x: Int, y: Int) -> Int { return x + y }
// CHECK: <doc-comment-line>/// Brief.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// Simple case.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> x: A number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> y: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>PaRamEteR</doc-comment-field> z-hyphen-q: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> : A strange number...
// CHECK: </doc-comment-line><doc-comment-line>/// - parameternope1: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope2
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter: nope3
// CHECK: </doc-comment-line><doc-comment-line>/// -parameter nope4: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// * parameter nope5: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope6: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - Parameters: nope7
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>:
// CHECK: </doc-comment-line><doc-comment-line>/// -seealso: nope
// CHECK: </doc-comment-line><doc-comment-line>/// - seealso : nope
// CHECK: </doc-comment-line><doc-comment-line>/// - seealso nope
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y`
// CHECK: </doc-comment-line><kw>func</kw> foo(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y }
/// Brief.
///
/// Simple case.
///
/// - Parameters:
/// - x: A number
/// - y: Another number
///
///- note: NOTE1
///
/// - NOTE: NOTE2
/// - note: Not a Note field (not at top level)
/// - returns: `x + y`
func bar(x: Int, y: Int) -> Int { return x + y }
// CHECK: <doc-comment-line>/// Brief.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// Simple case.
// CHECK: </doc-comment-line><doc-comment-line>///
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>Parameters</doc-comment-field>:
// CHECK: </doc-comment-line><doc-comment-line>/// - x: A number
// CHECK: </doc-comment-line><doc-comment-line>/// - y: Another number
// CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y`
// CHECK: </doc-comment-line><kw>func</kw> bar(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y }
/**
Does pretty much nothing.
Not a parameter list: improper indentation.
- Parameters: sdfadsf
- WARNING: - WARNING: Should only have one field
- $$$: Not a field.
Empty field, OK:
*/
func baz() {}
// CHECK: <doc-comment-block>/**
// CHECK: Does pretty much nothing.
// CHECK: Not a parameter list: improper indentation.
// CHECK: - Parameters: sdfadsf
// CHECK: - <doc-comment-field>WARNING</doc-comment-field>: - WARNING: Should only have one field
// CHECK: - $$$: Not a field.
// CHECK: Empty field, OK:
// CHECK: */</doc-comment-block>
// CHECK: <kw>func</kw> baz() {}
/***/
func emptyDocBlockComment() {}
// CHECK: <doc-comment-block>/***/</doc-comment-block>
// CHECK: <kw>func</kw> emptyDocBlockComment() {}
/**
*/
func emptyDocBlockComment2() {}
// CHECK: <doc-comment-block>/**
// CHECK: */
// CHECK: <kw>func</kw> emptyDocBlockComment2() {}
/** */
func emptyDocBlockComment3() {}
// CHECK: <doc-comment-block>/** */
// CHECK: <kw>func</kw> emptyDocBlockComment3() {}
/**/
func malformedBlockComment(f : () throws -> ()) rethrows {}
// CHECK: <doc-comment-block>/**/</doc-comment-block>
// CHECK: <kw>func</kw> malformedBlockComment(f : () <kw>throws</kw> -> ()) <attr-builtin>rethrows</attr-builtin> {}
//: playground doc comment line
func playgroundCommentLine(f : () throws -> ()) rethrows {}
// CHECK: <comment-line>//: playground doc comment line</comment-line>
/*:
playground doc comment multi-line
*/
func playgroundCommentMultiLine(f : () throws -> ()) rethrows {}
// CHECK: <comment-block>/*:
// CHECK: playground doc comment multi-line
// CHECK: */</comment-block>
/// [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings)
// CHECK: <doc-comment-line>/// [strict weak ordering](<comment-url>http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings</comment-url>
func funcTakingFor(for internalName: Int) {}
// CHECK: <kw>func</kw> funcTakingFor(for internalName: <type>Int</type>) {}
func funcTakingIn(in internalName: Int) {}
// CHECK: <kw>func</kw> funcTakingIn(in internalName: <type>Int</type>) {}
_ = 123
// CHECK: <int>123</int>
_ = -123
// CHECK: <int>-123</int>
_ = -1
// CHECK: <int>-1</int>
_ = -0x123
// CHECK: <int>-0x123</int>
_ = -3.1e-5
// CHECK: <float>-3.1e-5</float>
/** aaa
- returns: something
*/
// CHECK: - <doc-comment-field>returns</doc-comment-field>: something
let filename = #file
// CHECK: <kw>let</kw> filename = <kw>#file</kw>
let line = #line
// CHECK: <kw>let</kw> line = <kw>#line</kw>
let column = #column
// CHECK: <kw>let</kw> column = <kw>#column</kw>
let function = #function
// CHECK: <kw>let</kw> function = <kw>#function</kw>
let image = #imageLiteral(resourceName: "cloud.png")
// CHECK: <kw>let</kw> image = <object-literal>#imageLiteral(resourceName: "cloud.png")</object-literal>
let file = #fileLiteral(resourceName: "cloud.png")
// CHECK: <kw>let</kw> file = <object-literal>#fileLiteral(resourceName: "cloud.png")</object-literal>
let black = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
// CHECK: <kw>let</kw> black = <object-literal>#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)</object-literal>
let rgb = [#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1),
#colorLiteral(red: 0, green: 1, blue: 0, alpha: 1),
#colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)]
// CHECK: <kw>let</kw> rgb = [<object-literal>#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)</object-literal>,
// CHECK: <object-literal>#colorLiteral(red: 0, green: 1, blue: 0, alpha: 1)</object-literal>,
// CHECK: <object-literal>#colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)</object-literal>]
"--\"\(x) --"
// CHECK: <str>"--\"</str>\<anchor>(</anchor>x<anchor>)</anchor><str> --"</str>
func keywordAsLabel1(in: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel1(in: <type>Int</type>) {}
func keywordAsLabel2(for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel2(for: <type>Int</type>) {}
func keywordAsLabel3(if: Int, for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel3(if: <type>Int</type>, for: <type>Int</type>) {}
func keywordAsLabel4(_: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel4(<kw>_</kw>: <type>Int</type>) {}
func keywordAsLabel5(_: Int, for: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel5(<kw>_</kw>: <type>Int</type>, for: <type>Int</type>) {}
func keywordAsLabel6(if let: Int) {}
// CHECK: <kw>func</kw> keywordAsLabel6(if <kw>let</kw>: <type>Int</type>) {}
func foo1() {
// CHECK: <kw>func</kw> foo1() {
keywordAsLabel1(in: 1)
// CHECK: keywordAsLabel1(in: <int>1</int>)
keywordAsLabel2(for: 1)
// CHECK: keywordAsLabel2(for: <int>1</int>)
keywordAsLabel3(if: 1, for: 2)
// CHECK: keywordAsLabel3(if: <int>1</int>, for: <int>2</int>)
keywordAsLabel5(1, for: 2)
// CHECK: keywordAsLabel5(<int>1</int>, for: <int>2</int>)
_ = (if: 0, for: 2)
// CHECK: <kw>_</kw> = (if: <int>0</int>, for: <int>2</int>)
_ = (_: 0, _: 2)
// CHECK: <kw>_</kw> = (<kw>_</kw>: <int>0</int>, <kw>_</kw>: <int>2</int>)
}
func foo2(O1 : Int?, O2: Int?, O3: Int?) {
guard let _ = O1, var _ = O2, let _ = O3 else { }
// CHECK: <kw>guard</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 <kw>else</kw> { }
if let _ = O1, var _ = O2, let _ = O3 {}
// CHECK: <kw>if</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 {}
}
func keywordInCaseAndLocalArgLabel(_ for: Int, for in: Int, class _: Int) {
// CHECK: <kw>func</kw> keywordInCaseAndLocalArgLabel(<kw>_</kw> for: <type>Int</type>, for in: <type>Int</type>, class <kw>_</kw>: <type>Int</type>) {
switch(`for`, `in`) {
case (let x, let y):
// CHECK: <kw>case</kw> (<kw>let</kw> x, <kw>let</kw> y):
print(x, y)
}
}
// Keep this as the last test
/**
Trailing off ...
func unterminatedBlockComment() {}
// CHECK: <comment-line>// Keep this as the last test</comment-line>
// CHECK: <doc-comment-block>/**
// CHECK: Trailing off ...
// CHECK: func unterminatedBlockComment() {}
// CHECK: </doc-comment-block>
| apache-2.0 | 931b0655370ecaa65b6fb9e0c356d4c7 | 36.331179 | 178 | 0.604812 | 2.892477 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureSettings/Sources/FeatureSettingsUI/UpdateMobile/MobileCodeEntry/VerifyCodeEntryInteractor.swift | 1 | 1696 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformKit
import RxRelay
import RxSwift
import ToolKit
final class VerifyCodeEntryInteractor {
// MARK: - State
enum InteractionState {
/// Interactor is ready for code entry
case ready
/// User has entered a code and it is being verified
case verifying
/// The code has been verified
case complete
/// Code verification failed
case failed
}
// MARK: - Public
var triggerRelay = PublishRelay<Void>()
var contentRelay = BehaviorRelay<String>(value: "")
var interactionState: Observable<InteractionState> {
interactionStateRelay.asObservable()
}
// MARK: - Private Accessors
private let service: VerifyMobileSettingsServiceAPI
private let interactionStateRelay = BehaviorRelay<InteractionState>(value: .ready)
private let disposeBag = DisposeBag()
init(service: VerifyMobileSettingsServiceAPI) {
self.service = service
triggerRelay
.bindAndCatch(weak: self, onNext: { (self) in
self.interactionStateRelay.accept(.verifying)
self.submit()
})
.disposed(by: disposeBag)
}
private func submit() {
service
.verify(with: contentRelay.value)
.subscribe(
onCompleted: { [weak self] in
self?.interactionStateRelay.accept(.complete)
},
onError: { [weak self] _ in
self?.interactionStateRelay.accept(.failed)
}
)
.disposed(by: disposeBag)
}
}
| lgpl-3.0 | dac74ebd246cf2418e5c5ae915e83b14 | 25.904762 | 86 | 0.59941 | 5.31348 | false | false | false | false |
zmeyc/GRDB.swift | Tests/GRDBTests/TransactionObserverSavepointsTests.swift | 1 | 17854 | import XCTest
#if USING_SQLCIPHER
import GRDBCipher
#elseif USING_CUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
private class Observer : TransactionObserver {
var lastCommittedEvents: [DatabaseEvent] = []
var events: [DatabaseEvent] = []
#if SQLITE_ENABLE_PREUPDATE_HOOK
var preUpdateEvents: [DatabasePreUpdateEvent] = []
func databaseWillChange(with event: DatabasePreUpdateEvent) {
preUpdateEvents.append(event.copy())
}
#endif
func observes(eventsOfKind eventKind: DatabaseEventKind) -> Bool {
return true
}
func databaseDidChange(with event: DatabaseEvent) {
events.append(event.copy())
}
func databaseWillCommit() throws {
}
func databaseDidCommit(_ db: Database) {
lastCommittedEvents = events
events = []
}
func databaseDidRollback(_ db: Database) {
lastCommittedEvents = []
events = []
}
}
class TransactionObserverSavepointsTests: GRDBTestCase {
private func match(event: DatabaseEvent, kind: DatabaseEvent.Kind, tableName: String, rowId: Int64) -> Bool {
return (event.tableName == tableName) && (event.rowID == rowId) && (event.kind == kind)
}
#if SQLITE_ENABLE_PREUPDATE_HOOK
private func match(preUpdateEvent event: DatabasePreUpdateEvent, kind: DatabasePreUpdateEvent.Kind, tableName: String, initialRowID: Int64?, finalRowID: Int64?, initialValues: [DatabaseValue]?, finalValues: [DatabaseValue]?, depth: CInt = 0) -> Bool {
func check(databaseValues values: [DatabaseValue]?, expected: [DatabaseValue]?) -> Bool {
if let values = values {
guard let expected = expected else { return false }
return values == expected
}
else { return expected == nil }
}
var count : Int = 0
if let initialValues = initialValues { count = initialValues.count }
if let finalValues = finalValues { count = max(count, finalValues.count) }
guard (event.kind == kind) else { return false }
guard (event.tableName == tableName) else { return false }
guard (event.count == count) else { return false }
guard (event.depth == depth) else { return false }
guard (event.initialRowID == initialRowID) else { return false }
guard (event.finalRowID == finalRowID) else { return false }
guard check(databaseValues: event.initialDatabaseValues, expected: initialValues) else { return false }
guard check(databaseValues: event.finalDatabaseValues, expected: finalValues) else { return false }
return true
}
#endif
// MARK: - Events
func testSavepointAsTransaction() throws {
let dbQueue = try makeDatabaseQueue()
let observer = Observer()
dbQueue.add(transactionObserver: observer)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)")
try db.execute("SAVEPOINT sp1")
XCTAssertTrue(db.isInsideTransaction)
try db.execute("INSERT INTO items1 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 0)
try db.execute("INSERT INTO items2 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 0)
try db.execute("RELEASE SAVEPOINT sp1")
XCTAssertFalse(db.isInsideTransaction)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items1"), 1)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items2"), 1)
}
XCTAssertEqual(observer.lastCommittedEvents.count, 2)
XCTAssertTrue(match(event: observer.lastCommittedEvents[0], kind: .insert, tableName: "items1", rowId: 1))
XCTAssertTrue(match(event: observer.lastCommittedEvents[1], kind: .insert, tableName: "items2", rowId: 1))
#if SQLITE_ENABLE_PREUPDATE_HOOK
XCTAssertEqual(observer.preUpdateEvents.count, 2)
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[0], kind: .insert, tableName: "items1", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[1], kind: .insert, tableName: "items2", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
#endif
}
func testSavepointInsideTransaction() throws {
let dbQueue = try makeDatabaseQueue()
let observer = Observer()
dbQueue.add(transactionObserver: observer)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)")
try db.execute("BEGIN TRANSACTION")
try db.execute("INSERT INTO items1 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("SAVEPOINT sp1")
try db.execute("INSERT INTO items2 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("COMMIT")
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items1"), 1)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items2"), 1)
}
XCTAssertEqual(observer.lastCommittedEvents.count, 2)
XCTAssertTrue(match(event: observer.lastCommittedEvents[0], kind: .insert, tableName: "items1", rowId: 1))
XCTAssertTrue(match(event: observer.lastCommittedEvents[1], kind: .insert, tableName: "items2", rowId: 1))
#if SQLITE_ENABLE_PREUPDATE_HOOK
XCTAssertEqual(observer.preUpdateEvents.count, 2)
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[0], kind: .insert, tableName: "items1", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[1], kind: .insert, tableName: "items2", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
#endif
}
func testSavepointWithIdenticalName() throws {
let dbQueue = try makeDatabaseQueue()
let observer = Observer()
dbQueue.add(transactionObserver: observer)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items3 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items4 (id INTEGER PRIMARY KEY)")
try db.execute("BEGIN TRANSACTION")
try db.execute("INSERT INTO items1 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("SAVEPOINT sp1")
try db.execute("INSERT INTO items2 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("SAVEPOINT sp1")
try db.execute("INSERT INTO items3 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("RELEASE SAVEPOINT sp1")
XCTAssertEqual(observer.events.count, 1)
try db.execute("RELEASE SAVEPOINT sp1")
XCTAssertEqual(observer.events.count, 3)
try db.execute("INSERT INTO items4 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 4)
try db.execute("COMMIT")
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items1"), 1)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items2"), 1)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items3"), 1)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items4"), 1)
}
XCTAssertEqual(observer.lastCommittedEvents.count, 4)
XCTAssertTrue(match(event: observer.lastCommittedEvents[0], kind: .insert, tableName: "items1", rowId: 1))
XCTAssertTrue(match(event: observer.lastCommittedEvents[1], kind: .insert, tableName: "items2", rowId: 1))
XCTAssertTrue(match(event: observer.lastCommittedEvents[2], kind: .insert, tableName: "items3", rowId: 1))
XCTAssertTrue(match(event: observer.lastCommittedEvents[3], kind: .insert, tableName: "items4", rowId: 1))
#if SQLITE_ENABLE_PREUPDATE_HOOK
XCTAssertEqual(observer.preUpdateEvents.count, 4)
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[0], kind: .insert, tableName: "items1", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[1], kind: .insert, tableName: "items2", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[2], kind: .insert, tableName: "items3", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[3], kind: .insert, tableName: "items4", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
#endif
}
func testMultipleRollbackOfSavepoint() throws {
let dbQueue = try makeDatabaseQueue()
let observer = Observer()
dbQueue.add(transactionObserver: observer)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items3 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items4 (id INTEGER PRIMARY KEY)")
try db.execute("BEGIN TRANSACTION")
try db.execute("INSERT INTO items1 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("SAVEPOINT sp1")
try db.execute("INSERT INTO items2 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("INSERT INTO items3 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("ROLLBACK TO SAVEPOINT sp1")
try db.execute("INSERT INTO items4 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("ROLLBACK TO SAVEPOINT sp1")
try db.execute("INSERT INTO items4 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("COMMIT")
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items1"), 1)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items2"), 0)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items3"), 0)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items4"), 1)
}
XCTAssertEqual(observer.lastCommittedEvents.count, 2)
XCTAssertTrue(match(event: observer.lastCommittedEvents[0], kind: .insert, tableName: "items1", rowId: 1))
XCTAssertTrue(match(event: observer.lastCommittedEvents[1], kind: .insert, tableName: "items4", rowId: 1))
#if SQLITE_ENABLE_PREUPDATE_HOOK
XCTAssertEqual(observer.preUpdateEvents.count, 2)
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[0], kind: .insert, tableName: "items1", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[1], kind: .insert, tableName: "items4", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
#endif
}
func testReleaseSavepoint() throws {
let dbQueue = try makeDatabaseQueue()
let observer = Observer()
dbQueue.add(transactionObserver: observer)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items3 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items4 (id INTEGER PRIMARY KEY)")
try db.execute("BEGIN TRANSACTION")
try db.execute("INSERT INTO items1 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("SAVEPOINT sp1")
try db.execute("INSERT INTO items2 (id) VALUES (NULL)")
try db.execute("INSERT INTO items3 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("RELEASE SAVEPOINT sp1")
XCTAssertEqual(observer.events.count, 3)
try db.execute("INSERT INTO items4 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 4)
try db.execute("COMMIT")
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items1"), 1)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items2"), 1)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items3"), 1)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items4"), 1)
}
XCTAssertEqual(observer.lastCommittedEvents.count, 4)
XCTAssertTrue(match(event: observer.lastCommittedEvents[0], kind: .insert, tableName: "items1", rowId: 1))
XCTAssertTrue(match(event: observer.lastCommittedEvents[1], kind: .insert, tableName: "items2", rowId: 1))
XCTAssertTrue(match(event: observer.lastCommittedEvents[2], kind: .insert, tableName: "items3", rowId: 1))
XCTAssertTrue(match(event: observer.lastCommittedEvents[3], kind: .insert, tableName: "items4", rowId: 1))
#if SQLITE_ENABLE_PREUPDATE_HOOK
XCTAssertEqual(observer.preUpdateEvents.count, 4)
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[0], kind: .insert, tableName: "items1", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[1], kind: .insert, tableName: "items2", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[2], kind: .insert, tableName: "items3", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[3], kind: .insert, tableName: "items4", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
#endif
}
func testRollbackNonNestedSavepointInsideTransaction() throws {
let dbQueue = try makeDatabaseQueue()
let observer = Observer()
dbQueue.add(transactionObserver: observer)
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE items1 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items2 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items3 (id INTEGER PRIMARY KEY)")
try db.execute("CREATE TABLE items4 (id INTEGER PRIMARY KEY)")
try db.execute("BEGIN TRANSACTION")
try db.execute("INSERT INTO items1 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("SAVEPOINT sp1")
try db.execute("INSERT INTO items2 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("SAVEPOINT sp2")
try db.execute("INSERT INTO items3 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("RELEASE SAVEPOINT sp2")
XCTAssertEqual(observer.events.count, 1)
try db.execute("ROLLBACK TO SAVEPOINT sp1")
XCTAssertEqual(observer.events.count, 1)
try db.execute("INSERT INTO items4 (id) VALUES (NULL)")
XCTAssertEqual(observer.events.count, 1)
try db.execute("COMMIT")
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items1"), 1)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items2"), 0)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items3"), 0)
XCTAssertEqual(try Int.fetchOne(db, "SELECT COUNT(*) FROM items4"), 1)
}
XCTAssertEqual(observer.lastCommittedEvents.count, 2)
XCTAssertTrue(match(event: observer.lastCommittedEvents[0], kind: .insert, tableName: "items1", rowId: 1))
XCTAssertTrue(match(event: observer.lastCommittedEvents[1], kind: .insert, tableName: "items4", rowId: 1))
#if SQLITE_ENABLE_PREUPDATE_HOOK
XCTAssertEqual(observer.preUpdateEvents.count, 2)
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[0], kind: .insert, tableName: "items1", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
XCTAssertTrue(match(preUpdateEvent: observer.preUpdateEvents[1], kind: .insert, tableName: "items4", initialRowID: nil, finalRowID: 1, initialValues: nil, finalValues: [Int(1).databaseValue]))
#endif
}
}
| mit | c572886df21cb60cd98093b8facd4be4 | 54.447205 | 255 | 0.648202 | 4.654327 | false | false | false | false |
jindulys/HackerRankSolutions | Sources/Leetcode/Tree/100_SameTree.swift | 1 | 1016 | //
// 100_SameTree.swift
// HRSwift
//
// Created by yansong li on 2016-08-02.
// Copyright © 2016 yansong li. All rights reserved.
//
import Foundation
/**
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
*/
/**
Swift Knowledge:
Enum Comparison
Algorithem Knowledge:
Recursive call.
*/
/**
100. Same Tree
https://leetcode.com/problems/same-tree/
*/
class Solution_SameTree {
func isSameTree(p: TreeNode?, _ q: TreeNode?) -> Bool {
switch(p, q){
case (let .Some(leftRoot), let .Some(rightRoot)):
let valEqual = (leftRoot.val == rightRoot.val)
let leftEqual = isSameTree(leftRoot.left, rightRoot.left)
let rightEqual = isSameTree(leftRoot.right, rightRoot.right)
return valEqual && leftEqual && rightEqual
case (.None, .None):
return true
default:
return false
}
}
} | mit | 9c745e0c2d1ddad7107bae2bacdf3408 | 21.086957 | 109 | 0.651232 | 3.745387 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Threads/ThreadList/Views/Empty/ThreadListEmptyView.swift | 1 | 2712 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Reusable
@objc
protocol ThreadListEmptyViewDelegate: AnyObject {
func threadListEmptyViewTappedShowAllThreads(_ emptyView: ThreadListEmptyView)
}
/// View to be shown on the thread list screen when no thread is available. Use a `ThreadListEmptyModel` instance to configure.
class ThreadListEmptyView: UIView {
@IBOutlet weak var delegate: ThreadListEmptyViewDelegate?
@IBOutlet private weak var iconBackgroundView: UIView!
@IBOutlet private weak var iconView: UIImageView!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var infoLabel: UILabel!
@IBOutlet private weak var tipLabel: UILabel!
@IBOutlet private weak var showAllThreadsButton: UIButton!
required init?(coder: NSCoder) {
super.init(coder: coder)
loadNibContent()
}
func configure(withModel model: ThreadListEmptyModel) {
iconView.image = model.icon
titleLabel.text = model.title
infoLabel.text = model.info
tipLabel.text = model.tip
showAllThreadsButton.setTitle(model.showAllThreadsButtonTitle,
for: .normal)
showAllThreadsButton.isHidden = model.showAllThreadsButtonHidden
titleLabel.isHidden = titleLabel.text?.isEmpty ?? true
infoLabel.isHidden = infoLabel.text?.isEmpty ?? true
tipLabel.isHidden = tipLabel.text?.isEmpty ?? true
}
@IBAction private func showAllThreadsButtonTapped(_ sender: UIButton) {
delegate?.threadListEmptyViewTappedShowAllThreads(self)
}
}
extension ThreadListEmptyView: NibOwnerLoadable {}
extension ThreadListEmptyView: Themable {
func update(theme: Theme) {
iconBackgroundView.backgroundColor = theme.colors.system
iconView.tintColor = theme.colors.secondaryContent
titleLabel.textColor = theme.colors.primaryContent
infoLabel.textColor = theme.colors.secondaryContent
tipLabel.textColor = theme.colors.secondaryContent
showAllThreadsButton.tintColor = theme.colors.accent
}
}
| apache-2.0 | ef40354dd3496851cb796d22cceffcfd | 35.16 | 127 | 0.717183 | 4.92196 | false | false | false | false |
Brightify/DataMapper | Tests/PerformanceTest.swift | 1 | 3657 | //
// PerformanceTest.swift
// DataMapper
//
// Created by Filip Dolnik on 27.12.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import XCTest
import DataMapper
class PerformanceTest: XCTestCase {
private typealias Object = TestData.PerformanceStruct
private let objectMapper = ObjectMapper()
private let serializer = JsonSerializer()
private let objects = TestData.generate(x: 8)
func testDerializeDataToCodable() {
let data = try! JSONEncoder().encode(objects)
var result: Object!
measure {
result = try! JSONDecoder().decode(TestData.PerformanceStruct.self, from: data)
}
_ = result
}
func testSerializeCodableToData() {
var result: Data!
measure {
result = try! JSONEncoder().encode(self.objects)
}
_ = result
}
func testDeserializeDataToObject() {
let data: Data = serializer.serialize(objectMapper.serialize(objects))
var result: Object!
measure {
result = self.objectMapper.deserialize(self.serializer.deserialize(data))
}
_ = result
}
func testDeserializeSupportedTypeToObject() {
let data: SupportedType = objectMapper.serialize(objects)
var result: Object!
measure {
result = self.objectMapper.deserialize(data)
}
_ = result
}
func testDeserializeDataToSupportedType() {
let data: Data = serializer.serialize(objectMapper.serialize(objects))
var result: SupportedType!
measure {
result = self.serializer.deserialize(data)
}
_ = result
}
func testSerializeObjectToData() {
let data: Object = objects
var result: Data!
measure {
result = self.serializer.serialize(self.objectMapper.serialize(data))
}
_ = result
}
func testSerializeObjectToSupportedType() {
let data: Object = objects
var result: SupportedType!
measure {
result = self.objectMapper.serialize(data)
}
_ = result
}
func testSerializeSupportedTypeToData() {
let data: SupportedType = objectMapper.serialize(objects)
var result: Data!
measure {
result = self.serializer.serialize(data)
}
_ = result
}
// TODO Change Any
func testTypedSerialize() {
let data: SupportedType = objectMapper.serialize(objects)
var result: Any!
measure {
result = self.serializer.typedSerialize(data)
}
_ = result
}
func testTypedDeserialize() {
let data: Any = serializer.typedSerialize(objectMapper.serialize(objects))
var result: SupportedType!
measure {
result = self.serializer.typedDeserialize(data)
}
_ = result
}
// TODO Improve to use Swift objects
func _testSerializeFoundation() {
let data: Any = try! JSONSerialization.jsonObject(with: serializer.serialize(objectMapper.serialize(objects)), options: .allowFragments)
var result: Data!
measure {
result = try! JSONSerialization.data(withJSONObject: data)
}
_ = result
}
func _testDeserializeFoundation() {
let data: Data = serializer.serialize(objectMapper.serialize(objects))
var result: Any!
measure {
result = try! JSONSerialization.jsonObject(with: data, options: .allowFragments)
}
_ = result
}
}
| mit | 337e44697771c2e326183b9d4f53b8b3 | 26.488722 | 144 | 0.59628 | 5.049724 | false | true | false | false |
nmdias/FeedKit | Sources/FeedKit/Models/Namespaces/Media/MediaCommunity.swift | 2 | 2622 | //
// MediaCommunity.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
/// This element stands for the community related content. This allows
/// inclusion of the user perception about a media object in the form of view
/// count, ratings and tags.
public class MediaCommunity {
/// This element specifies the rating-related information about a media object.
/// Valid attributes are average, count, min and max.
public var mediaStarRating: MediaStarRating?
/// This element specifies various statistics about a media object like the
/// view count and the favorite count. Valid attributes are views and favorites.
public var mediaStatistics: MediaStatistics?
/// This element contains user-generated tags separated by commas in the
/// decreasing order of each tag's weight. Each tag can be assigned an integer
/// weight in tag_name:weight format. It's up to the provider to choose the way
/// weight is determined for a tag; for example, number of occurences can be
/// one way to decide weight of a particular tag. Default weight is 1.
public var mediaTags: [MediaTag]?
public init() { }
}
// MARK: - Equatable
extension MediaCommunity: Equatable {
public static func ==(lhs: MediaCommunity, rhs: MediaCommunity) -> Bool {
return
lhs.mediaStarRating == rhs.mediaStarRating &&
lhs.mediaStatistics == rhs.mediaStatistics &&
lhs.mediaTags == rhs.mediaTags
}
}
| mit | 904eadd44f42cf51a55d1f7dbce72114 | 41.290323 | 84 | 0.717773 | 4.632509 | false | false | false | false |
ghotjunwoo/Tiat | ChatViewController.swift | 1 | 1323 | //
// ChatViewController.swift
// Tiat
//
// Created by Ghotjunwoo on 2016. 10. 2..
// Copyright © 2016년 JW. All rights reserved.
//
import UIKit
import Firebase
class ChatViewController: UIViewController {
let userUid = FIRAuth.auth()?.currentUser?.uid
var toUid = ""
let childChatRef = FIRDatabase.database().reference().child("chat").childByAutoId()
var userName = ""
@IBOutlet weak var topBar: UINavigationItem!
@IBOutlet weak var containerView: UIView!
@IBOutlet var inputTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
topBar.title = "Hello"
}
@IBAction func handleSend(_ sender: AnyObject) {
handle()
}
@IBAction func handleSendByEnter(_ sender: AnyObject) {
handle()
}
func handle() {
print(toUid)
let message = inputTextField.text!
let timestamp: NSNumber = NSDate().timeIntervalSince1970 as NSNumber
let organizedTimeStamp = timestamp as Int
let fromId = userUid!
let toId = toUid
childChatRef.child("text").setValue(message)
childChatRef.child("timestamp").setValue(organizedTimeStamp)
childChatRef.child("fromId").setValue(fromId)
childChatRef.child("toId").setValue(toId)
}
}
| gpl-3.0 | 06d356247a92fdcff169f63232ebf88b | 25.938776 | 87 | 0.645455 | 4.536082 | false | false | false | false |
OpenStack-mobile/aerogear-ios-oauth2 | AeroGearOAuth2/DateUtils.swift | 4 | 1697 | /*
* JBoss, Home of Professional Open Source.
* Copyright Red Hat, Inc., and individual contributors
*
* 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
/**
Handy extensions to NSDate
*/
extension Date {
/**
Initialize a date object using the given string.
:param: dateString the string that will be used to instantiate the date object. The string is expected to be in the format 'yyyy-MM-dd hh:mm:ss a'.
:returns: the NSDate object.
*/
public init(dateString: String) {
let dateStringFormatter = DateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss a"
let d = dateStringFormatter.date(from: dateString)
if let unwrappedDate = d {
self.init(timeInterval:0, since:unwrappedDate)
} else {
self.init()
}
}
/**
Returns a string of the date object using the format 'yyyy-MM-dd hh:mm:ss a'.
:returns: a formatted string object.
*/
public func toString() -> String {
let dateStringFormatter = DateFormatter()
dateStringFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss a"
return dateStringFormatter.string(from: self)
}
}
| apache-2.0 | 50bb1325b3a7e73722b3afe615f75f01 | 30.425926 | 151 | 0.685916 | 4.253133 | false | true | false | false |
DrGo/LearningSwift | PLAYGROUNDS/LSB_B017_Functors.playground/section-2.swift | 2 | 5691 | import UIKit
/*
// Functors
//
// Based on:
// http://www.objc.io/books/ (Chapter 14, Functors, Applicative Functors, and Monads)
// (Functional Programming in Swift, by Chris Eidhof, Florian Kugler, and Wouter Swierstra)
/===================================*/
/*---------------------------------------------------------------------/
// Map - Why are there two?
/---------------------------------------------------------------------*/
// func map<T, U>(xs: [T], transform: T -> U) -> [U]
let numbers: Array<Int> = Array(1...5) // Array as type constructor
let numbersPlusOne = map(numbers) { $0 + 1 }
numbersPlusOne
// func map<T, U>(optional: T?, transform: T -> U) -> U?
let opt: Optional<Int> = 1 // Optional as type constructor
let optPlusOne = map(opt) { $0 + 1 }
optPlusOne! // <-- unwrap!
/*
`Array` is a type constructor
`Array` is not a valid type
`Array<T>` is a valid type
`Array<Int>` is a valid type (a concrete type)
`Optional` is a type constructor
`Optional<Int>` is a valid type (a concrete type)
Type constructors that support a map operation are sometimes referred
to as, "functors."
They are sometimes described as "containers."
Almost every generic enum you define in Swift is a functor.
*/
/*---------------------------------------------------------------------/
// Trees are functors
//
// From Learn You a Haskell for Great Good,
// Chapter 7, Making Our Own Types and Type Classes
// - by Miran Lipovača
//
// instance Functor Tree where
// fmap f EmptyTree = EmptyTree
// fmap f (Node x left right) = Node (f x) (fmap f left) (fmap f right)
/---------------------------------------------------------------------*/
class Box<T> {
let unbox: T
init(_ value: T) { self.unbox = value }
}
/*---------------------------------------------------------/
// Tree
/---------------------------------------------------------*/
enum Tree<T> {
case Empty
case Node(Box<T>, Box<Tree<T>>, Box<Tree<T>>)
}
let empty: Tree<Int> = Tree.Empty
let five: Tree<Int> = Tree.Node(Box(5), Box(empty), Box(empty))
/*---------------------------------------------------------/
// Tree - Map
/---------------------------------------------------------*/
func map<T>(tree: Tree<T>, transform f: T -> T) -> Tree<T> {
switch tree {
case let .Node(value, left, right):
return Tree.Node(Box(f(value.unbox)),
Box(map(left.unbox, transform: f)),
Box(map(right.unbox, transform: f)))
case .Empty:
return Tree.Empty
}
}
let fivePlusFive = map(five) { $0 + 5 }
// List Tree node values in an array
func elements<T>(tree: Tree<T>) -> [T] {
switch tree {
case Tree.Empty:
return []
case let Tree.Node(value, left, right):
return elements(left.unbox) + [value.unbox] + elements(right.unbox)
}
}
elements(five)
elements(fivePlusFive)
/*---------------------------------------------------------/
// Tree Insert
//
// singleton :: a -> Tree a
// singleton x = Node x EmptyTree EmptyTree
//
// treeInsert :: (Ord a) => a -> Tree a -> Tree a
// treeInsert x EmptyTree = singleton x
// treeInsert x (Node a left right)
// | x == a = Node x left right
// | x < a = Node a (treeInsert x left) right
// | x > a = Node a left (treeInsert x right)
/---------------------------------------------------------*/
// create a tree with a single value
func singleton<T>(x: T) -> Tree<T> {
return Tree.Node(Box(x), Box(Tree.Empty), Box(Tree.Empty))
}
func treeInsert<T: Comparable>(x: T, tree: Tree<T>) -> Tree<T> {
switch tree {
case .Empty:
return singleton(x)
case let .Node(value, _, _) where value.unbox == x:
return tree
case let .Node(value, left, right) where value.unbox > x:
return Tree.Node(value, Box(treeInsert(x, left.unbox)), right)
case let .Node(value, left, right) where value.unbox < x:
return Tree.Node(value, left, Box(treeInsert(x, right.unbox)))
default: assertionFailure("fail!")
}
}
elements(singleton(4))
elements(treeInsert(5, five))
elements(treeInsert(6, five))
elements(treeInsert(4, five))
/*---------------------------------------------------------/
// Check Element
//
// treeElem :: (Ord a) => a -> Tree a -> Bool
// treeElem x EmptyTree = False
// treeElem x (Node a left right)
// | x == a = True
// | x < a = treeElem x left
// | x > a = treeElem x right
/---------------------------------------------------------*/
func treeElem<T: Comparable>(x: T, tree: Tree<T>) -> Bool {
switch tree {
case .Empty:
return false
case let .Node(value, _, _) where x == value.unbox:
return true
case let .Node(value, left, _) where x < value.unbox:
return treeElem(x, left.unbox)
case let .Node(value, _, right) where x > value.unbox:
return treeElem(x, right.unbox)
default: assertionFailure("fail!")
}
}
treeElem(5, five)
treeElem(4, five)
treeElem(6, treeInsert(6, treeInsert(4, five)))
treeElem(3, treeInsert(6, treeInsert(4, five)))
/*---------------------------------------------------------/
// Fold to create a tree from a list
/---------------------------------------------------------*/
let treeValues = [8, 6, 4, 1, 7, 3, 5]
let vTree = reduce(treeValues, Tree.Empty) { treeInsert($1, $0) }
elements(vTree)
// Make this is a little nicer with `flip`
func flip<A, B, C>(f: (B, A) -> C) -> (A, B) -> C {
return { (x, y) in f(y, x) }
}
let vTree2 = reduce(treeValues, Tree.Empty, flip(treeInsert))
elements(vTree2)
/*---------------------------------------------------------/
// Tree - Map - Part 2
/---------------------------------------------------------*/
let vTreePlus10 = map(vTree) { $0 + 10 }
elements(vTreePlus10)
| gpl-3.0 | df95695bbc38734a36c17d65be9ee8d8 | 27.883249 | 94 | 0.513357 | 3.702017 | false | false | false | false |
zxpLearnios/MyProject | test_projectDemo1/GuideVC/Album/MyCollectionViewLayout.swift | 1 | 1952 | //
// MyCollectionViewLayout.swift
// test_projectDemo1
//
// Created by Jingnan Zhang on 16/7/22.
// Copyright © 2016年 Jingnan Zhang. All rights reserved.
//
import UIKit
class MyCollectionViewLayout: UICollectionViewFlowLayout {
/**
内部会重新调用prepareLayout和layoutAttributesForElementsInRect方法获得所有cell的布局属性
*/
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
// 每行显示3个cell
override func prepare() {
super.prepare()
let inset:CGFloat = 10
let width = (kwidth - inset * 4)/3
self.itemSize = CGSize(width: width, height: width)
self.sectionInset = UIEdgeInsetsMake(64, inset, 0, inset)
self.collectionView?.alwaysBounceVertical = true // 数据不够一屏时,默认不滚动
// 设置水平滚动
// self.scrollDirection = .Vertical
// 设置分区的头视图和尾视图是否始终固定在屏幕上边和下边
// self.sectionHeadersPinToVisibleBounds = true
// self.headerReferenceSize = CGSizeMake(50, kwidth)
// self.minimumLineSpacing = 10
// self.minimumInteritemSpacing = 10
}
// 此时不写此法或注释掉 即为prepareLayout里所设置的布局
// override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
//
// // 1.取得默认的cell的UICollectionViewLayoutAttributes
// let array = super.layoutAttributesForElementsInRect(rect) // 页面所有的元素
// for i in 0..<array!.count {
// let attrs = array![i]
// if attrs.representedElementCategory == .SupplementaryView {
// continue
// }
//// attrs.transform = CGAffineTransformMakeRotation(45)
// }
//
// return array;
//
// }
}
| mit | f83b4d9a671832d78c76efb9d197ce79 | 29.12069 | 108 | 0.629078 | 4.411616 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/WMFScrollViewController.swift | 1 | 2907 | import UIKit
class WMFScrollViewController: UIViewController {
@IBOutlet internal var scrollView: UIScrollView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
wmf_beginAdjustingScrollViewInsetsForKeyboard()
}
override func viewWillDisappear(_ animated: Bool) {
wmf_endAdjustingScrollViewInsetsForKeyboard()
super.viewWillDisappear(animated)
}
private var coverView: UIView?
func setViewControllerUserInteraction(enabled: Bool) {
if enabled {
coverView?.removeFromSuperview()
} else if coverView == nil {
let newCoverView = UIView()
newCoverView.backgroundColor = view.backgroundColor
newCoverView.alpha = 0.8
view.wmf_addSubviewWithConstraintsToEdges(newCoverView)
coverView = newCoverView
}
view.isUserInteractionEnabled = enabled
}
/// Adjusts 'scrollView' contentInset so its contents can be scrolled above the keyboard.
///
/// - Parameter notification: A UIKeyboardWillChangeFrame notification. Works for landscape and portrait.
private func wmf_adjustScrollViewInset(forKeyboardWillChangeFrameNotification notification: Notification) {
guard
notification.name == UIWindow.keyboardWillChangeFrameNotification,
let keyboardScreenRect = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect
else {
assertionFailure("Notification name was expected to be '\(UIWindow.keyboardWillChangeFrameNotification)' but was '\(notification.name)'")
return
}
guard scrollView != nil else {
assertionFailure("'scrollView' isn't yet hooked up to a storyboard/nib")
return
}
guard let window = view.window else {
return
}
let keyboardWindowRect = window.convert(keyboardScreenRect, from: nil)
let intersection = keyboardWindowRect.intersection(window.frame)
let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: intersection.size.height, right: 0)
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
}
private func wmf_beginAdjustingScrollViewInsetsForKeyboard() {
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(_:)), name: UIWindow.keyboardWillChangeFrameNotification, object: nil)
}
private func wmf_endAdjustingScrollViewInsetsForKeyboard() {
NotificationCenter.default.removeObserver(self, name: UIWindow.keyboardWillChangeFrameNotification, object: nil)
}
@objc private func keyboardWillChangeFrame(_ notification: Notification) {
wmf_adjustScrollViewInset(forKeyboardWillChangeFrameNotification: notification)
}
}
| mit | 9a852f27a3ffe641e4110d25103d272c | 43.045455 | 167 | 0.697626 | 6.12 | false | false | false | false |
OpsLabJPL/MarsImagesIOS | Pods/Swinject/Sources/ObjectScope.swift | 1 | 1752 | //
// Copyright © 2019 Swinject Contributors. All rights reserved.
//
/// A configuration how an instance provided by a `Container` is shared in the system.
/// The configuration is ignored if it is applied to a value type.
public protocol ObjectScopeProtocol: AnyObject {
/// Used to create `InstanceStorage` to persist an instance for single service.
/// Will be invoked once for each service registered in given scope.
func makeStorage() -> InstanceStorage
}
/// Basic implementation of `ObjectScopeProtocol`.
public class ObjectScope: ObjectScopeProtocol, CustomStringConvertible {
public private(set) var description: String
private var storageFactory: () -> InstanceStorage
private let parent: ObjectScopeProtocol?
/// Instantiates an `ObjectScope` with storage factory and description.
/// - Parameters:
/// - storageFactory: Closure for creating an `InstanceStorage`
/// - description: Description of object scope for `CustomStringConvertible` implementation
/// - parent: If provided, its storage will be composed with the result of `storageFactory`
public init(
storageFactory: @escaping () -> InstanceStorage,
description: String = "",
parent: ObjectScopeProtocol? = nil
) {
self.storageFactory = storageFactory
self.description = description
self.parent = parent
}
/// Will invoke and return the result of `storageFactory` closure provided during initialisation.
public func makeStorage() -> InstanceStorage {
if let parent = parent {
return CompositeStorage([storageFactory(), parent.makeStorage()])
} else {
return storageFactory()
}
}
}
| apache-2.0 | 1c0fde5117605ec8336acde6475aca1c | 40.690476 | 109 | 0.686465 | 5.322188 | false | false | false | false |
illescasDaniel/Questions | Questions/utils/downloads/OnlineImagesManager.swift | 1 | 2344 | import UIKit
public final class OnlineImagesManager {
public class LoadCachedImage {
private let stringURL: String
private var placeholderImage: UIImage? = nil
public init(url: String) {
self.stringURL = url
}
public func placeholder(image: UIImage) -> LoadCachedImage {
placeholderImage = image
return self
}
public func into(imageView: UIImageView) {
DispatchQueue.main.async {
if let placeholderImage = self.placeholderImage {
imageView.image = placeholderImage
}
}
OnlineImagesManager.shared.load(url: stringURL, onSuccess: { image in
imageView.image = image
})
}
public func into(buttonImage: UIButton) {
DispatchQueue.main.async {
if let placeholderImage = self.placeholderImage {
buttonImage.setImage(placeholderImage, for: .normal)
}
}
OnlineImagesManager.shared.load(url: stringURL, onSuccess: { image in
buttonImage.setImage(image, for: .normal)
})
}
}
public static let shared = OnlineImagesManager()
fileprivate init() { }
public func load(image imageURL: String, into imageView: UIImageView, placeholder: UIImage? = nil) {
let loadCachedImage = LoadCachedImage(url: imageURL)
if let placeholderImage = placeholder {
let _ = loadCachedImage.placeholder(image: placeholderImage)
}
loadCachedImage.into(imageView: imageView)
}
public func load(image imageURL: String) -> LoadCachedImage {
return LoadCachedImage(url: imageURL)
}
// TODO: might need some testing to check if is worth it, but it should since it downloads the image and stores it in a file that will later be used
public func preloadImage(withURL url: String?, onError: @escaping (DownloadManager.Errors) -> () = {_ in }) {
DownloadManager.shared.manageData(from: url, onSuccess: { _ in
// empty on purpose
}, onError: onError)
}
public func load(url: String,
prepareForDownload: @escaping () -> () = {},
onSuccess: @escaping (UIImage) -> (),
onError: @escaping (DownloadManager.Errors) -> () = {_ in }) {
DispatchQueue.main.async {
prepareForDownload()
}
DownloadManager.shared.manageData(from: url, onSuccess: { data in
if let validImage = UIImage(data: data) { // TODO: use global async here
DispatchQueue.main.async {
onSuccess(validImage)
}
}
}, onError: onError)
}
}
| mit | ab961ff790d5ce5315f309c7def56454 | 28.3 | 149 | 0.697099 | 3.926298 | false | false | false | false |
liduanw/Monkey | Monkey/OctoKit/Carthage/Checkouts/ReactiveCocoa/Carthage/Checkouts/Quick/Externals/Nimble/NimbleTests/Matchers/BeGreaterThanOrEqualToTest.swift | 76 | 1139 | import XCTest
import Nimble
class BeGreaterThanOrEqualToTest: XCTestCase {
func testGreaterThanOrEqualTo() {
expect(10).to(beGreaterThanOrEqualTo(10))
expect(10).to(beGreaterThanOrEqualTo(2))
expect(1).toNot(beGreaterThanOrEqualTo(2))
expect(NSNumber(int:1)).toNot(beGreaterThanOrEqualTo(2))
expect(NSNumber(int:2)).to(beGreaterThanOrEqualTo(NSNumber(int:2)))
expect(1).to(beGreaterThanOrEqualTo(NSNumber(int:0)))
failsWithErrorMessage("expected <0> to be greater than or equal to <2>") {
expect(0).to(beGreaterThanOrEqualTo(2))
return
}
failsWithErrorMessage("expected <1> to not be greater than or equal to <1>") {
expect(1).toNot(beGreaterThanOrEqualTo(1))
return
}
}
func testGreaterThanOrEqualToOperator() {
expect(0) >= 0
expect(1) >= 0
expect(NSNumber(int:1)) >= 1
expect(NSNumber(int:1)) >= NSNumber(int:1)
failsWithErrorMessage("expected <1> to be greater than or equal to <2>") {
expect(1) >= 2
return
}
}
}
| mit | 23c9e6f6bd7f92ad333fc3b17ff37845 | 31.542857 | 86 | 0.614574 | 4.501976 | false | true | false | false |
JackieQu/QP_DouYu | QP_DouYu/QP_DouYu/Classes/Home/Controller/FunnyViewController.swift | 1 | 1019 | //
// FunnyViewController.swift
// QP_DouYu
//
// Created by JackieQu on 2017/3/9.
// Copyright © 2017年 JackieQu. All rights reserved.
//
import UIKit
private let kTopMargin : CGFloat = 10
class FunnyViewController: BaseAnchorViewController {
// MARK:- 懒加载 VM 对象
fileprivate lazy var funnyVM : FunnyViewModel = FunnyViewModel()
}
extension FunnyViewController {
override func setupUI() {
super.setupUI()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.headerReferenceSize = CGSize.zero
collectionView.contentInset = UIEdgeInsets(top: kTopMargin, left: 0, bottom: 0, right: 0)
}
}
extension FunnyViewController {
override func loadData() {
// 1.给父类中 VM 赋值
baseVM = funnyVM
// 2.请求数据
funnyVM.loadFunnyData {
self.collectionView.reloadData()
self.loadDataFinished()
}
}
}
| mit | cd0540dbf2df07498cb139ca23c5b478 | 22.47619 | 97 | 0.63286 | 5.030612 | false | false | false | false |
wtrumler/FluentSwiftAssertions | FluentSwiftAssertions/BoolExtension.swift | 1 | 1641 | //
// BoolExtension.swift
// FluentSwiftAssertions
//
// Created by Wolfgang Trumler on 19.03.17.
// Copyright © 2017 Wolfgang Trumler. All rights reserved.
//
import Foundation
import XCTest
/*
The should property ist just for readability reasons which makes the assertion read more nicely
boolVariable.shoud.beTrue()
The signature of the assrtiongs is the same as those of the XCTAssertion functions.
However an assertion function with the same signature is added at the end of the parameter list to make the code tastable.
The default assertion function is the XCTAssertion. For the test a function with the same signature is provided to check that the assertion functionis called
*/
extension Bool {
public var should: Bool {
return self
}
public func beTrue(_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line,
assertionFunction: @escaping (_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertTrue) {
assertionFunction(self, message, file, line)
}
public func beFalse(_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line,
assertionFunction: @escaping (_ expression: @autoclosure () throws -> Bool, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertFalse) {
assertionFunction(self, message, file, line)
}
}
| mit | 3cb33ae2cce0f9136cc1440ed4ee8033 | 36.272727 | 201 | 0.640854 | 4.795322 | false | false | false | false |
semonchan/LearningSwift | Project/Project - 12 - VideoBackground/Project - 12 - VideoBackground/ViewController.swift | 1 | 2844 | //
// ViewController.swift
// Project - 12 - VideoBackground
//
// Created by 程超 on 2017/12/16.
// Copyright © 2017年 程超. All rights reserved.
//
import UIKit
import SnapKit
class ViewController: VideoSplashViewController {
fileprivate var imageView: UIImageView = {
let temp = UIImageView(image: UIImage(named: "Spotify"))
return temp
}()
fileprivate var loginButton: UIButton = {
let temp = UIButton(type: .custom)
temp.setTitle("Login", for: .normal)
temp.setTitleColor(UIColor.white, for: .normal)
temp.backgroundColor = UIColor.green
temp.layer.cornerRadius = 5.0
temp.layer.masksToBounds = true
return temp
}()
fileprivate var signUpButton: UIButton = {
let temp = UIButton(type: .custom)
temp.setTitle("Sign up", for: .normal)
temp.setTitleColor(UIColor.green, for: .normal)
temp.backgroundColor = UIColor.white
temp.layer.cornerRadius = 5.0
temp.layer.masksToBounds = true
return temp
}()
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.black
setupVideoBackground()
view.addSubview(imageView)
view.addSubview(loginButton)
view.addSubview(signUpButton)
setupLayoutSubviews()
}
fileprivate func setupVideoBackground() {
let tempPath = Bundle.main.path(forResource: "spotify", ofType: "mp4")
guard let videoPath = tempPath else {
return
}
let videoUrl = URL(fileURLWithPath: videoPath)
videoFrame = view.frame
fillMode = ScalingMode.resizeAspectFill
alwaysRepeat = true
sound = false
startTime = 2.0
alpha = 0.8
contentURL = videoUrl
view.isUserInteractionEnabled = false
}
fileprivate func setupLayoutSubviews() {
imageView.snp.makeConstraints { (make) in
make.centerX.equalTo(view)
make.top.equalTo(view).offset(50)
make.size.equalTo(CGSize(width: 300, height: 92))
}
signUpButton.snp.makeConstraints { (make) in
make.centerX.equalTo(view)
make.bottom.equalTo(view.snp.bottom).offset(-30)
make.right.equalTo(view).offset(-15)
make.left.equalTo(view).offset(15)
make.height.equalTo(45)
}
loginButton.snp.makeConstraints { (make) in
make.centerX.equalTo(signUpButton)
make.bottom.equalTo(signUpButton.snp.top).offset(-10)
make.left.right.equalTo(signUpButton)
make.height.equalTo(signUpButton)
}
}
}
| mit | 60ac1ba4dfbc5e98fe779a34906de3db | 29.793478 | 78 | 0.615602 | 4.729549 | false | false | false | false |
jhwayne/Brew | DNApp/Spring/DesignableTextField.swift | 1 | 2655 | //
// DesignableTextField.swift
// 3DTransform
//
// Created by Meng To on 2014-11-27.
// Copyright (c) 2014 Meng To. All rights reserved.
//
import UIKit
@IBDesignable public class DesignableTextField: SpringTextField {
@IBInspectable public var placeholderColor: UIColor = UIColor.clearColor() {
didSet {
attributedPlaceholder = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: placeholderColor])
layoutSubviews()
}
}
@IBInspectable public var sidePadding: CGFloat = 0 {
didSet {
var padding = UIView(frame: CGRectMake(0, 0, sidePadding, sidePadding))
leftViewMode = UITextFieldViewMode.Always
leftView = padding
rightViewMode = UITextFieldViewMode.Always
rightView = padding
}
}
@IBInspectable public var leftPadding: CGFloat = 0 {
didSet {
var padding = UIView(frame: CGRectMake(0, 0, leftPadding, 0))
leftViewMode = UITextFieldViewMode.Always
leftView = padding
}
}
@IBInspectable public var rightPadding: CGFloat = 0 {
didSet {
var padding = UIView(frame: CGRectMake(0, 0, 0, rightPadding))
rightViewMode = UITextFieldViewMode.Always
rightView = padding
}
}
@IBInspectable public var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable public var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable public var lineHeight: CGFloat = 1.5 {
didSet {
var font = UIFont(name: self.font.fontName, size: self.font.pointSize)
var text = self.text
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineHeight
var attributedString = NSMutableAttributedString(string: text!)
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
}
| mit | e37b10955f5df1076904b1af4fb8716c | 30.235294 | 143 | 0.60113 | 5.848018 | false | false | false | false |
RedRoma/Lexis | Code/Lexis/ImageProvider.swift | 1 | 1160 | //
// ImageProvider.swift
// Lexis
//
// Created by Wellington Moreno on 9/25/16.
// Copyright © 2016 RedRoma, Inc. All rights reserved.
//
import Archeota
import AromaSwiftClient
import Foundation
import LexisDatabase
import UIKit
protocol ImageProvider
{
func searchForImages(withTerm searchTerm: String) -> [URL]
}
extension ImageProvider
{
func searchForImages(withWord word: LexisWord, limitTo limit: Int = 0) -> [URL]
{
guard limit >= 0 else { return [] }
guard let searchTerm = word.forms.first else { return [] }
let urls = self.searchForImages(withTerm: searchTerm)
LOG.info("Loaded \(urls.count) URLs for word \(word.forms)")
if limit == 0 || urls.count <= limit
{
return urls
}
else
{
return Array(urls[0..<limit])
}
}
}
extension Int
{
func times<T>(function: () -> (T)) -> [T]
{
guard self > 0 else { return [] }
guard self > 1 else { return [function()] }
return (1...self).flatMap() { _ in
return function()
}
}
}
| apache-2.0 | bb62e05f450cdc67951bcd2e4d88fa3d | 20.072727 | 83 | 0.556514 | 4.080986 | false | false | false | false |
OscarSwanros/swift | test/IRGen/enum_resilience.swift | 2 | 12501 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience %s | %FileCheck %s
// RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -O %s
import resilient_enum
import resilient_struct
// CHECK: %swift.type = type { [[INT:i32|i64]] }
// CHECK: %T15enum_resilience5ClassC = type <{ %swift.refcounted }>
// CHECK: %T15enum_resilience9ReferenceV = type <{ %T15enum_resilience5ClassC* }>
// Public fixed layout struct contains a public resilient struct,
// cannot use spare bits
// CHECK: %T15enum_resilience6EitherO = type <{ [[REFERENCE_TYPE:\[(4|8) x i8\]]], [1 x i8] }>
// Public resilient struct contains a public resilient struct,
// can use spare bits
// CHECK: %T15enum_resilience15ResilientEitherO = type <{ [[REFERENCE_TYPE]] }>
// Internal fixed layout struct contains a public resilient struct,
// can use spare bits
// CHECK: %T15enum_resilience14InternalEitherO = type <{ [[REFERENCE_TYPE]] }>
// Public fixed layout struct contains a fixed layout struct,
// can use spare bits
// CHECK: %T15enum_resilience10EitherFastO = type <{ [[REFERENCE_TYPE]] }>
public class Class {}
public struct Reference {
public var n: Class
}
@_fixed_layout public enum Either {
case Left(Reference)
case Right(Reference)
}
public enum ResilientEither {
case Left(Reference)
case Right(Reference)
}
enum InternalEither {
case Left(Reference)
case Right(Reference)
}
@_fixed_layout public struct ReferenceFast {
public var n: Class
}
@_fixed_layout public enum EitherFast {
case Left(ReferenceFast)
case Right(ReferenceFast)
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience25functionWithResilientEnum010resilient_A06MediumOAEF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture)
public func functionWithResilientEnum(_ m: Medium) -> Medium {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias %0, %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return m
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience33functionWithIndirectResilientEnum010resilient_A00E8ApproachOAEF(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture)
public func functionWithIndirectResilientEnum(_ ia: IndirectApproach) -> IndirectApproach {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum16IndirectApproachOMa()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 4
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias %0, %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return ia
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience31constructResilientEnumNoPayload010resilient_A06MediumOyF
public func constructResilientEnumNoPayload() -> Medium {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 15
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* noalias %0, i32 0, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return Medium.Paper
}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience29constructResilientEnumPayload010resilient_A06MediumO0G7_struct4SizeVF
public func constructResilientEnumPayload(_ s: Size) -> Medium {
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T016resilient_struct4SizeVMa()
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK-NEXT: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: [[COPY:%.*]] = call %swift.opaque* %initializeWithCopy(%swift.opaque* noalias %0, %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: [[METADATA2:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa()
// CHECK-NEXT: [[METADATA_ADDR2:%.*]] = bitcast %swift.type* [[METADATA2]] to i8***
// CHECK-NEXT: [[VWT_ADDR2:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR2]], [[INT:i32|i64]] -1
// CHECK-NEXT: [[VWT2:%.*]] = load i8**, i8*** [[VWT_ADDR2]]
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT2]], i32 15
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* noalias %0, i32 -2, %swift.type* [[METADATA2]])
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 1
// CHECK-NEXT: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK-NEXT: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK-NEXT: call void [[WITNESS_FN]](%swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: ret void
return Medium.Postcard(s)
}
// CHECK-LABEL: define{{( protected)?}} swiftcc {{i32|i64}} @_T015enum_resilience19resilientSwitchTestSi0c1_A06MediumOF(%swift.opaque* noalias nocapture)
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T014resilient_enum6MediumOMa()
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 7
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FOR_SIZE:%.*]] = ptrtoint i8* [[WITNESS]]
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[ENUM_STORAGE:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque*
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[ENUM_COPY:%.*]] = call %swift.opaque* [[WITNESS_FN]](%swift.opaque* noalias [[ENUM_STORAGE]], %swift.opaque* noalias %0, %swift.type* [[METADATA]])
// CHECK: [[WITNESS_ADDR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 13
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_ADDR]]
// CHECK: [[WITNESS_FN:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[TAG:%.*]] = call i32 %getEnumTag(%swift.opaque* noalias [[ENUM_STORAGE]], %swift.type* [[METADATA]])
// CHECK: switch i32 [[TAG]], label %[[DEFAULT_CASE:.*]] [
// CHECK: i32 -1, label %[[PAMPHLET_CASE:.*]]
// CHECK: i32 0, label %[[PAPER_CASE:.*]]
// CHECK: i32 1, label %[[CANVAS_CASE:.*]]
// CHECK: ]
// CHECK: ; <label>:[[PAPER_CASE]]
// CHECK: br label %[[END:.*]]
// CHECK: ; <label>:[[CANVAS_CASE]]
// CHECK: br label %[[END]]
// CHECK: ; <label>:[[PAMPHLET_CASE]]
// CHECK: br label %[[END]]
// CHECK: ; <label>:[[DEFAULT_CASE]]
// CHECK: br label %[[END]]
// CHECK: ; <label>:[[END]]
// CHECK: ret
public func resilientSwitchTest(_ m: Medium) -> Int {
switch m {
case .Paper:
return 1
case .Canvas:
return 2
case .Pamphlet(let m):
return resilientSwitchTest(m)
default:
return 3
}
}
public func reabstraction<T>(_ f: (Medium) -> T) {}
// CHECK-LABEL: define{{( protected)?}} swiftcc void @_T015enum_resilience25resilientEnumPartialApplyySi0c1_A06MediumOcF(i8*, %swift.refcounted*)
public func resilientEnumPartialApply(_ f: (Medium) -> Int) {
// CHECK: [[CONTEXT:%.*]] = call noalias %swift.refcounted* @swift_rt_swift_allocObject
// CHECK: call swiftcc void @_T015enum_resilience13reabstractionyx010resilient_A06MediumOclF(i8* bitcast (void (%TSi*, %swift.opaque*, %swift.refcounted*)* @_T014resilient_enum6MediumOSiIxid_ACSiIxir_TRTA to i8*), %swift.refcounted* [[CONTEXT:%.*]], %swift.type* @_T0SiN)
reabstraction(f)
// CHECK: ret void
}
// CHECK-LABEL: define internal swiftcc void @_T014resilient_enum6MediumOSiIxid_ACSiIxir_TRTA(%TSi* noalias nocapture sret, %swift.opaque* noalias nocapture, %swift.refcounted* swiftself)
// Enums with resilient payloads from a different resilience domain
// require runtime metadata instantiation, just like generics.
public enum EnumWithResilientPayload {
case OneSize(Size)
case TwoSizes(Size, Size)
}
// Make sure we call a function to access metadata of enums with
// resilient layout.
// CHECK-LABEL: define{{( protected)?}} swiftcc %swift.type* @_T015enum_resilience20getResilientEnumTypeypXpyF()
// CHECK: [[METADATA:%.*]] = call %swift.type* @_T015enum_resilience24EnumWithResilientPayloadOMa()
// CHECK-NEXT: ret %swift.type* [[METADATA]]
public func getResilientEnumType() -> Any.Type {
return EnumWithResilientPayload.self
}
// Public metadata accessor for our resilient enum
// CHECK-LABEL: define{{( protected)?}} %swift.type* @_T015enum_resilience24EnumWithResilientPayloadOMa()
// CHECK: [[METADATA:%.*]] = load %swift.type*, %swift.type** @_T015enum_resilience24EnumWithResilientPayloadOML
// CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[METADATA]], null
// CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont
// CHECK: cacheIsNull:
// CHECK-NEXT: call void @swift_once([[INT]]* @_T015enum_resilience24EnumWithResilientPayloadOMa.once_token, i8* bitcast (void (i8*)* @initialize_metadata_EnumWithResilientPayload to i8*), i8* undef)
// CHECK-NEXT: [[METADATA2:%.*]] = load %swift.type*, %swift.type** @_T015enum_resilience24EnumWithResilientPayloadOML
// CHECK-NEXT: br label %cont
// CHECK: cont:
// CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[METADATA]], %entry ], [ [[METADATA2]], %cacheIsNull ]
// CHECK-NEXT: ret %swift.type* [[RESULT]]
// Methods inside extensions of resilient enums fish out type parameters
// from metadata -- make sure we can do that
extension ResilientMultiPayloadGenericEnum {
// CHECK-LABEL: define{{( protected)?}} swiftcc %swift.type* @_T014resilient_enum32ResilientMultiPayloadGenericEnumO0B11_resilienceE16getTypeParameterxmyF(%swift.type* %"ResilientMultiPayloadGenericEnum<T>", %swift.opaque* noalias nocapture swiftself)
// CHECK: [[METADATA:%.*]] = bitcast %swift.type* %"ResilientMultiPayloadGenericEnum<T>" to %swift.type**
// CHECK-NEXT: [[T_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[METADATA]], [[INT]] 2
// CHECK-NEXT: [[T:%.*]] = load %swift.type*, %swift.type** [[T_ADDR]]
public func getTypeParameter() -> T.Type {
return T.self
}
}
// CHECK-LABEL: define{{( protected)?}} private void @initialize_metadata_EnumWithResilientPayload(i8*)
| apache-2.0 | 8b141f916cdf817cc91465a44608aa71 | 46.352273 | 275 | 0.665867 | 3.447601 | false | false | false | false |
pjulien/flatbuffers | tests/FlatBuffers.Test.Swift/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift | 1 | 12685 | import XCTest
@testable import FlatBuffers
final class FlatBuffersUnionTests: XCTestCase {
func testCreateMonstor() {
var b = FlatBufferBuilder(initialSize: 20)
let dmg: Int16 = 5
let str = "Axe"
let axe = b.create(string: str)
let weapon = Weapon.createWeapon(builder: &b, offset: axe, dmg: dmg)
let weapons = b.createVector(ofOffsets: [weapon])
let root = LocalMonster.createMonster(builder: &b,
offset: weapons,
equipment: .Weapon,
equippedOffset: weapon.o)
b.finish(offset: root)
let buffer = b.sizedByteArray
XCTAssertEqual(buffer, [16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 8, 0, 7, 0, 12, 0, 10, 0, 0, 0, 0, 0, 0, 1, 8, 0, 0, 0, 20, 0, 0, 0, 1, 0, 0, 0, 12, 0, 0, 0, 8, 0, 12, 0, 8, 0, 6, 0, 8, 0, 0, 0, 0, 0, 5, 0, 4, 0, 0, 0, 3, 0, 0, 0, 65, 120, 101, 0])
let monster = LocalMonster.getRootAsMonster(bb: ByteBuffer(bytes: buffer))
XCTAssertEqual(monster.weapon(at: 0)?.dmg, dmg)
XCTAssertEqual(monster.weapon(at: 0)?.name, str)
XCTAssertEqual(monster.weapon(at: 0)?.nameVector, [65, 120, 101])
let p: Weapon? = monster.equiped()
XCTAssertEqual(p?.dmg, dmg)
XCTAssertEqual(p?.name, str)
XCTAssertEqual(p?.nameVector, [65, 120, 101])
}
func testEndTableFinish() {
var builder = FlatBufferBuilder(initialSize: 20)
let sword = builder.create(string: "Sword")
let axe = builder.create(string: "Axe")
let weaponOne = Weapon.createWeapon(builder: &builder, offset: sword, dmg: 3)
let weaponTwo = Weapon.createWeapon(builder: &builder, offset: axe, dmg: 5)
let name = builder.create(string: "Orc")
let inventory: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let inv = builder.createVector(inventory, size: 10)
let weapons = builder.createVector(ofOffsets: [weaponOne, weaponTwo])
var vecArray: [UnsafeMutableRawPointer] = []
vecArray.append(createVecWrite(x: 4.0, y: 5.0, z: 6.0))
vecArray.append(createVecWrite(x: 1.0, y: 2.0, z: 3.0))
let path = builder.createVector(structs: vecArray, type: Vec.self)
let orc = FinalMonster.createMonster(builder: &builder,
position: builder.create(struct: createVecWrite(x: 1.0, y: 2.0, z: 3.0), type: Vec.self),
hp: 300,
name: name,
inventory: inv,
color: .red,
weapons: weapons,
equipment: .Weapon,
equippedOffset: weaponTwo,
path: path)
builder.finish(offset: orc)
XCTAssertEqual(builder.sizedByteArray, [32, 0, 0, 0, 0, 0, 26, 0, 36, 0, 36, 0, 0, 0, 34, 0, 28, 0, 0, 0, 24, 0, 23, 0, 16, 0, 15, 0, 8, 0, 4, 0, 26, 0, 0, 0, 44, 0, 0, 0, 104, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 76, 0, 0, 0, 0, 0, 44, 1, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 2, 0, 0, 0, 0, 0, 128, 64, 0, 0, 160, 64, 0, 0, 192, 64, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 2, 0, 0, 0, 52, 0, 0, 0, 28, 0, 0, 0, 10, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 3, 0, 0, 0, 79, 114, 99, 0, 244, 255, 255, 255, 0, 0, 5, 0, 24, 0, 0, 0, 8, 0, 12, 0, 8, 0, 6, 0, 8, 0, 0, 0, 0, 0, 3, 0, 12, 0, 0, 0, 3, 0, 0, 0, 65, 120, 101, 0, 5, 0, 0, 0, 83, 119, 111, 114, 100, 0, 0, 0])
}
func testEnumVector() {
let vectorOfEnums: [ColorsNameSpace.RGB] = [.blue, .green]
var builder = FlatBufferBuilder(initialSize: 1)
let off = builder.createVector(vectorOfEnums)
let start = ColorsNameSpace.Monster.startMonster(&builder)
ColorsNameSpace.Monster.add(colors: off, &builder)
let end = ColorsNameSpace.Monster.endMonster(&builder, start: start)
builder.finish(offset: end)
XCTAssertEqual(builder.sizedByteArray, [12, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0])
let monster = ColorsNameSpace.Monster.getRootAsMonster(bb: builder.buffer)
XCTAssertEqual(monster.colorsCount, 2)
XCTAssertEqual(monster.colors(at: 0), .blue)
XCTAssertEqual(monster.colors(at: 1), .green)
}
func testUnionVector() {
var fb = FlatBufferBuilder()
let swordDmg: Int32 = 8
let attackStart = Attacker.startAttacker(&fb)
Attacker.add(swordAttackDamage: swordDmg, &fb)
let attack = Attacker.endAttacker(&fb, start: attackStart)
let characterType: [Character] = [.belle, .mulan, .bookfan]
let characters = [
fb.create(struct: createBookReader(booksRead: 7), type: BookReader.self),
attack,
fb.create(struct: createBookReader(booksRead: 2), type: BookReader.self),
]
let types = fb.createVector(characterType)
let characterVector = fb.createVector(ofOffsets: characters)
let end = Movie.createMovie(&fb, vectorOfCharactersType: types, vectorOfCharacters: characterVector)
Movie.finish(&fb, end: end)
var movie = Movie.getRootAsMovie(bb: fb.buffer)
XCTAssertEqual(movie.charactersTypeCount, Int32(characterType.count))
XCTAssertEqual(movie.charactersCount, Int32(characters.count))
for i in 0..<movie.charactersTypeCount {
XCTAssertEqual(movie.charactersType(at: i), characterType[Int(i)])
}
XCTAssertEqual(movie.characters(at: 0, type: BookReader.self)?.booksRead, 7)
XCTAssertEqual(movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage, swordDmg)
XCTAssertEqual(movie.characters(at: 2, type: BookReader.self)?.booksRead, 2)
var objc: MovieT? = movie.unpack()
XCTAssertEqual(movie.charactersTypeCount, Int32(objc?.characters.count ?? 0))
XCTAssertEqual(movie.characters(at: 0, type: BookReader.self)?.booksRead, (objc?.characters[0]?.value as? BookReaderT)?.booksRead)
fb.clear()
let newMovie = Movie.pack(&fb, obj: &objc)
fb.finish(offset: newMovie)
let packedMovie = Movie.getRootAsMovie(bb: fb.buffer)
XCTAssertEqual(packedMovie.characters(at: 0, type: BookReader.self)?.booksRead, movie.characters(at: 0, type: BookReader.self)?.booksRead)
XCTAssertEqual(packedMovie.characters(at: 1, type: Attacker.self)?.swordAttackDamage, movie.characters(at: 1, type: Attacker.self)?.swordAttackDamage)
XCTAssertEqual(packedMovie.characters(at: 2, type: BookReader.self)?.booksRead, movie.characters(at: 2, type: BookReader.self)?.booksRead)
}
}
public enum ColorsNameSpace {
enum RGB: Int32, Enum {
typealias T = Int32
static var byteSize: Int { return MemoryLayout<Int32>.size }
var value: Int32 { return self.rawValue }
case red = 0, green = 1, blue = 2
}
struct Monster: FlatBufferObject {
var __buffer: ByteBuffer! { _accessor.bb }
private var _accessor: Table
static func getRootAsMonster(bb: ByteBuffer) -> Monster { return Monster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + Int32(bb.reader))) }
init(_ t: Table) { _accessor = t }
init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) }
public var colorsCount: Int32 { let o = _accessor.offset(4); return o == 0 ? 0 : _accessor.vector(count: o) }
public func colors(at index: Int32) -> ColorsNameSpace.RGB? { let o = _accessor.offset(4); return o == 0 ? ColorsNameSpace.RGB(rawValue: 0)! : ColorsNameSpace.RGB(rawValue: _accessor.directRead(of: Int32.self, offset: _accessor.vector(at: o) + index * 4)) }
static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) }
static func add(colors: Offset<UOffset>, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: colors, at: 4) }
static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset<UOffset> { let end = Offset<UOffset>(offset: fbb.endTable(at: start)); return end }
}
}
enum Equipment: Byte { case none, Weapon }
enum Color3: Int8 { case red = 0, green, blue }
struct FinalMonster {
@inlinable static func createMonster(builder: inout FlatBufferBuilder,
position: Offset<UOffset>,
hp: Int16,
name: Offset<String>,
inventory: Offset<UOffset>,
color: Color3,
weapons: Offset<UOffset>,
equipment: Equipment = .none,
equippedOffset: Offset<Weapon>,
path: Offset<UOffset>) -> Offset<LocalMonster> {
let start = builder.startTable(with: 11)
builder.add(structOffset: 4)
builder.add(element: hp, def: 100, at: 8)
builder.add(offset: name, at: 10)
builder.add(offset: inventory, at: 14)
builder.add(element: color.rawValue, def: Color3.green.rawValue, at: 16)
builder.add(offset: weapons, at: 18)
builder.add(element: equipment.rawValue, def: Equipment.none.rawValue, at: 20)
builder.add(offset: equippedOffset, at: 22)
builder.add(offset: path, at: 24)
return Offset(offset: builder.endTable(at: start))
}
}
struct LocalMonster {
private var __t: Table
init(_ fb: ByteBuffer, o: Int32) { __t = Table(bb: fb, position: o) }
init(_ t: Table) { __t = t }
func weapon(at index: Int32) -> Weapon? { let o = __t.offset(4); return o == 0 ? nil : Weapon.assign(__t.indirect(__t.vector(at: o) + (index * 4)), __t.bb) }
func equiped<T: FlatBufferObject>() -> T? {
let o = __t.offset(8); return o == 0 ? nil : __t.union(o)
}
static func getRootAsMonster(bb: ByteBuffer) -> LocalMonster {
return LocalMonster(Table(bb: bb, position: Int32(bb.read(def: UOffset.self, position: 0))))
}
@inlinable static func createMonster(builder: inout FlatBufferBuilder,
offset: Offset<UOffset>,
equipment: Equipment = .none,
equippedOffset: UOffset) -> Offset<LocalMonster> {
let start = builder.startTable(with: 3)
builder.add(element: equippedOffset, def: 0, at: 8)
builder.add(offset: offset, at: 4)
builder.add(element: equipment.rawValue, def: Equipment.none.rawValue, at: 6)
return Offset(offset: builder.endTable(at: start))
}
}
struct Weapon: FlatBufferObject {
var __buffer: ByteBuffer! { __t.bb }
static let offsets: (name: VOffset, dmg: VOffset) = (4, 6)
private var __t: Table
init(_ t: Table) { __t = t }
init(_ fb: ByteBuffer, o: Int32) { __t = Table(bb: fb, position: o)}
var dmg: Int16 { let o = __t.offset(6); return o == 0 ? 0 : __t.readBuffer(of: Int16.self, at: o) }
var nameVector: [UInt8]? { return __t.getVector(at: 4) }
var name: String? { let o = __t.offset(4); return o == 0 ? nil : __t.string(at: o) }
static func assign(_ i: Int32, _ bb: ByteBuffer) -> Weapon { return Weapon(Table(bb: bb, position: i)) }
@inlinable static func createWeapon(builder: inout FlatBufferBuilder, offset: Offset<String>, dmg: Int16) -> Offset<Weapon> {
let _start = builder.startTable(with: 2)
Weapon.add(builder: &builder, name: offset)
Weapon.add(builder: &builder, dmg: dmg)
return Weapon.end(builder: &builder, startOffset: _start)
}
@inlinable static func end(builder: inout FlatBufferBuilder, startOffset: UOffset) -> Offset<Weapon> {
return Offset(offset: builder.endTable(at: startOffset))
}
@inlinable static func add(builder: inout FlatBufferBuilder, name: Offset<String>) {
builder.add(offset: name, at: Weapon.offsets.name)
}
@inlinable static func add(builder: inout FlatBufferBuilder, dmg: Int16) {
builder.add(element: dmg, def: 0, at: Weapon.offsets.dmg)
}
}
| apache-2.0 | 39430722b172c1f2e34ab7973efb8388 | 51.634855 | 707 | 0.573827 | 3.80018 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.