repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bazelbuild/tulsi | src/Tulsi/UIRuleEntry.swift | 2 | 1778 | // Copyright 2016 The Tulsi 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 Foundation
import TulsiGenerator
/// Wraps a TulsiGenerator::RuleInfo with functionality to allow it to track selection and be
/// accessed via bindings in the UI.
class UIRuleInfo: NSObject, Selectable {
@objc dynamic var targetName: String? {
return ruleInfo.label.targetName
}
@objc dynamic var type: String {
return ruleInfo.type
}
@objc dynamic var selected: Bool = false {
didSet {
if !selected { return }
let linkedInfos = linkedRuleInfos.allObjects as! [UIRuleInfo]
for linkedInfo in linkedInfos {
linkedInfo.selected = true
}
}
}
var fullLabel: String {
return ruleInfo.label.value
}
let ruleInfo: RuleInfo
/// RuleInfo instances for targets that must be selected if this target is selected.
private var linkedRuleInfos = NSHashTable<AnyObject>.weakObjects()
init(ruleInfo: RuleInfo) {
self.ruleInfo = ruleInfo
}
func resolveLinkages(_ ruleInfoMap: [BuildLabel: UIRuleInfo]) {
for label in ruleInfo.linkedTargetLabels {
guard let linkedUIRuleInfo = ruleInfoMap[label] else { continue }
linkedRuleInfos.add(linkedUIRuleInfo)
}
}
}
| apache-2.0 | 60ee7bd76468d05fd24d13090d32e391 | 29.655172 | 93 | 0.71991 | 4.263789 | false | false | false | false |
gerardogrisolini/Webretail | Sources/Webretail/Controllers/StoreController.swift | 1 | 2783 | //
// StoreController.swift
// Webretail
//
// Created by Gerardo Grisolini on 27/02/17.
//
//
import PerfectHTTP
class StoreController {
private let repository: StoreProtocol
init() {
self.repository = ioCContainer.resolve() as StoreProtocol
}
func getRoutes() -> Routes {
var routes = Routes()
routes.add(method: .get, uri: "/api/store", handler: storesHandlerGET)
routes.add(method: .get, uri: "/api/store/{id}", handler: storeHandlerGET)
routes.add(method: .post, uri: "/api/store", handler: storeHandlerPOST)
routes.add(method: .put, uri: "/api/store/{id}", handler: storeHandlerPUT)
routes.add(method: .delete, uri: "/api/store/{id}", handler: storeHandlerDELETE)
return routes
}
func storesHandlerGET(request: HTTPRequest, _ response: HTTPResponse) {
do {
let items = try self.repository.getAll()
try response.setJson(items)
response.completed(status: .ok)
} catch {
response.badRequest(error: "\(request.uri) \(request.method): \(error)")
}
}
func storeHandlerGET(request: HTTPRequest, _ response: HTTPResponse) {
let id = request.urlVariables["id"]!
do {
let item = try self.repository.get(id: Int(id)!)
try response.setJson(item)
response.completed(status: .ok)
} catch {
response.badRequest(error: "\(request.uri) \(request.method): \(error)")
}
}
func storeHandlerPOST(request: HTTPRequest, _ response: HTTPResponse) {
do {
let item: Store = request.getJson()!
try self.repository.add(item: item)
try response.setJson(item)
response.completed(status: .created)
} catch {
response.badRequest(error: "\(request.uri) \(request.method): \(error)")
}
}
func storeHandlerPUT(request: HTTPRequest, _ response: HTTPResponse) {
let id = request.urlVariables["id"]!
do {
let item: Store = request.getJson()!
try self.repository.update(id: Int(id)!, item: item)
try response.setJson(item)
response.completed(status: .accepted)
} catch {
response.badRequest(error: "\(request.uri) \(request.method): \(error)")
}
}
func storeHandlerDELETE(request: HTTPRequest, _ response: HTTPResponse) {
let id = request.urlVariables["id"]!
do {
try self.repository.delete(id: Int(id)!)
response.completed(status: .noContent)
} catch {
response.badRequest(error: "\(request.uri) \(request.method): \(error)")
}
}
}
| apache-2.0 | a293f3f94368bb5de0cbcd9a26375ed1 | 32.130952 | 88 | 0.575997 | 4.281538 | false | false | false | false |
kirby10023/4yrAnniversary | 2b1s/Extensions/UIColor+Hex.swift | 1 | 1648 | //
// UIColor+ Hex.swift
// 2b1s
//
// Created by Kirby on 5/31/17.
// Copyright © 2017 Kirby. All rights reserved.
//
import UIKit
extension UIColor {
convenience init?(hexCode: String) {
// guard hexCode.characters.count == 7 else {
// return nil
// }
guard hexCode.characters.first! == "#" else {
return nil
}
guard let value = Int(String(hexCode.characters.dropFirst()), radix: 16) else {
return nil
}
let hex = String(hexCode.characters.dropFirst())
switch hex.characters.count {
case 3:
self.init(hex3: value)
case 6:
self.init(hex6: value)
default:
self.init()
return nil
}
}
private convenience init?(hex3: Int) {
// bit ugly but it works
// My notes: shift hex to first then shift one place over and duplicate and add itself to first
// e.g. for red #fff -> take f00 -> shift to 00f -> shift again to 0f0 -> add 00f -> resul 0ff
let red = CGFloat(((hex3 & 0xF00) >> 8) << 4 + ((hex3 & 0xF00) >> 8)) / 255
let green = CGFloat(((hex3 & 0x0F0) >> 4) << 4 + ((hex3 & 0x0F0) >> 4)) / 255
let blue = CGFloat(((hex3 & 0x00F)) << 4 + (hex3 & 0x00F)) / 255
self.init(red: red, green: green, blue: blue, alpha: 1)
// print(((hex3 & 0xf00) >> 8) << 4 + ((hex3 & 0xf00) >> 8))
// print((hex3 & 0xf00) >> 8 + ((hex3 & 0xf00) >> 8 ) << 4)
}
private convenience init?(hex6: Int) {
let red = CGFloat(hex6 >> 16 & 0xFF) / 255
let green = CGFloat(hex6 >> 8 & 0xFF) / 255
let blue = CGFloat(hex6 & 0xFF) / 255
self.init(red: red, green: green, blue: blue, alpha: 1)
}
}
| mit | 61e111393da875ee700bd8ddea9b05b4 | 23.58209 | 99 | 0.566485 | 3.113422 | false | false | false | false |
jtbandes/swift | test/IRGen/builtins.swift | 2 | 32417 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -parse-stdlib -primary-file %s -emit-ir -o - -disable-objc-attr-requires-foundation-module | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
// REQUIRES: executable_test
// REQUIRES: CPU=x86_64
import Swift
// CHECK-DAG: [[REFCOUNT:%swift.refcounted.*]] = type
// CHECK-DAG: [[X:%T8builtins1XC]] = type
// CHECK-DAG: [[Y:%T8builtins1YC]] = type
typealias Int = Builtin.Int32
typealias Bool = Builtin.Int1
infix operator * {
associativity left
precedence 200
}
infix operator / {
associativity left
precedence 200
}
infix operator % {
associativity left
precedence 200
}
infix operator + {
associativity left
precedence 190
}
infix operator - {
associativity left
precedence 190
}
infix operator << {
associativity none
precedence 180
}
infix operator >> {
associativity none
precedence 180
}
infix operator ... {
associativity none
precedence 175
}
infix operator < {
associativity none
precedence 170
}
infix operator <= {
associativity none
precedence 170
}
infix operator > {
associativity none
precedence 170
}
infix operator >= {
associativity none
precedence 170
}
infix operator == {
associativity none
precedence 160
}
infix operator != {
associativity none
precedence 160
}
func * (lhs: Int, rhs: Int) -> Int {
return Builtin.mul_Int32(lhs, rhs)
// CHECK: mul i32
}
func / (lhs: Int, rhs: Int) -> Int {
return Builtin.sdiv_Int32(lhs, rhs)
// CHECK: sdiv i32
}
func % (lhs: Int, rhs: Int) -> Int {
return Builtin.srem_Int32(lhs, rhs)
// CHECK: srem i32
}
func + (lhs: Int, rhs: Int) -> Int {
return Builtin.add_Int32(lhs, rhs)
// CHECK: add i32
}
func - (lhs: Int, rhs: Int) -> Int {
return Builtin.sub_Int32(lhs, rhs)
// CHECK: sub i32
}
// In C, 180 is <<, >>
func < (lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_slt_Int32(lhs, rhs)
// CHECK: icmp slt i32
}
func > (lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_sgt_Int32(lhs, rhs)
// CHECK: icmp sgt i32
}
func <=(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_sle_Int32(lhs, rhs)
// CHECK: icmp sle i32
}
func >=(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_sge_Int32(lhs, rhs)
// CHECK: icmp sge i32
}
func ==(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_eq_Int32(lhs, rhs)
// CHECK: icmp eq i32
}
func !=(lhs: Int, rhs: Int) -> Bool {
return Builtin.cmp_ne_Int32(lhs, rhs)
// CHECK: icmp ne i32
}
func gepRaw_test(_ ptr: Builtin.RawPointer, offset: Builtin.Int64)
-> Builtin.RawPointer {
return Builtin.gepRaw_Int64(ptr, offset)
// CHECK: getelementptr inbounds i8, i8*
}
// CHECK: define hidden {{.*}}i64 @_T08builtins9load_test{{[_0-9a-zA-Z]*}}F
func load_test(_ ptr: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[CASTPTR:%.*]] = bitcast i8* [[PTR:%.*]] to i64*
// CHECK-NEXT: load i64, i64* [[CASTPTR]]
// CHECK: ret
return Builtin.load(ptr)
}
// CHECK: define hidden {{.*}}i64 @_T08builtins13load_raw_test{{[_0-9a-zA-Z]*}}F
func load_raw_test(_ ptr: Builtin.RawPointer) -> Builtin.Int64 {
// CHECK: [[CASTPTR:%.*]] = bitcast i8* [[PTR:%.*]] to i64*
// CHECK-NEXT: load i64, i64* [[CASTPTR]]
// CHECK: ret
return Builtin.loadRaw(ptr)
}
// CHECK: define hidden {{.*}}void @_T08builtins11assign_test{{[_0-9a-zA-Z]*}}F
func assign_test(_ value: Builtin.Int64, ptr: Builtin.RawPointer) {
Builtin.assign(value, ptr)
// CHECK: ret
}
// CHECK: define hidden {{.*}}%swift.refcounted* @_T08builtins16load_object_test{{[_0-9a-zA-Z]*}}F
func load_object_test(_ ptr: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[T0:%.*]] = load [[REFCOUNT]]*, [[REFCOUNT]]**
// CHECK: call void @swift_rt_swift_retain([[REFCOUNT]]* [[T0]])
// CHECK: ret [[REFCOUNT]]* [[T0]]
return Builtin.load(ptr)
}
// CHECK: define hidden {{.*}}%swift.refcounted* @_T08builtins20load_raw_object_test{{[_0-9a-zA-Z]*}}F
func load_raw_object_test(_ ptr: Builtin.RawPointer) -> Builtin.NativeObject {
// CHECK: [[T0:%.*]] = load [[REFCOUNT]]*, [[REFCOUNT]]**
// CHECK: call void @swift_rt_swift_retain([[REFCOUNT]]* [[T0]])
// CHECK: ret [[REFCOUNT]]* [[T0]]
return Builtin.loadRaw(ptr)
}
// CHECK: define hidden {{.*}}void @_T08builtins18assign_object_test{{[_0-9a-zA-Z]*}}F
func assign_object_test(_ value: Builtin.NativeObject, ptr: Builtin.RawPointer) {
Builtin.assign(value, ptr)
}
// CHECK: define hidden {{.*}}void @_T08builtins16init_object_test{{[_0-9a-zA-Z]*}}F
func init_object_test(_ value: Builtin.NativeObject, ptr: Builtin.RawPointer) {
// CHECK: [[DEST:%.*]] = bitcast i8* {{%.*}} to %swift.refcounted**
// CHECK-NEXT: store [[REFCOUNT]]* {{%.*}}, [[REFCOUNT]]** [[DEST]]
Builtin.initialize(value, ptr)
}
func cast_test(_ ptr: inout Builtin.RawPointer, i8: inout Builtin.Int8,
i64: inout Builtin.Int64, f: inout Builtin.FPIEEE32,
d: inout Builtin.FPIEEE64
) {
// CHECK: cast_test
i8 = Builtin.trunc_Int64_Int8(i64) // CHECK: trunc
i64 = Builtin.zext_Int8_Int64(i8) // CHECK: zext
i64 = Builtin.sext_Int8_Int64(i8) // CHECK: sext
i64 = Builtin.ptrtoint_Int64(ptr) // CHECK: ptrtoint
ptr = Builtin.inttoptr_Int64(i64) // CHECK: inttoptr
i64 = Builtin.fptoui_FPIEEE64_Int64(d) // CHECK: fptoui
i64 = Builtin.fptosi_FPIEEE64_Int64(d) // CHECK: fptosi
d = Builtin.uitofp_Int64_FPIEEE64(i64) // CHECK: uitofp
d = Builtin.sitofp_Int64_FPIEEE64(i64) // CHECK: sitofp
d = Builtin.fpext_FPIEEE32_FPIEEE64(f) // CHECK: fpext
f = Builtin.fptrunc_FPIEEE64_FPIEEE32(d) // CHECK: fptrunc
i64 = Builtin.bitcast_FPIEEE64_Int64(d) // CHECK: bitcast
d = Builtin.bitcast_Int64_FPIEEE64(i64) // CHECK: bitcast
}
func intrinsic_test(_ i32: inout Builtin.Int32, i16: inout Builtin.Int16) {
i32 = Builtin.int_bswap_Int32(i32) // CHECK: llvm.bswap.i32(
i16 = Builtin.int_bswap_Int16(i16) // CHECK: llvm.bswap.i16(
var x = Builtin.int_sadd_with_overflow_Int16(i16, i16) // CHECK: call { i16, i1 } @llvm.sadd.with.overflow.i16(
Builtin.int_trap() // CHECK: llvm.trap()
}
// CHECK: define hidden {{.*}}void @_T08builtins19sizeof_alignof_testyyF()
func sizeof_alignof_test() {
// CHECK: store i64 4, i64*
var xs = Builtin.sizeof(Int.self)
// CHECK: store i64 4, i64*
var xa = Builtin.alignof(Int.self)
// CHECK: store i64 1, i64*
var ys = Builtin.sizeof(Bool.self)
// CHECK: store i64 1, i64*
var ya = Builtin.alignof(Bool.self)
}
// CHECK: define hidden {{.*}}void @_T08builtins27generic_sizeof_alignof_testyxlF(
func generic_sizeof_alignof_test<T>(_: T) {
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 17
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[SIZE:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: store i64 [[SIZE]], i64* [[S:%.*]]
var s = Builtin.sizeof(T.self)
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 18
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[T2:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: [[T3:%.*]] = and i64 [[T2]], 65535
// CHECK-NEXT: [[ALIGN:%.*]] = add i64 [[T3]], 1
// CHECK-NEXT: store i64 [[ALIGN]], i64* [[A:%.*]]
var a = Builtin.alignof(T.self)
}
// CHECK: define hidden {{.*}}void @_T08builtins21generic_strideof_testyxlF(
func generic_strideof_test<T>(_: T) {
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 19
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[STRIDE:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: store i64 [[STRIDE]], i64* [[S:%.*]]
var s = Builtin.strideof(T.self)
}
class X {}
class Y {}
func move(_ ptr: Builtin.RawPointer) {
var temp : Y = Builtin.take(ptr)
// CHECK: define hidden {{.*}}void @_T08builtins4move{{[_0-9a-zA-Z]*}}F
// CHECK: [[SRC:%.*]] = bitcast i8* {{%.*}} to [[Y]]**
// CHECK-NEXT: [[VAL:%.*]] = load [[Y]]*, [[Y]]** [[SRC]]
// CHECK-NEXT: store [[Y]]* [[VAL]], [[Y]]** {{%.*}}
}
func allocDealloc(_ size: Builtin.Word, align: Builtin.Word) {
var ptr = Builtin.allocRaw(size, align)
Builtin.deallocRaw(ptr, size, align)
}
func fence_test() {
// CHECK: fence acquire
Builtin.fence_acquire()
// CHECK: fence singlethread acq_rel
Builtin.fence_acqrel_singlethread()
}
func cmpxchg_test(_ ptr: Builtin.RawPointer, a: Builtin.Int32, b: Builtin.Int32) {
// rdar://12939803 - ER: support atomic cmpxchg/xchg with pointers
// CHECK: [[Z_RES:%.*]] = cmpxchg i32* {{.*}}, i32 {{.*}}, i32 {{.*}} acquire acquire
// CHECK: [[Z_VAL:%.*]] = extractvalue { i32, i1 } [[Z_RES]], 0
// CHECK: [[Z_SUCCESS:%.*]] = extractvalue { i32, i1 } [[Z_RES]], 1
// CHECK: store i32 [[Z_VAL]], i32* {{.*}}, align 4
// CHECK: store i1 [[Z_SUCCESS]], i1* {{.*}}, align 1
var (z, zSuccess) = Builtin.cmpxchg_acquire_acquire_Int32(ptr, a, b)
// CHECK: [[Y_RES:%.*]] = cmpxchg volatile i32* {{.*}}, i32 {{.*}}, i32 {{.*}} monotonic monotonic
// CHECK: [[Y_VAL:%.*]] = extractvalue { i32, i1 } [[Y_RES]], 0
// CHECK: [[Y_SUCCESS:%.*]] = extractvalue { i32, i1 } [[Y_RES]], 1
// CHECK: store i32 [[Y_VAL]], i32* {{.*}}, align 4
// CHECK: store i1 [[Y_SUCCESS]], i1* {{.*}}, align 1
var (y, ySuccess) = Builtin.cmpxchg_monotonic_monotonic_volatile_Int32(ptr, a, b)
// CHECK: [[X_RES:%.*]] = cmpxchg volatile i32* {{.*}}, i32 {{.*}}, i32 {{.*}} singlethread acquire monotonic
// CHECK: [[X_VAL:%.*]] = extractvalue { i32, i1 } [[X_RES]], 0
// CHECK: [[X_SUCCESS:%.*]] = extractvalue { i32, i1 } [[X_RES]], 1
// CHECK: store i32 [[X_VAL]], i32* {{.*}}, align 4
// CHECK: store i1 [[X_SUCCESS]], i1* {{.*}}, align 1
var (x, xSuccess) = Builtin.cmpxchg_acquire_monotonic_volatile_singlethread_Int32(ptr, a, b)
// CHECK: [[W_RES:%.*]] = cmpxchg volatile i64* {{.*}}, i64 {{.*}}, i64 {{.*}} seq_cst seq_cst
// CHECK: [[W_VAL:%.*]] = extractvalue { i64, i1 } [[W_RES]], 0
// CHECK: [[W_SUCCESS:%.*]] = extractvalue { i64, i1 } [[W_RES]], 1
// CHECK: [[W_VAL_PTR:%.*]] = inttoptr i64 [[W_VAL]] to i8*
// CHECK: store i8* [[W_VAL_PTR]], i8** {{.*}}, align 8
// CHECK: store i1 [[W_SUCCESS]], i1* {{.*}}, align 1
var (w, wSuccess) = Builtin.cmpxchg_seqcst_seqcst_volatile_singlethread_RawPointer(ptr, ptr, ptr)
// CHECK: [[V_RES:%.*]] = cmpxchg weak volatile i64* {{.*}}, i64 {{.*}}, i64 {{.*}} seq_cst seq_cst
// CHECK: [[V_VAL:%.*]] = extractvalue { i64, i1 } [[V_RES]], 0
// CHECK: [[V_SUCCESS:%.*]] = extractvalue { i64, i1 } [[V_RES]], 1
// CHECK: [[V_VAL_PTR:%.*]] = inttoptr i64 [[V_VAL]] to i8*
// CHECK: store i8* [[V_VAL_PTR]], i8** {{.*}}, align 8
// CHECK: store i1 [[V_SUCCESS]], i1* {{.*}}, align 1
var (v, vSuccess) = Builtin.cmpxchg_seqcst_seqcst_weak_volatile_singlethread_RawPointer(ptr, ptr, ptr)
}
func atomicrmw_test(_ ptr: Builtin.RawPointer, a: Builtin.Int32,
ptr2: Builtin.RawPointer) {
// CHECK: atomicrmw add i32* {{.*}}, i32 {{.*}} acquire
var z = Builtin.atomicrmw_add_acquire_Int32(ptr, a)
// CHECK: atomicrmw volatile max i32* {{.*}}, i32 {{.*}} monotonic
var y = Builtin.atomicrmw_max_monotonic_volatile_Int32(ptr, a)
// CHECK: atomicrmw volatile xchg i32* {{.*}}, i32 {{.*}} singlethread acquire
var x = Builtin.atomicrmw_xchg_acquire_volatile_singlethread_Int32(ptr, a)
// rdar://12939803 - ER: support atomic cmpxchg/xchg with pointers
// CHECK: atomicrmw volatile xchg i64* {{.*}}, i64 {{.*}} singlethread acquire
var w = Builtin.atomicrmw_xchg_acquire_volatile_singlethread_RawPointer(ptr, ptr2)
}
func addressof_test(_ a: inout Int, b: inout Bool) {
// CHECK: bitcast i32* {{.*}} to i8*
var ap : Builtin.RawPointer = Builtin.addressof(&a)
// CHECK: bitcast i1* {{.*}} to i8*
var bp : Builtin.RawPointer = Builtin.addressof(&b)
}
func fneg_test(_ half: Builtin.FPIEEE16,
single: Builtin.FPIEEE32,
double: Builtin.FPIEEE64)
-> (Builtin.FPIEEE16, Builtin.FPIEEE32, Builtin.FPIEEE64)
{
// CHECK: fsub half 0xH8000, {{%.*}}
// CHECK: fsub float -0.000000e+00, {{%.*}}
// CHECK: fsub double -0.000000e+00, {{%.*}}
return (Builtin.fneg_FPIEEE16(half),
Builtin.fneg_FPIEEE32(single),
Builtin.fneg_FPIEEE64(double))
}
// The call to the builtins should get removed before we reach IRGen.
func testStaticReport(_ b: Bool, ptr: Builtin.RawPointer) -> () {
Builtin.staticReport(b, b, ptr);
return Builtin.staticReport(b, b, ptr);
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins12testCondFail{{[_0-9a-zA-Z]*}}F(i1, i1)
func testCondFail(_ b: Bool, c: Bool) {
// CHECK: br i1 %0, label %[[FAIL:.*]], label %[[CONT:.*]]
Builtin.condfail(b)
// CHECK: <label>:[[CONT]]
// CHECK: br i1 %1, label %[[FAIL2:.*]], label %[[CONT:.*]]
Builtin.condfail(c)
// CHECK: <label>:[[CONT]]
// CHECK: ret void
// CHECK: <label>:[[FAIL]]
// CHECK: call void @llvm.trap()
// CHECK: unreachable
// CHECK: <label>:[[FAIL2]]
// CHECK: call void @llvm.trap()
// CHECK: unreachable
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins8testOnce{{[_0-9a-zA-Z]*}}F(i8*, i8*) {{.*}} {
// CHECK: [[PRED_PTR:%.*]] = bitcast i8* %0 to [[WORD:i64|i32]]*
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: br i1 [[IS_DONE]], label %[[DONE:.*]], label %[[NOT_DONE:.*]]
// CHECK-objc: [[NOT_DONE]]:
// CHECK: call void @swift_once([[WORD]]* [[PRED_PTR]], i8* %1, i8* undef)
// CHECK-objc: br label %[[DONE]]
// CHECK-objc: [[DONE]]:
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: call void @llvm.assume(i1 [[IS_DONE]])
func testOnce(_ p: Builtin.RawPointer, f: @escaping @convention(thin) () -> ()) {
Builtin.once(p, f)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins19testOnceWithContext{{[_0-9a-zA-Z]*}}F(i8*, i8*, i8*) {{.*}} {
// CHECK: [[PRED_PTR:%.*]] = bitcast i8* %0 to [[WORD:i64|i32]]*
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: br i1 [[IS_DONE]], label %[[DONE:.*]], label %[[NOT_DONE:.*]]
// CHECK-objc: [[NOT_DONE]]:
// CHECK: call void @swift_once([[WORD]]* [[PRED_PTR]], i8* %1, i8* %2)
// CHECK-objc: br label %[[DONE]]
// CHECK-objc: [[DONE]]:
// CHECK-objc: [[PRED:%.*]] = load {{.*}} [[WORD]]* [[PRED_PTR]]
// CHECK-objc: [[IS_DONE:%.*]] = icmp eq [[WORD]] [[PRED]], -1
// CHECK-objc: call void @llvm.assume(i1 [[IS_DONE]])
func testOnceWithContext(_ p: Builtin.RawPointer, f: @escaping @convention(thin) (Builtin.RawPointer) -> (), k: Builtin.RawPointer) {
Builtin.onceWithContext(p, f, k)
}
class C {}
struct S {}
@objc class O {}
@objc protocol OP1 {}
@objc protocol OP2 {}
protocol P {}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins10canBeClass{{[_0-9a-zA-Z]*}}F
func canBeClass<T>(_ f: @escaping (Builtin.Int8) -> (), _: T) {
// CHECK: call {{.*}}void {{%.*}}(i8 1
f(Builtin.canBeClass(O.self))
// CHECK: call {{.*}}void {{%.*}}(i8 1
f(Builtin.canBeClass(OP1.self))
typealias ObjCCompo = OP1 & OP2
// CHECK: call {{.*}}void {{%.*}}(i8 1
f(Builtin.canBeClass(ObjCCompo.self))
// CHECK: call {{.*}}void {{%.*}}(i8 0
f(Builtin.canBeClass(S.self))
// CHECK: call {{.*}}void {{%.*}}(i8 1
f(Builtin.canBeClass(C.self))
// CHECK: call {{.*}}void {{%.*}}(i8 0
f(Builtin.canBeClass(P.self))
typealias MixedCompo = OP1 & P
// CHECK: call {{.*}}void {{%.*}}(i8 0
f(Builtin.canBeClass(MixedCompo.self))
// CHECK: call {{.*}}void {{%.*}}(i8 2
f(Builtin.canBeClass(T.self))
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins15destroyPODArray{{[_0-9a-zA-Z]*}}F(i8*, i64)
// CHECK-NOT: loop:
// CHECK: ret void
func destroyPODArray(_ array: Builtin.RawPointer, count: Builtin.Word) {
Builtin.destroyArray(Int.self, array, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins18destroyNonPODArray{{[_0-9a-zA-Z]*}}F(i8*, i64) {{.*}} {
// CHECK: iter:
// CHECK: loop:
// CHECK: call {{.*}} @swift_rt_swift_release
// CHECK: br label %iter
func destroyNonPODArray(_ array: Builtin.RawPointer, count: Builtin.Word) {
Builtin.destroyArray(C.self, array, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins15destroyGenArrayyBp_Bw5countxtlF(i8*, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
// CHECK-NOT: loop:
// CHECK: call void %destroyArray
func destroyGenArray<T>(_ array: Builtin.RawPointer, count: Builtin.Word, _: T) {
Builtin.destroyArray(T.self, array, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins12copyPODArray{{[_0-9a-zA-Z]*}}F(i8*, i8*, i64)
// CHECK: mul nuw i64 4, %2
// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false)
// CHECK: mul nuw i64 4, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false)
// CHECK: mul nuw i64 4, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 4, i1 false)
func copyPODArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) {
Builtin.copyArray(Int.self, dest, src, count)
Builtin.takeArrayFrontToBack(Int.self, dest, src, count)
Builtin.takeArrayBackToFront(Int.self, dest, src, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins11copyBTArray{{[_0-9a-zA-Z]*}}F(i8*, i8*, i64) {{.*}} {
// CHECK: iter:
// CHECK: loop:
// CHECK: call {{.*}} @swift_rt_swift_retain
// CHECK: br label %iter
// CHECK: mul nuw i64 8, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 8, i1 false)
// CHECK: mul nuw i64 8, %2
// CHECK: call void @llvm.memmove.p0i8.p0i8.i64(i8* {{.*}}, i8* {{.*}}, i64 {{.*}}, i32 8, i1 false)
func copyBTArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) {
Builtin.copyArray(C.self, dest, src, count)
Builtin.takeArrayFrontToBack(C.self, dest, src, count)
Builtin.takeArrayBackToFront(C.self, dest, src, count)
}
struct W { weak var c: C? }
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins15copyNonPODArray{{[_0-9a-zA-Z]*}}F(i8*, i8*, i64) {{.*}} {
// CHECK: iter:
// CHECK: loop:
// CHECK: swift_weakCopyInit
// CHECK: iter{{.*}}:
// CHECK: loop{{.*}}:
// CHECK: swift_weakTakeInit
// CHECK: iter{{.*}}:
// CHECK: loop{{.*}}:
// CHECK: swift_weakTakeInit
func copyNonPODArray(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word) {
Builtin.copyArray(W.self, dest, src, count)
Builtin.takeArrayFrontToBack(W.self, dest, src, count)
Builtin.takeArrayBackToFront(W.self, dest, src, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins12copyGenArray{{[_0-9a-zA-Z]*}}F(i8*, i8*, i64, %swift.opaque* noalias nocapture, %swift.type* %T)
// CHECK-NOT: loop:
// CHECK: call %swift.opaque* %initializeArrayWithCopy
// CHECK-NOT: loop:
// CHECK: call %swift.opaque* %initializeArrayWithTakeFrontToBack
// CHECK-NOT: loop:
// CHECK: call %swift.opaque* %initializeArrayWithTakeBackToFront
func copyGenArray<T>(_ dest: Builtin.RawPointer, src: Builtin.RawPointer, count: Builtin.Word, _: T) {
Builtin.copyArray(T.self, dest, src, count)
Builtin.takeArrayFrontToBack(T.self, dest, src, count)
Builtin.takeArrayBackToFront(T.self, dest, src, count)
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins24conditionallyUnreachableyyF
// CHECK-NEXT: entry
// CHECK-NEXT: unreachable
func conditionallyUnreachable() {
Builtin.conditionallyUnreachable()
}
struct Abc {
var value : Builtin.Word
}
// CHECK-LABEL define hidden {{.*}}@_T08builtins22assumeNonNegative_testBwAA3AbcVzF
func assumeNonNegative_test(_ x: inout Abc) -> Builtin.Word {
// CHECK: load {{.*}}, !range ![[R:[0-9]+]]
return Builtin.assumeNonNegative_Word(x.value)
}
@inline(never)
func return_word(_ x: Builtin.Word) -> Builtin.Word {
return x
}
// CHECK-LABEL define hidden {{.*}}@_T08builtins23assumeNonNegative_test2BwAA3AbcVzF
func assumeNonNegative_test2(_ x: Builtin.Word) -> Builtin.Word {
// CHECK: call {{.*}}, !range ![[R]]
return Builtin.assumeNonNegative_Word(return_word(x))
}
struct Empty {}
struct Pair { var i: Int, b: Bool }
// CHECK-LABEL: define hidden {{.*}}i64 @_T08builtins15zeroInitializerAA5EmptyV_AA4PairVtyF() {{.*}} {
// CHECK: [[ALLOCA:%.*]] = alloca { i64 }
// CHECK: bitcast
// CHECK: lifetime.start
// CHECK: [[EMPTYPAIR:%.*]] = bitcast { i64 }* [[ALLOCA]]
// CHECK: [[PAIR:%.*]] = getelementptr inbounds {{.*}} [[EMPTYPAIR]], i32 0, i32 0
// CHECK: [[FLDI:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 0
// CHECK: store i32 0, i32* [[FLDI]]
// CHECK: [[FLDB:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 1
// CHECK: store i1 false, i1* [[FLDB]]
// CHECK: [[RET:%.*]] = getelementptr inbounds {{.*}} [[ALLOCA]], i32 0, i32 0
// CHECK: [[RES:%.*]] = load i64, i64* [[RET]]
// CHECK: ret i64 [[RES]]
func zeroInitializer() -> (Empty, Pair) {
return (Builtin.zeroInitializer(), Builtin.zeroInitializer())
}
// CHECK-LABEL: define hidden {{.*}}i64 @_T08builtins20zeroInitializerTupleAA5EmptyV_AA4PairVtyF() {{.*}} {
// CHECK: [[ALLOCA:%.*]] = alloca { i64 }
// CHECK: bitcast
// CHECK: lifetime.start
// CHECK: [[EMPTYPAIR:%.*]] = bitcast { i64 }* [[ALLOCA]]
// CHECK: [[PAIR:%.*]] = getelementptr inbounds {{.*}} [[EMPTYPAIR]], i32 0, i32 0
// CHECK: [[FLDI:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 0
// CHECK: store i32 0, i32* [[FLDI]]
// CHECK: [[FLDB:%.*]] = getelementptr inbounds {{.*}} [[PAIR]], i32 0, i32 1
// CHECK: store i1 false, i1* [[FLDB]]
// CHECK: [[RET:%.*]] = getelementptr inbounds {{.*}} [[ALLOCA]], i32 0, i32 0
// CHECK: [[RES:%.*]] = load i64, i64* [[RET]]
// CHECK: ret i64 [[RES]]
func zeroInitializerTuple() -> (Empty, Pair) {
return Builtin.zeroInitializer()
}
// CHECK-LABEL: define hidden {{.*}}void @_T08builtins20zeroInitializerEmptyyyF() {{.*}} {
// CHECK: ret void
func zeroInitializerEmpty() {
return Builtin.zeroInitializer()
}
// ----------------------------------------------------------------------------
// isUnique variants
// ----------------------------------------------------------------------------
// CHECK: define hidden {{.*}}void @_T08builtins26acceptsBuiltinNativeObjectyBoSgzF([[BUILTIN_NATIVE_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} {
func acceptsBuiltinNativeObject(_ ref: inout Builtin.NativeObject?) {}
// native
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BoSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast [[BUILTIN_NATIVE_OBJECT_TY]]* %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_isUniquelyReferenced_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool {
return Builtin.isUnique(&ref)
}
// native nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BozF(%swift.refcounted** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %0
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferenced_nonNull_native(%swift.refcounted* %1)
// CHECK-NEXT: ret i1 %2
func isUnique(_ ref: inout Builtin.NativeObject) -> Bool {
return Builtin.isUnique(&ref)
}
// native pinned
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BoSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast [[BUILTIN_NATIVE_OBJECT_TY]]* %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUniqueOrPinned(_ ref: inout Builtin.NativeObject?) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// native pinned nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BozF(%swift.refcounted** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %0
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native(%swift.refcounted* %1)
// CHECK-NEXT: ret i1 %2
func isUniqueOrPinned(_ ref: inout Builtin.NativeObject) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// CHECK: define hidden {{.*}}void @_T08builtins27acceptsBuiltinUnknownObjectyBOSgzF([[BUILTIN_UNKNOWN_OBJECT_TY:%.*]]* nocapture dereferenceable({{.*}})) {{.*}} {
func acceptsBuiltinUnknownObject(_ ref: inout Builtin.UnknownObject?) {}
// ObjC
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BOSgzF({{%.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast [[BUILTIN_UNKNOWN_OBJECT_TY]]* %0 to %objc_object**
// CHECK-NEXT: load %objc_object*, %objc_object** %1
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedNonObjC(%objc_object* %2)
// CHECK-NEXT: ret i1 %3
func isUnique(_ ref: inout Builtin.UnknownObject?) -> Bool {
return Builtin.isUnique(&ref)
}
// ObjC nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BOzF(%objc_object** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %objc_object*, %objc_object** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedNonObjC_nonNull(%objc_object* %1)
// CHECK-NEXT: ret i1 %2
func isUnique(_ ref: inout Builtin.UnknownObject) -> Bool {
return Builtin.isUnique(&ref)
}
// ObjC pinned nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BOzF(%objc_object** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %objc_object*, %objc_object** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedOrPinnedNonObjC_nonNull(%objc_object* %1)
// CHECK-NEXT: ret i1 %2
func isUniqueOrPinned(_ ref: inout Builtin.UnknownObject) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// BridgeObject nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins8isUniqueBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.bridge*, %swift.bridge** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedNonObjC_nonNull_bridgeObject(%swift.bridge* %1)
// CHECK-NEXT: ret i1 %2
func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUnique(&ref)
}
// Bridge pinned nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins16isUniqueOrPinnedBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: load %swift.bridge*, %swift.bridge** %0
// CHECK-NEXT: call i1 @swift_isUniquelyReferencedOrPinnedNonObjC_nonNull_bridgeObject(%swift.bridge* %1)
// CHECK-NEXT: ret i1 %2
func isUniqueOrPinned(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUniqueOrPinned(&ref)
}
// BridgeObject nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins15isUnique_nativeBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast %swift.bridge** %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferenced_nonNull_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUnique_native(&ref)
}
// Bridge pinned nonNull
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins23isUniqueOrPinned_nativeBi1_BbzF(%swift.bridge** nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK-NEXT: bitcast %swift.bridge** %0 to %swift.refcounted**
// CHECK-NEXT: load %swift.refcounted*, %swift.refcounted** %1
// CHECK-NEXT: call i1 @swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native(%swift.refcounted* %2)
// CHECK-NEXT: ret i1 %3
func isUniqueOrPinned_native(_ ref: inout Builtin.BridgeObject) -> Bool {
return Builtin.isUniqueOrPinned_native(&ref)
}
// ImplicitlyUnwrappedOptional argument to isUnique.
// CHECK-LABEL: define hidden {{.*}}i1 @_T08builtins11isUniqueIUOBi1_BoSgzF(%{{.*}}* nocapture dereferenceable({{.*}})) {{.*}} {
// CHECK-NEXT: entry:
// CHECK: call i1 @swift_isUniquelyReferenced_native(%swift.refcounted*
// CHECK: ret i1
func isUniqueIUO(_ ref: inout Builtin.NativeObject?) -> Bool {
var iuo : Builtin.NativeObject! = ref
return Builtin.isUnique(&iuo)
}
// CHECK-LABEL: define {{.*}} @{{.*}}generic_ispod_test
func generic_ispod_test<T>(_: T) {
// CHECK: [[T0:%.*]] = getelementptr inbounds i8*, i8** [[T:%.*]], i32 18
// CHECK-NEXT: [[T1:%.*]] = load i8*, i8** [[T0]]
// CHECK-NEXT: [[FLAGS:%.*]] = ptrtoint i8* [[T1]] to i64
// CHECK-NEXT: [[ISNOTPOD:%.*]] = and i64 [[FLAGS]], 65536
// CHECK-NEXT: [[ISPOD:%.*]] = icmp eq i64 [[ISNOTPOD]], 0
// CHECK-NEXT: store i1 [[ISPOD]], i1* [[S:%.*]]
var s = Builtin.ispod(T.self)
}
// CHECK-LABEL: define {{.*}} @{{.*}}ispod_test
func ispod_test() {
// CHECK: store i1 true, i1*
// CHECK: store i1 false, i1*
var t = Builtin.ispod(Int.self)
var f = Builtin.ispod(Builtin.NativeObject)
}
// CHECK-LABEL: define {{.*}} @{{.*}}is_same_metatype
func is_same_metatype_test(_ t1: Any.Type, _ t2: Any.Type) {
// CHECK: [[MT1_AS_PTR:%.*]] = bitcast %swift.type* %0 to i8*
// CHECK: [[MT2_AS_PTR:%.*]] = bitcast %swift.type* %1 to i8*
// CHECK: icmp eq i8* [[MT1_AS_PTR]], [[MT2_AS_PTR]]
var t = Builtin.is_same_metatype(t1, t2)
}
// CHECK-LABEL: define {{.*}} @{{.*}}generic_unsafeGuaranteed_test
// CHECK: call void @{{.*}}swift_{{.*}}etain({{.*}}* %0)
// CHECK: call void @{{.*}}swift_{{.*}}elease({{.*}}* %0)
// CHECK: ret {{.*}}* %0
func generic_unsafeGuaranteed_test<T: AnyObject>(_ t : T) -> T {
let (g, _) = Builtin.unsafeGuaranteed(t)
return g
}
// CHECK-LABEL: define {{.*}} @{{.*}}unsafeGuaranteed_test
// CHECK: [[LOCAL:%.*]] = alloca %swift.refcounted*
// CHECK: call void @swift_rt_swift_retain(%swift.refcounted* %0)
// CHECK: store %swift.refcounted* %0, %swift.refcounted** [[LOCAL]]
// CHECK: call void @swift_rt_swift_release(%swift.refcounted* %0)
// CHECK: ret %swift.refcounted* %0
func unsafeGuaranteed_test(_ x: Builtin.NativeObject) -> Builtin.NativeObject {
var (g,t) = Builtin.unsafeGuaranteed(x)
Builtin.unsafeGuaranteedEnd(t)
return g
}
// CHECK-LABEL: define {{.*}} @{{.*}}unsafeGuaranteedEnd_test
// CHECK-NEXT: {{.*}}:
// CHECK-NEXT: ret void
func unsafeGuaranteedEnd_test(_ x: Builtin.Int8) {
Builtin.unsafeGuaranteedEnd(x)
}
// CHECK-LABEL: define {{.*}} @{{.*}}atomicload
func atomicload(_ p: Builtin.RawPointer) {
// CHECK: [[A:%.*]] = load atomic i8*, i8** {{%.*}} unordered, align 8
let a: Builtin.RawPointer = Builtin.atomicload_unordered_RawPointer(p)
// CHECK: [[B:%.*]] = load atomic i32, i32* {{%.*}} singlethread monotonic, align 4
let b: Builtin.Int32 = Builtin.atomicload_monotonic_singlethread_Int32(p)
// CHECK: [[C:%.*]] = load atomic volatile i64, i64* {{%.*}} singlethread acquire, align 8
let c: Builtin.Int64 =
Builtin.atomicload_acquire_volatile_singlethread_Int64(p)
// CHECK: [[D0:%.*]] = load atomic volatile i32, i32* {{%.*}} seq_cst, align 4
// CHECK: [[D:%.*]] = bitcast i32 [[D0]] to float
let d: Builtin.FPIEEE32 = Builtin.atomicload_seqcst_volatile_FPIEEE32(p)
// CHECK: store atomic i8* [[A]], i8** {{%.*}} unordered, align 8
Builtin.atomicstore_unordered_RawPointer(p, a)
// CHECK: store atomic i32 [[B]], i32* {{%.*}} singlethread monotonic, align 4
Builtin.atomicstore_monotonic_singlethread_Int32(p, b)
// CHECK: store atomic volatile i64 [[C]], i64* {{%.*}} singlethread release, align 8
Builtin.atomicstore_release_volatile_singlethread_Int64(p, c)
// CHECK: [[D1:%.*]] = bitcast float [[D]] to i32
// CHECK: store atomic volatile i32 [[D1]], i32* {{.*}} seq_cst, align 4
Builtin.atomicstore_seqcst_volatile_FPIEEE32(p, d)
}
// CHECK: ![[R]] = !{i64 0, i64 9223372036854775807}
| apache-2.0 | 590f6ac4ac90977a4a76f6393150fc21 | 39.070457 | 237 | 0.626492 | 3.277093 | false | true | false | false |
tonystone/geofeatures2 | Sources/GeoFeatures/GeometryCollection.swift | 1 | 6681 | ///
/// GeometryCollection.swift
///
/// Copyright (c) 2016 Tony Stone
///
/// 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.
///
/// Created by Tony Stone on 2/14/2016.
///
///
/// NOTE: This file was auto generated by gyb from file GeometryCollectionTypes.swift.gyb using the following command.
///
/// ~/gyb --line-directive '' -DSelf=GeometryCollection -DElement=Geometry -o GeometryCollection.swift GeometryCollectionTypes.swift.gyb
///
/// Do NOT edit this file directly as it will be regenerated automatically when needed.
///
import Swift
///
/// A GeometryCollection is a collection of some number of Geometry objects.
///
/// All the elements in a GeometryCollection will be converted to the same Spatial Reference System as `self`.
///
public struct GeometryCollection: Geometry {
///
/// The `Precision` of this GeometryCollection
///
public let precision: Precision
///
/// The `CoordinateSystem` of this GeometryCollection
///
public let coordinateSystem: CoordinateSystem
///
/// Construct an empty `GeometryCollection`.
///
public init() {
self.init([], precision: defaultPrecision, coordinateSystem: defaultCoordinateSystem)
}
///
/// Construct an empty `GeometryCollection`.
///
/// - Parameters:
/// - precision: The `Precision` model this `GeometryCollection` should use in calculations on it's coordinates.
/// - coordinateSystem: The 'CoordinateSystem` this `GeometryCollection` should use in calculations on it's coordinates.
///
public init(precision: Precision = defaultPrecision, coordinateSystem: CoordinateSystem = defaultCoordinateSystem) {
self.init([] as [Geometry], precision: precision, coordinateSystem: coordinateSystem)
}
///
/// Construct a GeometryCollection from another GeometryCollection (copy constructor) changing the precision and coordinateSystem.
///
/// - Parameters:
/// - other: The GeometryCollection of the same type that you want to construct a new GeometryCollection from.
/// - precision: Optionally change the `Precision` model this `GeometryCollection` should use in calculations on it's coordinates.
/// - coordinateSystem: Optionally change the 'CoordinateSystem` this `GeometryCollection` should use in calculations on it's coordinates.
///
public init(other: GeometryCollection, precision: Precision = defaultPrecision, coordinateSystem: CoordinateSystem = defaultCoordinateSystem) {
self.init(other.elements, precision: precision, coordinateSystem: coordinateSystem)
}
///
/// Construct a `GeometryCollection` from an `Array` which holds `Geometry` objects.
///
/// GeometryCollection can be constructed from any Swift.Collection type as
/// long as it has an Element type equal the Geometry type specified in Element.
///
/// - Parameters:
/// - elements: An `Array` of `Geometry`s.
/// - precision: The `Precision` model this `GeometryCollection` should use in calculations on it's coordinates.
/// - coordinateSystem: The 'CoordinateSystem` this `GeometryCollection` should use in calculations on it's coordinates.
///
public init(_ elements: [Geometry], precision: Precision = defaultPrecision, coordinateSystem: CoordinateSystem = defaultCoordinateSystem) {
self.precision = precision
self.coordinateSystem = coordinateSystem
/// Add the elements to our backing storage
self.replaceSubrange(0..<0, with: elements)
}
private var elements: [Geometry] = []
}
// MARK: - ExpressibleByArrayLiteral conformance
extension GeometryCollection: ExpressibleByArrayLiteral {
/// Creates an instance initialized with the given elements.
public init(arrayLiteral elements: Geometry...) {
self.init(elements)
}
}
// MARK: - `GeometryCollectionType` and `RangeReplaceableCollection` conformance.
extension GeometryCollection: GeometryCollectionType, RangeReplaceableCollection {
///
/// Returns the position immediately after `i`.
///
/// - Precondition: `(startIndex..<endIndex).contains(i)`
///
public func index(after i: Int) -> Int {
return i+1
}
///
/// Always zero, which is the index of the first element when non-empty.
///
public var startIndex: Int {
return 0
}
///
/// A "past-the-end" element index; the successor of the last valid subscript argument.
///
public var endIndex: Int {
return elements.count
}
///
/// Accesses the element at the specified position.
///
public subscript(index: Int) -> Geometry {
get {
/// Note: we rely on the array to return an error for any index out of range.
return elements[index]
}
set (newElement) {
self.replaceSubrange(index..<(index + 1), with: [newElement])
}
}
///
/// Replaces the specified subrange of elements with the given collection.
///
/// This method has the effect of removing the specified range of elements
/// from the collection and inserting the new elements at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
public mutating func replaceSubrange<C, R>(_ subrange: R, with newElements: C) where C : Collection, R : RangeExpression, Geometry == C.Element, Int == R.Bound {
self.elements.replaceSubrange(subrange, with: newElements)
}
}
// MARK: CustomStringConvertible & CustomDebugStringConvertible protocol conformance
extension GeometryCollection: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {
return "\(type(of: self))([\(self.map { String(describing: $0) }.joined(separator: ", "))])"
}
public var debugDescription: String {
return self.description
}
}
// MARK: - Equatable Conformance
extension GeometryCollection: Equatable {
static public func == (lhs: GeometryCollection, rhs: GeometryCollection) -> Bool {
return lhs.equals(rhs)
}
}
| apache-2.0 | 2b1f096dd589a7c3c48a3533e230adb1 | 35.708791 | 165 | 0.685526 | 4.869534 | false | false | false | false |
mpon/BeaconSample | BeaconSample/BeaconManager.swift | 2 | 4488 | //
// BeaconManager.swift
// BeaconSample
//
// Created by Masato Oshima on 2014/12/06.
// Copyright (c) 2014年 Masato Oshima. All rights reserved.
//
import UIKit
import CoreLocation
/**
ビーコンの受信を受けてNSNotificationをPostするシングルトンクラス
sharedInstance経由でアクセスする
*/
class BeaconManager: NSObject, CLLocationManagerDelegate {
/// ビーコンを受信したときの通知名
class var BeaconReceiveNotification :String { return "BeaconReceiveNotification" }
/// 監視するiBeacon
private let beaconRegion = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXXX"), identifier: NSBundle.mainBundle().bundleIdentifier)
private let locationManager = CLLocationManager()
/**
シングルトンインスタンス
*/
class var sharedInstance : BeaconManager {
struct Static {
static let instance : BeaconManager = BeaconManager()
}
return Static.instance
}
/**
iBeaconの監視を開始する
*/
func startMonitoring() {
self.locationManager.delegate = self
if !CLLocationManager.isMonitoringAvailableForClass(CLBeaconRegion) {
return
}
if !CLLocationManager.isRangingAvailable() {
return
}
// アプリがバックグラウンド状態の場合は位置情報のバックグラウンド更新をする
// これをしないとiBeaconの範囲に入ったか入っていないか検知してくれない
let appStatus = UIApplication.sharedApplication().applicationState
let isBackground = appStatus == .Background || appStatus == .Inactive
if isBackground {
self.locationManager.startUpdatingLocation()
}
// locationManager: didStartMonitoringForRegion: のdelegateが呼ばれる
self.locationManager.startMonitoringForRegion(self.beaconRegion)
}
/**
iBeaconのレンジングを再開する
*/
func resumeRanging() {
self.locationManager.startMonitoringForRegion(self.beaconRegion)
}
/**
iBeaconのレンジングをストップする。
*/
func stopRanging() {
self.locationManager.stopRangingBeaconsInRegion(self.beaconRegion)
}
// MARK: - CLLocationManagerDelegate
// region内にすでにいる場合に備えて、必ずregionについての状態を知らせてくれるように要求する必要がある
// このリクエストは非同期で行われ、結果は locationManager:didDetermineState:forRegion: で呼ばれる
func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) {
manager.requestStateForRegion(region)
}
// 位置情報を使うためのユーザーへの認証が必要になる
// 認証を依頼するためにコードでリクエストを出すないといけない
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .NotDetermined {
self.locationManager.requestAlwaysAuthorization()
}
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println(error)
}
// iBeaconの範囲内にいるのかいないのかが通知される
// いる場合はレンジングを開始する。
func locationManager(manager: CLLocationManager!, didDetermineState state: CLRegionState, forRegion region: CLRegion!) {
switch state {
case .Inside:
if region is CLBeaconRegion && CLLocationManager.isRangingAvailable() {
manager.startRangingBeaconsInRegion(region as CLBeaconRegion)
}
default:
break
}
}
// iBeaconの範囲内にいる場合に1秒間隔で呼ばれ、iBeaconの情報を取得できる。
func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) {
// Beacon情報とともにNSNotificationCenterで通知する
if !beacons.isEmpty {
NSNotificationCenter.defaultCenter()
.postNotificationName(BeaconManager.BeaconReceiveNotification, object: beacons)
}
}
}
| mit | 2c5e38cce51408949ab153bf96157b09 | 29.819672 | 173 | 0.671277 | 4.541063 | false | false | false | false |
laurentVeliscek/AudioKit | AudioKit/Common/Nodes/Generators/Noise/White Noise/AKWhiteNoise.swift | 1 | 3225 | //
// AKWhiteNoise.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// White noise generator
///
/// - parameter amplitude: Amplitude. (Value between 0-1).
///
public class AKWhiteNoise: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKWhiteNoiseAudioUnit?
internal var token: AUParameterObserverToken?
private var amplitudeParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Amplitude. (Value between 0-1).
public var amplitude: Double = 1 {
willSet {
if amplitude != newValue {
amplitudeParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this noise node
///
/// - parameter amplitude: Amplitude. (Value between 0-1).
///
public init(
amplitude: Double = 1) {
self.amplitude = amplitude
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Generator
description.componentSubType = 0x776e6f7a /*'wnoz'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKWhiteNoiseAudioUnit.self,
asComponentDescription: description,
name: "Local AKWhiteNoise",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitGenerator = avAudioUnit else { return }
self.avAudioNode = avAudioUnitGenerator
self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKWhiteNoiseAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
}
guard let tree = internalAU?.parameterTree else { return }
amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.amplitudeParameter!.address {
self.amplitude = Double(value)
}
}
}
internalAU?.amplitude = Float(amplitude)
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| mit | 7c985be15f4215761b356a6a61f3ece6 | 28.054054 | 88 | 0.618915 | 5.321782 | false | false | false | false |
masteranca/Flow | Flow/Response.swift | 1 | 569 | //
// Created by Anders Carlsson on 23/01/16.
// Copyright (c) 2016 CoreDev. All rights reserved.
//
import Foundation
public struct Response<T> {
let httpResponse: NSHTTPURLResponse
let parsedData: T?
let rawData: NSData?
init(httpResponse: NSHTTPURLResponse, parsedData: T? = nil, rawData: NSData? = nil) {
self.httpResponse = httpResponse
self.parsedData = parsedData
self.rawData = rawData
}
func valueForHeader(header: String) -> String? {
return httpResponse.allHeaderFields[header] as? String
}
}
| mit | fea42fd5a09903655d2972ba7a86990e | 23.73913 | 89 | 0.674868 | 4.278195 | false | false | false | false |
recruit-mp/RMPScrollingMenuBarController | Example_Swift2/RMPScrollingMenuBarController/AppDelegate.swift | 1 | 5656 | // Copyright (c) 2015 Recruit Marketing Partners Co.,Ltd. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import RMPScrollingMenuBarController
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.setup()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - private methods
func setup() {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
// Setup menu bar controller
let menuController = RMPScrollingMenuBarController()
menuController.delegate = self
// Customize appearance of menu bar.
menuController.view.backgroundColor = UIColor.whiteColor()
menuController.menuBar.indicatorColor = UIColor.blueColor()
//menuController.menuBar.style = .InfinitePaging
//menuController.menuBar.showsIndicator = false
//menuController.menuBar.showsSeparatorLine = false
// Set ViewControllers for menu bar controller
var viewControllers: [PageViewController] = []
for var i = 0 ; i < 10 ; ++i {
let vc = PageViewController()
vc.view.backgroundColor = UIColor(white: CGFloat(0.3) + CGFloat(0.05) * CGFloat(i), alpha: 1)
vc.message = "Message for No.\(i)"
viewControllers.append(vc)
}
menuController.setViewControllers(viewControllers, animated: false)
let naviController = UINavigationController(rootViewController: menuController)
self.window?.rootViewController = naviController
self.window?.makeKeyAndVisible()
}
}
extension AppDelegate: RMPScrollingMenuBarControllerDelegate {
func menuBarController(menuBarController: RMPScrollingMenuBarController!, willSelectViewController viewController: UIViewController!) {
print("will select \(viewController)")
}
func menuBarController(menuBarController: RMPScrollingMenuBarController!, didSelectViewController viewController: UIViewController!) {
print("did select \(viewController)")
}
func menuBarController(menuBarController: RMPScrollingMenuBarController!, didCancelViewController viewController: UIViewController!) {
print("did cancel \(viewController)")
}
func menuBarController(menuBarController: RMPScrollingMenuBarController!, menuBarItemAtIndex index: Int) -> RMPScrollingMenuBarItem! {
let item = RMPScrollingMenuBarItem()
item.title = "Title \(index)"
// Customize appearance of menu bar item.
let button = item.button()
button.setTitleColor(UIColor.lightGrayColor(), forState: .Normal)
button.setTitleColor(UIColor.blueColor(), forState: .Disabled)
button.setTitleColor(UIColor.grayColor(), forState: .Selected)
return item
}
}
| mit | d0965264db85a841ef335dcad8d1ab42 | 47.758621 | 285 | 0.730021 | 5.376426 | false | false | false | false |
Liujlai/DouYuD | DYTV/DYTV/BaseAnchorViewController.swift | 1 | 5646 | //
// BaseAnchorViewController.swift
// DYTV
//
// Created by idea on 2017/8/16.
// Copyright © 2017年 idea. All rights reserved.
//
import UIKit
private let kItemMargin: CGFloat = 10
let kNItemW = (kScreenW - 3 * kItemMargin)/2
let kNormalItemH = kNItemW * 3 / 4
let kPrettyItemH = kNItemW * 4 / 3
private let kHeaderViewH : CGFloat = 50
//标识
private let kNormalCellID = "kNormalCellID"
let kPrettyCellID = "kPrettyCellID"
private let kHeaderViewID = "kHeaderViewID"
class BaseAnchorViewController: BaseViewController {
var baseVm : BaseViewModel!
lazy var collectionView: UICollectionView = {[unowned self] in
// 1.创建布局
// 流水布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kNItemW, height: kNormalItemH)
// 行间距
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
// 设置组的内边距
layout .sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
// 2.创建UICollection
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
// 添加数据源
collectionView.dataSource = self
collectionView.delegate = self
// 随父控件的缩小而缩小
collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
// collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName:"CollectionNomalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID)
collectionView.register(UINib(nibName:"CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
// collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.register(UINib(nibName:"CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
//MARK:设置UI界面
extension BaseAnchorViewController{
override func setupUI(){
// 1.先给父类中的内容View的引用进行赋值
contenView = collectionView
//2. 再添加collectionView
view.addSubview(collectionView)
// 3.最后调用super.setupUI()
super.setupUI()
}
}
//MARK: 请求数据
extension BaseAnchorViewController{
func loadData(){
}
}
//MARK: 遵守UICollectionView的数据源&代理协议
extension BaseAnchorViewController : UICollectionViewDataSource{
//有几组
func numberOfSections(in collectionView: UICollectionView) -> Int {
return baseVm.anchorGroups.count
}
// 每组里🈶️几条数据
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return baseVm.anchorGroups[section].anchors.count
}
// 返回CELL放入方法
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.取出CEll
// 选择cell测类型---->为普通cell(kNormalCellID)
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNomalCell
// 2.给Cell设置数据
cell.anchor = baseVm.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
// 另一个数据源方法
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1.取出HeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
// 2.给Headerview设置数据
headerView.group = baseVm.anchorGroups[indexPath.section]
return headerView
}
}
extension BaseAnchorViewController: UICollectionViewDelegate{
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 1.先取出对应的主播信息
let anchor = baseVm.anchorGroups[indexPath.section].anchors[indexPath.item]
// 2.判断是秀场房间&普通房间
anchor.isVertical == 0 ? pushNormalRoomVc() : presentShowRoomVc()
}
private func presentShowRoomVc(){
// 1.创建ShowRoomVc
let showRoomVc = RoomShowViewController()
// 2.以modal的方式弹出
present(showRoomVc, animated: true, completion: nil)
}
private func pushNormalRoomVc(){
// 1.创建NormalRoomVc
let normalRoomVc = RoomNomalViewController()
// 2.以Push的方式弹出
navigationController?.pushViewController(normalRoomVc, animated: true)
}
}
| mit | 63e3683ff5a680e28b5572f131c6c264 | 33.064103 | 185 | 0.657697 | 5.501035 | false | false | false | false |
iwheelbuy/SquareMosaicLayout | Example/SquareMosaicLayout/FMMosaicLayoutController.swift | 1 | 3673 | import UIKit
import SquareMosaicLayout
final class FMMosaicLayoutCopyController: UIViewController, UICollectionViewDataSource {
override func viewDidLoad() {
super.viewDidLoad()
let collection = UICollectionView(frame: .zero, collectionViewLayout: FMMosaicLayoutCopy())
collection.register(UICollectionViewCell.self)
collection.dataSource = self
self.title = "FMMosaicLayoutCopy"
self.view = collection
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 49
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: UICollectionViewCell = collectionView.dequeueCell(indexPath: indexPath)
cell.contentView.backgroundColor = UIColor.init(white: (30.0 + CGFloat(indexPath.row * 4)) / 255.0, alpha: 1.0)
return cell
}
}
final class FMMosaicLayoutCopy: SquareMosaicLayout, SquareMosaicDataSource {
convenience init() {
self.init(direction: SquareMosaicDirection.vertical)
self.dataSource = self
}
func layoutPattern(for section: Int) -> SquareMosaicPattern {
return FMMosaicLayoutCopyPattern()
}
}
class FMMosaicLayoutCopyPattern: SquareMosaicPattern {
func patternBlocks() -> [SquareMosaicBlock] {
return [
FMMosaicLayoutCopyBlock1(),
FMMosaicLayoutCopyBlock2(),
FMMosaicLayoutCopyBlock3(),
FMMosaicLayoutCopyBlock2(),
FMMosaicLayoutCopyBlock2()
]
}
}
public class FMMosaicLayoutCopyBlock1: SquareMosaicBlock {
public func blockFrames() -> Int {
return 5
}
public func blockFrames(origin: CGFloat, side: CGFloat) -> [CGRect] {
let min = side / 4.0
let max = side - min - min
var frames = [CGRect]()
frames.append(CGRect(x: 0, y: origin, width: max, height: max))
frames.append(CGRect(x: max, y: origin, width: min, height: min))
frames.append(CGRect(x: max, y: origin + min, width: min, height: min))
frames.append(CGRect(x: max + min, y: origin, width: min, height: min))
frames.append(CGRect(x: max + min, y: origin + min, width: min, height: min))
return frames
}
}
public class FMMosaicLayoutCopyBlock2: SquareMosaicBlock {
public func blockFrames() -> Int {
return 4
}
public func blockFrames(origin: CGFloat, side: CGFloat) -> [CGRect] {
let min = side / 4.0
var frames = [CGRect]()
frames.append(CGRect(x: 0, y: origin, width: min, height: min))
frames.append(CGRect(x: min, y: origin, width: min, height: min))
frames.append(CGRect(x: min * 2, y: origin, width: min, height: min))
frames.append(CGRect(x: min * 3, y: origin, width: min, height: min))
return frames
}
}
public class FMMosaicLayoutCopyBlock3: SquareMosaicBlock {
public func blockFrames() -> Int {
return 5
}
public func blockFrames(origin: CGFloat, side: CGFloat) -> [CGRect] {
let min = side / 4.0
let max = side - min - min
var frames = [CGRect]()
frames.append(CGRect(x: 0, y: origin, width: min, height: min))
frames.append(CGRect(x: 0, y: origin + min, width: min, height: min))
frames.append(CGRect(x: min, y: origin, width: min, height: min))
frames.append(CGRect(x: min, y: origin + min, width: min, height: min))
frames.append(CGRect(x: max, y: origin, width: max, height: max))
return frames
}
}
| mit | f2f4d5735e6cd82099104713728a7d94 | 34.317308 | 121 | 0.635448 | 3.988056 | false | false | false | false |
dgoodine/Slogger | Slogger/Slogger/MemoryDestination.swift | 1 | 1865 | //
// MemoryDestination.swift
// Slogger
//
// Created by David Goodine on 10/25/15.
// Copyright © 2015 David Goodine. All rights reserved.
//
import Foundation
/**
An in-memory logging destination used by the test suite.
Provided as it might be a useful superclass for some use-cases (e.g. buffering lines for periodic
transfer to some other output sink.
*/
open class MemoryDestination: DestinationBase, Destination {
// MARK - Properties
/// The index of the last logged line. Returns `-1` if the destination is empty.
open var lastIndex: Int {
get {
return lines.count - 1
}
}
/// The last logged line. Returns *nil* if the storage is empty.
open var lastLine: String? {
get {
return self[lastIndex]
}
}
/// Storage
fileprivate var lines: [String] = []
// MARK - Initializer
override public init (details: [Detail]? = nil, generator: Generator = Generator(), colorMap: ColorMap? = nil, decorator: Decorator? = nil) {
super.init(details: details, generator: generator, colorMap: colorMap, decorator: decorator)
}
// MARK - Functions
/**
Protocol implementation. Simply appends the string to an internal array.
- Parameter string: The line to be logged.
- Parameter level: The level provided at the logging site.
*/
open func logString(_ string: String, level: Level) {
lines.append(string)
}
/// Clear the logging history.
open func clear () {
lines = []
}
/**
Subscript-based access to logging lines.
- Parameter index: The index of the line to return
- Returns: The logging output for the index or nil if the destination is empty or the index is out of bounds
*/
open subscript (index: Int) -> String? {
get {
guard index >= 0 && index < lines.count else {
return nil
}
return lines[index]
}
}
}
| mit | 3b4590ebdc34f4396588360128ce2ea3 | 24.534247 | 143 | 0.662554 | 4.096703 | false | false | false | false |
zeroc-ice/ice | swift/test/Ice/info/TestI.swift | 4 | 2261 | //
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Ice
func getIPEndpointInfo(_ info: Ice.EndpointInfo) -> Ice.IPEndpointInfo? {
var curr: Ice.EndpointInfo? = info
while curr != nil {
if curr is Ice.IPEndpointInfo {
return curr as? Ice.IPEndpointInfo
}
curr = curr?.underlying
}
return nil
}
func getIPConnectionInfo(_ info: Ice.ConnectionInfo) -> Ice.IPConnectionInfo? {
var curr: Ice.ConnectionInfo? = info
while curr != nil {
if curr is Ice.IPConnectionInfo {
return curr as? Ice.IPConnectionInfo
}
curr = curr?.underlying
}
return nil
}
class TestI: TestIntf {
func shutdown(current: Ice.Current) throws {
current.adapter!.getCommunicator().shutdown()
}
func getEndpointInfoAsContext(current: Ice.Current) throws -> Ice.Context {
var ctx = Ice.Context()
let info = current.con!.getEndpoint().getInfo()!
ctx["timeout"] = "\(info.timeout)"
ctx["compress"] = info.compress ? "true" : "false"
ctx["datagram"] = info.datagram() ? "true" : "false"
ctx["secure"] = info.datagram() ? "true" : "false"
ctx["type"] = "\(info.type())"
let ipinfo = getIPEndpointInfo(info)!
ctx["host"] = ipinfo.host
ctx["port"] = "\(ipinfo.port)"
if let udpinfo = ipinfo as? Ice.UDPEndpointInfo {
ctx["mcastInterface"] = udpinfo.mcastInterface
ctx["mcastTtl"] = "\(udpinfo.mcastTtl)"
}
return ctx
}
func getConnectionInfoAsContext(current: Ice.Current) throws -> Ice.Context {
var ctx = Ice.Context()
let info = try current.con!.getInfo()
ctx["adapterName"] = info.adapterName
ctx["incoming"] = info.incoming ? "true" : "false"
let ipinfo = getIPConnectionInfo(info)!
ctx["localAddress"] = ipinfo.localAddress
ctx["localPort"] = "\(ipinfo.localPort)"
ctx["remoteAddress"] = ipinfo.remoteAddress
ctx["remotePort"] = "\(ipinfo.remotePort)"
if let wsinfo = info as? WSConnectionInfo {
for (key, value) in wsinfo.headers {
ctx["ws.\(key)"] = value
}
}
return ctx
}
}
| gpl-2.0 | 5b5b6bd87ea7f5e9026478549e91b526 | 29.972603 | 81 | 0.58337 | 3.898276 | false | false | false | false |
Jerrrr/SwiftyStarRatingView | Source/SwiftyStarRatingView.swift | 1 | 12723 | //
// SwiftyStarRatingView.swift
// SwiftyStarRatingView
//
// Created by jerry on 16/12/2.
// Copyright © 2016年 jerry. All rights reserved.
//
import UIKit
public typealias SSRVGestureHandler = (_ gesture: UIGestureRecognizer) -> Bool
@IBDesignable
public class SwiftyStarRatingView: UIControl {
public var shouldBecomeFirstResponder: Bool = false
public var shouldBeginGestureHandler: SSRVGestureHandler!
fileprivate var _minimumValue: CGFloat = 0
fileprivate var _maximumValue: CGFloat = 5
fileprivate var _value: CGFloat = 0 {
didSet {
if _value != oldValue && _value >= _minimumValue && _value <= _maximumValue && continuous == true {
self.sendActions(for: .valueChanged)
}
setNeedsDisplay()
}
}
@IBInspectable public var minimumValue: CGFloat {
set {
if _minimumValue != newValue {
_minimumValue = newValue
}
}
get {
return max(_minimumValue, 0)
}
}
@IBInspectable public var maximumValue: CGFloat {
set {
if _maximumValue != newValue {
_maximumValue = newValue
}
}
get {
return max(_maximumValue, _minimumValue)
}
}
@IBInspectable public var value: CGFloat {
set {
if _value != newValue {
_value = newValue
}
}
get {
return min(max(_value, _minimumValue), _maximumValue)
}
}
public func observe<Value>(_ keyPath: KeyPath<SwiftyStarRatingView, Value>, options: NSKeyValueObservingOptions, changeHandler: @escaping (SwiftyStarRatingView, NSKeyValueObservedChange<Value>) -> Void) -> NSKeyValueObservation {
if [\SwiftyStarRatingView.allowsHalfStars,
\SwiftyStarRatingView.accurateHalfStars,
\SwiftyStarRatingView.emptyStarImage,
\SwiftyStarRatingView.halfStarImage,
\SwiftyStarRatingView.filledStarImage,
\SwiftyStarRatingView.maximumValue,
\SwiftyStarRatingView.minimumValue,
\SwiftyStarRatingView.spacing,].contains(keyPath) {
return observe(keyPath, changeHandler: { (_, _) in
self.setNeedsDisplay()
})
}
return observe(keyPath, changeHandler: { (_, _) in })
}
@IBInspectable public var spacing: CGFloat = 5
@IBInspectable public var continuous: Bool = true
@IBInspectable public var allowsHalfStars: Bool = true
@IBInspectable public var accurateHalfStars: Bool = true
@IBInspectable public var emptyStarImage: UIImage?
@IBInspectable public var halfStarImage: UIImage?
@IBInspectable public var filledStarImage: UIImage?
fileprivate var shouldUseImages: Bool {
get {
return (self.emptyStarImage != nil && self.filledStarImage != nil)
}
}
override public var isEnabled: Bool {
willSet {
updateAppearance(enabled: newValue)
}
}
override public var canBecomeFirstResponder: Bool {
get {
return shouldBecomeFirstResponder
}
}
override public var intrinsicContentSize: CGSize {
get {
let height: CGFloat = 44.0
return CGSize(width: _maximumValue * height + (_maximumValue-1) * spacing, height: height)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.customInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.customInit()
}
override public func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
context?.setFillColor((self.backgroundColor?.cgColor ?? UIColor.white.cgColor)!)
context?.fill(rect)
let availableWidth = rect.width - 2 - (spacing * (_maximumValue - 1))
let cellWidth = availableWidth / _maximumValue
let starSide = min(cellWidth, rect.height)
for idx in 0..<Int(_maximumValue) {
let center = CGPoint(x: (cellWidth + spacing) * CGFloat(idx) + cellWidth / 2 + 1, y: rect.size.height / 2)
let frame = CGRect(x: center.x - starSide / 2, y: center.y - starSide / 2, width: starSide, height: starSide)
let highlighted = Float(idx+1) <= ceilf(Float(_value))
if allowsHalfStars && highlighted && (CGFloat(idx+1) > _value) {
if accurateHalfStars {
drawAccurateStar(frame: frame, tintColor: tintColor, progress: _value-CGFloat(idx))
} else {
drawHalfStar(frame: frame, tintColor: tintColor)
}
} else {
drawStar(frame: frame, tintColor: tintColor, highlighted: highlighted)
}
}
}
}
fileprivate extension SwiftyStarRatingView {
func customInit() {
self.isExclusiveTouch = true
self.updateAppearance(enabled: self.isEnabled)
}
func drawStar(frame: CGRect, tintColor: UIColor, highlighted: Bool) {
if self.shouldUseImages {
drawStartImage(frame: frame, tintColor: tintColor, highlighted: highlighted)
} else {
drawStarShape(frame: frame, tintColor: tintColor, highlighted: highlighted)
}
}
func drawHalfStar(frame: CGRect, tintColor: UIColor) {
if self.shouldUseImages && (self.halfStarImage != nil) {
drawHalfStarImage(frame: frame, tintColor: tintColor)
} else {
drawHalfStarShape(frame: frame, tintColor: tintColor)
}
}
func drawAccurateStar(frame: CGRect, tintColor: UIColor, progress: CGFloat) {
if self.shouldUseImages && (self.halfStarImage != nil) {
drawAccurateHalfStarImage(frame: frame, tintColor: tintColor, progress: progress)
} else {
drawAccurateHalfStarShape(frame: frame, tintColor: tintColor, progress: progress)
}
}
func updateAppearance(enabled: Bool) {
self.alpha = enabled ? 1.0 : 0.5
}
}
fileprivate extension SwiftyStarRatingView {
//Image Drawing
func drawStartImage(frame: CGRect, tintColor: UIColor, highlighted: Bool) {
let image = highlighted ? self.filledStarImage : self.emptyStarImage
draw(image: image!, frame: frame, tintColor: tintColor)
}
func drawHalfStarImage(frame: CGRect, tintColor: UIColor) {
drawAccurateHalfStarImage(frame: frame, tintColor: tintColor, progress: 0.5)
}
func drawAccurateHalfStarImage(frame: CGRect, tintColor: UIColor, progress: CGFloat) {
guard let halfStarImage = self.halfStarImage else {
drawAccurateHalfStarShape(frame: frame, tintColor: tintColor, progress: progress)
return
}
var aFrame = frame
let imageF = CGRect(x: 0, y: 0, width: halfStarImage.size.width * halfStarImage.scale * progress, height: halfStarImage.size.height * halfStarImage.scale)
aFrame.size.width *= progress
let imageRef = halfStarImage.cgImage?.cropping(to: imageF)
let croppedImage = UIImage(cgImage: imageRef!, scale: halfStarImage.scale, orientation: halfStarImage.imageOrientation)
let image = croppedImage.withRenderingMode(halfStarImage.renderingMode)
self.draw(image: image, frame: aFrame, tintColor: tintColor)
}
func draw(image: UIImage, frame: CGRect, tintColor: UIColor) {
if image.renderingMode == .alwaysTemplate {
tintColor.setFill()
}
image.draw(in: frame)
}
}
fileprivate extension SwiftyStarRatingView {
//Shape Drawing
func drawStarShape(frame: CGRect, tintColor: UIColor, highlighted: Bool) {
drawAccurateHalfStarShape(frame: frame, tintColor: tintColor, progress: highlighted ? 1.0 : 0.0)
}
func drawHalfStarShape(frame: CGRect, tintColor: UIColor) {
drawAccurateHalfStarShape(frame: frame, tintColor: tintColor, progress: 0.5)
}
func drawAccurateHalfStarShape(frame: CGRect, tintColor: UIColor, progress: CGFloat) {
let starShapePath = UIBezierPath()
starShapePath.move(to: CGPoint(x: frame.minX + 0.62723 * frame.width, y: frame.minY + 0.37309 * frame.height))
starShapePath.addLine(to: CGPoint(x: frame.minX + 0.50000 * frame.width, y: frame.minY + 0.02500 * frame.height))
starShapePath.addLine(to: CGPoint(x: frame.minX + 0.37292 * frame.width, y: frame.minY + 0.37309 * frame.height))
starShapePath.addLine(to: CGPoint(x: frame.minX + 0.02500 * frame.width, y: frame.minY + 0.39112 * frame.height))
starShapePath.addLine(to: CGPoint(x: frame.minX + 0.30504 * frame.width, y: frame.minY + 0.62908 * frame.height))
starShapePath.addLine(to: CGPoint(x: frame.minX + 0.20642 * frame.width, y: frame.minY + 0.97500 * frame.height))
starShapePath.addLine(to: CGPoint(x: frame.minX + 0.50000 * frame.width, y: frame.minY + 0.78265 * frame.height))
starShapePath.addLine(to: CGPoint(x: frame.minX + 0.79358 * frame.width, y: frame.minY + 0.97500 * frame.height))
starShapePath.addLine(to: CGPoint(x: frame.minX + 0.69501 * frame.width, y: frame.minY + 0.62908 * frame.height))
starShapePath.addLine(to: CGPoint(x: frame.minX + 0.97500 * frame.width, y: frame.minY + 0.39112 * frame.height))
starShapePath.addLine(to: CGPoint(x: frame.minX + 0.62723 * frame.width, y: frame.minY + 0.37309 * frame.height))
starShapePath.close()
starShapePath.miterLimit = 4
let frameWidth = frame.size.width
let rightRectOfStar = CGRect(x: frame.origin.x + progress * frameWidth, y: frame.origin.y, width: frameWidth - progress * frameWidth, height: frame.size.height)
let clipPath = UIBezierPath(rect: CGRect.infinite)
clipPath.append(UIBezierPath(rect: rightRectOfStar))
clipPath.usesEvenOddFillRule = true
UIGraphicsGetCurrentContext()!.saveGState()
clipPath.addClip()
tintColor.setFill()
starShapePath.fill()
UIGraphicsGetCurrentContext()!.restoreGState()
tintColor.setStroke()
starShapePath.lineWidth = 1
starShapePath.stroke()
}
}
extension SwiftyStarRatingView {
override public func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
if isEnabled {
super.beginTracking(touch, with: event)
if shouldBecomeFirstResponder && !self.isFirstResponder {
self.becomeFirstResponder()
}
self.handle(touch: touch)
}
return isEnabled
}
override public func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
if isEnabled {
super.continueTracking(touch, with: event)
self.handle(touch: touch)
}
return isEnabled
}
override public func endTracking(_ touch: UITouch?, with event: UIEvent?) {
super.endTracking(touch, with: event)
if shouldBecomeFirstResponder && self.isFirstResponder {
self.resignFirstResponder()
}
self.handle(touch: touch!)
if !continuous {
self.sendActions(for: .valueChanged)
}
}
override public func cancelTracking(with event: UIEvent?) {
super.cancelTracking(with: event)
if shouldBecomeFirstResponder && self.isFirstResponder {
self.resignFirstResponder()
}
}
override public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let gestureView = gestureRecognizer.view, gestureView.isEqual(self) {
return !self.isUserInteractionEnabled
} else {
return self.shouldBeginGestureHandler(gestureRecognizer)
}
}
fileprivate func handle(touch: UITouch) {
let cellWidth = self.bounds.width / _maximumValue
let location = touch.location(in: self)
var aValue = location.x / cellWidth
if !allowsHalfStars {
aValue = ceil(aValue)
} else if !accurateHalfStars {
aValue = ceil(2*aValue + 1) / 2.0
}
self.value = aValue
}
}
extension SwiftyStarRatingView {
override public func accessibilityActivate() -> Bool {
return true
}
override public func accessibilityIncrement() {
let increment = allowsHalfStars ? 0.5 : 1.0
self.value += CGFloat(increment)
}
override public func accessibilityDecrement() {
let decrement = allowsHalfStars ? 0.5 : 1.0
self.value -= CGFloat(decrement)
}
}
| gpl-3.0 | 1fca9695f60053350b7702bbf475e2d2 | 35.763006 | 233 | 0.632469 | 4.560774 | false | false | false | false |
aatalyk/swift-algorithm-club | K-Means/KMeans.swift | 8 | 2823 | import Foundation
class KMeans<Label: Hashable> {
let numCenters: Int
let labels: [Label]
private(set) var centroids = [Vector]()
init(labels: [Label]) {
assert(labels.count > 1, "Exception: KMeans with less than 2 centers.")
self.labels = labels
self.numCenters = labels.count
}
private func indexOfNearestCenter(_ x: Vector, centers: [Vector]) -> Int {
var nearestDist = DBL_MAX
var minIndex = 0
for (idx, center) in centers.enumerated() {
let dist = x.distanceTo(center)
if dist < nearestDist {
minIndex = idx
nearestDist = dist
}
}
return minIndex
}
func trainCenters(_ points: [Vector], convergeDistance: Double) {
let zeroVector = Vector([Double](repeating: 0, count: points[0].length))
// Randomly take k objects from the input data to make the initial centroids.
var centers = reservoirSample(points, k: numCenters)
var centerMoveDist = 0.0
repeat {
// This array keeps track of which data points belong to which centroids.
var classification: [[Vector]] = .init(repeating: [], count: numCenters)
// For each data point, find the centroid that it is closest to.
for p in points {
let classIndex = indexOfNearestCenter(p, centers: centers)
classification[classIndex].append(p)
}
// Take the average of all the data points that belong to each centroid.
// This moves the centroid to a new position.
let newCenters = classification.map { assignedPoints in
assignedPoints.reduce(zeroVector, +) / Double(assignedPoints.count)
}
// Find out how far each centroid moved since the last iteration. If it's
// only a small distance, then we're done.
centerMoveDist = 0.0
for idx in 0..<numCenters {
centerMoveDist += centers[idx].distanceTo(newCenters[idx])
}
centers = newCenters
} while centerMoveDist > convergeDistance
centroids = centers
}
func fit(_ point: Vector) -> Label {
assert(!centroids.isEmpty, "Exception: KMeans tried to fit on a non trained model.")
let centroidIndex = indexOfNearestCenter(point, centers: centroids)
return labels[centroidIndex]
}
func fit(_ points: [Vector]) -> [Label] {
assert(!centroids.isEmpty, "Exception: KMeans tried to fit on a non trained model.")
return points.map(fit)
}
}
// Pick k random elements from samples
func reservoirSample<T>(_ samples: [T], k: Int) -> [T] {
var result = [T]()
// Fill the result array with first k elements
for i in 0..<k {
result.append(samples[i])
}
// Randomly replace elements from remaining pool
for i in k..<samples.count {
let j = Int(arc4random_uniform(UInt32(i + 1)))
if j < k {
result[j] = samples[i]
}
}
return result
}
| mit | 4c626fafe33fec0f898a57cbfb197296 | 28.715789 | 88 | 0.654269 | 4.009943 | false | false | false | false |
babyboy18/swift_code | Swifter/SwifterStreaming.swift | 1 | 12150 | //
// SwifterStreaming.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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 Swifter {
/*
POST statuses/filter
Returns public statuses that match one or more filter predicates. Multiple parameters may be specified which allows most clients to use a single connection to the Streaming API. Both GET and POST requests are supported, but GET requests with too many parameters may cause the request to be rejected for excessive URL length. Use a POST request to avoid long URLs.
The track, follow, and locations fields should be considered to be combined with an OR operator. track=foo&follow=1234 returns Tweets matching "foo" OR created by user 1234.
The default access level allows up to 400 track keywords, 5,000 follow userids and 25 0.1-360 degree location boxes. If you need elevated access to the Streaming API, you should explore our partner providers of Twitter data here: https://dev.twitter.com/programs/twitter-certified-products/products#Certified-Data-Products
At least one predicate parameter (follow, locations, or track) must be specified.
*/
public func postStatusesFilterWithFollow(follow: [String]?, track: [String]?, locations: [String]?, delimited: Bool?, stallWarnings: Bool?, progress: ((status: Dictionary<String, JSONValue>?) -> Void)?, stallWarningHandler: ((code: String?, message: String?, percentFull: Int?) -> Void)?, failure: FailureHandler?) -> SwifterHTTPRequest {
assert(follow != nil || track != nil || locations != nil, "At least one predicate parameter (follow, locations, or track) must be specified")
let path = "statuses/filter.json"
var parameters = Dictionary<String, AnyObject>()
if follow != nil {
parameters["follow"] = join(",", follow!)
}
if track != nil {
parameters["track"] = join(",", track!)
}
if locations != nil {
parameters["locations"] = join(",", locations!)
}
if delimited != nil {
parameters["delimited"] = delimited!
}
if stallWarnings != nil {
parameters["stall_warnings"] = stallWarnings!
}
return self.postJSONWithPath(path, baseURL: self.streamURL, parameters: parameters, uploadProgress: nil, downloadProgress: {
json, response in
if let stallWarning = json["warning"].object {
switch (stallWarning["code"]?.string, stallWarning["message"]?.string, stallWarning["percent_full"]?.integer) {
case (let code , let message, let percentFull):
stallWarningHandler?(code: code, message: message, percentFull: percentFull)
default:
stallWarningHandler?(code: nil, message: nil, percentFull: nil)
}
}
else {
progress?(status: json.object)
}
}, success: {
json, response in
progress?(status: json.object)
return
}, failure: failure)
}
/*
GET statuses/sample
Returns a small random sample of all public statuses. The Tweets returned by the default access level are the same, so if two different clients connect to this endpoint, they will see the same Tweets.
*/
public func getStatusesSampleDelimited(delimited: Bool?, stallWarnings: Bool?, progress: ((status: Dictionary<String, JSONValue>?) -> Void)?, stallWarningHandler: ((code: String?, message: String?, percentFull: Int?) -> Void)?, failure: FailureHandler?) -> SwifterHTTPRequest {
let path = "statuses/sample.json"
var parameters = Dictionary<String, AnyObject>()
if delimited != nil {
parameters["delimited"] = delimited!
}
if stallWarnings != nil {
parameters["stall_warnings"] = stallWarnings!
}
return self.getJSONWithPath(path, baseURL: self.streamURL, parameters: parameters, uploadProgress: nil, downloadProgress: {
json, response in
if let stallWarning = json["warning"].object {
switch (stallWarning["code"]?.string, stallWarning["message"]?.string, stallWarning["percent_full"]?.integer) {
case (let code , let message, let percentFull):
stallWarningHandler?(code: code, message: message, percentFull: percentFull)
default:
stallWarningHandler?(code: nil, message: nil, percentFull: nil)
}
}
else {
progress?(status: json.object)
}
}, success: {
json, response in
progress?(status: json.object)
return
}, failure: failure)
}
/*
GET statuses/firehose
This endpoint requires special permission to access.
Returns all public statuses. Few applications require this level of access. Creative use of a combination of other resources and various access levels can satisfy nearly every application use case.
*/
public func getStatusesFirehose(count: Int?, delimited: Bool?, stallWarnings: Bool?, progress: ((status: Dictionary<String, JSONValue>?) -> Void)?, stallWarningHandler: ((code: String?, message: String?, percentFull: Int?) -> Void)?, failure: FailureHandler?) -> SwifterHTTPRequest {
let path = "statuses/firehose.json"
var parameters = Dictionary<String, AnyObject>()
if count != nil {
parameters["count"] = count!
}
if delimited != nil {
parameters["delimited"] = delimited!
}
if stallWarnings != nil {
parameters["stall_warnings"] = stallWarnings!
}
return self.getJSONWithPath(path, baseURL: self.streamURL, parameters: parameters, uploadProgress: nil, downloadProgress: {
json, response in
if let stallWarning = json["warning"].object {
switch (stallWarning["code"]?.string, stallWarning["message"]?.string, stallWarning["percent_full"]?.integer) {
case (let code , let message, let percentFull):
stallWarningHandler?(code: code, message: message, percentFull: percentFull)
default:
stallWarningHandler?(code: nil, message: nil, percentFull: nil)
}
}
else {
progress?(status: json.object)
}
}, success: {
json, response in
progress?(status: json.object)
return
}, failure: failure)
}
/*
GET user
Streams messages for a single user, as described in User streams https://dev.twitter.com/docs/streaming-apis/streams/user
*/
public func getUserStreamDelimited(delimited: Bool?, stallWarnings: Bool?, includeMessagesFromFollowedAccounts: Bool?, includeReplies: Bool?, track: [String]?, locations: [String]?, stringifyFriendIDs: Bool?, progress: ((status: Dictionary<String, JSONValue>?) -> Void)?, stallWarningHandler: ((code: String?, message: String?, percentFull: Int?) -> Void)?, failure: FailureHandler?) -> SwifterHTTPRequest {
let path = "user.json"
var parameters = Dictionary<String, AnyObject>()
if delimited != nil {
parameters["delimited"] = delimited!
}
if stallWarnings != nil {
parameters["stall_warnings"] = stallWarnings!
}
if includeMessagesFromFollowedAccounts != nil {
if includeMessagesFromFollowedAccounts! {
parameters["with"] = "user"
}
}
if includeReplies != nil {
if includeReplies! {
parameters["replies"] = "all"
}
}
if track != nil {
parameters["track"] = join(",", track!)
}
if locations != nil {
parameters["locations"] = join(",", locations!)
}
if stringifyFriendIDs != nil {
parameters["stringify_friend_ids"] = stringifyFriendIDs!
}
return self.getJSONWithPath(path, baseURL: self.userStreamURL, parameters: parameters, uploadProgress: nil, downloadProgress: {
json, response in
if let stallWarning = json["warning"].object {
switch (stallWarning["code"]?.string, stallWarning["message"]?.string, stallWarning["percent_full"]?.integer) {
case (let code , let message, let percentFull):
stallWarningHandler?(code: code, message: message, percentFull: percentFull)
default:
stallWarningHandler?(code: nil, message: nil, percentFull: nil)
}
}
else {
progress?(status: json.object)
}
}, success: {
json, response in
progress?(status: json.object)
return
}, failure: failure)
}
/*
GET site
Streams messages for a set of users, as described in Site streams https://dev.twitter.com/docs/streaming-apis/streams/site
*/
public func getSiteStreamDelimited(delimited: Bool?, stallWarnings: Bool?, restrictToUserMessages: Bool?, includeReplies: Bool?, stringifyFriendIDs: Bool?, progress: ((status: Dictionary<String, JSONValue>?) -> Void)?, stallWarningHandler: ((code: String?, message: String?, percentFull: Int?) -> Void)?, failure: FailureHandler?) -> SwifterHTTPRequest {
let path = "site.json"
var parameters = Dictionary<String, AnyObject>()
if delimited != nil {
parameters["delimited"] = delimited!
}
if stallWarnings != nil {
parameters["stall_warnings"] = stallWarnings!
}
if restrictToUserMessages != nil {
if restrictToUserMessages! {
parameters["with"] = "user"
}
}
if includeReplies != nil {
if includeReplies! {
parameters["replies"] = "all"
}
}
if stringifyFriendIDs != nil {
parameters["stringify_friend_ids"] = stringifyFriendIDs!
}
return self.getJSONWithPath(path, baseURL: self.streamURL, parameters: parameters, uploadProgress: nil, downloadProgress: {
json, response in
switch (json["warning"]["code"].string, json["warning"]["message"].string, json["warning"]["percent_full"].integer) {
case (let code , let message, let percentFull):
stallWarningHandler?(code: code, message: message, percentFull: percentFull)
default:
stallWarningHandler?(code: nil, message: nil, percentFull: nil)
}
}, success: {
json, response in
progress?(status: json.object)
return
}, failure: failure)
}
}
| mit | fbea66afccf966aff051a5b1b9db30a6 | 42.548387 | 411 | 0.611276 | 4.963235 | false | false | false | false |
therealbnut/swift | test/SILGen/protocol_class_refinement.swift | 2 | 3989 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
protocol UID {
func uid() -> Int
var clsid: Int { get set }
var iid: Int { get }
}
extension UID {
var nextCLSID: Int {
get { return clsid + 1 }
set { clsid = newValue - 1 }
}
}
protocol ObjectUID : class, UID {}
extension ObjectUID {
var secondNextCLSID: Int {
get { return clsid + 2 }
set { }
}
}
class Base {}
// CHECK-LABEL: sil hidden @_TF25protocol_class_refinement12getObjectUID
func getObjectUID<T: ObjectUID>(x: T) -> (Int, Int, Int, Int) {
var x = x
// CHECK: [[XBOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ObjectUID> { var τ_0_0 } <T>
// CHECK: [[PB:%.*]] = project_box [[XBOX]]
// -- call x.uid()
// CHECK: [[X:%.*]] = load [copy] [[PB]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: [[X2:%.*]] = load [take] [[X_TMP]]
// CHECK: destroy_value [[X2]]
// -- call set x.clsid
// CHECK: [[SET_CLSID:%.*]] = witness_method $T, #UID.clsid!setter.1
// CHECK: apply [[SET_CLSID]]<T>([[UID]], [[PB]])
x.clsid = x.uid()
// -- call x.uid()
// CHECK: [[X:%.*]] = load [copy] [[PB]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: [[X2:%.*]] = load [take] [[X_TMP]]
// CHECK: destroy_value [[X2]]
// -- call nextCLSID from protocol ext
// CHECK: [[SET_NEXTCLSID:%.*]] = function_ref @_TFE25protocol_class_refinementPS_3UIDs9nextCLSIDSi
// CHECK: apply [[SET_NEXTCLSID]]<T>([[UID]], [[PB]])
x.nextCLSID = x.uid()
// -- call x.uid()
// CHECK: [[X1:%.*]] = load [copy] [[PB]]
// CHECK: [[X:%.*]] = load [copy] [[PB]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: [[X2:%.*]] = load [take] [[X_TMP]]
// CHECK: destroy_value [[X2]]
// -- call secondNextCLSID from class-constrained protocol ext
// CHECK: [[SET_SECONDNEXT:%.*]] = function_ref @_TFE25protocol_class_refinementPS_9ObjectUIDs15secondNextCLSIDSi
// CHECK: apply [[SET_SECONDNEXT]]<T>([[UID]], [[X1]])
// CHECK: destroy_value [[X1]]
x.secondNextCLSID = x.uid()
return (x.iid, x.clsid, x.nextCLSID, x.secondNextCLSID)
}
// CHECK-LABEL: sil hidden @_TF25protocol_class_refinement16getBaseObjectUID
func getBaseObjectUID<T: UID where T: Base>(x: T) -> (Int, Int, Int) {
var x = x
// CHECK: [[XBOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : Base, τ_0_0 : UID> { var τ_0_0 } <T>
// CHECK: [[PB:%.*]] = project_box [[XBOX]]
// -- call x.uid()
// CHECK: [[X:%.*]] = load [copy] [[PB]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: [[X2:%.*]] = load [take] [[X_TMP]]
// CHECK: destroy_value [[X2]]
// -- call set x.clsid
// CHECK: [[SET_CLSID:%.*]] = witness_method $T, #UID.clsid!setter.1
// CHECK: apply [[SET_CLSID]]<T>([[UID]], [[PB]])
x.clsid = x.uid()
// -- call x.uid()
// CHECK: [[X:%.*]] = load [copy] [[PB]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: [[X2:%.*]] = load [take] [[X_TMP]]
// CHECK: destroy_value [[X2]]
// -- call nextCLSID from protocol ext
// CHECK: [[SET_NEXTCLSID:%.*]] = function_ref @_TFE25protocol_class_refinementPS_3UIDs9nextCLSIDSi
// CHECK: apply [[SET_NEXTCLSID]]<T>([[UID]], [[PB]])
x.nextCLSID = x.uid()
return (x.iid, x.clsid, x.nextCLSID)
}
| apache-2.0 | 8df7b8198e1cfccdffa41421f889b33a | 36.214953 | 115 | 0.538172 | 2.85448 | false | false | false | false |
doo/das-quadrat | Source/Shared/DataCache.swift | 1 | 8979 | //
// DataCache.swift
// Quadrat
//
// Created by Constantine Fry on 01/12/14.
// Copyright (c) 2014 Constantine Fry. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
#endif
/** Configs for data cache. */
struct DataCacheConfiguration {
/** Time to keep a data in cache in seconds. Default is 1 week. */
private let maxCacheAge = (60 * 60 * 24 * 7) as NSTimeInterval
/** The maximum size for disk cache in bytes. Default is 10MB. */
private let maxDiskCacheSize = (1024 * 1024 * 10) as UInt
/** The maximum size for memory cache in bytes. Default is 10MB. */
private let maxMemoryCacheSize = (1024 * 1024 * 10) as UInt
}
/** The queue for I/O operations. Shared between several instances. */
private let privateQueue = NSOperationQueue()
/** Responsible for caching data on disk and memory. Thread safe. */
class DataCache {
/** Logger to log all errors. */
var logger : Logger?
/** The URL to directory where we put all the files. */
private let directoryURL: NSURL
/** In memory cache for NSData. */
private let cache = NSCache()
/** Obsever objects from NSNotificationCenter. */
private var observers = [AnyObject]()
/** The file manager to use for all file operations. */
private let fileManager = NSFileManager.defaultManager()
/** The configuration for cache. */
private let cacheConfiguration = DataCacheConfiguration()
init(name: String?) {
cache.totalCostLimit = Int(cacheConfiguration.maxMemoryCacheSize);
let directoryName = "net.foursquare.quadrat"
let subdirectiryName = (name != nil) ? ( "Cache" + name! ) : "DefaultCache"
let cacheURL = fileManager.URLForDirectory(.CachesDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true, error: nil)
directoryURL = cacheURL!.URLByAppendingPathComponent(directoryName).URLByAppendingPathComponent("DataCache").URLByAppendingPathComponent(subdirectiryName)
privateQueue.maxConcurrentOperationCount = 1
createBaseDirectory()
subscribeForNotifications()
}
deinit {
for observer in observers {
NSNotificationCenter.defaultCenter().removeObserver(observer)
}
}
/** Returns data for key. */
func dataForKey(key: String) -> NSData? {
var result: NSData?
privateQueue.addOperationWithBlock {
result = self.cache.objectForKey(key) as NSData?
if result == nil {
let targetURL = self.directoryURL.URLByAppendingPathComponent(key)
result = NSData(contentsOfURL: targetURL)
if result != nil {
self.cache.setObject(result!, forKey: key, cost: result!.length)
}
}
}
privateQueue.waitUntilAllOperationsAreFinished()
return result
}
/** Copies file into cache. */
func addFileAtURL(URL: NSURL, withKey key: String) {
privateQueue.addOperationWithBlock { () -> Void in
let targetURL = self.directoryURL.URLByAppendingPathComponent(key)
var error: NSError?
let copied = self.fileManager.copyItemAtURL(URL, toURL: targetURL, error: &error)
if !copied {
self.logger?.logError(error!, withMessage: "Cache can't copy file into cache directory.")
}
}
privateQueue.waitUntilAllOperationsAreFinished()
}
/** Saves data into cache. */
func addData(data: NSData, withKey key: String) {
privateQueue.addOperationWithBlock { () -> Void in
let targetURL = self.directoryURL.URLByAppendingPathComponent(key)
var error: NSError?
let written = data.writeToURL(targetURL, options: .DataWritingAtomic, error: &error)
if !written {
self.logger?.logError(error!, withMessage: "Cache can't save file into cache directory.")
}
}
}
/** Subcribes for iOS specific notifications to perform cache cleaning. */
private func subscribeForNotifications() {
#if os(iOS)
let center = NSNotificationCenter.defaultCenter()
let firstObserver = center.addObserverForName(UIApplicationDidEnterBackgroundNotification, object: nil, queue: nil) {
[unowned self] (notification) -> Void in
self.cleanupCache()
self.cache.removeAllObjects()
}
observers.append(firstObserver)
let secondObserver = center.addObserverForName(UIApplicationDidReceiveMemoryWarningNotification, object: nil, queue: nil) {
[unowned self] (notification) -> Void in
self.cache.removeAllObjects()
}
observers.append(secondObserver)
#endif
}
/** Creates base directory. */
private func createBaseDirectory() {
var error: NSError?
let created = fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil, error: &error)
if !created {
self.logger?.logError(error!, withMessage: "Cacho can't create base directory.")
}
}
/** Removes all cached files. */
func clearCache() {
privateQueue.addOperationWithBlock {
self.cache.removeAllObjects()
var error: NSError?
let removed = self.fileManager.removeItemAtURL(self.directoryURL, error: &error)
if !removed {
self.logger?.logError(error!, withMessage: "Cache can't remove base directory.")
}
self.createBaseDirectory()
}
}
/** Removes expired files. In addition removes 1/4 of files if total size exceeds `maxDiskCacheSize`. */
private func cleanupCache() {
privateQueue.addOperationWithBlock {
let expirationDate = NSDate(timeIntervalSinceNow: -self.cacheConfiguration.maxCacheAge)
var error: NSError?
let properties = [NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]
var fileURLs = self.fileManager.contentsOfDirectoryAtURL(self.directoryURL, includingPropertiesForKeys: properties, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error:&error) as [NSURL]?
if fileURLs == nil {
self.logger?.logError(error!, withMessage: "Cache can't get properties of files in base directory.")
return
}
var cacheSize: UInt = 0
var expiredFiles = [NSURL]()
var validFiles = [NSURL]()
/** Searching for expired files and calculation total size. */
for aFileURL in fileURLs! {
let values = aFileURL.resourceValuesForKeys(properties, error: nil) as [String: AnyObject]?
if let modificationDate = values?[NSURLContentModificationDateKey] as NSDate? {
if modificationDate.laterDate(expirationDate).isEqualToDate(modificationDate) {
validFiles.append(aFileURL)
if let fileSize = values?[NSURLTotalFileAllocatedSizeKey] as UInt? {
cacheSize += fileSize
}
} else {
expiredFiles.append(aFileURL)
}
}
}
if cacheSize > self.cacheConfiguration.maxDiskCacheSize {
/** Sorting files by modification date. From oldest to newest. */
validFiles.sort {
(url1: NSURL, url2: NSURL) -> Bool in
let values1 = url1.resourceValuesForKeys([NSURLContentModificationDateKey], error: nil) as [String: NSDate]?
let values2 = url2.resourceValuesForKeys([NSURLContentModificationDateKey], error: nil) as [String: NSDate]?
if let date1 = values1?[NSURLContentModificationDateKey] {
if let date2 = values2?[NSURLContentModificationDateKey] {
return date1.compare(date2) == .OrderedAscending
}
}
return false
}
/** Let's just remove 1/4 of all files. */
validFiles.removeRange(Range(start: 0, end: validFiles.count / 4))
expiredFiles += validFiles
}
for URL in expiredFiles {
var removeError: NSError?
let removed = self.fileManager.removeItemAtURL(URL as NSURL, error: &removeError)
if !removed {
self.logger?.logError(removeError!, withMessage: "Cache can't remove file.")
}
}
}
}
}
| bsd-2-clause | 55f4bd46b03d7e05672398d84578bdba | 40.762791 | 210 | 0.598508 | 5.485034 | false | false | false | false |
attaswift/Attabench | attachart/Options.swift | 2 | 2897 | // Copyright © 2017 Károly Lőrentey.
// This file is part of Attabench: https://github.com/lorentey/Attabench
// For licensing information, see the file LICENSE.md in the Git repository above.
import Cocoa
import OptionParser
import BenchmarkModel
import BenchmarkCharts
struct Options {
enum Command {
case listTasks
case listThemes
case render
}
enum Preset: String, OptionValue {
case none = "none"
case optimizingCollections = "OptimizingCollections"
}
var input: String = ""
var output: String = ""
var command: Command = .render
var tasks: [String] = []
var minSize: Int? = nil
var maxSize: Int? = nil
var minTime: Time? = nil
var maxTime: Time? = nil
var amortized: Bool = true
var logarithmicSize = true
var logarithmicTime = true
var preset: Preset = .none
var topBand: BandOption? = nil
var centerBand: BandOption? = nil
var bottomBand: BandOption? = nil
var theme: String? = nil
var width: Int? = nil
var height: Int? = nil
var scale: Int? = nil
var labelFontName: String? = nil
var monoFontName: String? = nil
var branding: Bool? = nil
mutating func applyPreset() {
switch preset {
case .none:
break
case .optimizingCollections:
topBand = topBand ?? BandOption(nil)
centerBand = centerBand ?? BandOption(.average)
bottomBand = bottomBand ?? BandOption(nil)
theme = theme ?? BenchmarkTheme.Predefined.colorPrint.name
width = width ?? 800
height = height ?? 260
scale = scale ?? 4
labelFontName = labelFontName ?? "Tiempos Text"
monoFontName = monoFontName ?? "Akkurat TT"
branding = branding ?? false
minSize = minSize ?? 1
maxSize = maxSize ?? (1 << 22)
}
}
}
struct BandOption: OptionValue {
let value: TimeSample.Band?
init(_ value: TimeSample.Band?) {
self.value = value
}
init(fromOptionValue string: String) throws {
switch string {
case "off", "none": self.value = nil
case "average", "avg": self.value = .average
case "minimum", "min": self.value = .minimum
case "maximum", "max": self.value = .maximum
case "sigma1", "s1": self.value = .sigma(1)
case "sigma2", "s2": self.value = .sigma(2)
case "sigma3", "s3": self.value = .sigma(3)
default:
throw OptionError("Invalid band value '\(string)' (expected: off|average|minimum|maximum|sigma1|sigma2|sigma3")
}
}
}
extension Time: OptionValue {
public init(fromOptionValue string: String) throws {
guard let value = Time(string) else {
throw OptionError("Invalid time value: '\(string)'")
}
self = value
}
}
| mit | 516f1afa43a923ef00781d29f6a0cbc0 | 27.372549 | 123 | 0.596406 | 4.164029 | false | false | false | false |
wesj/firefox-ios-1 | ClientTests/TestHistory.swift | 1 | 8371 | import Foundation
import XCTest
import Storage
class TestHistory : ProfileTest {
private func innerAddSite(history: History, url: String, title: String, callback: (success: Bool) -> Void) {
// Add an entry
let site = Site(url: url, title: title)
let visit = Visit(site: site, date: NSDate())
history.addVisit(visit) { success in
callback(success: success)
}
}
private func addSite(history: History, url: String, title: String, s: Bool = true) {
let expectation = self.expectationWithDescription("Wait for history")
innerAddSite(history, url: url, title: title) { success in
XCTAssertEqual(success, s, "Site added \(url)")
expectation.fulfill()
}
}
private func innerCheckSites(history: History, callback: (cursor: Cursor) -> Void) {
// Retrieve the entry
history.get(nil, complete: { cursor in
callback(cursor: cursor)
})
}
private func checkSites(history: History, urls: [String: String], s: Bool = true) {
let expectation = self.expectationWithDescription("Wait for history")
// Retrieve the entry
innerCheckSites(history) { cursor in
XCTAssertEqual(cursor.status, CursorStatus.Success, "returned success \(cursor.statusMessage)")
XCTAssertEqual(cursor.count, urls.count, "cursor has \(urls.count) entries")
for index in 0..<cursor.count {
let s = cursor[index] as Site
XCTAssertNotNil(s, "cursor has a site for entry")
let title = urls[s.url]
XCTAssertNotNil(title, "Found right url")
XCTAssertEqual(s.title, title!, "Found right title")
}
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(100, handler: nil)
}
private func innerClear(history: History, callback: (s: Bool) -> Void) {
history.clear({ success in
callback(s: success)
})
}
private func clear(history: History, s: Bool = true) {
let expectation = self.expectationWithDescription("Wait for history")
innerClear(history) { success in
XCTAssertEqual(s, success, "Sites cleared")
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(100, handler: nil)
}
private func checkVisits(history: History, url: String) {
let expectation = self.expectationWithDescription("Wait for history")
history.get(nil) { cursor in
let options = QueryOptions()
options.filter = url
history.get(options) { cursor in
XCTAssertEqual(cursor.status, CursorStatus.Success, "returned success \(cursor.statusMessage)")
// XXX - We don't allow querying much info about visits here anymore, so there isn't a lot to do
expectation.fulfill()
}
}
self.waitForExpectationsWithTimeout(100, handler: nil)
}
// This is a very basic test. Adds an entry. Retrieves it, and then clears the database
func testHistory() {
withTestProfile { profile -> Void in
let h = profile.history
self.addSite(h, url: "url1", title: "title")
self.addSite(h, url: "url1", title: "title")
self.addSite(h, url: "url1", title: "title 2")
self.addSite(h, url: "url2", title: "title")
self.addSite(h, url: "url2", title: "title")
self.checkSites(h, urls: ["url1": "title 2", "url2": "title"])
self.checkVisits(h, url: "url1")
self.checkVisits(h, url: "url2")
self.clear(h)
}
}
func testAboutUrls() {
withTestProfile { (profile) -> Void in
let h = profile.history
self.addSite(h, url: "about:home", title: "About Home", s: false)
self.clear(h)
}
}
let NumThreads = 5
let NumCmds = 10
func testInsertPerformance() {
withTestProfile { profile -> Void in
let h = profile.history
var j = 0
self.measureBlock({ () -> Void in
for i in 0...self.NumCmds {
self.addSite(h, url: "url \(j)", title: "title \(j)")
j++
}
self.clear(h)
})
}
}
func testGetPerformance() {
withTestProfile { profile -> Void in
let h = profile.history
var j = 0
var urls = [String: String]()
self.clear(h)
for i in 0...self.NumCmds {
self.addSite(h, url: "url \(j)", title: "title \(j)")
urls["url \(j)"] = "title \(j)"
j++
}
self.measureBlock({ () -> Void in
self.checkSites(h, urls: urls)
return
})
self.clear(h)
}
}
// Fuzzing tests. These fire random insert/query/clear commands into the history database from threads. The don't check
// the results. Just look for crashes.
func testRandomThreading() {
withTestProfile { profile -> Void in
var queue = dispatch_queue_create("My Queue", DISPATCH_QUEUE_CONCURRENT)
var done = [Bool]()
var counter = 0
let expectation = self.expectationWithDescription("Wait for history")
for i in 0..<self.NumThreads {
var history = profile.history
self.runRandom(&history, queue: queue, cb: { () -> Void in
counter++
if counter == self.NumThreads {
expectation.fulfill()
}
})
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
}
// Same as testRandomThreading, but uses one history connection for all threads
func testRandomThreading2() {
withTestProfile { profile -> Void in
var queue = dispatch_queue_create("My Queue", DISPATCH_QUEUE_CONCURRENT)
var history = profile.history
var counter = 0
let expectation = self.expectationWithDescription("Wait for history")
for i in 0..<self.NumThreads {
self.runRandom(&history, queue: queue, cb: { () -> Void in
counter++
if counter == self.NumThreads {
expectation.fulfill()
}
})
}
self.waitForExpectationsWithTimeout(10, handler: nil)
}
}
// Runs a random command on a database. Calls cb when finished
private func runRandom(inout history: History, cmdIn: Int, cb: () -> Void) {
var cmd = cmdIn
if cmd < 0 {
cmd = Int(rand() % 5)
}
switch cmd {
case 0...1:
let url = "url \(rand() % 100)"
let title = "title \(rand() % 100)"
innerAddSite(history, url: url, title: title) { success in cb() }
case 2...3:
innerCheckSites(history) { cursor in
for site in cursor {
let s = site as Site
}
}
cb()
default:
innerClear(history) { success in cb() }
}
}
// Calls numCmds random methods on this database. val is a counter used by this interally (i.e. always pass zero for it)
// Calls cb when finished
private func runMultiRandom(inout history: History, val: Int, numCmds: Int, cb: () -> Void) {
if val == numCmds {
cb()
return
} else {
runRandom(&history, cmdIn: -1) { _ in
self.runMultiRandom(&history, val: val+1, numCmds: numCmds, cb: cb)
}
}
}
// Helper for starting a new thread running NumCmds random methods on it. Calls cb when done
private func runRandom(inout history: History, queue: dispatch_queue_t, cb: () -> Void) {
dispatch_async(queue) {
// Each thread creates its own history provider
self.runMultiRandom(&history, val: 0, numCmds: self.NumCmds) { _ in
dispatch_async(dispatch_get_main_queue(), cb)
}
}
}
} | mpl-2.0 | 59ac4b6d1ffe05849016255efd1e3640 | 34.324895 | 124 | 0.542707 | 4.529762 | false | true | false | false |
cplaverty/KeitaiWaniKani | WaniKaniKit/WaniKaniURL.swift | 1 | 1691 | //
// WaniKaniURL.swift
// WaniKaniKit
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
public struct WaniKaniURL {
public static let home = URL(string: "https://www.wanikani.com/")!
public static let communityCentre = URL(string: "https://community.wanikani.com/")!
public static let loginPage = home.appendingPathComponent("login")
public static let dashboard = home.appendingPathComponent("dashboard")
public static let tokenSettings = home.appendingPathComponent("settings").appendingPathComponent("personal_access_tokens")
public static let reviewHome = home.appendingPathComponent("review")
public static let reviewSession = reviewHome.appendingPathComponent("session")
public static let lessonHome = home.appendingPathComponent("lesson")
public static let lessonSession = lessonHome.appendingPathComponent("session")
public static let levelRoot = home.appendingPathComponent("level")
public static let radicalRoot = home.appendingPathComponent("radicals")
public static let kanjiRoot = home.appendingPathComponent("kanji")
public static let vocabularyRoot = home.appendingPathComponent("vocabulary")
public static let appForumTopic = forumTopic(withRelativePath: "ios-mobile-allicrab-for-wanikani/10065")
public static func forumTopic(withRelativePath path: String) -> URL {
guard let path = path.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlPathAllowed) else {
fatalError("Unable to encode path '{path}'!")
}
return communityCentre.appendingPathComponent("t").appendingPathComponent(path).absoluteURL
}
}
| mit | 9e243fe3c42fc5a79d1a1a69183dbbe7 | 44.675676 | 126 | 0.73787 | 5.10574 | false | false | false | false |
tkremenek/swift | test/Concurrency/global_actor_inference.swift | 1 | 19143 | // RUN: %target-typecheck-verify-swift -enable-experimental-concurrency -disable-availability-checking
// REQUIRES: concurrency
actor SomeActor { }
@globalActor
struct SomeGlobalActor {
static let shared = SomeActor()
}
@globalActor
struct OtherGlobalActor {
static let shared = SomeActor()
}
@globalActor
struct GenericGlobalActor<T> {
static var shared: SomeActor { SomeActor() }
}
// ----------------------------------------------------------------------
// Check that MainActor exists
// ----------------------------------------------------------------------
@MainActor protocol Aluminium {
func method()
}
@MainActor class Copper {}
@MainActor func iron() {}
// ----------------------------------------------------------------------
// Check that @MainActor(blah) doesn't work
// ----------------------------------------------------------------------
// expected-error@+1{{global actor attribute 'MainActor' argument can only be '(unsafe)'}}
@MainActor(blah) func brokenMainActorAttr() { }
// ----------------------------------------------------------------------
// Global actor inference for protocols
// ----------------------------------------------------------------------
@SomeGlobalActor
protocol P1 {
func method()
}
protocol P2 {
@SomeGlobalActor func method1() // expected-note {{'method1()' declared here}}
func method2()
}
class C1: P1 {
func method() { } // expected-note {{calls to instance method 'method()' from outside of its actor context are implicitly asynchronous}}
@OtherGlobalActor func testMethod() {
method() // expected-error {{call to global actor 'SomeGlobalActor'-isolated instance method 'method()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
_ = method
}
}
class C2: P2 {
func method1() { } // expected-note {{calls to instance method 'method1()' from outside of its actor context are implicitly asynchronous}}
func method2() { }
@OtherGlobalActor func testMethod() {
method1() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method1()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
_ = method1
method2() // okay
}
}
struct AllInP1: P1 {
func method() { } // expected-note {{calls to instance method 'method()' from outside of its actor context are implicitly asynchronous}}
func other() { } // expected-note {{calls to instance method 'other()' from outside of its actor context are implicitly asynchronous}}
}
func testAllInP1(ap1: AllInP1) { // expected-note 2 {{add '@SomeGlobalActor' to make global function 'testAllInP1(ap1:)' part of global actor 'SomeGlobalActor'}}
ap1.method() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method()' in a synchronous nonisolated context}}
ap1.other() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'other()' in a synchronous nonisolated context}}
}
struct NotAllInP1 {
func other() { }
}
extension NotAllInP1: P1 {
func method() { } // expected-note{{calls to instance method 'method()' from outside of its actor context are implicitly asynchronous}}
}
func testNotAllInP1(nap1: NotAllInP1) { // expected-note{{add '@SomeGlobalActor' to make global function 'testNotAllInP1(nap1:)' part of global actor 'SomeGlobalActor'}}
nap1.method() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method()' in a synchronous nonisolated context}}
nap1.other() // okay
}
// ----------------------------------------------------------------------
// Global actor inference for classes and extensions
// ----------------------------------------------------------------------
@SomeGlobalActor class C3 {
func method1() { } // expected-note {{calls to instance method 'method1()' from outside of its actor context are implicitly asynchronous}}
}
extension C3 {
func method2() { } // expected-note {{calls to instance method 'method2()' from outside of its actor context are implicitly asynchronous}}
}
class C4: C3 {
func method3() { } // expected-note {{calls to instance method 'method3()' from outside of its actor context are implicitly asynchronous}}
}
extension C4 {
func method4() { } // expected-note {{calls to instance method 'method4()' from outside of its actor context are implicitly asynchronous}}
}
class C5 {
func method1() { }
}
@SomeGlobalActor extension C5 {
func method2() { } // expected-note {{calls to instance method 'method2()' from outside of its actor context are implicitly asynchronous}}
}
@OtherGlobalActor func testGlobalActorInference(c3: C3, c4: C4, c5: C5) {
// Propagation via class annotation
c3.method1() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method1()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
c3.method2() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method2()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
_ = c3.method1
_ = c3.method2
// Propagation via subclassing
c4.method3() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method3()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
c4.method4() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method4()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
_ = c4.method3
_ = c4.method4
// Propagation in an extension.
c5.method1() // OK: no propagation
c5.method2() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'method2()' in a synchronous global actor 'OtherGlobalActor'-isolated context}}
_ = c5.method1 // OK
_ = c5.method2
}
protocol P3 {
@OtherGlobalActor func method1() // expected-note{{'method1()' declared here}}
func method2()
}
class C6: P2, P3 {
func method1() { }
// expected-error@-1{{instance method 'method1()' must be isolated to the global actor 'SomeGlobalActor' to satisfy corresponding requirement from protocol 'P2'}}
// expected-error@-2{{instance method 'method1()' must be isolated to the global actor 'OtherGlobalActor' to satisfy corresponding requirement from protocol 'P3'}}
func method2() { }
func testMethod() {
method1() // okay: no inference
method2() // okay: no inference
let _ = method1 // okay: no inference
let _ = method2 // okay: no inference
}
}
// ----------------------------------------------------------------------
// Global actor checking for overrides
// ----------------------------------------------------------------------
actor GenericSuper<T> {
@GenericGlobalActor<T> func method() { } // expected-note {{overridden declaration is here}}
@GenericGlobalActor<T> func method2() { } // expected-note {{overridden declaration is here}}
@GenericGlobalActor<T> func method3() { } // expected-note {{overridden declaration is here}}
@GenericGlobalActor<T> func method4() { }
@GenericGlobalActor<T> func method5() { }
}
actor GenericSub<T> : GenericSuper<[T]> { // expected-error{{actor types do not support inheritance}}
override func method() { } // expected-note {{calls to instance method 'method()' from outside of its actor context are implicitly asynchronous}}
// expected-error@-1{{instance method overrides a 'final' instance method}}
@GenericGlobalActor<T> override func method2() { } // expected-error{{instance method overrides a 'final' instance method}}
nonisolated override func method3() { } // expected-error{{instance method overrides a 'final' instance method}}
@OtherGlobalActor func testMethod() {
method() // expected-error{{actor-isolated instance method 'method()' can not be referenced from global actor 'OtherGlobalActor'}}
_ = method // expected-error{{actor-isolated instance method 'method()' can not be partially applied}}
}
}
// ----------------------------------------------------------------------
// Global actor inference for superclasses
// ----------------------------------------------------------------------
struct Container<T> {
@GenericGlobalActor<T> class Superclass { }
@GenericGlobalActor<[T]> class Superclass2 { }
}
struct OtherContainer<U> {
// NOT Okay to change the global actor in a subclass.
@GenericGlobalActor<[U]> class Subclass1 : Container<[U]>.Superclass { }
@GenericGlobalActor<U> class Subclass2 : Container<[U]>.Superclass { }
// expected-error@-1{{global actor 'GenericGlobalActor<U>'-isolated class 'Subclass2' has different actor isolation from global actor 'GenericGlobalActor<T>'-isolated superclass 'Superclass'}}
// Ensure that substitutions work properly when inheriting.
class Subclass3<V> : Container<(U, V)>.Superclass2 {
func method() { }
@OtherGlobalActor func testMethod() async {
await method()
let _ = method
}
}
}
class SuperclassWithGlobalActors {
@GenericGlobalActor<Int> func f() { }
@GenericGlobalActor<Int> func g() { } // expected-note{{overridden declaration is here}}
func h() { }
func i() { }
func j() { }
}
@GenericGlobalActor<String> // expected-error@+1{{global actor 'GenericGlobalActor<String>'-isolated class 'SubclassWithGlobalActors' has different actor isolation from nonisolated superclass 'SuperclassWithGlobalActors'}}
class SubclassWithGlobalActors : SuperclassWithGlobalActors {
override func f() { } // okay: inferred to @GenericGlobalActor<Int>
@GenericGlobalActor<String> override func g() { } // expected-error{{global actor 'GenericGlobalActor<String>'-isolated instance method 'g()' has different actor isolation from global actor 'GenericGlobalActor<Int>'-isolated overridden declaration}}
override func h() { } // okay: inferred to unspecified
func onGenericGlobalActorString() { }
@GenericGlobalActor<Int> func onGenericGlobalActorInt() { }
}
// ----------------------------------------------------------------------
// Global actor inference for unspecified contexts
// ----------------------------------------------------------------------
// expected-note@+1 {{calls to global function 'foo()' from outside of its actor context are implicitly asynchronous}}
@SomeGlobalActor func foo() { sibling() }
@SomeGlobalActor func sibling() { foo() }
func bar() async {
// expected-error@+1{{expression is 'async' but is not marked with 'await'}}{{3-3=await }}
foo() // expected-note{{calls to global function 'foo()' from outside of its actor context are implicitly asynchronous}}
}
// expected-note@+1 {{add '@SomeGlobalActor' to make global function 'barSync()' part of global actor 'SomeGlobalActor'}} {{1-1=@SomeGlobalActor }}
func barSync() {
foo() // expected-error {{call to global actor 'SomeGlobalActor'-isolated global function 'foo()' in a synchronous nonisolated context}}
}
// ----------------------------------------------------------------------
// Property wrappers
// ----------------------------------------------------------------------
@propertyWrapper
@OtherGlobalActor
struct WrapperOnActor<Wrapped> {
private var stored: Wrapped
nonisolated init(wrappedValue: Wrapped) {
stored = wrappedValue
}
@MainActor var wrappedValue: Wrapped {
get { }
set { }
}
@SomeGlobalActor var projectedValue: Wrapped {
get { }
set { }
}
}
@MainActor
@propertyWrapper
public struct WrapperOnMainActor<Wrapped> {
// Make sure inference of @MainActor on wrappedValue doesn't crash.
public var wrappedValue: Wrapped
public init(wrappedValue: Wrapped) {
self.wrappedValue = wrappedValue
}
}
@propertyWrapper
actor WrapperActor<Wrapped> {
var storage: Wrapped
init(wrappedValue: Wrapped) {
storage = wrappedValue
}
nonisolated var wrappedValue: Wrapped {
get { }
set { }
}
nonisolated var projectedValue: Wrapped {
get { }
set { }
}
}
struct HasWrapperOnActor {
@WrapperOnActor var synced: Int = 0
// expected-note@-1 3{{property declared here}}
// expected-note@+1 3{{to make instance method 'testErrors()'}}
func testErrors() {
_ = synced // expected-error{{property 'synced' isolated to global actor 'MainActor' can not be referenced from this synchronous context}}
_ = $synced // expected-error{{property '$synced' isolated to global actor 'SomeGlobalActor' can not be referenced from this synchronous context}}
_ = _synced // expected-error{{property '_synced' isolated to global actor 'OtherGlobalActor' can not be referenced from this synchronous context}}
}
@MainActor mutating func testOnMain() {
_ = synced
synced = 17
}
@WrapperActor var actorSynced: Int = 0
func testActorSynced() {
_ = actorSynced
_ = $actorSynced
_ = _actorSynced
}
}
@propertyWrapper
actor WrapperActorBad1<Wrapped> {
var storage: Wrapped
init(wrappedValue: Wrapped) {
storage = wrappedValue
}
var wrappedValue: Wrapped { // expected-error{{'wrappedValue' property in property wrapper type 'WrapperActorBad1' cannot be isolated to the actor instance; consider 'nonisolated'}}}}
get { storage }
set { storage = newValue }
}
}
@propertyWrapper
actor WrapperActorBad2<Wrapped> {
var storage: Wrapped
init(wrappedValue: Wrapped) {
storage = wrappedValue
}
nonisolated var wrappedValue: Wrapped {
get { }
set { }
}
var projectedValue: Wrapped { // expected-error{{'projectedValue' property in property wrapper type 'WrapperActorBad2' cannot be isolated to the actor instance; consider 'nonisolated'}}
get { }
set { }
}
}
@propertyWrapper
struct WrapperWithMainActorDefaultInit {
var wrappedValue: Int { fatalError() }
@MainActor init() {} // expected-note {{calls to initializer 'init()' from outside of its actor context are implicitly asynchronous}}
}
actor ActorWithWrapper {
@WrapperOnActor var synced: Int = 0
// expected-note@-1 3{{property declared here}}
func f() {
_ = synced // expected-error{{'synced' isolated to global actor}}
_ = $synced // expected-error{{'$synced' isolated to global actor}}
_ = _synced // expected-error{{'_synced' isolated to global actor}}
@WrapperWithMainActorDefaultInit var value: Int // expected-error {{call to main actor-isolated initializer 'init()' in a synchronous actor-isolated context}}
}
}
@propertyWrapper
struct WrapperOnSomeGlobalActor<Wrapped> {
private var stored: Wrapped
nonisolated init(wrappedValue: Wrapped) {
stored = wrappedValue
}
@SomeGlobalActor var wrappedValue: Wrapped {
get { stored }
set { stored = newValue }
}
}
struct InferredFromPropertyWrapper {
@WrapperOnSomeGlobalActor var value = 17
func test() -> Int { // expected-note{{calls to instance method 'test()' from outside of its actor context are implicitly asynchronous}}
value
}
}
func testInferredFromWrapper(x: InferredFromPropertyWrapper) { // expected-note{{add '@SomeGlobalActor' to make global function 'testInferredFromWrapper(x:)' part of global actor 'SomeGlobalActor'}}
_ = x.test() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'test()' in a synchronous nonisolated context}}
}
// ----------------------------------------------------------------------
// Unsafe global actors
// ----------------------------------------------------------------------
protocol UGA {
@SomeGlobalActor(unsafe) func req() // expected-note{{calls to instance method 'req()' from outside of its actor context are implicitly asynchronous}}
}
struct StructUGA1: UGA {
@SomeGlobalActor func req() { }
}
struct StructUGA2: UGA {
nonisolated func req() { }
}
@SomeGlobalActor
struct StructUGA3: UGA {
func req() {
sibling()
}
}
@GenericGlobalActor<String>
func testUGA<T: UGA>(_ value: T) {
value.req() // expected-error{{call to global actor 'SomeGlobalActor'-isolated instance method 'req()' in a synchronous global actor 'GenericGlobalActor<String>'-isolated context}}
}
class UGAClass {
@SomeGlobalActor(unsafe) func method() { }
}
class UGASubclass1: UGAClass {
@SomeGlobalActor override func method() { }
}
class UGASubclass2: UGAClass {
override func method() { }
}
@propertyWrapper
@OtherGlobalActor(unsafe)
struct WrapperOnUnsafeActor<Wrapped> {
private var stored: Wrapped
init(wrappedValue: Wrapped) {
stored = wrappedValue
}
@MainActor(unsafe) var wrappedValue: Wrapped {
get { }
set { }
}
@SomeGlobalActor(unsafe) var projectedValue: Wrapped {
get { }
set { }
}
}
struct HasWrapperOnUnsafeActor {
@WrapperOnUnsafeActor var synced: Int = 0
// expected-note@-1 3{{property declared here}}
func testUnsafeOkay() {
_ = synced
_ = $synced
_ = _synced
}
nonisolated func testErrors() {
_ = synced // expected-error{{property 'synced' isolated to global actor 'MainActor' can not be referenced from}}
_ = $synced // expected-error{{property '$synced' isolated to global actor 'SomeGlobalActor' can not be referenced from}}
_ = _synced // expected-error{{property '_synced' isolated to global actor 'OtherGlobalActor' can not be referenced from}}
}
@MainActor mutating func testOnMain() {
_ = synced
synced = 17
}
}
// ----------------------------------------------------------------------
// Nonisolated closures
// ----------------------------------------------------------------------
@SomeGlobalActor func getGlobal7() -> Int { 7 }
func acceptClosure<T>(_: () -> T) { }
@SomeGlobalActor func someGlobalActorFunc() async {
acceptClosure { getGlobal7() } // okay
}
// ----------------------------------------------------------------------
// Unsafe main actor parameter annotation
// ----------------------------------------------------------------------
func takesUnsafeMainActor(@_unsafeMainActor fn: () -> Void) { }
@MainActor func onlyOnMainActor() { }
func useUnsafeMainActor() {
takesUnsafeMainActor {
onlyOnMainActor() // okay due to parameter attribute
}
}
// ----------------------------------------------------------------------
// @_inheritActorContext
// ----------------------------------------------------------------------
func acceptAsyncSendableClosure<T>(_: @Sendable () async -> T) { }
func acceptAsyncSendableClosureInheriting<T>(@_inheritActorContext _: @Sendable () async -> T) { }
@MainActor func testCallFromMainActor() {
acceptAsyncSendableClosure {
onlyOnMainActor() // expected-error{{expression is 'async' but is not marked with 'await'}}
// expected-note@-1 {{calls to global function 'onlyOnMainActor()' from outside of its actor context are implicitly asynchronous}}
}
acceptAsyncSendableClosure {
await onlyOnMainActor() // okay
}
acceptAsyncSendableClosureInheriting {
onlyOnMainActor() // okay
}
acceptAsyncSendableClosureInheriting {
await onlyOnMainActor() // expected-warning{{no 'async' operations occur within 'await' expression}}
}
}
// defer bodies inherit global actor-ness
@MainActor
var statefulThingy: Bool = false
@MainActor
func useFooInADefer() -> String {
defer {
statefulThingy = true
}
return "hello"
}
| apache-2.0 | b410c0725b7e6e3782ff4a8c05f8b31a | 33.554152 | 251 | 0.64995 | 4.562202 | false | false | false | false |
visualitysoftware/swift-sdk | CloudBoost/CloudSearch.swift | 1 | 7406 | //
// CloudSearch.swift
// CloudBoost
//
// Created by Randhir Singh on 20/04/16.
// Copyright © 2016 Randhir Singh. All rights reserved.
//
import Foundation
@available(*,deprecated=0.2) public class CloudSearch {
var collectionName: String?
var collectionArray = [String]()
var query = NSMutableDictionary()
var filtered = NSMutableDictionary()
var bool = NSMutableDictionary()
var from: Int?
var size: Int?
var sort = [AnyObject]()
var searchFilter: SearchFilter?
var searchQuery: SearchQuery?
///
/// CloudObject subclass to be used to construct objects fetched with the `.search` method
/// Usage:
/// 1. Declare your own CloudObject subclass
/// 2. Initialize a CloudSearch passing your subclass type as a parameter or set the objectClass property
/// 3. Call the .search method
///
public var objectClass: CloudObject.Type = CloudObject.self
/// Instantiate a new QuerySearch object
///
/// - parameters:
/// - tableName: Name of the table on the backend
/// - searchQuery: An SearchQuery object for the criteria of the search (optional)
/// - searchFiler: An SearchFilter object with the filtering options of the search (optional)
/// - objectClass: The type of object to be returned (must be a subclass of CloudObject); is optional and if omitted will be created CloudObject instances
///
public init(tableName: String,
searchQuery: SearchQuery? = nil,
searchFilter: SearchFilter? = nil,
objectClass: CloudObject.Type = CloudObject.self) {
self.objectClass = objectClass
self.collectionName = tableName
if searchQuery != nil {
self.bool["bool"] = searchQuery?.bool
self.filtered["query"] = self.bool
}else{
self.filtered["query"] = [:]
}
if searchFilter != nil {
self.bool["bool"] = searchFilter?.bool
self.filtered["filter"] = self.bool
}else{
self.filtered["filter"] = [:]
}
self.from = 0
self.size = 10
}
public init(tableName: [String],
searchQuery: SearchQuery? = nil,
searchFilter: SearchFilter? = nil,
objectClass: CloudObject.Type = CloudObject.self) {
self.objectClass = objectClass
self.collectionArray = tableName
if searchQuery != nil {
self.bool["bool"] = searchQuery?.bool
self.filtered["query"] = self.bool
}else{
self.filtered["query"] = [:]
}
if searchFilter != nil {
self.bool["bool"] = searchFilter?.bool
self.filtered["filter"] = self.bool
}else{
self.filtered["filter"] = [:]
}
self.from = 0
self.size = 10
}
// public init(tableName: String){
// self.collectionName = tableName
//
// self.filtered["query"] = [:]
// self.filtered["filter"] = [:]
//
// self.from = 0
// self.size = 10
//
// }
func setSearchFilter(searchFilter: SearchFilter) {
self.bool["bool"] = searchFilter.bool
self.filtered["query"] = self.bool
}
func setSearchQuery(searchQuery: SearchQuery){
self.bool["bool"] = searchQuery.bool
self.filtered["query"] = self.bool
}
// MARK: Setters and getter
public func setSkip(data: Int ){
self.from = data
}
public func setLimit(data: Int) {
self.size = data
}
public func orderByAsc(columnName: String) -> CloudSearch {
let colName = prependUnderscore(columnName)
let obj = NSMutableDictionary()
obj[colName] = ["order":"asc"]
self.sort.append(obj)
return self
}
public func orderByDesc(columnName: String) -> CloudSearch {
let colName = prependUnderscore(columnName)
let obj = NSMutableDictionary()
obj[colName] = ["order":"desc"]
self.sort.append(obj)
return self
}
public func search(callback: (CloudBoostResponse)->Void) throws {
if let sf = self.searchFilter {
self.setSearchFilter(sf)
}
if let sq = self.searchQuery {
self.setSearchQuery(sq)
}
var collectionString = ""
if self.collectionArray.count > 0 {
if collectionArray.count > 1 {
for i in 0...collectionArray.count-1 {
collectionString += (i>0 ? ","+self.collectionArray[i] : self.collectionArray[i])
}
}else{
collectionString = collectionArray[0]
}
self.collectionName = collectionString
}else{
collectionString = self.collectionName!
}
query["filtered"] = filtered
let params = NSMutableDictionary()
params["collectionName"] = collectionString
params["query"] = query
params["limit"] = size
params["skip"] = from
params["sort"] = sort
params["key"] = CloudApp.getAppKey()
var url = CloudApp.getApiUrl() + "/data/" + CloudApp.getAppId()!
url = url + "/" + collectionName! + "/search"
CloudCommunications._request("POST", url: NSURL(string: url)!, params: params, callback: {
(response: CloudBoostResponse) in
if response.status == 200 {
if let documents = response.object as? [NSMutableDictionary] {
var objectsArray = [CloudObject]()
for document in documents {
let object = self.objectClass.cloudObjectFromDocumentDictionary(document, documentType: self.objectClass)
objectsArray.append(object)
}
let theResponse = CloudBoostResponse()
theResponse.success = response.success
theResponse.object = objectsArray
theResponse.status = response.status
callback(theResponse)
} else if let document = response.object as? NSMutableDictionary {
let object = self.objectClass.cloudObjectFromDocumentDictionary(document, documentType: self.objectClass)
let theResponse = CloudBoostResponse()
theResponse.success = response.success
theResponse.object = object
theResponse.status = response.status
callback(theResponse)
} else {
callback(response)
}
} else {
callback(response)
}
})
}
private func prependUnderscore(col: String) -> String {
var returnString = col
let keyWords = ["id","isSearchable","expires"]
if keyWords.indexOf(col) != nil {
returnString = "_" + returnString
}
return returnString
}
} | mit | c047d09a3561cb35a9afaac3e8e7db9d | 31.340611 | 160 | 0.540986 | 5.05116 | false | false | false | false |
kentaiwami/masamon | masamon/masamon/ShiftListSetting.swift | 1 | 16760 | //
// ShiftListSetting.swift
// masamon
//
// Created by 岩見建汰 on 2016/01/31.
// Copyright © 2016年 Kenta. All rights reserved.
//
import UIKit
class ShiftListSetting: UIViewController, UITableViewDataSource, UITableViewDelegate{
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.hex("191919", alpha: 1.0)
table.delegate = self
table.dataSource = self
self.RefreshData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func RefreshData(){
self.texts.removeAll()
if DBmethod().GetShiftDBAllRecordArray() != nil {
let results = DBmethod().GetShiftDBAllRecordArray()
for i in (0 ..< results!.count).reversed() {
self.texts.append(results![i])
}
}
self.table.reloadData()
}
// セルに表示するテキスト
var texts: [ShiftDB] = []
let sections = ["最新順"]
//セクションの数を返す.
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
//セクションのタイトルを返す.
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
// セルの内容を変更
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
cell.textLabel?.text = texts[indexPath.row].shiftimportname
return cell
}
// セルの行数
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return texts.count
}
//セルの削除を許可
func tableView(_ tableView: UITableView,canEditRowAt indexPath: IndexPath) -> Bool
{
return true
}
//セルの選択を禁止する
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
return nil;
}
//セルを横スクロールした際に表示されるアクションを管理するメソッド
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
// Editボタン.
let EditButton: UITableViewRowAction = UITableViewRowAction(style: .normal, title: "編集") { (action, index) -> Void in
tableView.isEditing = false
self.alert(self.texts[indexPath.row].shiftimportname + "を編集します", messagetext: "新しいシフト取り込み名を入力して下さい\nxlxsやpdfなどはつけてもつけなくても大丈夫です。", index: indexPath.row, flag: 0)
}
EditButton.backgroundColor = UIColor.green
// Deleteボタン.
let DeleteButton: UITableViewRowAction = UITableViewRowAction(style: .normal, title: "削除") { (action, index) -> Void in
tableView.isEditing = false
self.alert(self.texts[indexPath.row].shiftimportname + "を削除します", messagetext: "関連する情報が全て削除されます。よろしいですか?", index: indexPath.row, flag: 1)
}
DeleteButton.backgroundColor = UIColor.red
return [EditButton, DeleteButton]
}
//アラートを表示する関数
func alert(_ titletext: String, messagetext: String, index: Int, flag: Int){
var buttontitle = ""
let alert:UIAlertController = UIAlertController(title: titletext,
message: messagetext,
preferredStyle: UIAlertControllerStyle.alert)
//flagが0は編集、flagが1は削除
switch(flag){
case 0:
buttontitle = "編集完了"
let Action:UIAlertAction = UIAlertAction(title: buttontitle,
style: UIAlertActionStyle.default,
handler:{
(action:UIAlertAction!) -> Void in
let textFields:Array<UITextField>? = alert.textFields as Array<UITextField>?
if textFields != nil {
if textFields![0].text! != "" {
var oldfileextension = ""
var oldfilepath = ""
//上書き処理を行う
let oldshiftdbrecord = DBmethod().SearchShiftDB(self.texts[index].shiftimportname)
oldfilepath = oldshiftdbrecord.shiftimportpath
let newshiftdbrecord = ShiftDB()
newshiftdbrecord.id = oldshiftdbrecord.id
newshiftdbrecord.year = oldshiftdbrecord.year
newshiftdbrecord.month = oldshiftdbrecord.month
//変更前のファイルの拡張子を判断
if self.texts[index].shiftimportname.contains(".xlsx") {
oldfileextension = ".xlsx"
}else if self.texts[index].shiftimportname.contains(".pdf") {
oldfileextension = ".pdf"
}else if self.texts[index].shiftimportname.contains(".PDF") {
oldfileextension = ".PDF"
}
var newpath = oldshiftdbrecord.shiftimportpath
//ユーザが入力した新規取り込み名に拡張子が含まれているか調べる
switch(oldfileextension){
case ".xlsx":
if textFields![0].text!.contains(".xlsx") == false {
newpath = newpath.replacingOccurrences(of: self.texts[index].shiftimportname, with: textFields![0].text! + oldfileextension)
newshiftdbrecord.shiftimportname = textFields![0].text! + oldfileextension
}
case ".pdf":
if textFields![0].text!.contains(".pdf") == false {
newpath = newpath.replacingOccurrences(of: self.texts[index].shiftimportname, with: textFields![0].text! + oldfileextension)
newshiftdbrecord.shiftimportname = textFields![0].text! + oldfileextension
}
case ".PDF":
if textFields![0].text!.contains(".PDF") == false {
newpath = newpath.replacingOccurrences(of: self.texts[index].shiftimportname, with: textFields![0].text! + oldfileextension)
newshiftdbrecord.shiftimportname = textFields![0].text! + oldfileextension
}
default:
break
}
newshiftdbrecord.shiftimportpath = newpath
newshiftdbrecord.salaly = oldshiftdbrecord.salaly
let oldshiftdetailarray = oldshiftdbrecord.shiftdetail
for i in 0 ..< oldshiftdetailarray.count{
newshiftdbrecord.shiftdetail.append(oldshiftdetailarray[i])
}
//関連するシフトを上書き更新する
for i in 0 ..< oldshiftdetailarray.count{
let newshiftdetaildbrecord = ShiftDetailDB()
newshiftdetaildbrecord.id = oldshiftdetailarray[i].id
newshiftdetaildbrecord.year = oldshiftdetailarray[i].year
newshiftdetaildbrecord.month = oldshiftdetailarray[i].month
newshiftdetaildbrecord.day = oldshiftdetailarray[i].day
newshiftdetaildbrecord.staff = oldshiftdetailarray[i].staff
newshiftdetaildbrecord.shiftDBrelationship = newshiftdbrecord
DBmethod().AddandUpdate(newshiftdetaildbrecord, update: true)
}
DBmethod().DeleteRecord(oldshiftdbrecord)
DBmethod().AddandUpdate(newshiftdbrecord, update: true)
//ファイル名を変更する
do {
try FileManager.default.moveItem(atPath: oldfilepath, toPath: newshiftdbrecord.shiftimportpath)
}
catch{
print(error)
}
}
}
self.RefreshData()
})
alert.addAction(Action)
//シフト取り込み名入力用のtextfieldを追加
alert.addTextField(configurationHandler: {(text:UITextField!) -> Void in
text.placeholder = "新規取り込み名の入力"
text.returnKeyType = .next
})
case 1:
buttontitle = "削除する"
let Action: UIAlertAction = UIAlertAction(title: buttontitle, style: UIAlertActionStyle.destructive, handler: { (action:UIAlertAction!) -> Void in
var filename = ""
//ShiftDBの穴埋めをするために基準となるidを記録
let shiftdbpivot_id = self.texts[index].id
//ShiftDetailの基準を見つけるための準備
var shiftdb_year = self.texts[index].year
let shiftdb_month = self.texts[index].month
//ShiftDBに記録されている月が1,2,3月の場合はyearを1つ増やしてShiftDetailDBとの整合性を取る
if shiftdb_month == 1 || shiftdb_month == 2 || shiftdb_month == 3 {
shiftdb_year += 1
}
//年月をもとに基準となるidを取り出す
let shiftdetailresults = DBmethod().TheDayStaffGet(shiftdb_year, month: shiftdb_month-1, date: 11)
if shiftdetailresults != nil {
if shiftdetailresults!.count != 0 {
let shiftdetaildbpivot_id = shiftdetailresults![0].id
//ShiftDetailDBレコードの削除
let shiftdbrecord = DBmethod().SearchShiftDB(self.texts[index].shiftimportname)
let shiftdetailarray = shiftdbrecord.shiftdetail
let deleterecordcount = shiftdetailarray.count
filename = shiftdbrecord.shiftimportname
DBmethod().DeleteShiftDetailDBRecords(shiftdetailarray)
//ShiftDBレコードの削除
DBmethod().DeleteRecord(self.texts[index])
//ShiftDetailDBレコードのソート
DBmethod().ShiftDetailDBSort()
//ShiftDBレコードのソート
DBmethod().ShiftDBSort()
//穴埋め
DBmethod().ShiftDBFillHole(shiftdbpivot_id)
DBmethod().ShiftDetailDBFillHole(shiftdetaildbpivot_id, deleterecords: deleterecordcount)
//関連づけ
var shiftdb_id_count = 0
var shiftdetaildb_array: [ShiftDetailDB] = []
var shiftdetail_recordcount = 0
//ShiftDetailDB内の11日であるレコードを配列で取得
let shiftdetaildb_day_array = DBmethod().GetShiftDetailDBRecordByDay(11)
for i in 0..<DBmethod().DBRecordCount(ShiftDetailDB.self) {
let shitdb_record = DBmethod().GetShiftDBRecordByID(shiftdb_id_count)
//shiftdb_recordの年月を持ってきて何日まであるかを把握
let shiftrange = Utility().GetShiftCoursMonthRange(shiftdetaildb_day_array[shiftdb_id_count].year, shiftstartmonth: shiftdetaildb_day_array[shiftdb_id_count].month)
//ShiftDetailDBのrelationshipを更新する
DBmethod().ShiftDetaiDB_relationshipUpdate(i, record: shitdb_record)
//リレーションシップを更新した後のShiftDetailDBのレコードを取得
let shiftdetaildb_record = DBmethod().GetShiftDetailDBRecordByID(i)
shiftdetaildb_array.append(shiftdetaildb_record)
shiftdetail_recordcount += 1
//処理済みのshiftdetailレコード数とクールの日数数が一致(当該クールのshiftdetailレコードを全て処理したら)
if shiftdetail_recordcount == shiftrange.length {
//ShiftDBのListにShiftDetaiDBListを更新する
let shiftimportname = DBmethod().ShiftDBGet(shiftdb_id_count)
DBmethod().ShiftDB_relationshipUpdate(shiftimportname, array: shiftdetaildb_array)
shiftdb_id_count += 1
shiftdetail_recordcount = 0
shiftdetaildb_array.removeAll()
}
}
//ファイルの削除
let Libralypath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0] as String
let filepath = Libralypath + "/" + filename
let filemanager:FileManager = FileManager()
do{
try filemanager.removeItem(atPath: filepath)
}catch{
print(error)
}
}else{
self.ShowDeleteError(self.texts[index].shiftimportname)
}
}else{
self.ShowDeleteError(self.texts[index].shiftimportname)
}
self.RefreshData()
})
alert.addAction(Action)
default:
break
}
let Back: UIAlertAction = UIAlertAction(title: "戻る", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(Back)
self.present(alert, animated: true, completion: nil)
}
//削除エラーを表示するアラート
func ShowDeleteError(_ importname: String){
let alertController = UIAlertController(title: "削除エラー", message: importname+"の削除に失敗しました", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
}
}
| mit | b081370ff1795f883ba3f572992edff2 | 42.800562 | 192 | 0.486757 | 5.312777 | false | false | false | false |
xwu/swift | test/expr/closure/multi_statement.swift | 1 | 2770 | // RUN: %target-typecheck-verify-swift -swift-version 5 -experimental-multi-statement-closures -enable-experimental-static-assert
func isInt<T>(_ value: T) -> Bool {
return value is Int
}
func maybeGetValue<T>(_ value: T) -> T? {
return value
}
enum MyError: Error {
case featureIsTooCool
func doIt() { }
}
enum State {
case suspended
case partial(Int, Int)
case finished
}
func random(_: Int) -> Bool { return false }
func mightThrow() throws -> Bool { throw MyError.featureIsTooCool }
func mapWithMoreStatements(ints: [Int], state: State) throws {
let _ = try ints.map { i in
guard var actualValue = maybeGetValue(i) else {
return String(0)
}
let value = actualValue + 1
do {
if isInt(i) {
print(value)
} else if value == 17 {
print("seventeen!")
}
}
while actualValue < 100 {
actualValue += 1
}
my_repeat:
repeat {
print("still here")
if i % 7 == 0 {
break my_repeat
}
} while random(i)
defer {
print("I am so done here")
}
for j in 0..<i where j % 2 == 0 {
if j % 7 == 0 {
continue
}
switch (state, j) {
case (.suspended, 0):
print("something")
fallthrough
case (.finished, 0):
print("something else")
case (.partial(let current, let end), let j):
print("\(current) of \(end): \(j)")
default:
print("so, here we are")
}
print("even")
throw MyError.featureIsTooCool
}
#assert(true)
// expected-warning@+1{{danger zone}}
#warning("danger zone")
#if false
struct NothingHere { }
#else
struct NestedStruct {
var x: Int
}
#endif
do {
print(try mightThrow())
} catch let e as MyError {
e.doIt()
} catch {
print(error)
}
return String(value)
}
}
func acceptsWhateverClosure<T, R>(_ value: T, _ fn: (T) -> R) { }
func testReturnWithoutExpr(i: Int) {
acceptsWhateverClosure(i) { i in
print(i)
return
}
}
// `withContiguousStorageIfAvailable` is overloaded, so let's make sure that
// filtering works correctly.
func test_overloaded_call(arr: [Int], body: (UnsafeBufferPointer<Int>) -> Void) -> Void {
arr.withContiguousStorageIfAvailable { buffer in
let _ = type(of: buffer)
body(buffer) // ok
}
}
// Used to wrap closure in `FunctionConversionExpr` in this case,
// but now solver would just inject return expression into optional where necessary.
func test_result_optional_injection() {
func fn<T>(_: () -> T?) -> [T] {
[]
}
_ = fn {
if true {
return // Ok
}
}
}
let _ = {
for i: Int8 in 0 ..< 20 { // Ok (pattern can inform a type of the sequence)
print(i)
}
}
| apache-2.0 | bfa43e07dbebdd785c8a3d55dddc2c57 | 18.64539 | 129 | 0.580505 | 3.606771 | false | false | false | false |
Novo1987/sdk | examples/Swift/MEGA/MEGA/CloudDrive/DetailsNodeInfoViewController.swift | 6 | 10535 | /**
* @file DetailsNodeInfoViewController.swift
* @brief View controller that show details info about a node
*
* (c) 2013-2015 by Mega Limited, Auckland, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
import UIKit
class DetailsNodeInfoViewController: UIViewController, MEGADelegate, UIAlertViewDelegate {
@IBOutlet weak var thumbnailImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var modificationTimeLabel: UILabel!
@IBOutlet weak var sizeLabel: UILabel!
@IBOutlet weak var downloadButton: UIButton!
@IBOutlet weak var downloadProgressView: UIProgressView!
@IBOutlet weak var saveLabel: UILabel!
@IBOutlet weak var cancelButton: UIButton!
var node : MEGANode!
var currentTransfer : MEGATransfer!
var renameAlertView : UIAlertView!
var removeAlertView : UIAlertView!
let megaapi : MEGASdk! = (UIApplication.sharedApplication().delegate as! AppDelegate).megaapi
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
reloadUI()
megaapi.addMEGADelegate(self)
megaapi.retryPendingConnections()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
megaapi.removeMEGADelegate(self)
}
func reloadUI() {
if node.type == MEGANodeType.Folder {
downloadButton.hidden = true
}
let thumbnailFilePath = Helper.pathForNode(node, path: NSSearchPathDirectory.CachesDirectory, directory: "thumbs")
let fileExists = NSFileManager.defaultManager().fileExistsAtPath(thumbnailFilePath)
if !fileExists {
thumbnailImageView.image = Helper.imageForNode(node)
} else {
thumbnailImageView.image = UIImage(contentsOfFile: thumbnailFilePath)
}
title = node.name
nameLabel.text = node.name
let dateFormatter = NSDateFormatter()
var theDateFormat = NSDateFormatterStyle.ShortStyle
let theTimeFormat = NSDateFormatterStyle.ShortStyle
dateFormatter.dateStyle = theDateFormat
dateFormatter.timeStyle = theTimeFormat
if node.isFile() {
modificationTimeLabel.text = dateFormatter.stringFromDate(node.modificationTime)
sizeLabel.text = NSByteCountFormatter.stringFromByteCount(node.size.longLongValue, countStyle: NSByteCountFormatterCountStyle.Memory)
} else {
modificationTimeLabel.text = dateFormatter.stringFromDate(node.creationTime)
sizeLabel.text = NSByteCountFormatter.stringFromByteCount(megaapi.sizeForNode(node).longLongValue, countStyle: NSByteCountFormatterCountStyle.Memory)
}
let documentFilePath = Helper.pathForNode(node, path: NSSearchPathDirectory.DocumentDirectory)
let fileDocumentExists = NSFileManager.defaultManager().fileExistsAtPath(documentFilePath)
if fileDocumentExists {
downloadProgressView.hidden = true
cancelButton.hidden = true
saveLabel.hidden = false
downloadButton.setImage(UIImage(named: "savedFile"), forState: UIControlState.Normal)
saveLabel.text = "Saved for offline"
} else if megaapi.transfers.size.intValue > 0 {
downloadProgressView.hidden = true
cancelButton.hidden = true
var i : Int
for i = 0 ; i < megaapi.transfers.size.integerValue ; i++ {
let transfer : MEGATransfer = megaapi.transfers.transferAtIndex(i)
if transfer.nodeHandle == node.handle {
downloadProgressView.hidden = false
cancelButton.hidden = false
currentTransfer = transfer
let progress = transfer.transferredBytes.floatValue / transfer.totalBytes.floatValue
downloadProgressView.setProgress(progress, animated: true)
continue
}
}
} else {
downloadProgressView.hidden = true
cancelButton.hidden = true
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - IBActions
@IBAction func touchUpInsideDownload(sender: UIButton) {
if node.type == MEGANodeType.File {
let documentFilePath = Helper.pathForNode(node, path: NSSearchPathDirectory.DocumentDirectory)
let fileExists = NSFileManager.defaultManager().fileExistsAtPath(documentFilePath)
if !fileExists {
megaapi.startDownloadNode(node, localPath: documentFilePath)
}
}
}
@IBAction func touchUpInsideGenerateLink(sender: UIButton) {
megaapi.exportNode(node)
}
@IBAction func touchUpInsideRename(sender: UIButton) {
renameAlertView = UIAlertView(title: "Rename", message: "Enter the new name", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Rename")
renameAlertView.alertViewStyle = UIAlertViewStyle.PlainTextInput
renameAlertView.textFieldAtIndex(0)?.text = node.name.lastPathComponent.stringByDeletingPathExtension
renameAlertView.tag = 0
renameAlertView.show()
}
@IBAction func touchUpInsideDelete(sender: UIButton) {
removeAlertView = UIAlertView(title: "Remove node", message: "Are you sure?", delegate: self, cancelButtonTitle: "Cancel", otherButtonTitles: "Remove")
removeAlertView.alertViewStyle = UIAlertViewStyle.Default
removeAlertView.tag = 1
removeAlertView.show()
}
@IBAction func touchUpInsideCancelDownload(sender: AnyObject) {
megaapi.cancelTransfer(currentTransfer)
}
// MARK: - AlertView delegate
func alertView(alertView: UIAlertView, didDismissWithButtonIndex buttonIndex: Int) {
if alertView.tag == 0 {
if buttonIndex == 1 {
if node.name.pathExtension == "" {
megaapi.renameNode(node, newName: alertView.textFieldAtIndex(0)?.text)
} else {
let newName = alertView.textFieldAtIndex(0)?.text.stringByAppendingString(".".stringByAppendingString(node.name.pathExtension))
nameLabel.text = newName
megaapi.renameNode(node, newName: newName)
}
}
}
if alertView.tag == 1 {
if buttonIndex == 1 {
megaapi.removeNode(node)
navigationController?.popViewControllerAnimated(true)
}
}
}
// MARK: - MEGA Request delegate
func onRequestStart(api: MEGASdk!, request: MEGARequest!) {
if request.type == MEGARequestType.Export {
SVProgressHUD.showWithStatus("Generate link...")
}
}
func onRequestFinish(api: MEGASdk!, request: MEGARequest!, error: MEGAError!) {
if error.type != MEGAErrorType.ApiOk {
return
}
switch request.type {
case MEGARequestType.GetAttrFile:
if request.nodeHandle == node.handle {
let node = megaapi.nodeForHandle(request.nodeHandle)
let thumbnailFilePath = Helper.pathForNode(node, path: NSSearchPathDirectory.CachesDirectory, directory: "thumbs")
let fileExists = NSFileManager.defaultManager().fileExistsAtPath(thumbnailFilePath)
if fileExists {
thumbnailImageView.image = UIImage(contentsOfFile: thumbnailFilePath)
}
}
case MEGARequestType.Export:
SVProgressHUD.showSuccessWithStatus("Link Generate")
SVProgressHUD.dismiss()
let items = [request.link]
let activity : UIActivityViewController = UIActivityViewController(activityItems: items, applicationActivities: nil)
activity.excludedActivityTypes = [UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll]
self.presentViewController(activity, animated: true, completion: nil)
default:
break
}
}
// MARK: - MEGA Global delegate
func onNodesUpdate(api: MEGASdk!, nodeList: MEGANodeList!) {
node = nodeList.nodeAtIndex(0)
}
// MARK: - MEGA Transfer delegate
func onTransferStart(api: MEGASdk!, transfer: MEGATransfer!) {
downloadProgressView.hidden = false
downloadProgressView.setProgress(0.0, animated: true)
cancelButton.hidden = false
currentTransfer = transfer
}
func onTransferUpdate(api: MEGASdk!, transfer: MEGATransfer!) {
if transfer.nodeHandle == node.handle {
let progress = transfer.transferredBytes.floatValue / transfer.totalBytes.floatValue
downloadProgressView.setProgress(progress, animated: true)
} else {
downloadProgressView.setProgress(0.0, animated: true)
}
}
func onTransferFinish(api: MEGASdk!, transfer: MEGATransfer!, error: MEGAError!) {
downloadProgressView.hidden = true
cancelButton.hidden = true
if error.type == MEGAErrorType.ApiEIncomplete {
downloadProgressView.setProgress(0.0, animated: true)
} else {
downloadProgressView.setProgress(1.0, animated: true)
saveLabel.hidden = false
downloadButton.setImage(UIImage(named: "savedFile"), forState: UIControlState.Normal)
saveLabel.text = "Saved for offline"
}
}
}
| bsd-2-clause | 43c5a270436cd8f5aab2e502857c2a57 | 38.456929 | 161 | 0.644234 | 5.254364 | false | false | false | false |
swiftcodex/Swift-Radio-Pro | SwiftRadio/PopUpMenuViewController.swift | 1 | 1722 | //
// PopUpMenuViewController.swift
// Swift Radio
//
// Created by Matthew Fecher on 7/9/15.
// Copyright (c) 2015 MatthewFecher.com. All rights reserved.
//
import UIKit
class PopUpMenuViewController: UIViewController {
@IBOutlet weak var popupView: UIView!
@IBOutlet weak var backgroundView: UIImageView!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
modalPresentationStyle = .custom
}
//*****************************************************************
// MARK: - ViewDidLoad
//*****************************************************************
override func viewDidLoad() {
super.viewDidLoad()
// Round corners
popupView.layer.cornerRadius = 10
// Set background color to clear
view.backgroundColor = UIColor.clear
// Add gesture recognizer to dismiss view when touched
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(closeButtonPressed))
backgroundView.isUserInteractionEnabled = true
backgroundView.addGestureRecognizer(gestureRecognizer)
}
//*****************************************************************
// MARK: - IBActions
//*****************************************************************
@IBAction func closeButtonPressed() {
dismiss(animated: true, completion: nil)
}
@IBAction func websiteButtonPressed(_ sender: UIButton) {
// Use your own website URL here
guard let url = URL(string: "https://github.com/analogcode/") else { return }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
| mit | 7b23f54e42dc6c2020f62f163f4f484a | 30.888889 | 107 | 0.547619 | 5.937931 | false | false | false | false |
gorozco58/Apps-List | Apps List/Application/Models/Category.swift | 1 | 3289 | //
// Category.swift
// Apps List
//
// Created by iOS on 3/24/16.
// Copyright © 2016 Giovanny Orozco. All rights reserved.
//
import Foundation
import Alamofire
private let CategoriesPath = "categories.obj"
class Category: NSObject, NSCoding {
//MARK: - Properties
var categoryId: String
var name: String
var applications: [App]
// MARK: - Enums and Structures
private enum EncodingKey: String {
case CategoryId = "CategoryId"
case CategoryName = "CategoryName"
case CategoryApps = "CategoryApps"
}
//MARK: - Initialization
init(categoryId: String, name: String, applications: [App]) {
self.categoryId = categoryId
self.name = name
self.applications = applications
super.init()
}
convenience init (jsonDictionary: [String : AnyObject]) throws {
do {
let categoryId = try jsonDictionary.valueForKey(InternalParameterKey.InternalId.rawValue) as String
let name = try jsonDictionary.valueForKey(InternalParameterKey.Label.rawValue) as String
self.init(categoryId: categoryId, name: name, applications: [])
} catch {
throw InitializationError.MissingMandatoryParameters
}
}
//MARK: - NSCoding
required convenience init?(coder aDecoder: NSCoder) {
let categoryId = aDecoder.decodeObjectForKey(EncodingKey.CategoryId.rawValue) as! String
let name = aDecoder.decodeObjectForKey(EncodingKey.CategoryName.rawValue) as! String
let applications = aDecoder.decodeObjectForKey(EncodingKey.CategoryApps.rawValue) as! [App]
self.init(categoryId: categoryId, name: name, applications: applications)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(categoryId, forKey: EncodingKey.CategoryId.rawValue)
aCoder.encodeObject(name, forKey: EncodingKey.CategoryName.rawValue)
aCoder.encodeObject(applications, forKey: EncodingKey.CategoryApps.rawValue)
}
//MARK: - Utils
override func isEqual(object: AnyObject?) -> Bool {
return self.categoryId == (object as! Category).categoryId
}
}
extension Category {
class func saveCategoriesToDisk(categories: [Category]) -> Bool {
let urlPath = Category.categoriesPath()
let dataToSave = NSKeyedArchiver.archivedDataWithRootObject(categories)
let success = dataToSave.writeToURL(urlPath, atomically: true)
return success
}
class func loadCategoriesFromDisk() -> [Category]? {
let urlPath = Category.categoriesPath()
var categories: [Category]?
if let data = NSData(contentsOfURL: urlPath) {
categories = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? [Category]
}
return categories
}
private class func categoriesPath() -> NSURL {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDict = NSURL(fileURLWithPath: paths.first!)
let urlPath = documentsDict.URLByAppendingPathComponent(CategoriesPath)
return urlPath
}
}
| mit | 84dd017e9ae58f5fb0582955f8eda0b5 | 30.92233 | 111 | 0.655109 | 5.153605 | false | false | false | false |
coodly/laughing-adventure | Source/UI/InputCellsViewController.swift | 1 | 11135 | /*
* Copyright 2015 Coodly LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
private extension Selector {
static let contentSizeChanged = #selector(InputCellsViewController.contentSizeChanged)
#if os(iOS)
static let willAppear = #selector(InputCellsViewController.keyboardWillAppear(notification:))
static let willDisappear = #selector(InputCellsViewController.keyboardWillDisappear(notification:))
#endif
}
public class InputCellsSection {
fileprivate let cells: [UITableViewCell]
fileprivate var title: String?
fileprivate var header: UIView?
public init(header: UIView, cells: [UITableViewCell]) {
self.header = header
self.cells = cells
}
public init(title: String? = nil, cells: [UITableViewCell]) {
self.title = title
self.cells = cells
}
func numberOfCells() -> Int {
return cells.count
}
func cellAtRow(_ row: Int) -> UITableViewCell {
return cells[row]
}
}
open class InputCellsViewController: UIViewController, FullScreenTableCreate, SmoothTableRowDeselection {
public var tableTop: NSLayoutConstraint?
@IBOutlet public var tableView: UITableView!
fileprivate var sections: [InputCellsSection] = []
fileprivate var activeCellInputValidation: InputValidation?
open var preferredStyle: UITableViewStyle {
return .plain
}
deinit {
NotificationCenter.default.removeObserver(self)
}
open override func viewDidLoad() {
checkTableView(preferredStyle)
#if os(iOS)
NotificationCenter.default.addObserver(self, selector: .willAppear, name: Notification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: .willDisappear, name: Notification.Name.UIKeyboardWillHide, object: nil)
#endif
NotificationCenter.default.addObserver(self, selector: .contentSizeChanged, name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil)
tableView.estimatedRowHeight = 44
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedSectionHeaderHeight = 20
tableView.tableFooterView = UIView()
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
smoothDeselectRows()
configureReturnButtons()
}
fileprivate func handleCellTap(_ cell: UITableViewCell, atIndexPath:IndexPath) -> Bool {
if cell.isKind(of: TextEntryCell.self) {
let entryCell = cell as! TextEntryCell
entryCell.entryField.becomeFirstResponder()
return false
} else {
return tapped(cell: cell, at: atIndexPath)
}
}
open func tapped(cell: UITableViewCell, at indexPath: IndexPath) -> Bool {
Logging.log("tappedCell")
return false
}
public func addSection(_ section: InputCellsSection) {
sections.append(section)
for cell in section.cells {
if let textCell = cell as? TextEntryCell {
textCell.entryField.delegate = self
} else if let multi = cell as? MultiEntryCell {
for field in multi.entryFields {
field.delegate = self
}
}
}
}
fileprivate func indexPathForCell(_ cell: UITableViewCell) -> IndexPath? {
for section in 0 ..< sections.count {
let sec = sections[section]
if let row = sec.cells.index(of: cell) {
return IndexPath(row: row, section: section)
}
}
return nil
}
fileprivate func nextEntryCellAfterIndexPath(_ indexPath: IndexPath) -> UITableViewCell? {
let section = indexPath.section
var row = indexPath.row + 1
let sectionRange = section..<sections.count
for section in sectionRange {
let sec = sections[section]
let rowRange = row..<sec.cells.count
for row in rowRange {
let checked = sec.cells[row]
if checked is TextEntryCell || checked is MultiEntryCell {
return checked
}
}
row = 0
}
return nil
}
@objc fileprivate func contentSizeChanged() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
fileprivate func configureReturnButtons() {
var lastEntryCell: TextEntryCell?
for section in sections {
for cell in section.cells {
guard let textEntry = cell as? TextEntryCell else {
continue
}
textEntry.setReturnKeyType(.next)
lastEntryCell = textEntry
}
}
if let last = lastEntryCell {
last.setReturnKeyType(.done)
}
}
}
// MARK: - Sections / cells
public extension InputCellsViewController {
func replaceCell(atIndexPath indexPath: IndexPath, withCell cell: UITableViewCell) {
if let textEntryCell = cell as? TextEntryCell {
textEntryCell.entryField.delegate = self
}
tableView.beginUpdates()
let section = sections[(indexPath as NSIndexPath).section]
var cells = section.cells
cells[(indexPath as NSIndexPath).row] = cell
sections[(indexPath as NSIndexPath).section] = InputCellsSection(cells: cells)
tableView.reloadRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
configureReturnButtons()
}
}
// MARK: - Table view delegates
extension InputCellsViewController: UITableViewDelegate, UITableViewDataSource {
public func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionCells = sections[section]
return sectionCells.numberOfCells()
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let sectionCells = sections[(indexPath as NSIndexPath).section]
return sectionCells.cellAtRow((indexPath as NSIndexPath).row)
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let section = sections[(indexPath as NSIndexPath).section]
let cell = section.cellAtRow((indexPath as NSIndexPath).row)
let detailsShonw = handleCellTap(cell, atIndexPath: indexPath)
if detailsShonw {
return
}
tableView.deselectRow(at: indexPath, animated: true)
}
public func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section].title
}
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return sections[section].header
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if let _ = sections[section].title {
return UITableViewAutomaticDimension
}
if let _ = sections[section].header {
return UITableViewAutomaticDimension
}
return 0
}
}
// MARK: - Text field delegate
extension InputCellsViewController: UITextFieldDelegate {
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
activeCellInputValidation = (textField.findContainingCell() as? EntryValidated)?.validator(for: textField)
return true
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let validation = activeCellInputValidation else {
return true
}
return validation.textField(textField, shouldChangeCharactersInRange: range, replacementString: string)
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
var resign = false
defer {
if resign {
textField.resignFirstResponder()
entryComplete()
}
}
if let cell = textField.findContainingCell() as? MultiEntryCell, let nextField = cell.nextEntry(after: textField) {
activeCellInputValidation = cell.validator(for: nextField)
nextField.becomeFirstResponder()
return true
}
guard let cell = textField.findContainingCell(), cell is TextEntryCell || cell is MultiEntryCell else {
resign = true
return true
}
guard let indexPath = indexPathForCell(cell), let nextCell = nextEntryCellAfterIndexPath(indexPath) else {
resign = true
return true
}
if let multiCell = nextCell as? MultiEntryCell, let field = multiCell.firstField() {
activeCellInputValidation = multiCell.validator(for: field)
field.becomeFirstResponder()
} else if let entry = nextCell as? TextEntryCell {
entry.entryField.becomeFirstResponder()
activeCellInputValidation = entry.validator(for: entry.entryField)
} else {
resign = true
}
return true
}
open func entryComplete() {
Logging.log("Entry complete")
}
}
#if os(iOS)
extension InputCellsViewController {
@objc fileprivate func keyboardWillAppear(notification: Notification) {
guard let info = notification.userInfo, let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue else {
return
}
let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber ?? NSNumber(value: 0.3)
tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
}
@objc fileprivate func keyboardWillDisappear(notification: Notification) {
let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber ?? NSNumber(value: 0.3)
tableView.contentInset = UIEdgeInsets.zero
}
}
#endif
| apache-2.0 | 2ce844e77080b3a3e6918e3811166e58 | 33.051988 | 154 | 0.63251 | 5.42113 | false | false | false | false |
ul7290/realm-cocoa | RealmSwift-swift2.0/Tests/SwiftUnicodeTests.swift | 16 | 2254 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import RealmSwift
let utf8TestString = "值значен™👍☞⎠‱௹♣︎☐▼❒∑⨌⧭иеمرحبا"
class SwiftUnicodeTests: TestCase {
func testUTF8StringContents() {
let realm = realmWithTestPath()
try! realm.write {
realm.create(SwiftStringObject.self, value: [utf8TestString])
return
}
let obj1 = realm.objects(SwiftStringObject).first!
XCTAssertEqual(obj1.stringCol, utf8TestString)
let obj2 = realm.objects(SwiftStringObject).filter("stringCol == %@", utf8TestString).first!
XCTAssertEqual(obj1, obj2)
XCTAssertEqual(obj2.stringCol, utf8TestString)
XCTAssertEqual(Int(0), realm.objects(SwiftStringObject).filter("stringCol != %@", utf8TestString).count)
}
func testUTF8PropertyWithUTF8StringContents() {
let realm = realmWithTestPath()
try! realm.write {
realm.create(SwiftUTF8Object.self, value: [utf8TestString])
return
}
let obj1 = realm.objects(SwiftUTF8Object).first!
XCTAssertEqual(obj1.柱колоéнǢкƱаم👍, utf8TestString, "Storing and retrieving a string with UTF8 content should work")
// Test fails because of rdar://17735684
let obj2 = realm.objects(SwiftUTF8Object).filter("%K == %@", "柱колоéнǢкƱаم👍", utf8TestString).first!
XCTAssertEqual(obj1, obj2, "Querying a realm searching for a string with UTF8 content should work")
}
}
| apache-2.0 | 162c1524893b77ca7ead8534c317f689 | 37.210526 | 123 | 0.640496 | 4.148571 | false | true | false | false |
Rahulclaritaz/rahul | ixprez/ixprez/XPFolllowsViewController.swift | 1 | 11217 | //
// XPFolllowsViewController.swift
// ixprez
//
// Created by Quad on 6/22/17.
// Copyright © 2017 Claritaz Techlabs. All rights reserved.
//
import UIKit
protocol passFollow
{
func followCount(value : Int)
}
class XPFolllowsViewController: UIViewController
{
var isUserFollowing = Int ()
let dashBoardCommonService = XPWebService()
let followUpdateCountURL = URLDirectory.audioVideoViewCount()
var getUploadData = MyUploadWebServices()
var getUploadURL = URLDirectory.MyUpload()
var followURL = URLDirectory.follow()
var recordFollow = [[String : Any]]()
var profileIconImage = UIImageView ()
var userPhoto = UIImage()
var userName = String()
var isPress : Bool!
var dele : passFollow!
@IBOutlet weak var followTableView: UITableView!
var followersEmail = String()
var followingUserId = String()
var activityIndicator = UIActivityIndicatorView()
// This will add the pull refresh in th etable view
lazy var refershController : UIRefreshControl = {
let refersh = UIRefreshControl()
refersh.addTarget(self, action: #selector(getPulledRefreshedData), for: .valueChanged)
return refersh
}()
override func viewDidLoad()
{
super.viewDidLoad()
followTableView.addSubview(refershController)
self.title = userName
self.navigationController?.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
self.navigationController?.navigationBar.tintColor = UIColor.white
activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge, spinColor: .white, bgColor: .clear, placeInTheCenterOf: followTableView)
// followTableView.addScalableCover(with: userPhoto)
getMyUploadPublicListData()
}
// override func viewWillAppear(_ animated: Bool)
// {
// DispatchQueue.main.async {
// self.followTableView.reloadData()
// }
//
// }
func getPulledRefreshedData () {
print("You Pulled the tableview")
// refershController.beginRefreshing()
getMyUploadPublicListData()
DispatchQueue.main.async
{
self.followTableView.reloadData()
}
self.refershController.endRefreshing()
}
@IBAction func backButton (_ sender : Any) {
self.navigationController?.popViewController(animated: true)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
func getMyUploadPublicListData()
{
let dicData = [ "user_email" : followersEmail , "index" : 0 , "limit" : 30] as [String : Any]
getUploadData.getPublicPrivateMyUploadWebService(urlString: getUploadURL.publicMyUpload(), dicData: dicData as NSDictionary, callback:{(dicc, err) in
if err == nil
{
print("matha check Data",dicc)
self.recordFollow = dicc
DispatchQueue.main.async
{
self.activityIndicator.stopAnimating()
self.followTableView.reloadData()
}
}
else
{
DispatchQueue.main.async
{
self.activityIndicator.startAnimating()
}
}
})
}
}
extension XPFolllowsViewController : UITableViewDataSource
{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return recordFollow.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "XPFollowsTableViewCell") as! XPFollowsTableViewCell
let followData = self.recordFollow[indexPath.row]
cell.lblTitle.text = followData["title"] as? String
cell.lblLikeCount.text = String(format: "%d Like", followData["likeCount"] as! Int)
cell.lblReactionCount.text = String(format: "%d Rect", followData["emotionCount"] as! Int)
cell.imgProfileImage.layer.cornerRadius = 4.0
cell.imgProfileImage.layer.masksToBounds = true
let viewCount : Int = followData["view_count"] as! Int
cell.lblViewCount.text = String(format: "%d Views", viewCount)
var thumbPath = followData["thumbtokenizedUrl"] as? String
// thumbPath?.replace("/root/cpanel3-skel/public_html/Xpress/", with: "http://103.235.104.118:3000/")
cell.imgProfileImage.getImageFromUrl(thumbPath!)
return cell
}
}
extension XPFolllowsViewController : UITableViewDelegate
{
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
return 165.0
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let cell = tableView.dequeueReusableCell(withIdentifier: "XPFollowHeaderTableViewCell") as! XPFollowHeaderTableViewCell
cell.followerProfileBGImage.image = userPhoto
cell.followerProfileBGImage.alpha = 0.3
// cell.imgProfileIcon.setBackgroundImage(userPhoto, for: .normal)
cell.followerProfileImage.image = userPhoto //profileIconImage.image
cell.followerProfileImage.layer.cornerRadius = cell.followerProfileImage.frame.size.width/2
cell.followerProfileImage.clipsToBounds = true
// cell.followerProfileImage.contentMode = .scaleAspectFit
cell.lblProfileName.text = userName
cell.imgFollowBG.layer.cornerRadius = cell.imgFollowBG.frame.size.width/2
cell.imgFollowBG.clipsToBounds = true
if (isUserFollowing == 0)
{
cell.imgFollow.image = UIImage(named: "FollowHeartIcon")
}
else
{
cell.imgFollow.image = UIImage(named: "DashboardUnFollowIcon")
}
cell.btnFollow.addTarget(self, action: #selector(followAction(Sender:)), for: .touchUpInside)
return cell
}
func followAction(Sender:UIButton)
{
if (isUserFollowing == 0)
{
// orignator - To whom you are going to follow & follower - who is follow you.
let followDic = ["user_id":followingUserId]
self.getUploadData.getDeleteMyUploadWebService(urlString: followURL.follower(), dicData: followDic as NSDictionary, callback: { (dic, err) in
print(dic)
if( dic["status"] as! String == "OK" )
{
// self.dele.followCount(value: 1)
self.isUserFollowing = 1
DispatchQueue.main.async(execute: {
self.followTableView.reloadData()
})
}
})
}
else
{
// orignator - to whom going to follow & follower - who is going to follow.
let followDic = ["user_id":followingUserId]
self.getUploadData.getDeleteMyUploadWebService(urlString: followURL.unFollower(), dicData: followDic as NSDictionary, callback: { (dic, err) in
print(dic)
if( dic["status"] as! String == "OK" )
{
//self.dele.followCount(value: 0)
self.isUserFollowing = 0
DispatchQueue.main.async(execute: {
self.followTableView.reloadData()
})
}
})
}
}
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int)
{
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let storyBoard = self.storyboard?.instantiateViewController(withIdentifier: "XPMyUploadPlayViewController") as! XPMyUploadPlayViewController
// let cellIndexPath = sender.tag
// This will send the parameter to the view count service and return the response
var recordFollowData = self.recordFollow[indexPath.row]
let fileType: String = recordFollowData["filemimeType"] as! String
let followFileType = fileType.replacingOccurrences(of: "/mp4", with: "")
var fileTypeData = String()
if (followFileType == "video"){
fileTypeData = followFileType
} else {
fileTypeData = "audio"
}
print(followFileType)
let requestParameter = ["id" : recordFollowData["_id"],"video_type": fileTypeData] as [String : Any]
dashBoardCommonService.updateNumberOfViewOfCount(urlString: followUpdateCountURL.viewCount(), dicData: requestParameter as NSDictionary) { (updateCountresponse, error
) in
print(updateCountresponse)
if (error == nil) {
// storyBoard.playView = labelPlayView + 1
} else {
// storyBoard.playView = labelPlayView
}
}
let urlPath = recordFollowData["tokenizedUrl"] as! String
var finalURlPath = urlPath.replacingOccurrences(of: "/root/cpanel3-skel/public_html/Xpress/", with: "http://103.235.104.118:3000/")
storyBoard.playUrlString = finalURlPath
storyBoard.nextID = recordFollowData["_id"] as! String
let labelLikeCount: NSInteger = recordFollowData["likeCount"] as! NSInteger
storyBoard.playLike = labelLikeCount
let labelSmileyCount: NSInteger = recordFollowData["emotionCount"] as! NSInteger
storyBoard.playSmiley = labelSmileyCount
storyBoard.playTitle = recordFollowData["title"] as! String
let labelPlayView: NSInteger = recordFollowData["view_count"] as! NSInteger
storyBoard.playView = labelPlayView + 1
print("the carousel video url path is \(storyBoard.playUrlString)")
self.navigationController?.pushViewController(storyBoard, animated: true)
}
}
| mit | 1d039f150387e8ffcdb56ced2b4b0a05 | 29.478261 | 174 | 0.566601 | 5.397498 | false | false | false | false |
denis631/Bankathon-Vienna- | frontend/cashSlicer/cashSlicer/Recommendation/RecommendationViewModel.swift | 1 | 2680 | //
// RecommendationViewModel.swift
// Bankathon[Vienna]
//
// Created by Denis Grebennicov on 30.05.17.
// Copyright © 2017 readdy GmbH. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import RxDataSources
import ObjectMapper
struct SavingRecommendation {
var savingId: Int = -1
var savingDescribtion: String? = nil
var isEnabled = Variable(false)
init(id: Int, description: String) {
savingId = id
savingDescribtion = description
}
}
extension SavingRecommendation: Mappable {
mutating func mapping(map: Map) {
savingId <- map["id"]
savingDescribtion <- map["description"]
}
init?(map: Map) {
guard let _ = map.JSON["id"] as? Int else {
return nil
}
}
}
struct SavingRecommendations {
var header: String
var items: [Item]
}
extension SavingRecommendations: SectionModelType {
typealias Item = SavingRecommendation
init(original: SavingRecommendations, items: [Item]) {
self = original
self.items = items
}
}
final class RecommendationViewModel {
typealias RecommendationSectionType = SavingRecommendations
let dataSource = RxTableViewSectionedReloadDataSource<RecommendationViewModel.RecommendationSectionType>()
var storedRecommendations = [SavingRecommendation]()
var recommendations: Driver<[RecommendationSectionType]> {
return URLSession.shared
.rx
.json(url: URL(string: "\(baseUrl)/recommendations")!) // "\(baseUrl)/expenses"
.do(onNext: {
debugPrint($0)
})
.map {
var result = [SavingRecommendation]()
if let JSONArray = $0 as? [[String: AnyObject]] {
result = JSONArray
.map {
guard let savingRecommendation = SavingRecommendation(JSON: $0) else {
return nil
}
savingRecommendation.isEnabled.value = self.storedRecommendations.contains { (item) -> Bool in
return item.savingId == savingRecommendation.savingId
}
return savingRecommendation
}
.flatMap {
$0
}
}
return [RecommendationSectionType(header: "", items: result)]
}.asDriver(onErrorJustReturn: [])
}
}
| mit | 28d43b0b5479ebb55cca59f471eae3f1 | 28.766667 | 122 | 0.544233 | 5.467347 | false | false | false | false |
stephentyrone/swift | test/IRGen/protocol_resilience_descriptors.swift | 3 | 6566 | // RUN: %empty-directory(%t)
// Resilient protocol definition
// RUN: %target-swift-frontend -emit-ir -enable-library-evolution -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift | %FileCheck -DINT=i%target-ptrsize -check-prefix=CHECK-DEFINITION %s
// Resilient protocol usage
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift
// RUN: %target-swift-frontend -I %t -emit-ir -enable-library-evolution %s | %FileCheck %s -DINT=i%target-ptrsize -check-prefix=CHECK-USAGE
// ----------------------------------------------------------------------------
// Resilient protocol definition
// ----------------------------------------------------------------------------
// CHECK: @"default assoc type x" = linkonce_odr hidden constant
// CHECK-SAME: i8 -1, [1 x i8] c"x", i8 0
// CHECK: @"default assoc type \01____y2T118resilient_protocol29ProtocolWithAssocTypeDefaultsPQzG 18resilient_protocol7WrapperV" =
// Protocol descriptor
// CHECK-DEFINITION-LABEL: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsMp" ={{( dllexport)?}}{{( protected)?}} constant
// CHECK-DEFINITION-SAME: @"default associated conformance2T218resilient_protocol29ProtocolWithAssocTypeDefaultsP_AB014OtherResilientD0"
// Associated type default + flags
// CHECK-DEFINITION-SAME: getelementptr
// CHECK-DEFINITION-SAME: @"default assoc type _____y2T1_____QzG 18resilient_protocol7WrapperV AA29ProtocolWithAssocTypeDefaultsP"
// CHECK-DEFINITION-SAME: [[INT]] 1
// Protocol requirements base descriptor
// CHECK-DEFINITION: @"$s18resilient_protocol21ResilientBaseProtocolTL" ={{( dllexport)?}}{{( protected)?}} alias %swift.protocol_requirement, getelementptr (%swift.protocol_requirement, %swift.protocol_requirement* getelementptr inbounds (<{ i32, i32, i32, i32, i32, i32, %swift.protocol_requirement }>, <{ i32, i32, i32, i32, i32, i32, %swift.protocol_requirement }>* @"$s18resilient_protocol21ResilientBaseProtocolMp", i32 0, i32 6), i32 -1)
// Associated conformance descriptor for inherited protocol
// CHECK-DEFINITION-LABEL: s18resilient_protocol24ResilientDerivedProtocolPAA0c4BaseE0Tb" ={{( dllexport)?}}{{( protected)?}} alias
// Associated type and conformance
// CHECK-DEFINITION: @"$s1T18resilient_protocol24ProtocolWithRequirementsPTl" ={{( dllexport)?}}{{( protected)?}} alias
// CHECK-DEFINITION: @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn" ={{( dllexport)?}}{{( protected)?}} alias
// Default associated conformance witnesses
// CHECK-DEFINITION-LABEL: define internal swiftcc i8** @"$s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0TN"
import resilient_protocol
// ----------------------------------------------------------------------------
// Resilient witness tables
// ----------------------------------------------------------------------------
// CHECK-USAGE-LABEL: $s31protocol_resilience_descriptors34ConformsToProtocolWithRequirementsVyxG010resilient_A00fgH0AAMc" =
// CHECK-USAGE-SAME: {{got.|__imp_}}$s1T18resilient_protocol24ProtocolWithRequirementsPTl
// CHECK-USAGE-SAME: @"symbolic x"
public struct ConformsToProtocolWithRequirements<Element>
: ProtocolWithRequirements {
public typealias T = Element
public func first() { }
public func second() { }
}
public protocol P { }
public struct ConditionallyConforms<Element> { }
public struct Y { }
// CHECK-USAGE-LABEL: @"$s31protocol_resilience_descriptors1YV010resilient_A022OtherResilientProtocolAAMc" =
// -- flags: has generic witness table
// CHECK-USAGE-SAME: i32 131072,
// -- number of witness table entries
// CHECK-USAGE-SAME: i16 0,
// -- size of private area + 'requires instantiation' bit
// CHECK-USAGE-SAME: i16 1,
// -- instantiator function
// CHECK-USAGE-SAME: i32 0,
// -- private data area
// CHECK-USAGE-SAME: {{@[0-9]+}}
// --
// CHECK-USAGE-SAME: }
extension Y: OtherResilientProtocol { }
// CHECK-USAGE: @"$s31protocol_resilience_descriptors29ConformsWithAssocRequirementsV010resilient_A008ProtocoleF12TypeDefaultsAAMc" =
// CHECK-USAGE-SAME: $s18resilient_protocol29ProtocolWithAssocTypeDefaultsP2T2AC_AA014OtherResilientC0Tn
// CHECK-USAGE-SAME: @"associated conformance 31protocol_resilience_descriptors29ConformsWithAssocRequirementsV010resilient_A008ProtocoleF12TypeDefaultsAA2T2AdEP_AD014OtherResilientI0"
public struct ConformsWithAssocRequirements : ProtocolWithAssocTypeDefaults {
}
// CHECK-USAGE: @"$s31protocol_resilience_descriptors21ConditionallyConformsVyxG010resilient_A024ProtocolWithRequirementsAaeFRzAA1YV1TRtzlMc"
extension ConditionallyConforms: ProtocolWithRequirements
where Element: ProtocolWithRequirements, Element.T == Y {
public typealias T = Element.T
public func first() { }
public func second() { }
}
// CHECK-USAGE: @"$s31protocol_resilience_descriptors17ConformsToDerivedV010resilient_A009ResilientF8ProtocolAAMc" =
// CHECK-SAME: @"associated conformance 31protocol_resilience_descriptors17ConformsToDerivedV010resilient_A009ResilientF8ProtocolAaD0h4BaseI0"
public struct ConformsToDerived : ResilientDerivedProtocol {
public func requirement() -> Int { return 0 }
}
// ----------------------------------------------------------------------------
// Resilient protocol usage
// ----------------------------------------------------------------------------
// CHECK-USAGE: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.type* @"$s31protocol_resilience_descriptors17assocTypeMetadatay1TQzmxm010resilient_A024ProtocolWithRequirementsRzlF"(%swift.type* %0, %swift.type* [[PWD:%.*]], i8** [[WTABLE:%.*]])
public func assocTypeMetadata<PWR: ProtocolWithRequirements>(_: PWR.Type) -> PWR.T.Type {
// CHECK-USAGE: call swiftcc %swift.metadata_response @swift_getAssociatedTypeWitness([[INT]] 0, i8** %PWR.ProtocolWithRequirements, %swift.type* %PWR, %swift.protocol_requirement* @"$s18resilient_protocol24ProtocolWithRequirementsTL", %swift.protocol_requirement* @"$s1T18resilient_protocol24ProtocolWithRequirementsPTl")
return PWR.T.self
}
func useOtherResilientProtocol<T: OtherResilientProtocol>(_: T.Type) { }
// CHECK-USAGE: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s31protocol_resilience_descriptors23extractAssocConformanceyyx010resilient_A0012ProtocolWithE12TypeDefaultsRzlF"
public func extractAssocConformance<T: ProtocolWithAssocTypeDefaults>(_: T) {
// CHECK-USAGE: swift_getAssociatedConformanceWitness
useOtherResilientProtocol(T.T2.self)
}
| apache-2.0 | 0477498216f7ff19c76748bb479de39c | 57.106195 | 444 | 0.727993 | 4.106316 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals/Business/Today/TodayWorkloadCalculator.swift | 1 | 1252 | //
// TodayWorkloadInfo.swift
// YourGoals
//
// Created by André Claaßen on 08.01.18.
// Copyright © 2018 André Claaßen. All rights reserved.
//
import Foundation
struct WorkloadInfo {
let totalRemainingTime: TimeInterval
let totalTasksLeft: Int
let endTime: Date
}
class TodayWorkloadCalculator: StorageManagerWorker {
typealias infoTuple = (remainingTime: TimeInterval, tasksLeft: Int)
func calcWorkload(forDate date: Date, backburnedGoals: Bool) throws -> WorkloadInfo {
let todayDataSource = TodayAllActionablesDataSource(manager: self.manager)
let items = try todayDataSource.fetchItems(forDate: date, withBackburned: backburnedGoals, andSection: nil)
let actionables = items.map { $0.actionable }
let sumInfo = actionables.reduce((remainingTime: TimeInterval(0.0), tasksLeft: 0)) { i, actionable in
let remainingTime = actionable.calcRemainingTimeInterval(atDate: date)
return (i.remainingTime + remainingTime, i.tasksLeft + 1)
}
let endTime = date.addingTimeInterval(sumInfo.remainingTime)
return WorkloadInfo(totalRemainingTime: sumInfo.remainingTime, totalTasksLeft: sumInfo.tasksLeft, endTime: endTime )
}
}
| lgpl-3.0 | de8f7ddc9419620e842fc6e37ddad4fc | 36.787879 | 124 | 0.717723 | 4.329861 | false | false | false | false |
naithar/MagickWand | Tests/MagickWandTests/Utils.swift | 1 | 1491 | //
// Utils.swift
// MagickWand
//
// Created by Sergey Minakov on 19.01.17.
//
//
import Foundation
internal enum Utils {
static func path(filePath: String = #file) -> String {
let path = filePath.components(separatedBy: "/").dropLast(3).joined(separator: "/")
return path
}
static func delete(fileName: String, filePath: String = #file) {
let path = filePath.components(separatedBy: "/").dropLast(3).joined(separator: "/")
let url = URL(fileURLWithPath: "\(path)/\(fileName)")
try? FileManager.default.removeItem(at: url)
}
static func save(fileName: String, data: Data, filePath: String = #file) -> Bool {
do {
let path = filePath.components(separatedBy: "/").dropLast(3).joined(separator: "/")
let url = URL(fileURLWithPath: "\(path)/\(fileName)")
try data.write(to: url)
return true
} catch {
return false
}
}
static func open(file: String, ofType type: String, filePath: String = #file) -> Data? {
var fileData: Data?
if let data = try? Data(contentsOf: URL(fileURLWithPath: "\(file).\(type)")) {
fileData = data
} else {
let path = filePath.components(separatedBy: "/").dropLast(3).joined(separator: "/")
fileData = try? Data(contentsOf: URL(fileURLWithPath: "\(path)/\(file).\(type)"))
}
return fileData
}
}
| mit | 24d21a66dea1f22f14e22385d6bbe160 | 30.723404 | 95 | 0.566063 | 4.346939 | false | false | false | false |
glorybird/KeepReading2 | kr/Pods/YapDatabaseExtensions/YapDatabaseExtensions/Shared/Persistable/Read.swift | 2 | 3594 | //
// Created by Daniel Thorpe on 22/04/2015.
//
//
import Foundation
import ValueCoding
import YapDatabase
// MARK: - Readable
/// Generic protocol for Reader types.
public protocol Readable {
typealias ItemType
typealias Database: DatabaseType
var transaction: Database.Connection.ReadTransaction? { get }
var connection: Database.Connection { get }
}
/// A generic structure used to read from a database type.
public struct Read<Item, D: DatabaseType>: Readable {
public typealias ItemType = Item
public typealias Database = D
let reader: Handle<D>
public var transaction: D.Connection.ReadTransaction? {
if case let .Transaction(transaction) = reader {
return transaction
}
return .None
}
public var connection: D.Connection {
switch reader {
case .Transaction(_):
fatalError("Attempting to get connection from a transaction.")
case .Connection(let connection):
return connection
default:
return database.makeNewConnection()
}
}
internal var database: D {
if case let .Database(database) = reader {
return database
}
fatalError("Attempting to get database from \(reader)")
}
internal init(_ transaction: D.Connection.ReadTransaction) {
reader = .Transaction(transaction)
}
internal init(_ connection: D.Connection) {
reader = .Connection(connection)
}
internal init(_ database: D) {
reader = .Database(database)
}
}
extension Persistable {
/**
Returns a type suitable for *reading* from the transaction. The available
functions will depend on your own types correctly implementing Persistable,
MetadataPersistable and ValueCoding.
For example, given the key for a `Person` type, and you are in a read
transaction block, the following would read the object for you.
if let person = Person.read(transaction).key(key) {
print("Hello \(person.name)")
}
Note that this API is consistent for Object types, Value types, with or
without metadata.
- parameter transaction: a type conforming to ReadTransactionType such as
YapDatabaseReadTransaction
*/
public static func read<D: DatabaseType>(transaction: D.Connection.ReadTransaction) -> Read<Self, D> {
return Read(transaction)
}
/**
Returns a type suitable for Reading from a database connection. The available
functions will depend on your own types correctly implementing Persistable,
MetadataPersistable and ValueCoding.
For example, given the key for a `Person` type, and you have a database
connection.
if let person = Person.read(connection).key(key) {
print("Hello \(person.name)")
}
Note that this API is consistent for Object types, Value types, with or
without metadata.
- parameter connection: a type conforming to ConnectionType such as
YapDatabaseConnection.
*/
public static func read<D: DatabaseType>(connection: D.Connection) -> Read<Self, D> {
return Read(connection)
}
internal static func read<D: DatabaseType>(database: D) -> Read<Self, D> {
return Read(database)
}
}
extension Readable
where
ItemType: Persistable {
func sync<T>(block: (Database.Connection.ReadTransaction) -> T) -> T {
if let transaction = transaction {
return block(transaction)
}
return connection.read(block)
}
}
| apache-2.0 | 9e09abe16a1a1ad299751c02777864c8 | 26.227273 | 106 | 0.657206 | 4.830645 | false | false | false | false |
Snowy1803/BreakBaloon-mobile | BreakBaloon/Start/Button.swift | 1 | 1487 | //
// Button.swift
// Button
//
// Created by Emil Pedersen on 20/07/2021.
// Copyright © 2021 Snowy_1803. All rights reserved.
//
import SpriteKit
class Button: SKSpriteNode {
static let fontName = "ChalkboardSE-Light"
static let textures: [Size: SKTexture] = [
.normal: SKTexture(imageNamed: "buttonbg"),
.mini: SKTexture(imageNamed: "buttonminibg"),
]
let label: SKLabelNode
init(size: Size, text: String) {
let texture = Button.textures[size]!
label = SKLabelNode(text: text)
super.init(texture: texture, color: .clear, size: texture.size())
self.zPosition = 1
label.fontSize = size.fontSize
label.fontName = Button.fontName
label.fontColor = SKColor.black
label.zPosition = 2
label.position = CGPoint(x: 0, y: size.labelOffset)
addChild(label)
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
enum Size {
case normal
case mini
var fontSize: CGFloat {
switch self {
case .normal:
return 35
case .mini:
return 20
}
}
var labelOffset: CGFloat {
switch self {
case .normal:
return -15
case .mini:
return -10
}
}
}
}
| mit | 220f4940cc377530c2c08b31358bb936 | 23.766667 | 73 | 0.533647 | 4.516717 | false | false | false | false |
ubi-naist/SenStick | SenStickSDK/SenStickSDK/BrightnessSensorService.swift | 1 | 2068 | //
// BrightnessSensorService.swift
// SenStickSDK
//
// Created by AkihiroUehara on 2016/05/24.
// Copyright © 2016年 AkihiroUehara. All rights reserved.
//
import Foundation
public enum BrightnessRange : UInt16, CustomStringConvertible
{
case brightnessRangeDefault = 0x00
public var description : String {
switch self {
case .brightnessRangeDefault: return "brightnessRangeDefault"
}
}
}
struct BrightnessRawData
{
var rawValue : UInt16
init(rawValue:UInt16)
{
self.rawValue = rawValue
}
// 物理センサーの1luxあたりのLBSの値
static func getLSBperLux(_ range: BrightnessRange) -> Double
{
switch range {
case .brightnessRangeDefault: return 1
}
}
static func unpack(_ data: [Byte]) -> BrightnessRawData
{
let value = UInt16.unpack(data[0..<2])
return BrightnessRawData(rawValue: value!)
}
}
public struct BrightnessData : SensorDataPackableType
{
public var brightness: Double
public init(brightness: Double) {
self.brightness = brightness
}
public typealias RangeType = BrightnessRange
public static func unpack(_ range:BrightnessRange, value: [UInt8]) -> BrightnessData?
{
guard value.count >= 2 else {
return nil
}
let rawData = BrightnessRawData.unpack(value)
let LSBperLux = BrightnessRawData.getLSBperLux(range)
//debugPrint("Brightness, raw:\(rawData), lsbPerLux:\(LSBperLux), value:\((Double(rawData.rawValue) / LSBperLux))")
return BrightnessData(brightness: (Double(rawData.rawValue) / LSBperLux));
}
}
// センサー各種のベースタイプ, Tはセンサデータ独自のデータ型, Sはサンプリングの型、
open class BrightnessSensorService: SenStickSensorService<BrightnessData, BrightnessRange>
{
required public init?(device:SenStickDevice)
{
super.init(device: device, sensorType: SenStickSensorType.brightnessSensor)
}
}
| mit | 93e412e2e7174318a5fae75a24e05d39 | 24.855263 | 115 | 0.664122 | 3.922156 | false | false | false | false |
kbelter/SnazzyList | SnazzyList/Classes/src/TableView/DataSources/GenericTableViewDataSource.swift | 1 | 17481 | //
// TableView.swift
// Noteworth2
//
// Created by Kevin on 12/20/18.
// Copyright © 2018 Noteworth. All rights reserved.
//
import UIKit
public class GenericTableViewDataSource: NSObject, UITableViewDataSource {
weak var tableView: UITableView!
public var configFiles: [GenericTableCellConfigurator] {
didSet {
registerCells()
}
}
public init(tableView: UITableView, configFiles: [GenericTableCellConfigurator], sectionIndexTitlesDatasource: GenericTableSectionIndexTitlesDatasource? = nil) {
self.tableView = tableView
self.configFiles = configFiles
self.sectionIndexTitlesDatasource = sectionIndexTitlesDatasource
super.init()
registerCells()
self.tableView.dataSource = self
}
public func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return self.sectionIndexTitlesDatasource?.sectionForSectionIndexTitle(title: title, at: index) ?? 0
}
// MARK: - TableView Data Source Methods.
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let configFile = (configFiles.filter { $0.section == indexPath.section && $0.typeCell == .cell })[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: configFile.className, for: indexPath)
cell.accessibilityIdentifier = "\(type(of: cell)).s\(indexPath.section)-r\(indexPath.row)"
cell.isAccessibilityElement = false
(cell as! GenericTableCellProtocol).tableView(tableView, cellForRowAt: indexPath, with: configFile.item)
var accessibilityInfo = configFile.accessibilityInfo
accessibilityInfo?.indexPath = indexPath
cell.setupAccessibilityIdentifiersForViewProperties(withAccessibilityInfo: accessibilityInfo)
return cell
}
public func numberOfSections(in tableView: UITableView) -> Int {
guard let maxSectionNumber = (configFiles.map { $0.section }.sorted { $0 > $1 }).first else { return 1 }
return maxSectionNumber + 1
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return configFiles.filter { $0.section == section && $0.typeCell == .cell }.count
}
public func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return self.sectionIndexTitlesDatasource?.sectionIndexTitles
}
public func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
guard let cell = tableView.cellForRow(at: indexPath) as? GenericTableCellProtocol else { return }
let filteredConfigFiles = configFiles.filter { $0.section == indexPath.section && $0.typeCell == .cell }
if filteredConfigFiles.count < indexPath.row + 1 { return }
let configFile = filteredConfigFiles[indexPath.row]
cell.tableView?(tableView, commit: editingStyle, forRowAt: indexPath, with: configFile.item)
}
public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
guard let cell = tableView.cellForRow(at: indexPath) as? GenericTableCellProtocol else { return false }
let filteredConfigFiles = configFiles.filter { $0.section == indexPath.section && $0.typeCell == .cell }
if filteredConfigFiles.count < indexPath.row + 1 { return false }
let configFile = filteredConfigFiles[indexPath.row]
return cell.tableView?(tableView, canEditRowAt: indexPath, with: configFile.item) ?? false
}
// ---
private weak var sectionIndexTitlesDatasource: GenericTableSectionIndexTitlesDatasource?
}
extension GenericTableViewDataSource {
// MARK: - Util Public Methods.
public func getCell<T>(by filter: (GenericTableCellConfigurator)->Bool) -> T? {
guard let indexPath = getIndexPath(by: filter) else { return nil }
return self.tableView.cellForRow(at: indexPath) as? T
}
public func getIndexPath(by filter: (GenericTableCellConfigurator)->Bool) -> IndexPath? {
guard let configFile = configFiles.filter(filter).first else { return nil }
let allRowsForSection = configFiles.filter { $0.section == configFile.section && $0.typeCell == .cell }
guard let indexInSection = allRowsForSection.firstIndex(where: filter) else { return nil }
return IndexPath(item: indexInSection, section: configFile.section)
}
public func getAllIndexPaths() -> [IndexPath] {
var indexPaths = [IndexPath]()
let numberOfSections = tableView.numberOfSections - 1
if numberOfSections == 0 { return [] }
for section in 0 ... numberOfSections {
let configFilesForSection = self.configFiles.filter { $0.typeCell == .cell && $0.section == section }
for (index, _) in configFilesForSection.enumerated() {
indexPaths.append(IndexPath(item: index, section: section))
}
}
return indexPaths
}
public func update<T,U:UITableViewCell>(cellFinder filter: @escaping (GenericTableCellConfigurator)->Bool, updates: ((T, U?) -> ())) {
guard let item = configFiles.first(where: filter)?.item as? T else { return }
guard let indexPath = getIndexPath(by: filter) else {
updates(item, nil)
return
}
let cell = tableView.cellForRow(at: indexPath) as? U
updates(item, cell)
}
public func reload() {
tableView.reloadData()
}
public func reloadAt(section: Int, animation: UITableView.RowAnimation = .automatic) {
tableView.reloadSections(IndexSet(integer: section), with: animation)
}
public func reloadAtSections(indexSet: IndexSet, animation: UITableView.RowAnimation = .automatic) {
tableView.reloadSections(indexSet, with: animation)
}
public func reloadAt(indexPaths: [IndexPath], animation: UITableView.RowAnimation = .automatic) {
tableView.reloadRows(at: indexPaths, with: animation)
}
public func reloadAt(indexPath: IndexPath, animation: UITableView.RowAnimation = .automatic) {
reloadAt(indexPaths: [indexPath], animation: animation)
}
// MARK: - Delete Methods.
public func deleteRow(with animation: UITableView.RowAnimation = .automatic, filter: @escaping (GenericTableCellConfigurator)->Bool) {
guard let indexPath = self.getIndexPath(by: filter) else { return }
tableView.beginUpdates()
self.configFiles = self.configFiles.filter { !filter($0) }
tableView.deleteRows(at: [indexPath], with: animation)
let numberOfSections = self.tableView.numberOfSections
let rowsWithHeaders = self.configFiles.filter { $0.section == indexPath.section }
if numberOfSections - 1 == indexPath.section && rowsWithHeaders.count == 0 && numberOfSections > 1 {
self.tableView.deleteSections(getIndexSetToDelete(forSection: indexPath.section), with: animation)
}
tableView.endUpdates()
}
public func deleteRow(with animation: UITableView.RowAnimation = .automatic, filter: @escaping (GenericTableCellConfigurator)->Bool, andInsert configFiles: [GenericTableCellConfigurator]) {
guard let indexPath = self.getIndexPath(by: filter) else {
insertRows(configFiles: configFiles)
return
}
tableView.beginUpdates()
self.configFiles = self.configFiles.filter { !filter($0) }
tableView.deleteRows(at: [indexPath], with: animation)
let numberOfSections = self.tableView.numberOfSections
let rowsWithHeaders = self.configFiles.filter { $0.section == indexPath.section }
if numberOfSections - 1 == indexPath.section && rowsWithHeaders.count == 0 && numberOfSections > 1 {
self.tableView.deleteSections(getIndexSetToDelete(forSection: indexPath.section), with: animation)
}
insertRowsRaw(configFiles: configFiles)
tableView.endUpdates()
}
public func deleteRow(with animation: UITableView.RowAnimation = .automatic, filter: @escaping (GenericTableCellConfigurator)->Bool, andInsert configFile: GenericTableCellConfigurator) {
deleteRow(with: animation, filter: filter, andInsert: [configFile])
}
public func deleteAllRowsAt(section: Int, with animation: UITableView.RowAnimation = .automatic) {
let configFilesToDelete = self.configFiles.filter { $0.section == section && $0.typeCell == .cell }
if configFilesToDelete.count == 0 { return }
var indexPaths = [IndexPath]()
for (index, _) in configFilesToDelete.enumerated() {
indexPaths.append(IndexPath(item: index, section: section))
}
tableView.beginUpdates()
// Delete section if needed.
let headersOrFootersInSection = self.configFiles.filter { $0.section == section && $0.typeCell != .cell }
self.tableView.deleteRows(at: indexPaths, with: animation)
self.configFiles = self.configFiles.filter { !($0.section == section && $0.typeCell == .cell) }
if section == self.tableView.numberOfSections - 1 &&
self.tableView.numberOfSections > 1 &&
headersOrFootersInSection.count == 0 {
self.tableView.deleteSections(getIndexSetToDelete(forSection: section), with: animation)
}
// ---
tableView.endUpdates()
}
public func delete(at section: Int, andInsert configFiles: [GenericTableCellConfigurator], withAnimation animation: UITableView.RowAnimation = .automatic) {
let configFilesToDelete = self.configFiles.filter { $0.section == section && $0.typeCell == .cell }
var indexPaths = [IndexPath]()
for (index, _) in configFilesToDelete.enumerated() {
indexPaths.append(IndexPath(item: index, section: section))
}
tableView.beginUpdates()
self.tableView.deleteRows(at: indexPaths, with: animation)
self.configFiles = self.configFiles.filter { !($0.section == section && $0.typeCell == .cell) }
// Delete section if needed.
let headersOrFootersInSection = self.configFiles.filter { $0.section == section && $0.typeCell != .cell }
var maxSectionInsertedOpt: Int? = nil
if section == self.tableView.numberOfSections - 1 &&
self.tableView.numberOfSections > 1 &&
headersOrFootersInSection.count == 0 {
let indexSet = getIndexSetToDelete(forSection: section)
self.tableView.deleteSections(indexSet, with: animation)
maxSectionInsertedOpt = indexSet.first
}
// ---
self.insertRowsRaw(configFiles: configFiles, with: animation, maxSectionInsertedOpt: maxSectionInsertedOpt)
tableView.endUpdates()
}
public func deleteEverything(andInsert configFiles: [GenericTableCellConfigurator], withAnimation animation: UITableView.RowAnimation = .automatic) {
let insertIndexPaths = getStandaloneIndexPaths(configFiles: configFiles.filter { $0.typeCell == .cell })
let maxOldSection = self.configFiles.sorted { $0.section > $1.section }.first?.section ?? 0
let maxSection = configFiles.sorted { $0.section > $1.section }.first?.section ?? 0
self.tableView.beginUpdates()
self.tableView.deleteSections(IndexSet(integersIn: 0 ... maxOldSection), with: animation)
self.configFiles = configFiles
self.tableView.insertSections(IndexSet(integersIn: 0 ... maxSection), with: animation)
self.tableView.insertRows(at: insertIndexPaths, with: animation)
self.tableView.endUpdates()
}
// MARK: - Insert Methods.
public func insertRows(configFiles: [GenericTableCellConfigurator], with animation: UITableView.RowAnimation = .automatic, maxSectionInsertedOpt: Int? = nil) {
tableView.beginUpdates()
self.insertRowsRaw(configFiles: configFiles, with: animation, maxSectionInsertedOpt: maxSectionInsertedOpt)
tableView.endUpdates()
}
public func insertRowsAtTopOfEachSection(configFiles: [GenericTableCellConfigurator], with animation: UITableView.RowAnimation = .automatic) {
let sections = Set(configFiles.map { $0.section }).sorted { $0 < $1 }
var maxSectionInserted = self.tableView.numberOfSections
tableView.beginUpdates()
for section in sections {
if maxSectionInserted <= section {
self.tableView.insertSections(
IndexSet(integersIn: (maxSectionInserted...section)),
with: animation
)
maxSectionInserted = section + 1
}
let configFilesRowsForSection = configFiles.filter { $0.section == section && $0.typeCell == .cell }
let configFilesForSection = configFiles.filter { $0.section == section }
var indexPaths = [IndexPath]()
for (index, _) in configFilesRowsForSection.enumerated() {
indexPaths.append(IndexPath(item: index, section: section))
}
self.configFiles.insert(contentsOf: configFilesForSection, at: 0)
self.tableView.insertRows(at: indexPaths, with: animation)
}
tableView.endUpdates()
}
public func insertRowAtTopOfSection(configFile: GenericTableCellConfigurator) {
insertRowsAtTopOfEachSection(configFiles: [configFile])
}
public func insertRow(configFile: GenericTableCellConfigurator, withAnimation: UITableView.RowAnimation = .automatic) {
insertRows(configFiles: [configFile], with: withAnimation)
}
}
// MARK: - Private Inner Framework Methods
extension GenericTableViewDataSource {
private func registerCells() {
let classesToRegister = Set(configFiles)
for classToRegister in classesToRegister {
switch classToRegister.typeCell {
case .cell:
tableView.register(
classToRegister.classType,
forCellReuseIdentifier: classToRegister.className
)
case .header, .footer:
tableView.register(
classToRegister.classType,
forHeaderFooterViewReuseIdentifier: classToRegister.className
)
}
}
}
private func getIndexPaths(section: Int, configFiles: [GenericTableCellConfigurator]) -> [IndexPath] {
var indexPaths = [IndexPath]()
let numberOfCellsInSection = self.configFiles.filter { $0.section == section && $0.typeCell == .cell }.count
for (index, _) in configFiles.enumerated() {
indexPaths.append(IndexPath(item: index + numberOfCellsInSection, section: section))
}
return indexPaths
}
private func getStandaloneIndexPaths(configFiles: [GenericTableCellConfigurator]) -> [IndexPath] {
var indexPaths = [IndexPath]()
let allSections = Set(configFiles.map { $0.section }).sorted(by: >)
for section in allSections {
let rowsInSection = configFiles.filter { $0.section == section }
for (index, _) in rowsInSection.enumerated() {
indexPaths.append(IndexPath(item: index, section: section))
}
}
return indexPaths
}
private func getIndexSetToDelete(forSection section: Int) -> IndexSet {
let sectionToDeleteFrom: Int
if let sec = ((self.configFiles.filter { $0.section < section }).sorted { $0.section > $1.section }).first?.section {
sectionToDeleteFrom = sec + 1
} else {
sectionToDeleteFrom = 1
}
return IndexSet(integersIn: sectionToDeleteFrom ... section)
}
private func insertRowsRaw(configFiles: [GenericTableCellConfigurator], with animation: UITableView.RowAnimation = .automatic, maxSectionInsertedOpt: Int? = nil) {
let sections = Set(configFiles.map { $0.section }).sorted { $0 < $1 }
var maxSectionInserted = maxSectionInsertedOpt ?? self.tableView.numberOfSections
for section in sections {
if maxSectionInserted <= section {
self.tableView.insertSections(
IndexSet(integersIn: (maxSectionInserted...section)),
with: animation
)
maxSectionInserted = section + 1
}
let configFilesRowsForSection = configFiles.filter { $0.section == section && $0.typeCell == .cell }
let configFilesForSection = configFiles.filter { $0.section == section }
let indexPaths = self.getIndexPaths(section: section, configFiles: configFilesRowsForSection)
self.configFiles += configFilesForSection
self.tableView.insertRows(at: indexPaths, with: animation)
}
}
}
| apache-2.0 | 8a8d90cd2c3d00fd79c05e0be8f154de | 43.935733 | 193 | 0.647426 | 5.148748 | false | true | false | false |
SPECURE/rmbt-ios-client | Sources/QOS/QualityOfServiceTest.swift | 1 | 31760 | /*****************************************************************************************************
* Copyright 2014-2016 SPECURE GmbH
*
* 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
class RMBTConcurencyGroup {
var identifier: UInt = 0
private(set) var testExecutors: [QOSTestExecutorProtocol] = []
var passedExecutors: Int = 0
var percent: Float {
return Float(self.passedExecutors) / Float(self.testExecutors.count)
}
let mutualQuery = DispatchQueue(label: "Add executors")
func addTestExecutor(testExecutor: QOSTestExecutorProtocol) {
mutualQuery.sync {
testExecutors.append(testExecutor)
}
}
func removeTestExecutor(testExecutor: QOSTestExecutorProtocol) {
mutualQuery.sync {
if let index = testExecutors.firstIndex(where: { (executor) -> Bool in
return testExecutor === executor
}) {
testExecutors.remove(at: index)
}
}
}
func countExecutors(of type: QosMeasurementType) -> (passed: Int, total: Int) {
var totalCount = 0
var passedCount = 0
for executor in testExecutors {
if executor.testObjectType() == type {
totalCount += 1
if executor.testExecutorHasFinished() {
passedCount += 1
}
}
}
return (passedCount, totalCount)
}
}
///
open class QualityOfServiceTest: NSObject {
///
public typealias ConcurrencyGroup = UInt
///
public typealias JsonObjectivesType = [String: [[String: Any]]]
//
///
private let executorQueue = DispatchQueue(label: "com.specure.rmbt.executorQueue")
private let delegateQueue = DispatchQueue(label: "com.specure.rmbt.delegateQueue", attributes: DispatchQueue.Attributes.concurrent)
private let mutualExclusionQueue = DispatchQueue(label: "com.specure.rmbt.qos.mutualExclusionQueue")
///
private let qosQueue = DispatchQueue(label: "com.specure.rmbt.qosQueue", attributes: DispatchQueue.Attributes.concurrent)
var concurencyGroups: [RMBTConcurencyGroup] = []
///
open weak var delegate: QualityOfServiceTestDelegate?
///
var isPartOfMainTest = false
///
private let testToken: String
///
private let measurementUuid: String
///
private let speedtestStartTime: UInt64
///
private var testCount: UInt16 = 0
///
private var currentTestCount: UInt16 = 0
///
private var activeTestsInConcurrencyGroup = 0
///
private var controlConnectionMap: [String: QOSControlConnection] = [:]
///
private var qosTestConcurrencyGroupMap: [ConcurrencyGroup: [QOSTest]] = [:]
private var qosTestExecutors: [String: QOSTestExecutorProtocol] = [:]
///
private var testTypeCountMap: [QosMeasurementType: UInt16] = [:]
///
private var sortedConcurrencyGroups: [ConcurrencyGroup] = []
///
private var resultArray: [QOSTestResult] = []
///
private var stopped = false
//
deinit {
defer {
if self.stopped == false {
self.closeAllControlConnections()
}
}
}
///
public init(testToken: String, measurementUuid: String, speedtestStartTime: UInt64, isPartOfMainTest: Bool) {
self.testToken = testToken
self.measurementUuid = measurementUuid
self.speedtestStartTime = speedtestStartTime
self.isPartOfMainTest = isPartOfMainTest
Log.logger.debug("QualityOfServiceTest initialized with test token: \(testToken) at start time \(speedtestStartTime)")
}
///
open func start() {
if !stopped {
qosQueue.async {
self.fetchQOSTestParameters()
}
}
}
///
open func stop() {
Log.logger.debug("ABORTING QOS TEST")
self.stopped = true
DispatchQueue.main.async {
// close all control connections
self.closeAllControlConnections()
// inform delegate
self.delegate?.qualityOfServiceTestDidStop(self)
return
}
}
//
///
private func fetchQOSTestParameters() {
if stopped {
return
}
let controlServer = ControlServer.sharedControlServer
controlServer.requestQosMeasurement(measurementUuid, success: { [weak self] response in
self?.qosQueue.async {
if self?.isPartOfMainTest == true {
if let jitterParams = response.objectives?[QosMeasurementType.JITTER.rawValue],
let firstParams = jitterParams.first {
response.objectives = [QosMeasurementType.VOIP.rawValue: [firstParams]]
} else if let voipParams = response.objectives?[QosMeasurementType.VOIP.rawValue] {
response.objectives = [QosMeasurementType.VOIP.rawValue: voipParams]
} else {
response.objectives = [:]
}
} else {
response.objectives?[QosMeasurementType.JITTER.rawValue] = nil
// response.objectives?[QosMeasurementType.UDP.rawValue] = nil
// response.objectives?[QosMeasurementType.TCP.rawValue] = nil
// response.objectives?[QosMeasurementType.HttpProxy.rawValue] = nil
// response.objectives?[QosMeasurementType.NonTransparentProxy.rawValue] = nil
// response.objectives?[QosMeasurementType.WEBSITE.rawValue] = nil
// response.objectives?[QosMeasurementType.DNS.rawValue] = nil
// response.objectives?[QosMeasurementType.VOIP.rawValue] = nil
// response.objectives?[QosMeasurementType.TRACEROUTE.rawValue] = nil
}
self?.continueWithQOSParameters(response)
}
}) { [weak self] error in
Log.logger.debug("ERROR fetching qosTestRequest")
self?.fail(nil) // TODO: error message...
}
}
///
private func continueWithQOSParameters(_ responseObject: QosMeasurmentResponse) {
if stopped {
return
}
// call didStart delegate method // TODO: right place here?
DispatchQueue.main.async {
self.delegate?.qualityOfServiceTestDidStart(self)
return
}
parseRequestResult(responseObject)
createTestTypeCountMap()
// openAllControlConnections() // open all control connections before tests
self.runQOSTests()
}
func findNextTestExecutor(in group: RMBTConcurencyGroup) -> QOSTestExecutorProtocol? {
for testExecutor in group.testExecutors {
if !testExecutor.testExecutorHasFinished() {
return testExecutor
}
}
return nil
}
func findNextConcurencyGroup() -> RMBTConcurencyGroup? {
for group in concurencyGroups {
if group.passedExecutors != group.testExecutors.count {
return group
}
}
return nil
}
func findConcurencyGroup(with id: UInt) -> RMBTConcurencyGroup {
for group in concurencyGroups {
if group.identifier == id {
return group
}
}
let group = RMBTConcurencyGroup()
group.identifier = id
concurencyGroups.append(group)
return group
}
///
private func parseRequestResult(_ responseObject: QosMeasurmentResponse) {
if stopped {
return
}
guard let objectives = responseObject.objectives else { return }
for (objectiveType, objectiveValues) in objectives {
for (objectiveParams) in objectiveValues {
if let qosTest = QOSFactory.createQOSTest(objectiveType, params: objectiveParams),
let testExecutor = QOSFactory.createTestExecutor(qosTest, delegateQueue: delegateQueue, speedtestStartTime: speedtestStartTime) {
let group = self.findConcurencyGroup(with: qosTest.concurrencyGroup)
group.addTestExecutor(testExecutor: testExecutor)
testCount += 1
if isPartOfMainTest == true && objectiveType == QosMeasurementType.VOIP.rawValue {
testExecutor.setProgressCallback { [weak self] (_, percent) in
guard let strongSelf = self else { return }
strongSelf.delegate?.qualityOfServiceTest(strongSelf, didProgressToValue: percent)
}
}
testExecutor.setCurrentTestToken(self.testToken)
}
}
}
self.concurencyGroups = self.concurencyGroups.sorted(by: { (group1, group2) -> Bool in
return group1.identifier < group2.identifier
})
return
// loop through objectives
// objective type is TCP, UDP, etc.
// objective values are arrays of dictionaries for each test
// for (objectiveType, objectiveValues) in objectives {
//
// // loop each test
// for (objectiveParams) in objectiveValues {
// Log.logger.verbose("-----")
// Log.logger.verbose("\(objectiveType): \(objectiveParams)")
// Log.logger.verbose("-------------------")
//
// // try to create qos test object from params
// if let qosTest = QOSFactory.createQOSTest(objectiveType, params: objectiveParams) {
// ///////////// ONT
// if isPartOfMainTest {
//
// if let type = QosMeasurementType(rawValue: objectiveType) {
//
// if type == .VOIP {
//
// Log.logger.debug("created VOIP test as the main test: \(qosTest)")
//
// var concurrencyGroupArray: [QOSTest]? = qosTestConcurrencyGroupMap[qosTest.concurrencyGroup]
// if concurrencyGroupArray == nil {
// concurrencyGroupArray = []
// }
//
// concurrencyGroupArray?.append(qosTest)
// qosTestConcurrencyGroupMap[qosTest.concurrencyGroup] = concurrencyGroupArray // is this line needed? wasn't this passed by reference?
//
// // increase test count
// testCount += 1
// }
// }
//
// } else {
//
// if let type = QosMeasurementType(rawValue: objectiveType) {
// if type != .JITTER {
// Log.logger.debug("created qos test: \(qosTest)")
//
// var concurrencyGroupArray: [QOSTest]? = qosTestConcurrencyGroupMap[qosTest.concurrencyGroup]
// if concurrencyGroupArray == nil {
// concurrencyGroupArray = [QOSTest]()
// }
//
// concurrencyGroupArray!.append(qosTest)
// qosTestConcurrencyGroupMap[qosTest.concurrencyGroup] = concurrencyGroupArray // is this line needed? wasn't this passed by reference?
//
// // increase test count
// testCount += 1
// }
// }
// }
//
//
//
// } else {
// Log.logger.debug("unimplemented/unknown qos type: \(objectiveType)")
// }
// }
// }
//
// currentTestCount = testCount
//
// // create sorted array of keys to let the concurrencyGroups increase
// sortedConcurrencyGroups = Array(qosTestConcurrencyGroupMap.keys).sorted(by: <)
//
// Log.logger.debug("sorted concurrency groups: \(self.sortedConcurrencyGroups)")
}
///
private func createTestTypeCountMap() {
if stopped {
return
}
let testTypeArray = NSMutableSet()
for group in concurencyGroups {
for executor in group.testExecutors {
testTypeArray.add(executor.testObjectType())
}
}
DispatchQueue.main.async {
self.delegate?.qualityOfServiceTest(self, didFetchTestTypes: testTypeArray.map({ (type) -> String in
if let type = type as? QosMeasurementType {
return type.rawValue
}
return ""
}))
}
return
// var testTypeSortDictionary: [QosMeasurementType: ConcurrencyGroup] = [:]
//
// // fill testTypeCount map (used for displaying the finished test types in ui)
// for (cg, testArray) in qosTestConcurrencyGroupMap { // loop each concurrency group
// for test in testArray { // loop the tests inside each concurrency group
// let testType = test.getType()
//
// var count: UInt16? = testTypeCountMap[testType!]
// if count == nil {
// count = 0
// }
//
// count! += 1
//
// testTypeCountMap[testType!] = count!
//
// //////
//
// if testTypeSortDictionary[testType!] == nil {
// testTypeSortDictionary[testType!] = cg
// }
// }
// }
//
// // get test types and sort them according to their first execution
// var testTypeArray = [QosMeasurementType](self.testTypeCountMap.keys)
// testTypeArray.sort { (lhs, rhs) -> Bool in
// guard let firstType = testTypeSortDictionary[lhs],
// let secondType = testTypeSortDictionary[rhs]
// else {
// return false
// }
// return firstType < secondType
// }
//
// // call didFetchTestTypes delegate method
// DispatchQueue.main.async {
// self.delegate?.qualityOfServiceTest(self, didFetchTestTypes: testTypeArray.map({ (type) -> String in
// return type.rawValue
// }))
// return
// }
//
// Log.logger.debug("TEST TYPE COUNT MAP: \(self.testTypeCountMap)")
}
///
private func runQOSTests() {
Log.logger.debug("RUN QOS TESTS (stopped: \(self.stopped))")
if stopped {
return
}
// start with first concurrency group
runTestsOfNextConcurrencyGroup()
}
private func runNextTest(in concurencyGroup: RMBTConcurencyGroup) {
if stopped {
return
}
if let testExecutor = self.findNextTestExecutor(in: concurencyGroup) {
// for testExecutor in concurencyGroup.testExecutors {
// execute test
executorQueue.async {
testExecutor.execute { [weak self, weak concurencyGroup] (testResult: QOSTestResult) in
self?.mutualExclusionQueue.sync { [weak self] in
self?.resultArray.append(testResult)
concurencyGroup?.passedExecutors += 1
self?.checkProgress()
if let concurencyGroup = concurencyGroup {
self?.runNextTest(in: concurencyGroup)
}
// if concurencyGroup?.passedExecutors == concurencyGroup?.testExecutors.count {
// self?.closeAllControlConnections()
// self?.mutualExclusionQueue.asyncAfter(deadline: .now() + 0.5, execute: {
// self?.controlConnectionMap = [:]
// self?.runTestsOfNextConcurrencyGroup()
// })
// }
}
}
}
// }
}
else {
self.closeAllControlConnections()
self.controlConnectionMap = [:]
self.runTestsOfNextConcurrencyGroup()
}
}
///
private func runTestsOfNextConcurrencyGroup() {
if stopped {
return
}
if let concurencyGroup = self.findNextConcurencyGroup() {
for testExecutor in concurencyGroup.testExecutors {
if testExecutor.needsControlConnection() {
let qosTest = testExecutor.getTestObject()
if let controlConnection = getControlConnection(qosTest) {
if !testExecutor.needsCustomTimeoutHandling() {
controlConnection.setTimeout(QOS_CONTROL_CONNECTION_TIMEOUT_NS)
}
testExecutor.setControlConnection(controlConnection)
}
else {
// don't do this test
Log.logger.info("skipping test because it needs control connection but we don't have this connection. \(qosTest)")
concurencyGroup.removeTestExecutor(testExecutor: testExecutor)
testCount -= 1
continue
}
}
}
// self.runNextTest(in: concurencyGroup)
// return
for testExecutor in concurencyGroup.testExecutors {
// execute test
executorQueue.async {
testExecutor.execute { [weak self, weak concurencyGroup] (testResult: QOSTestResult) in
self?.mutualExclusionQueue.sync { [weak self] in
self?.resultArray.append(testResult)
concurencyGroup?.passedExecutors += 1
self?.checkProgress()
if concurencyGroup?.passedExecutors == concurencyGroup?.testExecutors.count {
self?.mutualExclusionQueue.asyncAfter(deadline: .now() + 0.5, execute: {
self?.runTestsOfNextConcurrencyGroup()
})
}
}
}
}
}
}
else {
self.finalizeQOSTests()
}
// if sortedConcurrencyGroups.count > 0 {
// let concurrencyGroup = sortedConcurrencyGroups.remove(at: 0) // what happens if empty?
//
// Log.logger.debug("run tests of next concurrency group: \(concurrencyGroup) (\(self.sortedConcurrencyGroups.count))")
//
// if let testArray = qosTestConcurrencyGroupMap[concurrencyGroup] {
//
// // set count of tests
// activeTestsInConcurrencyGroup = testArray.count
//
// // calculate control connection timeout (TODO: improve)
// // var controlConnectionTimeout: UInt64 = 0
// // for qosTest in testArray {
// // controlConnectionTimeout += qosTest.timeout
// // }
// /////
//
// // loop test array
// for qosTest in testArray {
// if stopped {
// return
// }
//
// // get previously opened control connection
// let controlConnection = getControlConnection(qosTest) // blocking if new connection has to be established
//
// // get test executor
// if let testExecutor = QOSFactory.createTestExecutor(qosTest, controlConnection: controlConnection, delegateQueue: executorQueue, speedtestStartTime: speedtestStartTime) {
// // TODO: which queue?
//
// let key = UUID().uuidString
// self.qosTestExecutors[key] = testExecutor //Need keep it in memory
//
// // set test token (TODO: IMPROVE)
// testExecutor.setCurrentTestToken(self.testToken)
//
// if testExecutor.needsControlConnection() {
// // set control connection timeout (TODO: compute better! (not all tests may use same control connection))
// Log.logger.debug("setting control connection timeout to \(nsToMs(qosTest.timeout)) ms")
// controlConnection.setTimeout(qosTest.timeout)
//
// // TODO: DETERMINE IF TEST NEEDS CONTROL CONNECTION
// // IF IT NEEDS IT, AND CONTROL CONNECTION CONNECT FAILED THEN SKIP THIS TEST AND DON'T SEND RESULT TO SERVER
// if !controlConnection.connected {
// // don't do this test
// Log.logger.info("skipping test because it needs control connection but we don't have this connection. \(qosTest)")
//
// self.mutualExclusionQueue.sync {
// self.qosTestFinishedWithResult(qosTest.getType(), withTestResult: nil) // no result because test didn't run
// }
//
// continue
// }
// }
//
// Log.logger.debug("starting execution of test: \(qosTest)")
//
// // execute test
// self.executorQueue.async {
// testExecutor.execute { [weak self] (testResult: QOSTestResult) in
//
// self?.mutualExclusionQueue.sync { [weak self] in
// self?.qosTestExecutors[key] = nil
// self?.qosTestFinishedWithResult(testResult.testType, withTestResult: testResult)
// }
// }
// }
// }
// }
// }
// }
// else {
// fail(nil)
// }
}
///
private func qosTestFinishedWithResult(_ testType: QosMeasurementType, withTestResult testResult: QOSTestResult?) {
if stopped {
return
}
Log.logger.debug("qos test finished with result: \(String(describing: testResult))")
if let testResult = testResult {
if testResult.fatalError {
// TODO: quit whole test due to fatal error
// !!
// TODO: dispatch delegate method
self.fail(nil) // TODO: error message...
}
// add result to result map
resultArray.append(testResult)
}
checkProgress()
checkTypeCount(testType)
// checkTestState()
}
///
private func checkProgress() {
if stopped {
return
}
// if self.currentTestCount > 0 {
// // decrement test counts
// self.currentTestCount -= 1
// }
// // check for progress
// let testsLeft = self.testCount - self.currentTestCount
// let percent: Float = Float(testsLeft) / Float(self.testCount)
var percent: Float = 0.0
for group in concurencyGroups {
percent += group.percent
}
percent /= Float(concurencyGroups.count)
Log.logger.debug("QOS: increasing progress to \(percent)")
DispatchQueue.main.async {
self.delegate?.qualityOfServiceTest(self, didProgressToValue: percent)
return
}
}
///
private func checkTypeCount(_ testType: QosMeasurementType) {
if stopped {
return
}
var totalTests: Int = 0
var passedTests: Int = 0
for group in concurencyGroups {
let counts = group.countExecutors(of: testType)
totalTests += counts.total
passedTests += counts.passed
}
if totalTests == passedTests {
DispatchQueue.main.async {
self.delegate?.qualityOfServiceTest(self, didFinishTestType: testType.rawValue)
}
}
// // check for finished test type
// if let count = self.testTypeCountMap[testType] {
// if count > 0 {
// self.testTypeCountMap[testType] = count - 1
// }
// if count == 0 {
//
// Log.logger.debug("QOS: finished test type: \(testType)")
//
// DispatchQueue.main.async {
// self.delegate?.qualityOfServiceTest(self, didFinishTestType: testType.rawValue)
// return
// }
// }
// }
}
///
private func checkTestState() {
if stopped {
return
}
activeTestsInConcurrencyGroup -= 1
if activeTestsInConcurrencyGroup == 0 {
// all tests in concurrency group finished
// -> go on with next concurrency group
if sortedConcurrencyGroups.count > 0 {
// there are more concurrency groups (and tests)
self.qosQueue.async {
self.runTestsOfNextConcurrencyGroup()
}
} else {
// all concurrency groups finished
self.qosQueue.async {
self.finalizeQOSTests()
}
}
}
}
///
private func finalizeQOSTests() {
if stopped {
return
}
Log.logger.debug("ALL FINISHED")
closeAllControlConnections()
// submit results
submitQOSTestResults()
}
///
private func getControlConnection(_ qosTest: QOSTest) -> QOSControlConnection? {
// determine control connection
let controlConnectionKey: String = "\(qosTest.serverAddress)_\(qosTest.serverPort)"
// TODO: make instantiation of control connection synchronous with locks!
var conn: QOSControlConnection? = self.controlConnectionMap[controlConnectionKey]
if conn == nil {
Log.logger.debug("\(controlConnectionKey): trying to open new control connection")
// Log.logger.debug("NO CONTROL CONNECTION PRESENT FOR \(controlConnectionKey), creating a new one")
Log.logger.debug("\(controlConnectionKey): BEFORE LOCK")
// TODO: fail after timeout if qos server not available
conn = QOSControlConnection(testToken: testToken)
// conn.delegate = self
controlConnectionMap[controlConnectionKey] = conn
} else {
Log.logger.debug("\(controlConnectionKey): control connection already opened")
}
if conn?.connected == false {
// reconnect
let isConnected = conn?.connect(qosTest.serverAddress, onPort: qosTest.serverPort)
if isConnected == false {
controlConnectionMap[controlConnectionKey] = nil
conn = nil
}
}
return conn
}
///
private func openAllControlConnections() {
Log.logger.info("opening all control connections")
for concurrencyGroup in self.sortedConcurrencyGroups {
if let testArray = qosTestConcurrencyGroupMap[concurrencyGroup] {
for qosTest in testArray {
// dispatch_sync(mutualExclusionQueue) {
/* let controlConnection = */_ = self.getControlConnection(qosTest)
// Log.logger.debug("opened control connection for qosTest \(qosTest)")
// }
}
}
}
}
///
private func closeAllControlConnections() {
Log.logger.info("closing all control connections")
// TODO: if everything is done: close all control connections
for (_, controlConnection) in self.controlConnectionMap {
Log.logger.debug("closing control connection \(controlConnection)")
controlConnection.disconnect()
}
}
///////////////
///
private func fail(_ error: NSError?) {
if stopped {
return
}
stop()
DispatchQueue.main.async {
self.delegate?.qualityOfServiceTest(self, didFailWithError: error)
return
}
}
///
private func success() {
if stopped {
return
}
DispatchQueue.main.async {
self.closeAllControlConnections()
self.delegate?.qualityOfServiceTest(self, didFinishWithResults: self.resultArray)
return
}
}
////////////////////////////////////////////
///
private func submitQOSTestResults() {
if stopped {
return
}
var _testResultArray: [QOSTestResults] = []
for testResult in resultArray { // TODO: resultArray == _testResultArray? just use resultArray?
if !testResult.isEmpty() {
_testResultArray.append(testResult.resultDictionary)
}
}
print("SUBMIT RESULTS")
print(_testResultArray)
// don't send results if all results are empty (e.g. only tcp tests and no control connection) or added additional test as part of the main test group
if _testResultArray.isEmpty || self.isPartOfMainTest {
// inform delegate
success()
return
}
//
let qosMeasurementResult = QosMeasurementResultRequest()
qosMeasurementResult.measurementUuid = measurementUuid
qosMeasurementResult.testToken = testToken
// RMBTTimestampWithNSDate(NSDate() as Date) as? UInt64
qosMeasurementResult.time = UInt64.currentTimeMillis() // currently unused on server!
qosMeasurementResult.qosResultList = _testResultArray
let controlServer = ControlServer.sharedControlServer
controlServer.submitQosMeasurementResult(qosMeasurementResult, success: { [weak self] response in
Log.logger.debug("QOS TEST RESULT SUBMIT SUCCESS")
// now the test has finished...succeeding methods should go here
self?.success()
}) { [weak self] error in
Log.logger.debug("QOS TEST RESULT SUBMIT ERROR: \(error)")
// here the test failed...
self?.fail(error as NSError?)
}
}
}
| apache-2.0 | 62b62232519101a0ef3e520d498e43ae | 34.96829 | 192 | 0.53454 | 5.148322 | false | true | false | false |
bradhowes/SynthInC | SynthInC/SoundFonts.swift | 1 | 22748 | // SoundFonts.swift
// SynthInC
//
// Created by Brad Howes
// Copyright (c) 2016 Brad Howes. All rights reserved.
import Foundation
/**
Representation of a sound font library. NOTE: all sound font files must have 'sf2' extension.
*/
class SoundFont: NSObject {
/**
Mapping of registered sound fonts. Add additional sound font entries here to make them available to the
SoundFont code.
*/
static let library: [String:SoundFont] = [
// -INSERT_HERE-
FreeFont.name: FreeFont.register(),
GeneralUser.name: GeneralUser.register(),
RolandPiano.name: RolandPiano.register(),
FluidR3.name:FluidR3.register()
]
/**
Array of registered sound font names sorted in alphabetical order. Generated from `library` entries.
*/
static var keys = library.keys.sort()
static var patchCount = library.reduce(0) { $0 + $1.1.patches.count }
/**
Obtain a random patch from all registered sound fonts.
- returns: radom Patch object
*/
static func randomPatch() -> Patch {
var pos = RandomUniform.sharedInstance.uniform(0, upper: patchCount)
let soundFont = library.filter {
(k, sf) -> Bool in
let result = (pos >= 0 && pos < sf.patches.count)
if pos >= 0 { pos -= sf.patches.count }
return result
}.last!.1
let index = pos + soundFont.patches.count
precondition(index >= 0 && index < soundFont.patches.count)
return soundFont.patches[index]
}
/**
Obtain a SoundFont using an index into the `keys` name array. If the index is out-of-bounds this will return the
FreeFont sound font.
- parameter index: the key to use
- returns: found SoundFont object
*/
static func getByIndex(index: Int) -> SoundFont {
guard index >= 0 && index < keys.count else { return FreeFont }
let key = keys[index]
return library[key]!
}
/**
Obtain the index in `keys` for the given sound font name. If not found, return 0
- parameter name: the name to look for
- returns: found index or zero
*/
static func indexForName(name: String) -> Int {
return keys.indexOf(name) ?? 0
}
let soundFontExtension = "sf2"
/// Presentation name of the sound font
let name: String
/// The file name of the sound font (sans extension)
let fileName: String
/// The resolved URL for the sound font
let fileURL: NSURL
/// The collection of Patches found in the sound font
var patches: [Patch]
/**
Initialize new SoundFont instance.
- parameter name: the display name for the sound font
- parameter fileName: the file name of the sound font in the application bundle
- parameter patches: the array of Patch objects for the sound font
*/
init(_ name: String, fileName: String, _ patches:[Patch]) {
self.name = name
self.fileName = fileName
self.patches = patches
self.fileURL = NSBundle.mainBundle().URLForResource(fileName, withExtension: soundFontExtension)!
}
/**
Link a SoundFont instance with its patches.
- returns: self
*/
func register() -> SoundFont {
patches.forEach { $0.soundFont = self }
return self
}
/**
Locate a patch in the SoundFont using a display name.
- parameter name: the display name to search for
- returns: found Patch or nil
*/
func findPatch(name: String) -> Patch? {
guard let found = findPatchIndex(name) else { return nil }
return patches[found]
}
/**
Obtain the index to a Patch with a given name.
- parameter name: the display name to search for
- returns: index of found object or nil if not found
*/
func findPatchIndex(name: String) -> Int? {
return patches.indexOf({ return $0.name == name })
}
}
/**
Representation of a patch in a sound font.
*/
class Patch: NSObject {
/// Display name for the patch
let name: String
/// Bank number where the patch resides in the sound font
let bank: Int
/// Program patch number where the patch resides in the sound font
let patch: Int
/// Reference to the SoundFont parent
weak var soundFont: SoundFont?
/**
Initialize Patch instance.
- parameter name: the diplay name for the patch
- parameter bank: the bank where the patch resides
- parameter patch: the program ID of the patch in the sound font
*/
init(_ name: String, _ bank: Int, _ patch: Int) {
self.name = name
self.bank = bank
self.patch = patch
self.soundFont = nil
}
}
/// Definition of the FreeFont sound font
let FreeFont = SoundFont("FreeFont", fileName: "FreeFont", [
Patch("Piano 1", 0, 0),
Patch("Piano 2", 0, 1),
Patch("Piano 3", 0, 2),
Patch("Honky-tonk", 0, 3),
Patch("E.Piano 1", 0, 4),
Patch("E.Piano 2", 0, 5),
Patch("Harpsichord", 0, 6),
Patch("Clav.", 0, 7),
Patch("Celesta", 0, 8),
Patch("Glockenspiel", 0, 9),
Patch("Music Box", 0, 10),
Patch("Vibraphone", 0, 11),
Patch("Marimba", 0, 12),
Patch("Xylophone", 0, 13),
Patch("Tubular-bell", 0, 14),
Patch("Santur", 0, 15),
Patch("Organ 1", 0, 16),
Patch("Organ 2", 0, 17),
Patch("Organ 3", 0, 18),
Patch("Church Org.1", 0, 19),
Patch("Reed Organ", 0, 20),
Patch("Accordion Fr", 0, 21),
Patch("Harmonica", 0, 22),
Patch("Bandoneon", 0, 23),
Patch("Nylon-str.Gt", 0, 24),
Patch("Steel-str.Gt", 0, 25),
Patch("Jazz Gt.", 0, 26),
Patch("Clean Gt.", 0, 27),
Patch("Muted Gt.", 0, 28),
Patch("Overdrive Gt", 0, 29),
Patch("DistortionGt", 0, 30),
Patch("Gt.Harmonics", 0, 31),
Patch("Acoustic Bs.", 0, 32),
Patch("Fingered Bs.", 0, 33),
Patch("Picked Bs.", 0, 34),
Patch("Fretless Bs.", 0, 35),
Patch("Slap Bass 1", 0, 36),
Patch("Slap Bass 2", 0, 37),
Patch("Synth Bass 1", 0, 38),
Patch("Synth Bass 2", 0, 39),
Patch("Violin", 0, 40),
Patch("Viola", 0, 41),
Patch("Cello", 0, 42),
Patch("Contrabass", 0, 43),
Patch("Tremolo Str", 0, 44),
Patch("PizzicatoStr", 0, 45),
Patch("Harp", 0, 46),
Patch("Timpani", 0, 47),
Patch("Strings", 0, 48),
Patch("Slow Strings", 0, 49),
Patch("Syn.Strings1", 0, 50),
Patch("Syn.Strings2", 0, 51),
Patch("Choir Aahs", 0, 52),
Patch("Voice Oohs", 0, 53),
Patch("SynVox", 0, 54),
Patch("OrchestraHit", 0, 55),
Patch("Trumpet", 0, 56),
Patch("Trombone", 0, 57),
Patch("Tuba", 0, 58),
Patch("MutedTrumpet", 0, 59),
Patch("French Horns", 0, 60),
Patch("Brass 1", 0, 61),
Patch("Synth Brass1", 0, 62),
Patch("Synth Brass2", 0, 63),
Patch("Soprano Sax", 0, 64),
Patch("Alto Sax", 0, 65),
Patch("Tenor Sax", 0, 66),
Patch("Baritone Sax", 0, 67),
Patch("Oboe", 0, 68),
Patch("English Horn", 0, 69),
Patch("Bassoon", 0, 70),
Patch("Clarinet", 0, 71),
Patch("Piccolo", 0, 72),
Patch("Flute", 0, 73),
Patch("Recorder", 0, 74),
Patch("Pan Flute", 0, 75),
Patch("Bottle Blow", 0, 76),
Patch("Shakuhachi", 0, 77),
Patch("Whistle", 0, 78),
Patch("Ocarina", 0, 79),
Patch("Square Wave", 0, 80),
Patch("Saw Wave", 0, 81),
Patch("Syn.Calliope", 0, 82),
Patch("Chiffer Lead", 0, 83),
Patch("Charang", 0, 84),
Patch("Solo Vox", 0, 85),
Patch("5th Saw Wave", 0, 86),
Patch("Bass & Lead", 0, 87),
Patch("Fantasia", 0, 88),
Patch("Warm Pad", 0, 89),
Patch("Polysynth", 0, 90),
Patch("Space Voice", 0, 91),
Patch("Bowed Glass", 0, 92),
Patch("Metal Pad", 0, 93),
Patch("Halo Pad", 0, 94),
Patch("Sweep Pad", 0, 95),
Patch("Ice Rain", 0, 96),
Patch("Soundtrack", 0, 97),
Patch("Crystal", 0, 98),
Patch("Atmosphere", 0, 99),
Patch("Brightness", 0, 100),
Patch("Goblin", 0, 101),
Patch("Echo Drops", 0, 102),
Patch("Star Theme", 0, 103),
Patch("Sitar", 0, 104),
Patch("Banjo", 0, 105),
Patch("Shamisen", 0, 106),
Patch("Koto", 0, 107),
Patch("Kalimba", 0, 108),
Patch("Bagpipe", 0, 109),
Patch("Fiddle", 0, 110),
Patch("Shanai", 0, 111),
Patch("Tinkle Bell", 0, 112),
Patch("Agogo", 0, 113),
Patch("Steel Drums", 0, 114),
Patch("Woodblock", 0, 115),
Patch("Taiko", 0, 116),
Patch("Melo. Tom 1", 0, 117),
Patch("Synth Drum", 0, 118),
Patch("Reverse Cym.", 0, 119),
Patch("Gt.FretNoise", 0, 120),
Patch("Breath Noise", 0, 121),
Patch("Seashore", 0, 122),
Patch("Bird", 0, 123),
Patch("Telephone 1", 0, 124),
Patch("Helicopter", 0, 125),
Patch("Applause", 0, 126),
Patch("Gun Shot", 0, 127),
Patch("SynthBass101", 1, 38),
Patch("Trombone 2", 1, 57),
Patch("Fr.Horn 2", 1, 60),
Patch("Square", 1, 80),
Patch("Saw", 1, 81),
Patch("Syn Mallet", 1, 98),
Patch("Echo Bell", 1, 102),
Patch("Sitar 2", 1, 104),
Patch("Gt.Cut Noise", 1, 120),
Patch("Fl.Key Click", 1, 121),
Patch("Rain", 1, 122),
Patch("Dog", 1, 123),
Patch("Telephone 2", 1, 124),
Patch("Car-Engine", 1, 125),
Patch("Laughing", 1, 126),
Patch("Machine Gun", 1, 127),
Patch("Echo Pan", 2, 102),
Patch("String Slap", 2, 120),
Patch("Thunder", 2, 122),
Patch("Horse-Gallop", 2, 123),
Patch("DoorCreaking", 2, 124),
Patch("Car-Stop", 2, 125),
Patch("Screaming", 2, 126),
Patch("Lasergun", 2, 127),
Patch("Wind", 3, 122),
Patch("Bird 2", 3, 123),
Patch("Door", 3, 124),
Patch("Car-Pass", 3, 125),
Patch("Punch", 3, 126),
Patch("Explosion", 3, 127),
Patch("Stream", 4, 122),
Patch("Scratch", 4, 124),
Patch("Car-Crash", 4, 125),
Patch("Heart Beat", 4, 126),
Patch("Bubble", 5, 122),
Patch("Wind Chimes", 5, 124),
Patch("Siren", 5, 125),
Patch("Footsteps", 5, 126),
Patch("Train", 6, 125),
Patch("Jetplane", 7, 125),
Patch("Piano 1", 8, 0),
Patch("Piano 2", 8, 1),
Patch("Piano 3", 8, 2),
Patch("Honky-tonk", 8, 3),
Patch("Detuned EP 1", 8, 4),
Patch("Detuned EP 2", 8, 5),
Patch("Coupled Hps.", 8, 6),
Patch("Vibraphone", 8, 11),
Patch("Marimba", 8, 12),
Patch("Church Bell", 8, 14),
Patch("Detuned Or.1", 8, 16),
Patch("Detuned Or.2", 8, 17),
Patch("Church Org.2", 8, 19),
Patch("Accordion It", 8, 21),
Patch("Ukulele", 8, 24),
Patch("12-str.Gt", 8, 25),
Patch("Hawaiian Gt.", 8, 26),
Patch("Chorus Gt.", 8, 27),
Patch("Funk Gt.", 8, 28),
Patch("Feedback Gt.", 8, 30),
Patch("Gt. Feedback", 8, 31),
Patch("Synth Bass 3", 8, 38),
Patch("Synth Bass 4", 8, 39),
Patch("Slow Violin", 8, 40),
Patch("Orchestra", 8, 48),
Patch("Syn.Strings3", 8, 50),
Patch("Brass 2", 8, 61),
Patch("Synth Brass3", 8, 62),
Patch("Synth Brass4", 8, 63),
Patch("Sine Wave", 8, 80),
Patch("Doctor Solo", 8, 81),
Patch("Taisho Koto", 8, 107),
Patch("Castanets", 8, 115),
Patch("Concert BD", 8, 116),
Patch("Melo. Tom 2", 8, 117),
Patch("808 Tom", 8, 118),
Patch("Starship", 8, 125),
Patch("Carillon", 9, 14),
Patch("Elec Perc.", 9, 118),
Patch("Burst Noise", 9, 125),
Patch("Piano 1d", 16, 0),
Patch("E.Piano 1v", 16, 4),
Patch("E.Piano 2v", 16, 5),
Patch("Harpsichord", 16, 6),
Patch("60's Organ 1", 16, 16),
Patch("Church Org.3", 16, 19),
Patch("Nylon Gt.o", 16, 24),
Patch("Mandolin", 16, 25),
Patch("Funk Gt.2", 16, 28),
Patch("Rubber Bass", 16, 39),
Patch("AnalogBrass1", 16, 62),
Patch("AnalogBrass2", 16, 63),
Patch("60's E.Piano", 24, 4),
Patch("Harpsi.o", 24, 6),
Patch("Organ 4", 32, 16),
Patch("Organ 5", 32, 17),
Patch("Nylon Gt.2", 32, 24),
Patch("Choir Aahs 2", 32, 52),
Patch("Standard", 128, 0),
Patch("Room", 128, 8),
Patch("Power", 128, 16),
Patch("Electronic", 128, 24),
Patch("TR-808", 128, 25),
Patch("Jazz", 128, 32),
Patch("Brush", 128, 40),
Patch("Orchestra", 128, 48),
Patch("SFX", 128, 56)])
/// Definition of the GeneralUser GS MuseScore sound font
let GeneralUser = SoundFont("GeneralUser", fileName: "GeneralUser GS MuseScore v1.442", [
Patch("Acoustic Grand Piano", 0, 0),
Patch("Bright Acoustic Piano", 0, 1),
Patch("Electric Grand Piano", 0, 2),
Patch("Honky-tonk Piano", 0, 3),
Patch("Electric Piano 1", 0, 4),
Patch("Electric Piano 2", 0, 5),
Patch("Harpsichord", 0, 6),
Patch("Clavi", 0, 7),
Patch("Celesta", 0, 8),
Patch("Glockenspiel", 0, 9),
Patch("Music Box", 0, 10),
Patch("Vibraphone", 0, 11),
Patch("Marimba", 0, 12),
Patch("Xylophone", 0, 13),
Patch("Tubular Bells", 0, 14),
Patch("Dulcimer", 0, 15),
Patch("Drawbar Organ", 0, 16),
Patch("Percussive Organ", 0, 17),
Patch("Rock Organ", 0, 18),
Patch("ChurchPipe", 0, 19),
Patch("Positive", 0, 20),
Patch("Accordion", 0, 21),
Patch("Harmonica", 0, 22),
Patch("Tango Accordion", 0, 23),
Patch("Classic Guitar", 0, 24),
Patch("Acoustic Guitar", 0, 25),
Patch("Jazz Guitar", 0, 26),
Patch("Clean Guitar", 0, 27),
Patch("Muted Guitar", 0, 28),
Patch("Overdriven Guitar", 0, 29),
Patch("Distortion Guitar", 0, 30),
Patch("Guitar harmonics", 0, 31),
Patch("JazzBass", 0, 32),
Patch("DeepBass", 0, 33),
Patch("PickBass", 0, 34),
Patch("FretLess", 0, 35),
Patch("SlapBass1", 0, 36),
Patch("SlapBass2", 0, 37),
Patch("SynthBass1", 0, 38),
Patch("SynthBass2", 0, 39),
Patch("Violin", 0, 40),
Patch("Viola", 0, 41),
Patch("Cello", 0, 42),
Patch("ContraBass", 0, 43),
Patch("TremoloStr", 0, 44),
Patch("Pizzicato", 0, 45),
Patch("Harp", 0, 46),
Patch("Timpani", 0, 47),
Patch("String Ensemble 1", 0, 48),
Patch("String Ensemble 2", 0, 49),
Patch("SynthStrings 1", 0, 50),
Patch("SynthStrings 2", 0, 51),
Patch("Choir", 0, 52),
Patch("DooVoice", 0, 53),
Patch("Voices", 0, 54),
Patch("OrchHit", 0, 55),
Patch("Trumpet", 0, 56),
Patch("Trombone", 0, 57),
Patch("Tuba", 0, 58),
Patch("MutedTrumpet", 0, 59),
Patch("FrenchHorn", 0, 60),
Patch("Brass", 0, 61),
Patch("SynBrass1", 0, 62),
Patch("SynBrass2", 0, 63),
Patch("SopranoSax", 0, 64),
Patch("AltoSax", 0, 65),
Patch("TenorSax", 0, 66),
Patch("BariSax", 0, 67),
Patch("Oboe", 0, 68),
Patch("EnglishHorn", 0, 69),
Patch("Bassoon", 0, 70),
Patch("Clarinet", 0, 71),
Patch("Piccolo", 0, 72),
Patch("Flute", 0, 73),
Patch("Recorder", 0, 74),
Patch("PanFlute", 0, 75),
Patch("Bottle", 0, 76),
Patch("Shakuhachi", 0, 77),
Patch("Whistle", 0, 78),
Patch("Ocarina", 0, 79),
Patch("SquareWave", 0, 80),
Patch("SawWave", 0, 81),
Patch("Calliope", 0, 82),
Patch("SynChiff", 0, 83),
Patch("Charang", 0, 84),
Patch("AirChorus", 0, 85),
Patch("fifths", 0, 86),
Patch("BassLead", 0, 87),
Patch("New Age", 0, 88),
Patch("WarmPad", 0, 89),
Patch("PolyPad", 0, 90),
Patch("GhostPad", 0, 91),
Patch("BowedGlas", 0, 92),
Patch("MetalPad", 0, 93),
Patch("HaloPad", 0, 94),
Patch("Sweep", 0, 95),
Patch("IceRain", 0, 96),
Patch("SoundTrack", 0, 97),
Patch("Crystal", 0, 98),
Patch("Atmosphere", 0, 99),
Patch("Brightness", 0, 100),
Patch("Goblin", 0, 101),
Patch("EchoDrop", 0, 102),
Patch("SciFi effect", 0, 103),
Patch("Sitar", 0, 104),
Patch("Banjo", 0, 105),
Patch("Shamisen", 0, 106),
Patch("Koto", 0, 107),
Patch("Kalimba", 0, 108),
Patch("Scotland", 0, 109),
Patch("Fiddle", 0, 110),
Patch("Shanai", 0, 111),
Patch("MetalBell", 0, 112),
Patch("Agogo", 0, 113),
Patch("SteelDrums", 0, 114),
Patch("Woodblock", 0, 115),
Patch("Taiko", 0, 116),
Patch("Tom", 0, 117),
Patch("SynthTom", 0, 118),
Patch("RevCymbal", 0, 119),
Patch("FretNoise", 0, 120),
Patch("NoiseChiff", 0, 121),
Patch("Seashore", 0, 122),
Patch("Birds", 0, 123),
Patch("Telephone", 0, 124),
Patch("Helicopter", 0, 125),
Patch("Stadium", 0, 126),
Patch("GunShot", 0, 127)
])
/// Definition of the RolandNicePiano sound font
let RolandPiano = SoundFont("Roland", fileName: "RolandNicePiano", [
Patch("Piano", 0, 1)
])
/// Definition of the FluidR3 sound font
let FluidR3 = SoundFont("FluidR3", fileName: "FluidR3_GM", [
Patch("Yamaha Grand Piano", 0, 0),
Patch("Bright Yamaha Grand", 0, 1),
Patch("Electric Piano", 0, 2),
Patch("Honky Tonk", 0, 3),
Patch("Rhodes EP", 0, 4),
Patch("Legend EP 2", 0, 5),
Patch("Harpsichord", 0, 6),
Patch("Clavinet", 0, 7),
Patch("Celesta", 0, 8),
Patch("Glockenspiel", 0, 9),
Patch("Music Box", 0, 10),
Patch("Vibraphone", 0, 11),
Patch("Marimba", 0, 12),
Patch("Xylophone", 0, 13),
Patch("Tubular Bells", 0, 14),
Patch("Dulcimer", 0, 15),
Patch("DrawbarOrgan", 0, 16),
Patch("Percussive Organ", 0, 17),
Patch("Rock Organ", 0, 18),
Patch("Church Organ", 0, 19),
Patch("Reed Organ", 0, 20),
Patch("Accordian", 0, 21),
Patch("Harmonica", 0, 22),
Patch("Bandoneon", 0, 23),
Patch("Nylon String Guitar", 0, 24),
Patch("Steel String Guitar", 0, 25),
Patch("Jazz Guitar", 0, 26),
Patch("Clean Guitar", 0, 27),
Patch("Palm Muted Guitar", 0, 28),
Patch("Overdrive Guitar", 0, 29),
Patch("Distortion Guitar", 0, 30),
Patch("Guitar Harmonics", 0, 31),
Patch("Acoustic Bass", 0, 32),
Patch("Fingered Bass", 0, 33),
Patch("Picked Bass", 0, 34),
Patch("Fretless Bass", 0, 35),
Patch("Slap Bass", 0, 36),
Patch("Pop Bass", 0, 37),
Patch("Synth Bass 1", 0, 38),
Patch("Synth Bass 2", 0, 39),
Patch("Violin", 0, 40),
Patch("Viola", 0, 41),
Patch("Cello", 0, 42),
Patch("Contrabass", 0, 43),
Patch("Tremolo", 0, 44),
Patch("Pizzicato Section", 0, 45),
Patch("Harp", 0, 46),
Patch("Timpani", 0, 47),
Patch("Strings", 0, 48),
Patch("Slow Strings", 0, 49),
Patch("Synth Strings 1", 0, 50),
Patch("Synth Strings 2", 0, 51),
Patch("Ahh Choir", 0, 52),
Patch("Ohh Voices", 0, 53),
Patch("Synth Voice", 0, 54),
Patch("Orchestra Hit", 0, 55),
Patch("Trumpet", 0, 56),
Patch("Trombone", 0, 57),
Patch("Tuba", 0, 58),
Patch("Muted Trumpet", 0, 59),
Patch("French Horns", 0, 60),
Patch("Brass Section", 0, 61),
Patch("Synth Brass 1", 0, 62),
Patch("Synth Brass 2", 0, 63),
Patch("Soprano Sax", 0, 64),
Patch("Alto Sax", 0, 65),
Patch("Tenor Sax", 0, 66),
Patch("Baritone Sax", 0, 67),
Patch("Oboe", 0, 68),
Patch("English Horn", 0, 69),
Patch("Bassoon", 0, 70),
Patch("Clarinet", 0, 71),
Patch("Piccolo", 0, 72),
Patch("Flute", 0, 73),
Patch("Recorder", 0, 74),
Patch("Pan Flute", 0, 75),
Patch("Bottle Chiff", 0, 76),
Patch("Shakuhachi", 0, 77),
Patch("Whistle", 0, 78),
Patch("Ocarina", 0, 79),
Patch("Square Lead", 0, 80),
Patch("Saw Wave", 0, 81),
Patch("Calliope Lead", 0, 82),
Patch("Chiffer Lead", 0, 83),
Patch("Charang", 0, 84),
Patch("Solo Vox", 0, 85),
Patch("Fifth Sawtooth Wave", 0, 86),
Patch("Bass & Lead", 0, 87),
Patch("Fantasia", 0, 88),
Patch("Warm Pad", 0, 89),
Patch("Polysynth", 0, 90),
Patch("Space Voice", 0, 91),
Patch("Bowed Glass", 0, 92),
Patch("Metal Pad", 0, 93),
Patch("Halo Pad", 0, 94),
Patch("Sweep Pad", 0, 95),
Patch("Ice Rain", 0, 96),
Patch("Soundtrack", 0, 97),
Patch("Crystal", 0, 98),
Patch("Atmosphere", 0, 99),
Patch("Brightness", 0, 100),
Patch("Goblin", 0, 101),
Patch("Echo Drops", 0, 102),
Patch("Star Theme", 0, 103),
Patch("Sitar", 0, 104),
Patch("Banjo", 0, 105),
Patch("Shamisen", 0, 106),
Patch("Koto", 0, 107),
Patch("Kalimba", 0, 108),
Patch("BagPipe", 0, 109),
Patch("Fiddle", 0, 110),
Patch("Shenai", 0, 111),
Patch("Tinker Bell", 0, 112),
Patch("Agogo", 0, 113),
Patch("Steel Drums", 0, 114),
Patch("Woodblock", 0, 115),
Patch("Taiko Drum", 0, 116),
Patch("Melodic Tom", 0, 117),
Patch("Synth Drum", 0, 118),
Patch("Reverse Cymbal", 0, 119),
Patch("Fret Noise", 0, 120),
Patch("Breath Noise", 0, 121),
Patch("Sea Shore", 0, 122),
Patch("Bird Tweet", 0, 123),
Patch("Telephone", 0, 124),
Patch("Helicopter", 0, 125),
Patch("Applause", 0, 126),
Patch("Gun Shot", 0, 127),
Patch("Detuned EP 1", 8, 4),
Patch("Detuned EP 2", 8, 5),
Patch("Coupled Harpsichord", 8, 6),
Patch("Church Bell", 8, 14),
Patch("Detuned Organ 1", 8, 16),
Patch("Detuned Organ 2", 8, 17),
Patch("Church Organ 2", 8, 19),
Patch("Italian Accordion", 8, 21),
Patch("Ukulele", 8, 24),
Patch("12 String Guitar", 8, 25),
Patch("Hawaiian Guitar", 8, 26),
Patch("Funk Guitar", 8, 28),
Patch("Feedback Guitar", 8, 30),
Patch("Guitar Feedback", 8, 31),
Patch("Synth Bass 3", 8, 38),
Patch("Synth Bass 4", 8, 39),
Patch("Slow Violin", 8, 40),
Patch("Orchestral Pad", 8, 48),
Patch("Synth Strings 3", 8, 50),
Patch("Brass 2", 8, 61),
Patch("Synth Brass 3", 8, 62),
Patch("Synth Brass 4", 8, 63),
Patch("Sine Wave", 8, 80),
Patch("Taisho Koto", 8, 107),
Patch("Castanets", 8, 115),
Patch("Concert Bass Drum", 8, 116),
Patch("Melo Tom 2", 8, 117),
Patch("808 Tom", 8, 118),
Patch("Burst Noise", 9, 125),
Patch("Mandolin", 16, 25),
Patch("Standard", 128, 0),
Patch("Standard 1", 128, 1),
Patch("Standard 2", 128, 2),
Patch("Standard 3", 128, 3),
Patch("Standard 4", 128, 4),
Patch("Standard 5", 128, 5),
Patch("Standard 6", 128, 6),
Patch("Standard 7", 128, 7),
Patch("Room", 128, 8),
Patch("Room 1", 128, 9),
Patch("Room 2", 128, 10),
Patch("Room 3", 128, 11),
Patch("Room 4", 128, 12),
Patch("Room 5", 128, 13),
Patch("Room 6", 128, 14),
Patch("Room 7", 128, 15),
Patch("Power", 128, 16),
Patch("Power 1", 128, 17),
Patch("Power 2", 128, 18),
Patch("Power 3", 128, 19),
Patch("Electronic", 128, 24),
Patch("TR-808", 128, 25),
Patch("Jazz", 128, 32),
Patch("Jazz 1", 128, 33),
Patch("Jazz 2", 128, 34),
Patch("Jazz 3", 128, 35),
Patch("Jazz 4", 128, 36),
Patch("Brush", 128, 40),
Patch("Brush 1", 128, 41),
Patch("Brush 2", 128, 42),
Patch("Orchestra Kit", 128, 48),
])
| mit | e89e98eb911ea8eae8b3c5975dda990c | 30.247253 | 117 | 0.558906 | 3.138088 | false | false | false | false |
andrebocchini/SwiftChatty | Pods/Alamofire/Source/ParameterEncoding.swift | 2 | 19684 | //
// ParameterEncoding.swift
//
// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/)
//
// 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
/// HTTP method definitions.
///
/// See https://tools.ietf.org/html/rfc7231#section-4.3
public enum HTTPMethod: String {
case options = "OPTIONS"
case get = "GET"
case head = "HEAD"
case post = "POST"
case put = "PUT"
case patch = "PATCH"
case delete = "DELETE"
case trace = "TRACE"
case connect = "CONNECT"
}
// MARK: -
/// A dictionary of parameters to apply to a `URLRequest`.
public typealias Parameters = [String: Any]
/// A type used to define how a set of parameters are applied to a `URLRequest`.
public protocol ParameterEncoding {
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `AFError.parameterEncodingFailed` error if encoding fails.
///
/// - returns: The encoded request.
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest
}
// MARK: -
/// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP
/// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as
/// the HTTP body depends on the destination of the encoding.
///
/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to
/// `application/x-www-form-urlencoded; charset=utf-8`.
///
/// There is no published specification for how to encode collection types. By default the convention of appending
/// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for
/// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the
/// square brackets appended to array keys.
///
/// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode
/// `true` as 1 and `false` as 0.
public struct URLEncoding: ParameterEncoding {
// MARK: Helper Types
/// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the
/// resulting URL request.
///
/// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE`
/// requests and sets as the HTTP body for requests with any other HTTP method.
/// - queryString: Sets or appends encoded query string result to existing query string.
/// - httpBody: Sets encoded query string result as the HTTP body of the URL request.
public enum Destination {
case methodDependent, queryString, httpBody
}
/// Configures how `Array` parameters are encoded.
///
/// - brackets: An empty set of square brackets is appended to the key for every value.
/// This is the default behavior.
/// - noBrackets: No brackets are appended. The key is encoded as is.
public enum ArrayEncoding {
case brackets, noBrackets
func encode(key: String) -> String {
switch self {
case .brackets:
return "\(key)[]"
case .noBrackets:
return key
}
}
}
/// Configures how `Bool` parameters are encoded.
///
/// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior.
/// - literal: Encode `true` and `false` as string literals.
public enum BoolEncoding {
case numeric, literal
func encode(value: Bool) -> String {
switch self {
case .numeric:
return value ? "1" : "0"
case .literal:
return value ? "true" : "false"
}
}
}
// MARK: Properties
/// Returns a default `URLEncoding` instance.
public static var `default`: URLEncoding { return URLEncoding() }
/// Returns a `URLEncoding` instance with a `.methodDependent` destination.
public static var methodDependent: URLEncoding { return URLEncoding() }
/// Returns a `URLEncoding` instance with a `.queryString` destination.
public static var queryString: URLEncoding { return URLEncoding(destination: .queryString) }
/// Returns a `URLEncoding` instance with an `.httpBody` destination.
public static var httpBody: URLEncoding { return URLEncoding(destination: .httpBody) }
/// The destination defining where the encoded query string is to be applied to the URL request.
public let destination: Destination
/// The encoding to use for `Array` parameters.
public let arrayEncoding: ArrayEncoding
/// The encoding to use for `Bool` parameters.
public let boolEncoding: BoolEncoding
// MARK: Initialization
/// Creates a `URLEncoding` instance using the specified destination.
///
/// - parameter destination: The destination defining where the encoded query string is to be applied.
/// - parameter arrayEncoding: The encoding to use for `Array` parameters.
/// - parameter boolEncoding: The encoding to use for `Bool` parameters.
///
/// - returns: The new `URLEncoding` instance.
public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) {
self.destination = destination
self.arrayEncoding = arrayEncoding
self.boolEncoding = boolEncoding
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) {
guard let url = urlRequest.url else {
throw AFError.parameterEncodingFailed(reason: .missingURL)
}
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty {
let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters)
urlComponents.percentEncodedQuery = percentEncodedQuery
urlRequest.url = urlComponents.url
}
} else {
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false)
}
return urlRequest
}
/// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion.
///
/// - parameter key: The key of the query component.
/// - parameter value: The value of the query component.
///
/// - returns: The percent-escaped, URL encoded query string components.
public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: Any] {
for (nestedKey, value) in dictionary {
components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value)
}
} else if let array = value as? [Any] {
for value in array {
components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value)
}
} else if let value = value as? NSNumber {
if value.isBool {
components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue))))
} else {
components.append((escape(key), escape("\(value)")))
}
} else if let bool = value as? Bool {
components.append((escape(key), escape(boolEncoding.encode(value: bool))))
} else {
components.append((escape(key), escape("\(value)")))
}
return components
}
/// Returns a percent-escaped string following RFC 3986 for a query string key or value.
///
/// RFC 3986 states that the following characters are "reserved" characters.
///
/// - General Delimiters: ":", "#", "[", "]", "@", "?", "/"
/// - Sub-Delimiters: "!", "$", "&", "'", "(", ")", "*", "+", ",", ";", "="
///
/// In RFC 3986 - Section 3.4, it states that the "?" and "/" characters should not be escaped to allow
/// query strings to include a URL. Therefore, all "reserved" characters with the exception of "?" and "/"
/// should be percent-escaped in the query string.
///
/// - parameter string: The string to be percent-escaped.
///
/// - returns: The percent-escaped string.
public func escape(_ string: String) -> String {
let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowedCharacterSet = CharacterSet.urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
var escaped = ""
//==========================================================================================================
//
// Batching is required for escaping due to an internal bug in iOS 8.1 and 8.2. Encoding more than a few
// hundred Chinese characters causes various malloc error crashes. To avoid this issue until iOS 8 is no
// longer supported, batching MUST be used for encoding. This introduces roughly a 20% overhead. For more
// info, please refer to:
//
// - https://github.com/Alamofire/Alamofire/issues/206
//
//==========================================================================================================
if #available(iOS 8.3, *) {
escaped = string.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? string
} else {
let batchSize = 50
var index = string.startIndex
while index != string.endIndex {
let startIndex = index
let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex
let range = startIndex..<endIndex
let substring = string[range]
escaped += substring.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? String(substring)
index = endIndex
}
}
return escaped
}
private func query(_ parameters: [String: Any]) -> String {
var components: [(String, String)] = []
for key in parameters.keys.sorted(by: <) {
let value = parameters[key]!
components += queryComponents(fromKey: key, value: value)
}
return components.map { "\($0)=\($1)" }.joined(separator: "&")
}
private func encodesParametersInURL(with method: HTTPMethod) -> Bool {
switch destination {
case .queryString:
return true
case .httpBody:
return false
default:
break
}
switch method {
case .get, .head, .delete:
return true
default:
return false
}
}
}
// MARK: -
/// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the
/// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
public struct JSONEncoding: ParameterEncoding {
// MARK: Properties
/// Returns a `JSONEncoding` instance with default writing options.
public static var `default`: JSONEncoding { return JSONEncoding() }
/// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options.
public static var prettyPrinted: JSONEncoding { return JSONEncoding(options: .prettyPrinted) }
/// The options for writing the parameters as JSON data.
public let options: JSONSerialization.WritingOptions
// MARK: Initialization
/// Creates a `JSONEncoding` instance using the specified options.
///
/// - parameter options: The options for writing the parameters as JSON data.
///
/// - returns: The new `JSONEncoding` instance.
public init(options: JSONSerialization.WritingOptions = []) {
self.options = options
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
do {
let data = try JSONSerialization.data(withJSONObject: parameters, options: options)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
/// Creates a URL request by encoding the JSON object and setting the resulting data on the HTTP body.
///
/// - parameter urlRequest: The request to apply the JSON object to.
/// - parameter jsonObject: The JSON object to apply to the request.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let jsonObject = jsonObject else { return urlRequest }
do {
let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
}
return urlRequest
}
}
// MARK: -
/// Uses `PropertyListSerialization` to create a plist representation of the parameters object, according to the
/// associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header
/// field of an encoded request is set to `application/x-plist`.
public struct PropertyListEncoding: ParameterEncoding {
// MARK: Properties
/// Returns a default `PropertyListEncoding` instance.
public static var `default`: PropertyListEncoding { return PropertyListEncoding() }
/// Returns a `PropertyListEncoding` instance with xml formatting and default writing options.
public static var xml: PropertyListEncoding { return PropertyListEncoding(format: .xml) }
/// Returns a `PropertyListEncoding` instance with binary formatting and default writing options.
public static var binary: PropertyListEncoding { return PropertyListEncoding(format: .binary) }
/// The property list serialization format.
public let format: PropertyListSerialization.PropertyListFormat
/// The options for writing the parameters as plist data.
public let options: PropertyListSerialization.WriteOptions
// MARK: Initialization
/// Creates a `PropertyListEncoding` instance using the specified format and options.
///
/// - parameter format: The property list serialization format.
/// - parameter options: The options for writing the parameters as plist data.
///
/// - returns: The new `PropertyListEncoding` instance.
public init(
format: PropertyListSerialization.PropertyListFormat = .xml,
options: PropertyListSerialization.WriteOptions = 0)
{
self.format = format
self.options = options
}
// MARK: Encoding
/// Creates a URL request by encoding parameters and applying them onto an existing request.
///
/// - parameter urlRequest: The request to have parameters applied.
/// - parameter parameters: The parameters to apply.
///
/// - throws: An `Error` if the encoding process encounters an error.
///
/// - returns: The encoded request.
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
guard let parameters = parameters else { return urlRequest }
do {
let data = try PropertyListSerialization.data(
fromPropertyList: parameters,
format: format,
options: options
)
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
} catch {
throw AFError.parameterEncodingFailed(reason: .propertyListEncodingFailed(error: error))
}
return urlRequest
}
}
// MARK: -
extension NSNumber {
fileprivate var isBool: Bool { return CFBooleanGetTypeID() == CFGetTypeID(self) }
}
| mit | dc6ab3267026cd181bab5da8008a6c13 | 39.753623 | 143 | 0.642146 | 5.069276 | false | false | false | false |
cweatureapps/SwiftScraper | Sources/StepRunner.swift | 1 | 4220 | //
// StepRunner.swift
// SwiftScraper
//
// Created by Ken Ko on 21/04/2017.
// Copyright © 2017 Ken Ko. All rights reserved.
//
import Foundation
import Observable
// MARK: - StepRunnerState
/// Indicates the progress and status of the `StepRunner`.
public enum StepRunnerState {
/// Not yet started, `run()` has not been called.
case notStarted
/// The pipeline is running, and currently executing the step at the index.
case inProgress(index: Int)
/// The execution finished successfully.
case success
/// The execution failed with the given error.
case failure(error: Error)
}
public func == (lhs: StepRunnerState, rhs: StepRunnerState) -> Bool {
switch (lhs, rhs) {
case (.notStarted, .notStarted): return true
case (.success, .success): return true
case (.failure, .failure): return true
case (.inProgress(let lhsIndex), .inProgress(let rhsIndex)):
return lhsIndex == rhsIndex
default: return false
}
}
public func != (lhs: StepRunnerState, rhs: StepRunnerState) -> Bool {
return !(lhs == rhs)
}
// MARK: - StepRunner
/// The `StepRunner` is the engine that runs the steps in the pipeline.
///
/// Once initialized, call the `run()` method to execute the steps,
/// and observe the `state` property to be notified of progress and status.
public class StepRunner {
/// The observable state which indicates the progress and status.
public private(set) var state: Observable<StepRunnerState> = Observable(.notStarted)
/// A model dictionary which can be used to pass data from step to step.
public private(set) var model: JSON = [:]
private let browser: Browser
private var steps: [Step]
private var index = 0
/// Initializer to create the `StepRunner`.
///
/// - parameter moduleName: The name of the JavaScript module which has your customer functions.
/// By convention, the filename of the JavaScript file is the same as the module name.
/// - parameter scriptBundle: The bundle from which to load the JavaScript file. Defaults to the main bundle.
/// - parameter customUserAgent: The custom user agent string (only works for iOS 9+).
/// - parameter steps: The steps to run in the pipeline.
public init(
moduleName: String,
scriptBundle: Bundle = Bundle.main,
customUserAgent: String? = nil,
steps: [Step]) {
browser = Browser(moduleName: moduleName, scriptBundle: scriptBundle, customUserAgent: customUserAgent)
self.steps = steps
}
/// Execute the steps.
public func run() {
guard index < steps.count else {
state ^= .failure(error: SwiftScraperError.incorrectStep)
return
}
let stepToExecute = steps[index]
state ^= .inProgress(index: index)
stepToExecute.run(with: browser, model: model) { [weak self] result in
guard let this = self else { return }
this.model = result.model
switch result {
case .finish:
this.state ^= .success
case .proceed:
this.index += 1
guard this.index < this.steps.count else {
this.state ^= .success
return
}
this.run()
case .jumpToStep(let nextStep, _):
this.index = nextStep
this.run()
case .failure(let error, _):
this.state ^= .failure(error: error)
}
}
}
/// Resets the existing StepRunner and execute the given steps in the existing browser.
///
/// Use this to perform more steps on a StepRunner which has previously finished processing.
public func run(steps: [Step]) {
state ^= .notStarted
self.steps = steps
index = 0
run()
}
/// Insert the WebView used for scraping at index 0 of the given parent view, using AutoLayout to pin all 4 sides to the parent.
///
/// Useful if the app would like to see the scraping in the foreground.
public func insertWebViewIntoView(parent: UIView) {
browser.insertIntoView(parent: parent)
}
}
| mit | a250c6f1dcbf95626c589c86391d5517 | 33.024194 | 132 | 0.625741 | 4.497868 | false | false | false | false |
groue/GRDB.swift | GRDB/Record/MutablePersistableRecord+Insert.swift | 1 | 20141 | // MARK: - Insert Callbacks
extension MutablePersistableRecord {
@inline(__always)
@inlinable
public mutating func willInsert(_ db: Database) throws { }
@inline(__always)
@inlinable
public func aroundInsert(_ db: Database, insert: () throws -> InsertionSuccess) throws {
_ = try insert()
}
@inline(__always)
@inlinable
public mutating func didInsert(_ inserted: InsertionSuccess) { }
}
// MARK: - Insert
extension MutablePersistableRecord {
/// Executes an `INSERT` statement.
///
/// For example:
///
/// ```swift
/// try dbQueue.write { db in
/// var player = Player(name: "Arthur")
/// try player.insert(db)
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func insert(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws
{
try willSave(db)
var saved: PersistenceSuccess?
try aroundSave(db) {
let inserted = try insertWithCallbacks(db, onConflict: conflictResolution)
saved = PersistenceSuccess(inserted)
return saved!
}
guard let saved else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(saved)
}
/// Executes an `INSERT` statement, and returns the inserted record.
///
/// For example:
///
/// ```swift
/// let player = Player(name: "Arthur")
/// let insertedPlayer = try await dbQueue.write { [player] db in
/// try player.inserted(db)
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The inserted record.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@inlinable // allow specialization so that empty callbacks are removed
public func inserted(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self
{
var result = self
try result.insert(db, onConflict: conflictResolution)
return result
}
}
// MARK: - Insert and Fetch
extension MutablePersistableRecord {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
/// This method is equivalent to ``insertAndFetch(_:onConflict:as:)``,
/// with `Self` as the `returnedType` argument:
///
/// ```swift
/// // Equivalent
/// let insertedPlayer = try player.insertAndFetch(db)
/// let insertedPlayer = try player.insertAndFetch(db, as: Player.self)
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The inserted record, if any. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@inlinable // allow specialization so that empty callbacks are removed
public func insertAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
where Self: FetchableRecord
{
var result = self
return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// ```swift
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: MutablePersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // A full player, with all database information
/// struct Player: TableRecord, FetchableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
/// }
///
/// // Insert a partial player, get a full one
/// try dbQueue.write { db in
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
}
}
/// Executes an `INSERT RETURNING` statement, and returns the selected
/// columns from the inserted row.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// ```swift
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: MutablePersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // Insert a partial player, get the inserted score
/// try dbQueue.write { db in
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
/// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in
/// try Int.fetchOne(statement)
/// }
/// print(score) // The inserted score
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A closure that executes its ``Statement`` argument.
/// If the conflict policy is `IGNORE`, the statement may return no row.
/// - returns: The result of the `fetch` function.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
public mutating func insertAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var success: (inserted: InsertionSuccess, returned: T)?
try aroundSave(db) {
success = try insertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return PersistenceSuccess(success!.inserted)
}
guard let success else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(PersistenceSuccess(success.inserted))
return success.returned
}
#else
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
/// This method is equivalent to ``insertAndFetch(_:onConflict:as:)``,
/// with `Self` as the `returnedType` argument:
///
/// ```swift
/// // Equivalent
/// let insertedPlayer = try player.insertAndFetch(db)
/// let insertedPlayer = try player.insertAndFetch(db, as: Player.self)
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - returns: The inserted record, if any. The result can be nil when the
/// conflict policy is `IGNORE`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public func insertAndFetch(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil)
throws -> Self?
where Self: FetchableRecord
{
var result = self
return try result.insertAndFetch(db, onConflict: conflictResolution, as: Self.self)
}
/// Executes an `INSERT RETURNING` statement, and returns a new record built
/// from the inserted row.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// ```swift
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: MutablePersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // A full player, with all database information
/// struct Player: TableRecord, FetchableRecord {
/// var id: Int64
/// var name: String
/// var score: Int
/// }
///
/// // Insert a partial player, get a full one
/// try dbQueue.write { db in
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING *
/// if let player = try partialPlayer.insertAndFetch(db, as: FullPlayer.self) {
/// print(player.id) // The inserted id
/// print(player.name) // The inserted name
/// print(player.score) // The default score
/// }
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter returnedType: The type of the returned record.
/// - returns: A record of type `returnedType`, if any. The result can be
/// nil when the conflict policy is `IGNORE`.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public mutating func insertAndFetch<T: FetchableRecord & TableRecord>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
as returnedType: T.Type)
throws -> T?
{
try insertAndFetch(db, onConflict: conflictResolution, selection: T.databaseSelection) {
try T.fetchOne($0)
}
}
/// Executes an `INSERT RETURNING` statement, and returns the selected
/// columns from the inserted row.
///
/// This method helps dealing with default column values and
/// generated columns.
///
/// For example:
///
/// ```swift
/// // A table with an auto-incremented primary key and a default value
/// try dbQueue.write { db in
/// try db.execute(sql: """
/// CREATE TABLE player(
/// id INTEGER PRIMARY KEY AUTOINCREMENT,
/// name TEXT,
/// score INTEGER DEFAULT 1000)
/// """)
/// }
///
/// // A player with partial database information
/// struct PartialPlayer: MutablePersistableRecord {
/// static let databaseTableName = "player"
/// var name: String
/// }
///
/// // Insert a partial player, get the inserted score
/// try dbQueue.write { db in
/// var partialPlayer = PartialPlayer(name: "Alice")
///
/// // INSERT INTO player (name) VALUES ('Alice') RETURNING score
/// let score = try partialPlayer.insertAndFetch(db, selection: [Column("score")]) { statement in
/// try Int.fetchOne(statement)
/// }
/// print(score) // The inserted score
/// }
/// ```
///
/// - parameter db: A database connection.
/// - parameter conflictResolution: A policy for conflict resolution. If
/// nil, <doc:/MutablePersistableRecord/persistenceConflictPolicy-1isyv>
/// is used.
/// - parameter selection: The returned columns (must not be empty).
/// - parameter fetch: A closure that executes its ``Statement`` argument.
/// If the conflict policy is `IGNORE`, the statement may return no row.
/// - returns: The result of the `fetch` function.
/// - throws: A ``DatabaseError`` whenever an SQLite error occurs, or any
/// error thrown by the persistence callbacks defined by the record type.
/// - precondition: `selection` is not empty.
@inlinable // allow specialization so that empty callbacks are removed
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) // SQLite 3.35.0+
public mutating func insertAndFetch<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution? = nil,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> T
{
GRDBPrecondition(!selection.isEmpty, "Invalid empty selection")
try willSave(db)
var success: (inserted: InsertionSuccess, returned: T)?
try aroundSave(db) {
success = try insertAndFetchWithCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return PersistenceSuccess(success!.inserted)
}
guard let success else {
try persistenceCallbackMisuse("aroundSave")
}
didSave(PersistenceSuccess(success.inserted))
return success.returned
}
#endif
}
// MARK: - Internals
extension MutablePersistableRecord {
/// Executes an `INSERT` statement, and runs insertion callbacks.
@inlinable // allow specialization so that empty callbacks are removed
mutating func insertWithCallbacks(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?)
throws -> InsertionSuccess
{
let (inserted, _) = try insertAndFetchWithCallbacks(db, onConflict: conflictResolution, selection: []) {
// Nothing to fetch
try $0.execute()
}
return inserted
}
/// Executes an `INSERT` statement, with `RETURNING` clause if `selection`
/// is not empty, and runs insertion callbacks.
@inlinable // allow specialization so that empty callbacks are removed
mutating func insertAndFetchWithCallbacks<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> (InsertionSuccess, T)
{
try willInsert(db)
var success: (inserted: InsertionSuccess, returned: T)?
try aroundInsert(db) {
success = try insertAndFetchWithoutCallbacks(
db, onConflict: conflictResolution,
selection: selection,
fetch: fetch)
return success!.inserted
}
guard let success else {
try persistenceCallbackMisuse("aroundInsert")
}
didInsert(success.inserted)
return success
}
/// Executes an `INSERT` statement, with `RETURNING` clause if `selection`
/// is not empty, and DOES NOT run insertion callbacks.
@usableFromInline
func insertAndFetchWithoutCallbacks<T>(
_ db: Database,
onConflict conflictResolution: Database.ConflictResolution?,
selection: [any SQLSelectable],
fetch: (Statement) throws -> T)
throws -> (InsertionSuccess, T)
{
let conflictResolution = conflictResolution ?? type(of: self)
.persistenceConflictPolicy
.conflictResolutionForInsert
let dao = try DAO(db, self)
let statement = try dao.insertStatement(
db,
onConflict: conflictResolution,
returning: selection)
let returned = try fetch(statement)
let rowIDColumn = dao.primaryKey.rowIDColumn
let rowid = db.lastInsertedRowID
// Update the persistenceContainer with the inserted rowid.
// This allows the Record class to set its `hasDatabaseChanges` property
// to false in its `aroundInsert` callback.
var persistenceContainer = dao.persistenceContainer
if let rowIDColumn {
persistenceContainer[caseInsensitive: rowIDColumn] = rowid
}
let inserted = InsertionSuccess(
rowID: rowid,
rowIDColumn: rowIDColumn,
persistenceContainer: persistenceContainer)
return (inserted, returned)
}
}
| mit | 8d2101311193c615ea9005f77ec41e3a | 37.218216 | 112 | 0.609751 | 4.711345 | false | false | false | false |
practicalswift/swift | test/SILGen/global_resilience.swift | 4 | 4374 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-sil-ownership -enable-resilience -emit-module-path=%t/resilient_global.swiftmodule -module-name=resilient_global %S/../Inputs/resilient_global.swift
// RUN: %target-swift-emit-silgen -I %t -enable-resilience -enable-sil-ownership -parse-as-library %s | %FileCheck %s
// RUN: %target-swift-emit-sil -I %t -O -enable-resilience -parse-as-library %s | %FileCheck --check-prefix=CHECK-OPT %s
import resilient_global
public struct MyEmptyStruct {}
// CHECK-LABEL: sil_global private @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvp : $MyEmptyStruct
public var myEmptyGlobal = MyEmptyStruct()
// CHECK-LABEL: sil_global @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvp : $MyEmptyStruct
@_fixed_layout public var myFixedLayoutGlobal = MyEmptyStruct()
// Mutable addressor for resilient global
// CHECK-LABEL: sil hidden [global_init] [ossa] @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau : $@convention(thin) () -> Builtin.RawPointer
// CHECK: global_addr @$s17global_resilience13myEmptyGlobalAA02MyD6StructVv
// CHECK: return
// Synthesized accessors for our resilient global variable
// CHECK-LABEL: sil [ossa] @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvg
// CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: return
// CHECK-LABEL: sil [ossa] @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvs
// CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: return
// CHECK-LABEL: sil [ossa] @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvM
// CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: begin_access [modify] [dynamic]
// CHECK: yield
// CHECK: end_access
// Mutable addressor for fixed-layout global
// CHECK-LABEL: sil [global_init] [ossa] @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvau
// CHECK: global_addr @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK: return
// CHECK-OPT-LABEL: sil private @globalinit_{{.*}}_func0
// CHECK-OPT: alloc_global @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK-OPT: return
// CHECK-OPT-LABEL: sil [global_init] @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvau
// CHECK-OPT: global_addr @$s17global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVvp
// CHECK-OPT: function_ref @globalinit_{{.*}}_func0
// CHECK-OPT: return
// Accessing resilient global from our resilience domain --
// call the addressor directly
// CHECK-LABEL: sil [ossa] @$s17global_resilience16getMyEmptyGlobalAA0dE6StructVyF
// CHECK: function_ref @$s17global_resilience13myEmptyGlobalAA02MyD6StructVvau
// CHECK: return
public func getMyEmptyGlobal() -> MyEmptyStruct {
return myEmptyGlobal
}
// Accessing resilient global from a different resilience domain --
// access it with accessors
// CHECK-LABEL: sil [ossa] @$s17global_resilience14getEmptyGlobal010resilient_A00D15ResilientStructVyF
// CHECK: function_ref @$s16resilient_global11emptyGlobalAA20EmptyResilientStructVvg
// CHECK: return
public func getEmptyGlobal() -> EmptyResilientStruct {
return emptyGlobal
}
// CHECK-LABEL: sil [ossa] @$s17global_resilience17modifyEmptyGlobalyyF
// CHECK: [[MODIFY:%.*]] = function_ref @$s16resilient_global11emptyGlobalAA20EmptyResilientStructVvM
// CHECK-NEXT: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFY]]()
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[FN:%.*]] = function_ref @$s16resilient_global20EmptyResilientStructV6mutateyyF
// CHECK-NEXT: apply [[FN]]([[ADDR]])
// CHECK-NEXT: end_apply [[TOKEN]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
public func modifyEmptyGlobal() {
emptyGlobal.mutate()
}
// Accessing fixed-layout global from a different resilience domain --
// call the addressor directly
// CHECK-LABEL: sil [ossa] @$s17global_resilience20getFixedLayoutGlobal010resilient_A020EmptyResilientStructVyF
// CHECK: function_ref @$s16resilient_global17fixedLayoutGlobalAA20EmptyResilientStructVvau
// CHECK: return
public func getFixedLayoutGlobal() -> EmptyResilientStruct {
return fixedLayoutGlobal
}
| apache-2.0 | d7bf4f0c9a360cfb60c6f7bf34178acf | 44.5625 | 200 | 0.749657 | 4.016529 | false | false | false | false |
lingoslinger/SwiftLibraries | SwiftLibraries/View Controllers/LibraryDetailViewController.swift | 1 | 1767 | //
// LibraryDetailViewController.swift
// SwiftLibraries
//
// Created by Allan Evans on 7/25/16.
// Copyright © 2016 - 2021 Allan Evans. All rights reserved.
//
import UIKit
import Foundation
import MapKit
class LibraryDetailViewController: UIViewController {
@IBOutlet weak var libraryPhoneTextView: UITextView!
@IBOutlet weak var libraryAddressLabel: UILabel!
@IBOutlet weak var libraryHoursLabel: UILabel!
@IBOutlet weak var libraryMapView: MKMapView!
var detailLibrary : Library?
override func viewDidLoad() {
super.viewDidLoad()
title = detailLibrary?.name ?? "Library name not available"
let phone = detailLibrary?.phone ?? "Library phone unavailable"
libraryPhoneTextView.text = "Phone: \(phone)"
libraryAddressLabel.text = detailLibrary?.address ?? "Library address unavailable"
libraryHoursLabel.text = detailLibrary?.hoursOfOperation?.formattedHours ?? "Library hours unavailable"
annotateMap()
}
func annotateMap() {
let latitudeString = detailLibrary?.location?.latitude ?? ""
let longitudeString = detailLibrary?.location?.longitude ?? ""
let zoomLocation = CLLocationCoordinate2D.init(latitude: Double(latitudeString) ?? 0.0, longitude: Double(longitudeString) ?? 0.0)
let span = MKCoordinateSpan.init(latitudeDelta: 0.01, longitudeDelta: 0.01)
let viewRegion = MKCoordinateRegion.init(center: zoomLocation, span: span)
let point = MKPointAnnotation.init()
point.coordinate = zoomLocation
point.title = detailLibrary?.name
libraryMapView.addAnnotation(point)
libraryMapView.setRegion(libraryMapView.regionThatFits(viewRegion), animated: true)
}
}
| mit | 8e98af101e40746643801e9df0414200 | 38.244444 | 138 | 0.703851 | 4.798913 | false | false | false | false |
SergeyVorontsov/SimpleNewsApp | SimpleNewsApp/AppSettings.swift | 1 | 1219 | //
// AppSettings.swift
// SimpleNewsApp
//
// Created by Sergey Vorontsov
// Copyright (c) 2015 Sergey Vorontsov. All rights reserved.
//
import Foundation
class AppSettings {
//copy keys from https://www.parse.com/account/keys
static let parseApplicationId = "YrPZkd9Tf4pscswvWNd2APVResR8KXHpghfcFVbS"
static let parseClientKey = "41Y9HufiB1MQvQq38ADSqPlreNqUu3trgqjYBEzz"
static let parseApiKey = "YOUR_PARSE_APPLICATION_REST_API_KEY"
static let parseServerHost = "https://api.parse.com"
static let parseApiPathPrefix = "/1/classes"
static let parseNewsClassName = "Article"
static let parseNewsPathPattern = "\(parseApiPathPrefix)/\(parseNewsClassName)"
static let parseNewsPath = "\(parseServerHost)\(parseApiPathPrefix)/\(parseNewsClassName)"
var newsService:NewsService
var newsInternalStorage:NewsInternalStorage
static var defaultSetting:AppSettings!
init(newsService:NewsService, newsInternalStorage:NewsInternalStorage){
self.newsService = newsService
self.newsInternalStorage = newsInternalStorage
if AppSettings.defaultSetting == nil {
AppSettings.defaultSetting = self
}
}
}
| mit | 9490318736ac92e206feba1c94ec6945 | 30.25641 | 94 | 0.728466 | 3.944984 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Swift/Extensions/String/String+Safe.swift | 1 | 4529 | //
// Xcore
// Copyright © 2014 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
extension StringProtocol {
public func index(from: Int) -> Index? {
guard
from > -1,
let index = self.index(startIndex, offsetBy: from, limitedBy: endIndex)
else {
return nil
}
return index
}
/// Returns the element at the specified `index` iff it is within bounds,
/// otherwise `nil`.
public func at(_ index: Int) -> String? {
guard let index = self.index(from: index), let character = at(index) else {
return nil
}
return String(character)
}
}
// MARK: - `at(:)`
extension String {
/// Returns the `Substring` at the specified range iff it is within bounds;
/// otherwise, `nil`.
///
/// e.g., `"Hello world"[..<5] // → "Hello"`
public func at(_ range: PartialRangeUpTo<Int>) -> Substring? {
hasIndex(range) ? self[range] : nil
}
/// Returns the `Substring` at the specified range iff it is within bounds;
/// otherwise, `nil`.
///
/// e.g., `"Hello world"[...4] // → "Hello"`
public func at(_ range: PartialRangeThrough<Int>) -> Substring? {
hasIndex(range) ? self[range] : nil
}
/// Returns the `Substring` at the specified range iff it is within bounds;
/// otherwise, `nil`.
///
/// e.g., `"Hello world"[0...] // → "Hello world"`
public func at(_ range: PartialRangeFrom<Int>) -> Substring? {
hasIndex(range) ? self[range] : nil
}
/// Returns the `Substring` at the specified range iff it is within bounds;
/// otherwise, `nil`.
///
/// e.g., `"Hello world"[0..<5] // → "Hello"`
public func at(_ range: CountableRange<Int>) -> Substring? {
hasIndex(range) ? self[range] : nil
}
/// Returns the `Substring` at the specified range iff it is within bounds;
/// otherwise, `nil`.
///
/// e.g., `"Hello world"[0...4] // → "Hello"`
public func at(range: CountableClosedRange<Int>) -> Substring? {
hasIndex(range) ? self[range] : nil
}
}
// MARK: - Ranges
extension String {
/// e.g., `"Hello world"[..<5] // → "Hello"`
private subscript(range: PartialRangeUpTo<Int>) -> Substring {
self[..<index(startIndex, offsetBy: range.upperBound)]
}
/// e.g., `"Hello world"[...4] // → "Hello"`
private subscript(range: PartialRangeThrough<Int>) -> Substring {
self[...index(startIndex, offsetBy: range.upperBound)]
}
/// e.g., `"Hello world"[0...] // → "Hello world"`
private subscript(range: PartialRangeFrom<Int>) -> Substring {
self[index(startIndex, offsetBy: range.lowerBound)...]
}
/// e.g., `"Hello world"[0..<5] // → "Hello"`
private subscript(range: CountableRange<Int>) -> Substring {
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(startIndex, offsetBy: range.upperBound)
return self[start..<end]
}
/// e.g., `"Hello world"[0...4] // → "Hello"`
private subscript(range: CountableClosedRange<Int>) -> Substring {
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(startIndex, offsetBy: range.upperBound)
return self[start...end]
}
}
// MARK: - `hasIndex(:)`
extension String {
/// Return true iff range is in `self`.
private func hasIndex(_ range: PartialRangeUpTo<Int>) -> Bool {
range.upperBound >= firstIndex && range.upperBound < lastIndex
}
/// Return true iff range is in `self`.
private func hasIndex(_ range: PartialRangeThrough<Int>) -> Bool {
range.upperBound >= firstIndex && range.upperBound < lastIndex
}
/// Return true iff range is in `self`.
private func hasIndex(_ range: PartialRangeFrom<Int>) -> Bool {
range.lowerBound >= firstIndex && range.lowerBound < lastIndex
}
/// Return true iff range is in `self`.
private func hasIndex(_ range: CountableRange<Int>) -> Bool {
range.lowerBound >= firstIndex && range.upperBound < lastIndex
}
/// Return true iff range is in `self`.
private func hasIndex(_ range: CountableClosedRange<Int>) -> Bool {
range.lowerBound >= firstIndex && range.upperBound < lastIndex
}
}
extension String {
private var firstIndex: Int {
startIndex.utf16Offset(in: self)
}
private var lastIndex: Int {
endIndex.utf16Offset(in: self)
}
}
| mit | c4a4b1ad1c95dc3800a086f9b6572bc5 | 29.876712 | 83 | 0.593611 | 4.087035 | false | false | false | false |
lexrus/HNAPI | Sources/Models/User.swift | 1 | 1523 | //
// User.swift
// HNAPI
//
// Created by lexrus on 01/28/2016.
// Copyright (c) 2016 lexrus.com. All rights reserved.
//
import Foundation
/**
* Users are identified by case-sensitive ids,
* and live under https://hacker-news.firebaseio.com/v0/user/.
* Only users that have public activity (comments or story submissions) on the
* site are available through the API.
*/
public struct User: DictionaryMappable {
/// The user's unique username. Case-sensitive. Required.
public let id: String!
/// Delay in minutes between a comment's creation and its visibility to other users.
public let delay: Int?
/// Creation date of the user, in Unix Time.
public let created: NSDate?
/// The user's karma.
public let karma: Int?
/// The user's optional self-description. HTML.
public let about: String?
/// List of the user's stories, polls and comments.
public let submitted: [Int]?
public init?(_ dictionary: [String: AnyObject]) {
guard let id = dictionary["id"] as? String else {
return nil
}
self.id = id
self.delay = dictionary["delay"] as? Int
if let created = dictionary["created"] as? Double {
self.created = NSDate(timeIntervalSince1970: created)
} else {
self.created = nil
}
self.karma = dictionary["karma"] as? Int
self.about = dictionary["about"] as? String
self.submitted = dictionary["submitted"] as? [Int]
}
}
| mit | ddbca652f51d7daaf177c727d8fb927e | 24.813559 | 88 | 0.626395 | 4.039788 | false | false | false | false |
Tj3n/TVNExtensions | TlvParser/TlvTag.swift | 1 | 9731 | //
// TlvTag.swift
// BlingTerminal
//
// Created by Tien Nhat Vu on 12/28/17.
// Copyright © 2017 Tien Nhat Vu. All rights reserved.
//
import Foundation
struct TlvTag {
static func isValid(_ byte: Int) -> Bool {
let byteNumber: Int = 1
if byteNumber <= 2 && byte == 0x00 {
return false
}
if byteNumber == 2 && (byte == 0x1e || byte == 0x80) {
return false
}
return true
}
static func isConstructed(_ byte: Int) -> Bool {
return TlvTag.getEncoding(byte) == 0x20
}
static func getEncoding(_ byte: Int) -> Int {
return byte & 0x20
}
static func isMultiByte(_ byte: Int) -> Bool {
return 0x1f == (byte & 0x1f)
}
static func isLast(_ byte: Int) -> Bool {
return 0x00 == (byte >> 7)
}
static func getName(tag: String) -> String {
let tagList = ["42" : "Issuer Identification Number (IIN)",
"4F" : "Application Identifier (AID) – card",
"50" : "Application Label",
"57" : "Track 2 Equivalent Data",
"5A" : "Application Primary Account Number (PAN)",
"61" : "Application Template",
"6F" : "File Control Information (FCI) Template",
"70" : "EMV Proprietary Template",
"71" : "Issuer Script Template 1",
"72" : "Issuer Script Template 2",
"73" : "Directory Discretionary Template",
"77" : "Response Message Template Format 2",
"80" : "Response Message Template Format 1",
"81" : "Amount, Authorised (Binary)",
"82" : "Application Interchange Profile",
"83" : "Command Template",
"84" : "Dedicated File (DF) Name",
"86" : "Issuer Script Command",
"87" : "Application Priority Indicator",
"88" : "Short File Identifier (SFI)",
"89" : "Authorisation Code",
"8A" : "Authorisation Response Code",
"8C" : "Card Risk Management Data Object List 1 (CDOL1)",
"8D" : "Card Risk Management Data Object List 2 (CDOL2)",
"8E" : "Cardholder Verification Method (CVM) List",
"8F" : "Certification Authority Public Key Index",
"90" : "Issuer Public Key Certificate",
"91" : "Issuer Authentication Data",
"92" : "Issuer Public Key Remainder",
"93" : "Signed Static Application Data",
"94" : "Application File Locator (AFL)",
"95" : "Terminal Verification Results",
"97" : "Transaction Certificate Data Object List (TDOL)",
"98" : "Transaction Certificate (TC) Hash Value",
"99" : "Transaction Personal Identification Number (PIN) Data",
"9A" : "Transaction Date",
"9B" : "Transaction Status Information",
"9C" : "Transaction Type",
"9D" : "Directory Definition File (DDF) Name",
"A5" : "File Control Information (FCI) Proprietary Template",
"E0" : "Receive Data Elements",
"E1" : "Issue Data Elements (Secure)",
"E2" : "Decision",
"E3" : "Issue Data Elements (Non-Secure)",
"C2" : "Encrypted Data",
"5F20" : "Cardholder Name",
"5F24" : "Application Expiration Date",
"5F25" : "Application Effective Date",
"5F28" : "Issuer Country Code",
"5F2A" : "Transaction Currency Code",
"5F2D" : "Language Preference",
"5F30" : "Service Code",
"5F34" : "Application Primary Account Number (PAN) Sequence Number",
"5F36" : "Transaction Currency Exponent",
"5F50" : "Issuer URL",
"5F53" : "International Bank Account Number (IBAN)",
"5F54" : "Bank Identifier Code (BIC)",
"5F55" : "Issuer Country Code (alpha2 format)",
"5F56" : "Issuer Country Code (alpha3format)",
"5F57" : "Account Type",
"9F01" : "Acquirer Identifier",
"9F02" : "Amount, Authorised (Numeric)",
"9F03" : "Amount, Other (Numeric)",
"9F04" : "Amount, Other (Binary)",
"9F05" : "Application Discretionary Data",
"9F06" : "Application Identifier (AID) – terminal",
"9F07" : "Application Usage Control",
"9F08" : "Application Version Number",
"9F09" : "Application Version Number",
"9F0B" : "Cardholder Name Extended",
"9F0D" : "Issuer Action Code – Default",
"9F0E" : "Issuer Action Code – Denial",
"9F0F" : "Issuer Action Code – Online",
"9F10" : "Issuer Application Data",
"9F11" : "Issuer Code Table Index",
"9F12" : "Application Preferred Name",
"9F13" : "Last Online Application Transaction Counter (ATC) Register",
"9F14" : "Lower Consecutive Offline Limit",
"9F15" : "Merchant Category Code",
"9F16" : "Merchant Identifier",
"9F17" : "Personal Identification Number (PIN) Try Counter",
"9F18" : "Issuer Script Identifier",
"9F1A" : "Terminal Country Code",
"9F1B" : "Terminal Floor Limit",
"9F1C" : "Terminal Identification",
"9F1D" : "Terminal Risk Management Data",
"9F1E" : "Interface Device (IFD) Serial Number",
"9F1F" : "Track 1 Discretionary Data",
"9F20" : "Track 2 Discretionary Data",
"9F21" : "Transaction Time",
"9F22" : "Certification Authority Public Key Index",
"9F23" : "Upper Consecutive Offline Limit",
"9F26" : "Application Cryptogram",
"9F27" : "Cryptogram Information Data",
"9F2D" : "Integrated Circuit Card (ICC) PIN Encipherment Public Key Certificate",
"9F2E" : "Integrated Circuit Card (ICC) PIN Encipherment Public Key Exponent",
"9F2F" : "Integrated Circuit Card (ICC) PIN Encipherment Public Key Remainder",
"9F32" : "Issuer Public Key Exponent",
"9F33" : "Terminal Capabilities",
"9F34" : "Cardholder Verification Method (CVM) Results",
"9F35" : "Terminal Type",
"9F36" : "Application Transaction Counter (ATC)",
"9F37" : "Unpredictable Number",
"9F38" : "Processing Options Data Object List (PDOL)",
"9F39" : "Point-of-Service (POS) Entry Mode",
"9F3A" : "Amount, Reference Currency",
"9F3B" : "Application Reference Currency",
"9F3C" : "Transaction Reference Currency Code",
"9F3D" : "TransactionReference Currency Exponent",
"9F40" : "Additional Terminal Capabilities",
"9F41" : "Transaction SequenceCounter",
"9F42" : "Application Currency Code",
"9F43" : "Application Reference Currency Exponent",
"9F44" : "Application Currency Exponent",
"9F45" : "Data Authentication Code",
"9F46" : "Integrated Circuit Card (ICC) Public Key Certificate",
"9F47" : "Integrated Circuit Card (ICC) Public Key Exponent",
"9F48" : "Integrated Circuit Card (ICC) Public Key Remainder",
"9F49" : "Dynamic Data Authentication Data Object List(DDOL)",
"9F4A" : "Static Data Authentication Tag List",
"9F4B" : "Signed Dynamic Application Data",
"9F4C" : "ICC Dynamic Number",
"9F4D" : "Log Entry",
"9F4E" : "Merchant Name and Location",
"9F4F" : "Log Format",
"BF0C" : "File Control Information (FCI) Issuer Discretionary Data",
"DF01" : "Digits",
"DF02" : "Status Bytes",
"DF11" : "Acquirer ID",
"DF12" : "Answer To Reset (ATR)",
"DF13" : "ISO 7811 Track 1 card data",
"DF14" : "ISO 7811 Track 2 card data",
"DF15" : "ISO 7811 Track 3 card data",
"DF16" : "Enciphered PIN Block",
"DF17" : "Key Serial Number",
"DF18" : "Risk Management"]
return tagList[tag] ?? ""
}
}
| mit | 3b01ce8feb9ddb11f9454b2947b387a4 | 53.606742 | 104 | 0.456893 | 4.569817 | false | false | false | false |
laurentVeliscek/AudioKit | AudioKit/Common/MIDI/AKMIDI+SendingMIDI.swift | 1 | 4302 | //
// AKMIDI+SendingMIDI.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2016 AudioKit. All rights reserved.
//
extension AKMIDI {
/// Array of destination names
public var destinationNames: [String] {
var nameArray = [String]()
let outputCount = MIDIGetNumberOfDestinations()
for i in 0 ..< outputCount {
let destination = MIDIGetDestination(i)
var endpointName: Unmanaged<CFString>?
endpointName = nil
MIDIObjectGetStringProperty(destination, kMIDIPropertyName, &endpointName)
let endpointNameStr = (endpointName?.takeRetainedValue())! as String
nameArray.append(endpointNameStr)
}
return nameArray
}
/// Open a MIDI Output Port
///
/// - parameter namedOutput: String containing the name of the MIDI Input
///
public func openOutput(namedOutput: String = "") {
var result = noErr
let outputCount = MIDIGetNumberOfDestinations()
var foundDest = false
result = MIDIOutputPortCreate(client, outputPortName, &outputPort)
if result != noErr {
print("Error creating MIDI output port : \(result)")
}
for i in 0 ..< outputCount {
let src = MIDIGetDestination(i)
var endpointName: Unmanaged<CFString>? = nil
MIDIObjectGetStringProperty(src, kMIDIPropertyName, &endpointName)
let endpointNameStr = (endpointName?.takeRetainedValue())! as String
if namedOutput.isEmpty || namedOutput == endpointNameStr {
print("Found destination at \(endpointNameStr)")
endpoints[endpointNameStr] = MIDIGetDestination(i)
foundDest = true
}
}
if !foundDest {
print("no midi destination found named \"\(namedOutput)\"")
}
}
/// Send Message with data
public func sendMessage(data: [UInt8]) {
var result = noErr
let packetListPointer: UnsafeMutablePointer<MIDIPacketList> = UnsafeMutablePointer.alloc(1)
var packet: UnsafeMutablePointer<MIDIPacket> = nil
packet = MIDIPacketListInit(packetListPointer)
packet = MIDIPacketListAdd(packetListPointer, 1024, packet, 0, data.count, data)
for endpointName in endpoints.keys {
if let endpoint = endpoints[endpointName] {
result = MIDISend(outputPort, endpoint, packetListPointer)
if result != noErr {
print("error sending midi : \(result)")
}
}
}
if virtualOutput != 0 {
MIDIReceived(virtualOutput, packetListPointer)
}
packetListPointer.destroy()
packetListPointer.dealloc(1)//necessary? wish i could do this without the alloc above
}
/// Send Messsage from midi event data
public func sendEvent(event: AKMIDIEvent) {
sendMessage(event.internalData)
}
/// Send a Note On Message
public func sendNoteOnMessage(noteNumber noteNumber: MIDINoteNumber,
velocity: MIDIVelocity,
channel: MIDIChannel = 0) {
let noteCommand: UInt8 = UInt8(0x90) + UInt8(channel)
let message: [UInt8] = [noteCommand, UInt8(noteNumber), UInt8(velocity)]
self.sendMessage(message)
}
/// Send a Note Off Message
public func sendNoteOffMessage(noteNumber noteNumber: MIDINoteNumber,
velocity: MIDIVelocity,
channel: MIDIChannel = 0) {
let noteCommand: UInt8 = UInt8(0x80) + UInt8(channel)
let message: [UInt8] = [noteCommand, UInt8(noteNumber), UInt8(velocity)]
self.sendMessage(message)
}
/// Send a Continuous Controller message
public func sendControllerMessage(control: Int, value: Int, channel: MIDIChannel = 0) {
let controlCommand: UInt8 = UInt8(0xB0) + UInt8(channel)
let message: [UInt8] = [controlCommand, UInt8(control), UInt8(value)]
self.sendMessage(message)
}
}
| mit | 75e301c71c529d2039675ef2f72f6c06 | 37.061947 | 99 | 0.595443 | 5.144737 | false | false | false | false |
tecgirl/firefox-ios | Storage/SQL/SQLiteHistoryRecommendations.swift | 1 | 8484 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
import Deferred
fileprivate let log = Logger.syncLogger
extension SQLiteHistory: HistoryRecommendations {
// Bookmarks Query
static let removeMultipleDomainsSubquery = """
INNER JOIN (SELECT view_history_visits.domain_id AS domain_id
FROM view_history_visits
GROUP BY view_history_visits.domain_id) AS domains ON domains.domain_id = history.domain_id
"""
static let urisForSimpleSyncedBookmarks = """
SELECT bmkUri FROM bookmarksBuffer WHERE server_modified > ? AND is_deleted = 0
UNION ALL
SELECT bmkUri FROM bookmarksLocal WHERE local_modified > ? AND is_deleted = 0
"""
static let urisForLocalBookmarks = """
SELECT bmkUri
FROM view_bookmarksLocal_on_mirror
WHERE view_bookmarksLocal_on_mirror.server_modified > ? OR view_bookmarksLocal_on_mirror.local_modified > ?
"""
static let bookmarkHighlights = """
SELECT historyID, url, siteTitle, guid, is_bookmarked
FROM (
SELECT history.id AS historyID, history.url AS url, history.title AS siteTitle, guid, history.domain_id, NULL AS visitDate, 1 AS is_bookmarked
FROM (\(urisForSimpleSyncedBookmarks))
LEFT JOIN history ON history.url = bmkUri
\(removeMultipleDomainsSubquery)
WHERE
history.title NOT NULL AND
history.title != '' AND
url NOT IN (SELECT activity_stream_blocklist.url FROM activity_stream_blocklist)
LIMIT ?
)
"""
static let bookmarksQuery = """
SELECT historyID, url, siteTitle AS title, guid, is_bookmarked, iconID, iconURL, iconType, iconDate, iconWidth, page_metadata.title AS metadata_title, media_url, type, description, provider_name
FROM (\(bookmarkHighlights))
LEFT JOIN view_history_id_favicon ON
view_history_id_favicon.id = historyID
LEFT OUTER JOIN page_metadata ON
page_metadata.cache_key = url
GROUP BY url
"""
// Highlights Query
static let highlightsLimit = 8
static let blacklistedHosts: Args = [
"google.com",
"google.ca",
"calendar.google.com",
"mail.google.com",
"mail.yahoo.com",
"search.yahoo.com",
"localhost",
"t.co"
]
static let blacklistSubquery =
"SELECT domains.id FROM domains WHERE domains.domain IN " +
BrowserDB.varlist(blacklistedHosts.count)
static let removeMultipleDomainsSubqueryFromHighlights = """
INNER JOIN (
SELECT view_history_visits.domain_id AS domain_id, max(view_history_visits.visitDate) AS visit_date
FROM view_history_visits
GROUP BY view_history_visits.domain_id
) AS domains ON
domains.domain_id = history.domain_id AND
visitDate = domains.visit_date
"""
static let nonRecentHistory = """
SELECT historyID, url, siteTitle, guid, visitCount, visitDate, is_bookmarked, visitCount * icon_url_score * media_url_score AS score
FROM (
SELECT history.id AS historyID, url, history.title AS siteTitle, guid, visitDate, history.domain_id,
(SELECT count(1) FROM visits WHERE s = visits.siteID) AS visitCount,
(SELECT count(1) FROM view_bookmarksLocal_on_mirror WHERE view_bookmarksLocal_on_mirror.bmkUri == url) AS is_bookmarked,
CASE WHEN iconURL IS NULL THEN 1 ELSE 2 END AS icon_url_score,
CASE WHEN media_url IS NULL THEN 1 ELSE 4 END AS media_url_score
FROM (
SELECT siteID AS s, max(date) AS visitDate
FROM visits
WHERE date < ?
GROUP BY siteID
ORDER BY visitDate DESC
)
LEFT JOIN history ON
history.id = s
\(removeMultipleDomainsSubqueryFromHighlights)
LEFT OUTER JOIN view_history_id_favicon ON
view_history_id_favicon.id = history.id
LEFT OUTER JOIN page_metadata ON
page_metadata.site_url = history.url
WHERE
visitCount <= 3 AND
history.title NOT NULL AND
history.title != '' AND
is_bookmarked == 0 AND
url NOT IN (SELECT url FROM activity_stream_blocklist) AND
history.domain_id NOT IN (\(blacklistSubquery))
)
"""
public func getHighlights() -> Deferred<Maybe<Cursor<Site>>> {
let highlightsProjection = [
"historyID",
"highlights.cache_key AS cache_key",
"url",
"highlights.title AS title",
"guid",
"visitCount",
"visitDate",
"is_bookmarked"
]
let faviconsProjection = ["iconID", "iconURL", "iconType", "iconDate", "iconWidth"]
let metadataProjections = [
"page_metadata.title AS metadata_title",
"media_url",
"type",
"description",
"provider_name"
]
let allProjection = highlightsProjection + faviconsProjection + metadataProjections
let highlightsHistoryIDs = "SELECT historyID FROM highlights"
// Search the history/favicon view with our limited set of highlight IDs
// to avoid doing a full table scan on history
let faviconSearch =
"SELECT * FROM view_history_id_favicon WHERE id IN (\(highlightsHistoryIDs))"
let sql = """
SELECT \(allProjection.joined(separator: ","))
FROM highlights
LEFT JOIN (\(faviconSearch)) AS f1 ON
f1.id = historyID
LEFT OUTER JOIN page_metadata ON
page_metadata.cache_key = highlights.cache_key
"""
return self.db.runQuery(sql, args: nil, factory: SQLiteHistory.iconHistoryMetadataColumnFactory)
}
public func removeHighlightForURL(_ url: String) -> Success {
return self.db.run([("INSERT INTO activity_stream_blocklist (url) VALUES (?)", [url])])
}
private func repopulateHighlightsQuery() -> [(String, Args?)] {
let (query, args) = computeHighlightsQuery()
let clearHighlightsQuery = "DELETE FROM highlights"
let sql = """
INSERT INTO highlights
SELECT historyID, url as cache_key, url, title, guid, visitCount, visitDate, is_bookmarked
FROM (\(query))
"""
return [(clearHighlightsQuery, nil), (sql, args)]
}
public func repopulate(invalidateTopSites shouldInvalidateTopSites: Bool, invalidateHighlights shouldInvalidateHighlights: Bool) -> Success {
var queries: [(String, Args?)] = []
if shouldInvalidateTopSites {
queries.append(contentsOf: self.refreshTopSitesQuery())
}
if shouldInvalidateHighlights {
queries.append(contentsOf: self.repopulateHighlightsQuery())
}
return self.db.run(queries)
}
public func getRecentBookmarks(_ limit: Int = 3) -> Deferred<Maybe<Cursor<Site>>> {
let fiveDaysAgo: UInt64 = Date.now() - (OneDayInMilliseconds * 5) // The data is joined with a millisecond not a microsecond one. (History)
let args = [fiveDaysAgo, fiveDaysAgo, limit] as Args
return self.db.runQuery(SQLiteHistory.bookmarksQuery, args: args, factory: SQLiteHistory.iconHistoryMetadataColumnFactory)
}
private func computeHighlightsQuery() -> (String, Args) {
let microsecondsPerMinute: UInt64 = 60_000_000 // 1000 * 1000 * 60
let now = Date.nowMicroseconds()
let thirtyMinutesAgo: UInt64 = now - 30 * microsecondsPerMinute
let highlightsQuery = """
SELECT historyID, url, siteTitle AS title, guid, visitCount, visitDate, is_bookmarked, score
FROM (\(SQLiteHistory.nonRecentHistory))
GROUP BY url
ORDER BY score DESC
LIMIT \(SQLiteHistory.highlightsLimit)
"""
let args: Args = [thirtyMinutesAgo] + SQLiteHistory.blacklistedHosts
return (highlightsQuery, args)
}
}
| mpl-2.0 | b44c290782016b1879904bc1c8a6bf78 | 39.985507 | 202 | 0.615512 | 4.763616 | false | false | false | false |
damienpontifex/LinearAlgebraExtensions | Sources/LinearRegression.swift | 1 | 4165 | //
// LinearRegression.swift
// LinearAlgebraExtensions
//
// Created by Damien Pontifex on 16/09/2014.
// Copyright (c) 2014 Damien Pontifex. All rights reserved.
//
import Foundation
import Accelerate
/**
* Class to calculate linear regression of a set of data points
*/
open class LinearRegression {
fileprivate var m: Int
fileprivate var x: la_object_t
fileprivate var y: la_object_t
fileprivate var theta: la_object_t
fileprivate var alpha: Double
fileprivate var numIterations: Int
public init(_ x: la_object_t, _ y: la_object_t, theta: la_object_t? = nil, alpha: Double = 0.01, numIterations: Int = 1500) {
self.m = Int(la_matrix_rows(x))
// let cols = Int(la_matrix_cols(x))
let ones = la_ones_matrix(rows: Int(la_matrix_rows(x)))
self.x = x.prependColumnsFrom(ones)
self.y = y
if theta != nil {
self.theta = theta!
} else {
self.theta = la_zero_matrix(columns: Int(la_matrix_cols(self.x)))
}
self.alpha = alpha
self.numIterations = numIterations
}
/**
Initialise the LinearRegression object
- parameter x: Input data values
- parameter y: Expected output values
- parameter theta: Initial theta value
- parameter alpha: Learning rate
- parameter numIterations: Number of iterations to run the algorithm
- returns: Instance of the LinearRegression
*/
public init(_ x: [Double], _ y: [Double], theta: [Double]? = nil, alpha: Double = 0.01, numIterations: Int = 1500) {
self.m = x.count
var xValues = Array<Double>(repeating: 1.0, count: m * 2)
for i in stride(from: 0, to: x.count * 2, by: 2) {
xValues[i] = x[i / 2]
}
let xMatrix = la_matrix_from_double_array(xValues, rows: m, columns: 2)
self.x = xMatrix
self.y = la_vector_column_from_double_array(y)
var thetaArray = theta
if thetaArray == nil {
// Default the theta array to zeros with appropriate size of x array
thetaArray = Array<Double>(repeating: 0.0, count: Int(2))
}
self.theta = la_vector_row_from_double_array(thetaArray!)
self.alpha = alpha
self.numIterations = numIterations
}
/**
Run the gradient descent algorithm for linear regression
- parameter returnCostHistory: Boolean value to indicate whether the cost history should be returned. Some performance hit if this is true due to doing array computations in every iteration rather than just at the end
- returns: Tuple of theta values and optional jHistory parameter if requested
*/
open func gradientDescent(_ returnCostHistory: Bool = false) -> (theta: [Double], jHistory: [Double]?) {
print("initial theta \(theta.description())")
print(x.description())
print(y.description())
// Number of training examples
let alphaOverM = alpha / Double(m)
var jHistory: [Double]?
if returnCostHistory {
jHistory = Array<Double>(repeating: 0.0, count: numIterations)
}
for iter in 0..<numIterations {
// h(x) = transpose(theta) * x
let prediction = x * theta
let errors = prediction - y
let sum = la_transpose(errors) * x
let partial = la_transpose(sum) * alphaOverM
// Simultaneous theta update:
// theta_j = theta_j - alpha / m * sum_{i=1}^m (h_theta(x^(i)) - y^(i)) * x_j^(i)
theta = theta - partial
print("next theta \(theta.description())")
if returnCostHistory {
jHistory![iter] = computeCost()
}
}
let thetaArray = theta.toArray()
return (theta: thetaArray, jHistory: jHistory)
}
/**
Calculate theta values using the normal equations.
- returns: Double array with theta coefficients
*/
open func normalEquations() -> [Double] {
// 𝜃 = inverse(X' * X) * X' * y
// Equivalent to (X' * X) * 𝜃 = X' * y hence can use la_solve
let newTheta = la_solve(la_transpose(x) * x, la_transpose(x) * y)
return newTheta.toArray()
}
/**
Computes the cost with our current values of theta
- returns: Cost value for the data with value of theta
*/
open func computeCost() -> Double {
let twoM = 2.0 * Double(m)
let xTheta = x * theta
let diff = xTheta - y
var partial = diff^2
partial = partial / twoM
return partial.toArray().first!
}
}
| mit | c7650f219b9b4f1e5c22a4c91379e1ad | 26.912752 | 218 | 0.664823 | 3.28515 | false | false | false | false |
OatmealCode/Oatmeal | Pod/Classes/Serialization/SerializebleObject.swift | 1 | 3509 | //
// SerializeObject.swift
// Pods
//
// Created by Michael Kantor on 9/12/15.
//
//
import Foundation
public class SerializebleObject: NSObject,Resolveable, Serializes
{
//Required Init
public static var entityName : String?
public var serializationKey = String(NSDate().timeIntervalSince1970)
public var cacheBust : NSTimeInterval = 600.00 {
didSet{
setCacheBust()
}
}
public var expires : NSTimeInterval = 0
public required override init()
{
super.init()
self.expires = NSDate().dateByAddingTimeInterval(self.cacheBust).timeIntervalSinceReferenceDate
}
public func setCacheBust()
{
}
public func bindsToContainer()->Bool
{
return false
}
public func didSerialize()
{
}
/*
required public init?(coder aDecoder: NSCoder)
{
super.init()
let properties = toProps()
for i in properties
{
let jValue = i.1.value
let key = i.0
var value : Any? = nil
switch jValue
{
case _ as Int:
value = aDecoder.decodeIntegerForKey(key)
case _ as Double:
value = aDecoder.decodeDoubleForKey(key)
case _ as AnyObject:
value = aDecoder.decodeObjectForKey(key)
case _ as CGPoint:
value = aDecoder.decodeCGPointForKey(key)
case _ as CGVector:
value = aDecoder.decodeCGVectorForKey(key)
case _ as CGSize:
value = aDecoder.decodeCGSizeForKey(key)
default:
print("something else")
}
//setValue(value, forKey: key)
}
}
public func encodeWithCoder(aCoder: NSCoder)
{
let properties = toProps()
for i in properties
{
let jValue = i.1.value
let key = i.0
switch jValue
{
case let v as Int:
aCoder.encodeInteger(v, forKey: key)
case let v as Double:
aCoder.encodeDouble(v, forKey: key)
case let v as Int64:
aCoder.encodeInt64(v, forKey: key)
case let v as Int32:
aCoder.encodeInt32(v, forKey: key)
case let v as CGPoint:
aCoder.encodeCGPoint(v, forKey: key)
case let v as CGVector:
aCoder.encodeCGVector(v, forKey: key)
case let v as CGSize:
aCoder.encodeCGSize(v, forKey: key)
case let v as NSData:
aCoder.encodeDataObject(v)
case let v as String:
aCoder.encodeObject(v, forKey: key)
case let v as AnyObject:
aCoder.encodeObject(v, forKey: key)
default:
#if debug
print("Missed encoding key for \(key) of \(jValue)")
#endif
}
}
}
*/
public override func setValue(value: AnyObject!, forUndefinedKey key: String)
{
if let log : FileLog = ~Oats()
{
log.error("\nWARNING: The object '\(value.dynamicType)' is not bridgable to ObjectiveC")
}
}
}
| mit | 382232325f59b932ac8be4534b0f2c3e | 25.992308 | 103 | 0.494158 | 4.949224 | false | false | false | false |
ashfurrow/FunctionalReactiveAwesome | Pods/RxCocoa/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift | 1 | 2240 | //
// UISearchBar+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
import UIKit
class RxSearchBarDelegate: NSObject, UISearchBarDelegate {
typealias Observer = ObserverOf<String>
typealias DisposeKey = Bag<ObserverOf<String>>.KeyType
var observers: Bag<Observer> = Bag()
func addObserver(observer: Observer) -> DisposeKey {
MainScheduler.ensureExecutingOnScheduler()
return observers.put(observer)
}
func removeObserver(key: DisposeKey) {
MainScheduler.ensureExecutingOnScheduler()
let observer = observers.removeKey(key)
if observer == nil {
removingObserverFailed()
}
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
dispatchNext(searchText, observers)
}
}
extension UISearchBar {
public var rx_searchText: Observable<String> {
rx_checkSearchBarDelegate()
return AnonymousObservable { observer in
MainScheduler.ensureExecutingOnScheduler()
var maybeDelegate = self.rx_checkSearchBarDelegate()
if maybeDelegate == nil {
maybeDelegate = RxSearchBarDelegate()
self.delegate = maybeDelegate
}
let delegate = maybeDelegate!
let key = delegate.addObserver(observer)
return AnonymousDisposable {
delegate.removeObserver(key)
}
}
}
// private
private func rx_checkSearchBarDelegate() -> RxSearchBarDelegate? {
MainScheduler.ensureExecutingOnScheduler()
if self.delegate == nil {
return nil
}
let maybeDelegate = self.delegate as? RxSearchBarDelegate
if maybeDelegate == nil {
rxFatalError("Search bar already has incompatible delegate set. To use rx observable (for now) please remove earlier delegate registration.")
}
return maybeDelegate!
}
} | mit | d18c230e440c4cd9a4d17c4725d97097 | 26 | 153 | 0.598214 | 5.788114 | false | false | false | false |
red-spotted-newts-2014/Im-In | im-in-ios/im-in-ios/untitled folder/APISignUpController.swift | 1 | 1321 | //
// APIController.swift
//
// Created by fahia mohamed on 2014-08-14.
// Copyright (c) 2014 fahia mohamed. All rights reserved.
//
import Foundation
protocol APISignUpControllerProtocol {
func didReceiveAPIResults(results: NSDictionary)
}
class APISignUpController {
var delegate: APISignUpControllerProtocol?
init() {
}
func sendSignUpInfo(info: NSDictionary) {
var request = NSMutableURLRequest(URL: NSURL(string: "http://10.0.2.26:3000/users"))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var params = ["username": info.objectForKey("username"), "email": info.objectForKey("email"), "password": info.objectForKey("password")] as Dictionary
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("\(countElements(params))", forHTTPHeaderField: "Content-Length")
var connection = NSURLConnection(request: request, delegate: self, startImmediately: false)
connection.start()
println("Sending request")
}
} | mit | 4633f725a99618137f333227fe3801c0 | 32.05 | 158 | 0.676003 | 4.701068 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | byuSuite/Classes/Reusable/Extensions.swift | 1 | 36775 | //
// Extensions.swift
// byuSuite
//
// Created by Nathan Johnson on 4/14/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
import UIKit
import SafariServices
import MapKit
//MARK: Basic data types
extension Int {
func toString() -> String {
return String(self)
}
//Return an int equivalent to the first specified number of digits (ie. 123.firstXDigits(2) returns 12
func firstXDigits(_ numDigits: Int) -> Int? {
if numDigits > 0 {
var firstDigits = self
while firstDigits >= (10 * numDigits) {
firstDigits /= 10
}
return firstDigits
} else {
return nil
}
}
//Returns number of digits in Int number
var digitCount: Int {
get {
return numberOfDigits(in: self)
}
}
//Private recursive method for counting digits
private func numberOfDigits(in number: Int) -> Int {
if abs(number) < 10 {
return 1
} else {
return 1 + numberOfDigits(in: number / 10)
}
}
}
extension Double {
func currency(numberStyle: NumberFormatter.Style = .currency) -> String {
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.numberStyle = numberStyle
guard let currency = formatter.string(from: NSNumber(floatLiteral: self)) else {
return "$0.00"
}
return currency
}
func toString() -> String {
return String(self)
}
}
extension Date {
var isToday: Bool {
return Calendar.current.isDateInToday(self)
}
static func dateWithoutTime() -> Date? {
return Date().stripTime()
}
func stripTime() -> Date? {
let components = NSCalendar.current.dateComponents([.day, .month, .year], from: self)
return Calendar.current.date(from: components)
}
func isBetween(date1: Date, and date2: Date, inclusive: Bool = true) -> Bool {
if inclusive {
return date1.compare(self).rawValue * self.compare(date2).rawValue >= 0
} else {
return date1.compare(self) == self.compare(date2)
}
}
func laterDate(date: Date) -> Date {
if self == date, self > date {
return self
} else {
return date
}
}
}
extension Character {
init(integer: Int) {
if let unicodeScalar = UnicodeScalar(integer) {
self.init(unicodeScalar)
} else {
self.init("")
}
}
}
extension Calendar {
static func defaultCalendar(_ timeZone: TimeZone? = TimeZone(identifier: "America/Denver")) -> Calendar {
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = timeZone ?? calendar.timeZone
return calendar
}
func endOfDay(for date: Date) -> Date? {
return Calendar.current.date(bySettingHour: 23, minute: 59, second: 59, of: date)
}
func combine(date: Date, time: Date) -> Date? {
let dateComponents = self.dateComponents([.year, .month, .day], from: date)
let timeComponents = self.dateComponents([.hour, .minute, .second], from: time)
let mergedComponents = DateComponents(calendar: self, timeZone: self.timeZone, year: dateComponents.year, month: dateComponents.month, day: dateComponents.day, hour: timeComponents.hour, minute: timeComponents.minute, second: timeComponents.second)
return self.date(from: mergedComponents)
}
}
extension String {
init(unicodeValue: Int) {
if let unicodeScalar = UnicodeScalar(unicodeValue) {
self.init(unicodeScalar)
} else {
self.init()
}
}
func captializedFirstLetter() -> String {
return prefix(1).uppercased()
}
func stringWithFirstLetterCapitalized() -> String {
return prefix(1).uppercased() + dropFirst()
}
func currency(numberStyle: NumberFormatter.Style = .currency) -> Double {
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "en_US")
formatter.numberStyle = numberStyle
guard let currency = formatter.number(from: self) else {
return 0
}
return currency.doubleValue
}
func asDouble() -> Double? {
return Double(self)
}
func asBool() -> Bool? {
return Bool(self)
}
func asInt() -> Int? {
return Int(self)
}
func urlEncoded(characterSet: CharacterSet = .alphanumerics) -> String {
return self.addingPercentEncoding(withAllowedCharacters: characterSet) ?? ""
}
func decodedHTMLEntities() -> String {
let asciiMap = [
" ": " ", //32
"!": "!",
""": "\"\"",
""": "\"\"",
"#": "#",
"$": "$",
"%": "%",
"&": "&", //38
"&": "&",
"'": "'",
"'": "'",
"(": "(",
")": ")",
"*": "*",
"+": "+",
",": ",",
"-": "-",
".": ".",
"/": "/",
"0": "0",
"1": "1",
"2": "2",
"3": "3",
"4": "4",
"5": "5",
"6": "6",
"7": "7",
"8": "8",
"9": "9",
":": ":",
";": ";",
"<": "<", //60
"<": "<",
"=": "=",
">": ">", //62
">": ">",
"?": "?",
"@": "@",
"A": "A",
"B": "B",
"C": "C",
"D": "D",
"E": "E",
"F": "F",
"G": "G",
"H": "H",
"I": "I",
"J": "J",
"K": "K",
"L": "L",
"M": "M",
"N": "N",
"O": "O",
"P": "P",
"Q": "Q",
"R": "R",
"S": "S",
"T": "T",
"U": "U",
"V": "V",
"W": "W",
"X": "X",
"Y": "Y",
"Z": "Z",
"[": "[",
"\": "\\",
"]": "]",
"^": "^",
"_": "_",
"`": "`",
"a": "a",
"b": "b",
"c": "c",
"d": "d", //100
"e": "e",
"f": "f",
"g": "g",
"h": "h",
"i": "i",
"j": "j",
"k": "k",
"l": "l",
"m": "m",
"n": "n",
"o": "o",
"p": "p",
"q": "q",
"r": "r",
"s": "s",
"t": "t",
"u": "u",
"v": "v",
"w": "w",
"x": "x",
"y": "y",
"z": "z",
"{": "{",
"|": "|",
"}": "}",
"~": "~",
"": " ", //127
" ": " ", //160
" ": " ",
"¡": "¡",
"¢": "¢",
"£": "£",
"¤": "¤",
"¥": "¥",
"¦": "¦",
"§": "§",
"¨": "¨",
"©": "©",
"ª": "ª",
"«": "«",
"¬": "¬",
"­": "",
"®": "®",
"¯": "¯",
"°": "°",
"±": "±",
"²": "²",
"³": "³",
"´": "´",
"µ": "µ",
"¶": "¶",
"·": "·",
"¸": "¸",
"¹": "¹",
"º": "º",
"»": "»",
"¼": "¼",
"½": "½",
"¾": "¾",
"¿": "¿",
"À": "À",
"Á": "Á",
"Â": "Â",
"Ã": "Ã",
"Ä": "Ä",
"Å": "Å",
"Æ": "Æ",
"Ç": "Ç",
"È": "È", //200
"É": "É",
"Ê": "",
"Ë": "Ë",
"Ì": "Ì",
"Í": "Í",
"Î": "Î",
"Ï": "Ï",
"Ð": "Ð",
"Ñ": "Ñ",
"Ò": "Ò",
"Ó": "Ó",
"Ô": "Ô",
"Õ": "Õ",
"Ö": "Ö",
"×": "×",
"Ø": "Ø",
"Ù": "Ù",
"Ú": "Ú",
"Û": "Û",
"Ü": "Ü",
"Ý": "Ý",
"Þ": "Þ",
"ß": "ß",
"à": "à",
"á": "á",
"â": "â",
"ã": "ã",
"ä": "ä",
"å": "å",
"æ": "æ",
"ç": "ç",
"è": "è",
"é": "é",
"ê": "ê",
"ë": "ë",
"ì": "ì",
"í": "í",
"î": "î",
"ï": "ï",
"ð": "ð",
"ñ": "ñ",
"ò": "ò",
"ó": "ó",
"ô": "ô",
"õ": "õ",
"ö": "ö",
"÷": "÷",
"ø": "ø",
"ù": "ù",
"ú": "ú",
"û": "û",
"ü": "ü",
"ý": "ý",
"þ": "þ",
"ÿ": "ÿ", //255
"∀": "∀", // for all
"∂": "∂", // part
"∃": "∃", // exists
"∅": "∅", // empty
"∇": "∇", // nabla
"∈": "∈", // isin
"∉": "∉", // notin
"∋": "∋", // ni
"∏": "∏", // prod
"∑": "∑", // sum
"−": "−", // minus
"∗": "∗", // lowast
"√": "√", // square root
"∝": "∝", // proportional to
"∞": "∞", // infinity
"∠": "∠", // angle
"∧": "∧", // and
"∨": "∨", // or
"∩": "∩", // cap
"∪": "∪", // cup
"∫": "∫", // integral
"∴": "∴", // therefore
"∼": "∼", // similar to
"≅": "≅", // congruent to
"≈": "≈", // almost equal
"≠": "≠", // not equal
"≡": "≡", // equivalent
"≤": "≤", // less or equal
"≥": "≥", // greater or equal
"⊂": "⊂", // subset of
"⊃": "⊃", // superset of
"⊄": "⊄", // not subset of
"⊆": "⊆", // subset or equal
"⊇": "⊇", // superset or equal
"⊕": "⊕", // circled plus
"⊗": "⊗", // circled times
"⊥": "⊥", // perpendicular
"⋅": "⋅", // dot operator
"Α": "Α", // Alpha
"Β": "Β", // Beta
"Γ": "Γ", // Gamma
"Δ": "Δ", // Delta
"Ε": "Ε", // Epsilon
"Ζ": "Ζ", // Zeta
"Η": "Η", // Eta
"Θ": "Θ", // Theta
"Ι": "Ι", // Iota
"Κ": "Κ", // Kappa
"Λ": "Λ", // Lambda
"Μ": "Μ", // Mu
"Ν": "Ν", // Nu
"Ξ": "Ξ", // Xi
"Ο": "Ο", // Omicron
"Π": "Π", // Pi
"Ρ": "Ρ", // Rho
"Σ": "Σ", // Sigma
"Τ": "Τ", // Tau
"Υ": "Υ", // Upsilon
"Φ": "Φ", // Phi
"Χ": "Χ", // Chi
"Ψ": "Ψ", // Psi
"Ω": "Ω", // Omega
"α": "α", // alpha
"β": "β", // beta
"γ": "γ", // gamma
"δ": "δ", // delta
"ε": "ε", // epsilon
"ζ": "ζ", // zeta
"η": "η", // eta
"θ": "θ", // theta
"ι": "ι", // iota
"κ": "κ", // kappa
"λ": "λ", // lambda
"μ": "μ", // mu
"ν": "ν", // nu
"ξ": "ξ", // xi
"ο": "ο", // omicron
"π": "π", // pi
"ρ": "ρ", // rho
"ς": "ς", // sigmaf
"σ": "σ", // sigma
"τ": "τ", // tau
"υ": "υ", // upsilon
"φ": "φ", // phi
"χ": "χ", // chi
"ψ": "ψ", // psi
"ω": "ω", // omega
"ϑ": "ϑ", // theta symbol
"ϒ": "ϒ", // upsilon symbol
"ϖ": "ϖ", // pi symbol
"Œ": "Œ", // capital ligature OE
"œ": "œ", // small ligature oe
"Š": "Š", // capital S with caron
"š": "š", // small S with caron
"Ÿ": "Ÿ", // capital Y with diaeres
"ƒ": "ƒ", // f with hook
"ˆ": "ˆ", // modifier letter circumflex accent
"˜": "˜", // small tilde
" ": " ", // en space
" ": " ", // em space
" ": " ", // thin space
"‌": "", // zero width non-joiner
"‍": "", // zero width joiner
"‎": "", // left-to-right mark
"‏": "", // right-to-left mark
"–": "–", // en dash
"—": "—", // em dash
"‘": "‘", // left single quotation mark
"’": "’", // right single quotation mark
"‚": "‚", // single low-9 quotation mark
"“": "“", // left double quotation mark
"”": "”", // right double quotation mark
"„": "„", // double low-9 quotation mark
"†": "†", // dagger
"‡": "‡", // double dagger
"•": "•", // bullet
"…": "…", // horizontal ellipsis
"‰": "‰", // per mille
"′": "′", // minutes
"″": "″", // seconds
"‹": "‹", // single left angle quotation
"›": "›", // single right angle quotation
"‾": "‾", // overline
"€": "€", // euro
"™": "™", // trademark
"™": "™", // trademark
"←": "←", // left arrow
"↑": "↑", // up arrow
"→": "→", // right arrow
"↓": "↓", // down arrow
"↔": "↔", // left right arrow
"↵": "↵", // carriage return arrow
"⌈": "⌈", // left ceiling
"⌉": "⌉", // right ceiling
"⌊": "⌊", // left floor
"⌋": "⌋", // right floor
"◊": "◊", // lozenge
"♠": "♠", // spade
"♣": "♣", // club
"♥": "♥", // heart
"♦": "♦", // diamond
"∀": "∀", // for all
"∂": "∂", // part
"∃": "∃", // exists
"∅": "∅", // empty
"∇": "∇", // nabla
"∈": "∈", // isin
"∉": "∉", // notin
"∋": "∋", // ni
"∏": "∏", // prod
"∑": "∑", // sum
"−": "−", // minus
"∗": "∗", // lowast
"√": "√", // square root
"∝": "∝", // proportional to
"∞": "∞", // infinity
"∠": "∠", // angle
"∧": "∧", // and
"∨": "∨", // or
"∩": "∩", // cap
"∪": "∪", // cup
"∫": "∫", // integral
"∴": "∴", // therefore
"∼": "∼", // similar to
"≅": "≅", // congruent to
"≈": "≈", // almost equal
"≠": "≠", // not equal
"≡": "≡", // equivalent
"≤": "≤", // less or equal
"≥": "≥", // greater or equal
"⊂": "⊂", // subset of
"⊃": "⊃", // superset of
"⊄": "⊄", // not subset of
"⊆": "⊆", // subset or equal
"⊇": "⊇", // superset or equal
"⊕": "⊕", // circled plus
"⊗": "⊗", // circled times
"⊥": "⊥", // perpendicular
"⋅": "⋅", // dot operator
"Α": "Α", // Alpha
"Β": "Β", // Beta
"Γ": "Γ", // Gamma
"Δ": "Δ", // Delta
"Ε": "Ε", // Epsilon
"Ζ": "Ζ", // Zeta
"Η": "Η", // Eta
"Θ": "Θ", // Theta
"Ι": "Ι", // Iota
"Κ": "Κ", // Kappa
"Λ": "Λ", // Lambda
"Μ": "Μ", // Mu
"Ν": "Ν", // Nu
"Ξ": "Ξ", // Xi
"Ο": "Ο", // Omicron
"Π": "Π", // Pi
"Ρ": "Ρ", // Rho
"Σ": "Σ", // Sigma
"Τ": "Τ", // Tau
"Υ": "Υ", // Upsilon
"Φ": "Φ", // Phi
"Χ": "Χ", // Chi
"Ψ": "Ψ", // Psi
"Ω": "Ω", // Omega
"α": "α", // alpha
"β": "β", // beta
"γ": "γ", // gamma
"δ": "δ", // delta
"ε": "ε", // epsilon
"ζ": "ζ", // zeta
"η": "η", // eta
"θ": "θ", // theta
"ι": "ι", // iota
"κ": "κ", // kappa
"λ": "λ", // lambda
"μ": "μ", // mu
"ν": "ν", // nu
"ξ": "ξ", // xi
"ο": "ο", // omicron
"π": "π", // pi
"ρ": "ρ", // rho
"ς": "ς", // sigmaf
"σ": "σ", // sigma
"τ": "τ", // tau
"υ": "υ", // upsilon
"φ": "φ", // phi
"χ": "χ", // chi
"ψ": "ψ", // psi
"ω": "ω", // omega
"ϑ": "ϑ", // theta symbol
"ϒ": "ϒ", // upsilon symbol
"ϖ": "ϖ", // pi symbol
"Œ": "Œ", // capital ligature OE
"œ": "œ", // small ligature oe
"Š": "Š", // capital S with caron
"š": "š", // small S with caron
"Ÿ": "Ÿ", // capital Y with diaeres
"ƒ": "ƒ", // f with hook
"ˆ": "ˆ", // modifier letter circumflex accent
"˜": "˜", // small tilde
" ": " ", // en space
" ": " ", // em space
" ": " ", // thin space
"‌": "", // zero width non-joiner
"‍": "", // zero width joiner
"‎": "", // left-to-right mark
"‏": "", // right-to-left mark
"–": "–", // en dash
"—": "—", // em dash
"‘": "‘", // left single quotation mark
"’": "’", // right single quotation mark
"‚": "‚", // single low-9 quotation mark
"“": "“", // left double quotation mark
"”": "”", // right double quotation mark
"„": "„", // double low-9 quotation mark
"†": "†", // dagger
"‡": "‡", // double dagger
"•": "•", // bullet
"…": "…", // horizontal ellipsis
"‰": "‰", // per mille
"′": "′", // minutes
"″": "″", // seconds
"‹": "‹", // single left angle quotation
"›": "›", // single right angle quotation
"‾": "‾", // overline
"€": "€", // euro
"™": "™", // trademark
"←": "←", // left arrow
"↑": "↑", // up arrow
"→": "→", // right arrow
"↓": "↓", // down arrow
"↔": "↔", // left right arrow
"↵": "↵", // carriage return arrow
"⌈": "⌈", // left ceiling
"⌉": "⌉", // right ceiling
"⌊": "⌊", // left floor
"⌋": "⌋", // right floor
"◊": "◊", // lozenge
"♠": "♠", // spade
"♣": "♣", // club
"♥": "♥", // heart
"♦": "♦", // diamond
]
var temp = self.trimmingCharacters(in: NSCharacterSet.newlines)
//ASCII standard says you can optionally have zero before any two digit codes:
//http://www-ee.eng.hawaii.edu/~tep/EE160/Book/chap4/subsection2.1.1.1.html
temp = temp.replacingOccurrences(of: "�", with: "&#")
for ascii in asciiMap.keys {
temp = temp.replacingOccurrences(of: ascii, with: asciiMap[ascii]!)
}
return temp
}
func stringByStrippingHTML(trimmingWhitespace: Bool) -> String {
var temp = self.decodedHTMLEntities()
let regex1 = try? NSRegularExpression(pattern: "<[^>]+>")
temp = regex1?.stringByReplacingMatches(in: temp, range: NSMakeRange(0, temp.count), withTemplate: "") ?? temp
let regex2 = try? NSRegularExpression(pattern: "\t+")
temp = regex2?.stringByReplacingMatches(in: temp, range: NSMakeRange(0, temp.count), withTemplate: " ") ?? temp
if trimmingWhitespace {
temp = temp.trimmingCharacters(in: .whitespacesAndNewlines)
}
let regex3 = try? NSRegularExpression(pattern: " {2,}")
temp = regex3?.stringByReplacingMatches(in: temp, range: NSMakeRange(0, temp.count), withTemplate: " ") ?? temp
return temp
}
func stringByLinkifyingURLs() -> String {
let pattern = "(?<!=\")\\b((http|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%%&:/~\\+#]*[\\w\\-\\@?^=%%&/~\\+#])?)"
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
return self
}
return regex.stringByReplacingMatches(in: self, options: [], range: NSMakeRange(0, self.count), withTemplate: "<a href=\"$1\" class=\"linkified\">$1</a>")
}
func applyBYUTitleCapitalization() -> String {
let wordsWithCapitalizationExceptions = ["and", "BYU", "BYUSA", "CAEDM", "CB", "CIO", "CITES", "CES", "CNA", "CTB", "DNA", "FLAS", "FM", "for", "ICLA", "ID", "KBYU", "LDS", "McDonald", "McKay", "MTC", "MPH", "N7BYU", "NMELRC", "of", "ORCA", "RB", "ROTC", "SAS", "SFH", "TEC", "the", "TV", "WSC", "YNews", "YSA"]
var temp = self.trimmingCharacters(in: .whitespacesAndNewlines)
temp = temp.capitalized
for word in wordsWithCapitalizationExceptions {
let regex = try? NSRegularExpression(pattern: "\\b\(word)\\b", options: .caseInsensitive)
temp = regex?.stringByReplacingMatches(in: temp, range: NSMakeRange(0, temp.count), withTemplate: word) ?? temp
}
//Capitalize first letter in the string, even if it was changed to lowercase because of an exception word
return temp.stringWithFirstLetterCapitalized()
}
}
extension CLLocationCoordinate2D {
func isWithinBounds(minLat: Double, maxLat: Double, minLong: Double, maxLong: Double) -> Bool {
let (lat, long) = (Double(self.latitude), Double(self.longitude))
//Return a boolean indicating whether the coordinate's latitude and longitude are within the minimum and maximum points provided
return lat >= minLat && lat <= maxLat && long >= minLong && long <= maxLong
}
}
extension Array where Element: CampusBuilding2 {
func sorted(using location: CLLocation) -> [CampusBuilding2] {
return self.sorted {
//Sort by distance from provided location
return CLLocation(latitude: $0.coordinate.latitude, longitude: $0.coordinate.longitude).distance(from: location) < CLLocation(latitude: $1.coordinate.latitude, longitude: $1.coordinate.longitude).distance(from: location)
}
}
func findBuilding(with acronym: String) -> CampusBuilding2? {
//Some acronym arguments might have a hyphen in them (e.g., B-66 coming from Department Directory)
return self.first { $0.acronym == acronym.replacingOccurrences(of: "-", with: "") }
}
func buildings(matching searchText: String) -> [CampusBuilding2] {
return self.filter {
$0.name?.range(of: searchText, options: .caseInsensitive) != nil || $0.acronym.range(of: searchText, options: .caseInsensitive) != nil
}
}
}
//MARK: NS (Advanced data types)
extension DateFormatter {
@objc static func defaultDateFormat(_ format: String) -> DateFormatter {
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "US")
formatter.dateFormat = format
return formatter
}
func date(from string: String?) -> Date? {
if let string = string {
return self.date(from: string)
} else {
return nil
}
}
func string(fromOptional date: Date?) -> String? {
if let date = date {
return self.string(from: date)
} else {
return nil
}
}
}
extension Array {
mutating func filterAndRemove(where closure: (Element) -> Bool) -> [Element] {
var filteredElements = [Element]()
var rejectedElements = [Element]()
for item in self {
if closure(item) {
filteredElements.append(item)
} else {
rejectedElements.append(item)
}
}
self = rejectedElements
return filteredElements
}
}
extension Dictionary where Key == String, Value == Any {
init(tuples: [(String, Any?)]) {
self = Dictionary()
for tuple in tuples {
self[tuple.0] = tuple.1
}
}
}
extension Dictionary {
func keysAsArray() -> [Key] {
return Array(self.keys)
}
}
extension IndexPath {
init(row: Int) {
self.init(row: row, section: 0)
}
}
extension MKMapView {
func deselectSelectedAnnotation() {
self.deselectAnnotation(self.selectedAnnotations.last, animated: true)
}
func dequeueDefaultReusablePin(pinId: String = "pin") -> MKPinAnnotationView? {
return self.dequeueReusableAnnotationView(withIdentifier: pinId) as? MKPinAnnotationView
}
func defaultBuildingAnnotationView(annotation: MKAnnotation, displayDetailDisclosureButton: Bool = true) -> MKAnnotationView? {
//Only one annotation will not be a CampusBuilding for features using this (user location)
guard let building = annotation as? CampusBuilding2 else { return nil }
if let pinView = dequeueDefaultReusablePin() {
return pinView
} else {
return pinAnnotationView(displayDetailDisclosureButton: displayDetailDisclosureButton, forBuildingAnnotation: building, animatingDrop: false)
}
}
func pinAnnotationView(displayDetailDisclosureButton: Bool, forBuildingAnnotation annotation: CampusBuilding2, animatingDrop: Bool) -> MKPinAnnotationView {
let pinView = MKPinAnnotationView(annotation: annotation)
pinView.canShowCallout = true
pinView.animatesDrop = animatingDrop
pinView.tintColor = .byuTint //Colors the detail disclosure button
pinView.pinTintColor = .byuTint
if displayDetailDisclosureButton {
//Add detail button to callout
pinView.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
} else {
pinView.rightCalloutAccessoryView = nil
}
return pinView
}
func zoomToAnnotation(_ annotation: MKAnnotation, delta: Double = 0.003, animated: Bool = true) {
self.setRegion(MKCoordinateRegion(center: annotation.coordinate, span: MKCoordinateSpan(latitudeDelta: delta, longitudeDelta: delta) ), animated: animated)
}
}
extension MKPinAnnotationView {
convenience init(annotation: MKAnnotation, id: String = "pin", pinTintColor: UIColor = UIColor.byuBlue, animatesDrop: Bool = false, canShowCallout: Bool = true, rightCalloutAccessoryView: UIButton? = nil) {
self.init(annotation: annotation, reuseIdentifier: id)
self.pinTintColor = pinTintColor
self.animatesDrop = animatesDrop
self.canShowCallout = rightCalloutAccessoryView != nil ? true : canShowCallout
self.rightCalloutAccessoryView = rightCalloutAccessoryView
}
}
extension NSLayoutConstraint {
convenience init(item: Any, attr1: NSLayoutAttribute, relatedBy: NSLayoutRelation = .equal, toItem: Any? = nil, attr2: NSLayoutAttribute = .notAnAttribute, multiplier: CGFloat = 1, constant: CGFloat = 0) {
self.init(item: item, attribute: attr1, relatedBy: relatedBy, toItem: toItem, attribute: attr2, multiplier: multiplier, constant: constant)
}
}
extension NSLayoutDimension {
func constraint(equalTo anchor: NSLayoutDimension, multiplier: CGFloat, priority: Float) -> NSLayoutConstraint {
let constraintWithPriority: NSLayoutConstraint = constraint(equalTo: anchor, multiplier: multiplier)
constraintWithPriority.priority = priority
return constraintWithPriority
}
}
extension NSAttributedString {
convenience init(html: String) throws {
if let data = html.data(using: .utf8) {
try self.init(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
} else {
self.init(string: html)
}
}
}
//MARK: UI
extension UIApplication {
static func open(url: URL) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}
}
extension UICollectionView {
func deselectSelectedItems() {
if let indexPaths = self.indexPathsForSelectedItems {
for indexPath in indexPaths {
self.deselectItem(at: indexPath, animated: true)
}
}
}
func dequeueReusableCell(for indexPath: IndexPath, reuseIdentifier: String = "cell") -> UICollectionViewCell {
return self.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
}
}
extension UIColor {
convenience init(red: CGFloat, green: CGFloat, blue: CGFloat, opacity: CGFloat = 1) {
self.init(red: red/255.0, green: green/255.0, blue: blue/255.0, alpha: opacity)
}
// this defines the global tint color for interactive elements - set to a lightish blue #1b5d9d
static var byuTint: UIColor {
return UIColor(red: 27, green: 93, blue: 157)
}
// background of the views -> white
static var byuBackground: UIColor {
return UIColor(red: 255, green: 255, blue: 255)
}
// the interactive tint color for the nav bars - set to a lighter blue than the typical tint color, at #8ec4ff
static var byuNavigationBarTint: UIColor {
return UIColor(red: 142, green: 196, blue: 255)
}
// top nav bar color -> Dark Blue - #315c8c
static var byuNavigationBarBarTint: UIColor {
return UIColor(red: 49, green: 92, blue: 140)
}
// these are the bottom "action" buttons, such as "add features, launch feature" - set to #eeeeee
static var byuToolbarTint: UIColor {
return UIColor(red: 0, green: 51, blue: 102)
}
static var byuToolbarBarTint: UIColor {
return UIColor(red:238, green:238, blue:238)
}
// TODO: it doesn't display the correct color
static var byuSearchBarTint: UIColor {
return UIColor.byuNavigationBarTint
}
static var byuSearchBarBarTint: UIColor {
return UIColor.byuNavigationBarBarTint
}
//this is actually the tint color
//#1B5D9D
static var byuSwitchSegmentHighlighted: UIColor {
return UIColor(red: 27, green: 93, blue: 157)
}
//this is the text color
static var byuSwitchSegment: UIColor {
return UIColor(red: 0, green: 51, blue: 102)
}
static var byuSwitchOnTint: UIColor {
return .green
}
static var byuTextFieldBackground: UIColor {
return UIColor(red:250, green:250, blue:250)
}
static var byuTextFieldBorder: UIColor {
return UIColor.byuDetailText
}
static var byuTableSeparatorDefault: UIColor {
return UIColor(red:174, green:176, blue:177)
}
// the colors of the section headers
static var byuTableSectionHeaderBackground: UIColor {
return UIColor(red:238, green:238, blue:238)
}
//the color of the section header text
static var byuTableSectionHeader: UIColor {
return UIColor(red:120, green:120, blue:120)
}
static var byuText: UIColor {
return UIColor.black
}
static var byuDetailText: UIColor {
return UIColor(red: 189, green: 189, blue: 189)
}
static var byuBlue: UIColor {
return .byuTint
}
static var byuRed: UIColor {
return UIColor(red:184, green:95, blue:95)
}
static var byuGreen: UIColor {
return UIColor(red:95, green:184, blue:95);
}
static var yTimeGreen: UIColor {
return UIColor(red: 0, green: 170, blue: 0);
}
static var yTimeRed: UIColor {
return UIColor(red: 170, green: 0, blue: 0);
}
@objc static var byuRedFaded: UIColor {
return UIColor(red: 184, green: 95, blue: 95, opacity: 0.25)
}
@objc static var byuGreenFaded: UIColor {
return UIColor(red: 95, green: 184, blue:95, opacity: 0.25)
}
static var transparent: UIColor {
return UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0)
}
}
extension UIFont {
static var byuTableViewCellTextLabel: UIFont {
return UIFont.systemFont(ofSize: 17)
}
static var byuTableViewCellDetailTextLebl: UIFont {
return UIFont.byuTableViewCellTextLabel
}
static var byuTableViewCellSubtitle: UIFont {
return UIFont.systemFont(ofSize: 12)
}
static var byuTableViewHeader: UIFont {
return UIFont.systemFont(ofSize: 14)
}
}
extension UIImage {
func reduceSize(maxDemension: CGFloat) -> UIImage? {
if self.size.width < maxDemension && self.size.height < maxDemension {
return self
}
let imgRatio = self.size.width > self.size.height ? self.size.height / self.size.width : self.size.width / self.size.height
let newSize = self.size.width > self.size.height ? CGSize(width: maxDemension, height: maxDemension * imgRatio) : CGSize(width: maxDemension * imgRatio, height: maxDemension)
//Do the resizing with the ImageContext
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
extension UINavigationBar {
func applyByuFormatting() {
self.isTranslucent = false
self.barTintColor = .byuNavigationBarBarTint
self.tintColor = .byuNavigationBarTint
self.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
}
}
extension UISegmentedControl {
func applyByuFormatting() {
self.tintColor = .byuSwitchSegmentHighlighted
self.backgroundColor = .white
}
}
extension UITabBar {
func applyByuFormatting() {
self.barTintColor = .byuToolbarBarTint
self.tintColor = .byuTint
}
}
extension UITableView {
func deselectSelectedRow() {
if let selectedIndex = self.indexPathForSelectedRow {
self.deselectRow(at: selectedIndex, animated: true)
}
}
func hideEmptyCells() {
tableFooterView = UIView()
}
//This method will make the rows of a tableView cell automatically adjust to fit contents
//NOTE: The number of lines on the cell's textLabel must be set to 0 for this to work.
//This can be done programatically or from the storyboard
@objc func variableHeightForRows() {
self.estimatedRowHeight = 44.0 //Arbitrary value, set to default cell height
self.rowHeight = UITableViewAutomaticDimension //Needed to resize cells to fit contents
}
func registerNib(nibName: String, forCellIdentifier cellId: String = "cell") {
self.register(UINib(nibName: nibName, bundle: nil), forCellReuseIdentifier: cellId)
}
func dequeueReusableCell(for indexPath: IndexPath, identifier: String = "cell") -> UITableViewCell {
return self.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
}
func addDefaultRefreshControl(target: Any?, action: Selector) -> UIRefreshControl {
let refreshControl = UIRefreshControl()
refreshControl.attributedTitle = NSAttributedString(string: "Loading...")
refreshControl.addTarget(target, action: action, for: .valueChanged)
refreshControl.beginRefreshing()
self.addSubview(refreshControl)
return refreshControl
}
func peekSwipeOptions(onRight: Bool = true, indexPath: IndexPath, buttonOptions: [(String, UIColor)], afterDelay delay: Double = 0, duration: Double = 0.8, withCallback callback: (() -> Void)? = nil) {
self.layoutIfNeeded()
if let cell = self.cellForRow(at: indexPath) {
self.isUserInteractionEnabled = false
var buttons = [UIButton]()
// Keep track of the total button widths so that the next button is placed next to the previous one
var totalWidth: CGFloat = 0.0
for buttonOption in buttonOptions {
let button = UIButton()
button.backgroundColor = buttonOption.1
button.setTitle(buttonOption.0, for: .normal)
button.setTitleColor(.white, for: .normal)
button.sizeToFit()
let width = button.frame.width + 30
let xOrigin = onRight ? cell.frame.width + totalWidth : -totalWidth - width
button.frame = CGRect(x: xOrigin, y: 0, width: width, height: cell.frame.height)
cell.contentView.addSubview(button)
buttons.append(button)
totalWidth += button.frame.width
}
UIView.animate(withDuration: duration, delay: delay, animations: {
// For each view in the cell, move it by the combined widths of all buttons
cell.subviews.forEach { $0.frame.origin.x += onRight ? -totalWidth : totalWidth }
}, completion: { _ in
UIView.animate(withDuration: duration, delay: 0.4, animations: {
// For each view in the cell, move it by the combined widths of all buttons
cell.subviews.forEach { $0.frame.origin.x += onRight ? totalWidth : -totalWidth }
}, completion: { _ in
// Remove buttons after we are done displaying the swipe options
buttons.forEach { $0.removeFromSuperview() }
self.isUserInteractionEnabled = true
if let callback = callback {
callback()
}
})
})
}
}
func scrollToTop(animated: Bool = false) {
self.scrollToRow(at: IndexPath(row: 0), at: .top, animated: animated)
}
}
extension UIView {
func setGradientBackground(bottom: UIColor, top: UIColor) {
let gradient = CAGradientLayer()
gradient.colors = [top.cgColor, bottom.cgColor]
gradient.locations = [0.0, 1.0]
gradient.frame.size = self.frame.size
gradient.frame.origin = CGPoint(x: 0.0, y: 0.0)
self.layer.insertSublayer(gradient, at: 0)
}
}
extension UIViewController {
@objc func presentSafariViewController(urlString: String, delegate: SFSafariViewControllerDelegate? = nil, errorHandler: (() -> Void)? = nil) {
if let url = URL(string: urlString) {
let svc = SFSafariViewController(url: url)
svc.delegate = delegate
if #available(iOS 10.0, *) {
svc.preferredBarTintColor = .byuNavigationBarBarTint
svc.preferredControlTintColor = .white
}
self.present(svc, animated: true)
} else {
displayAlert(title: "Error loading URL", message: "There was an error loading this web page. If this error persists please provide feedback or contact the OIT service desk.", alertHandler: { (_) in
if let errorHandler = errorHandler {
errorHandler()
}
})
}
}
//This function is for convenience only. Sadly, we have fought for too long to try and make "popBack" the default alertHandler for the function below... to no avail. This will have to do.
func displayAlert(error: ByuError? = nil, title: String = "Error", message: String? = nil) {
displayAlert(error: error, title: title, message: message) { (_) in
self.popBack()
}
}
func displayAlert(error: ByuError? = nil, title: String = "Error", message: String? = nil, alertHandler: ((UIAlertAction?) -> Void)?) {
guard let vc = self.navigationController?.visibleViewController, !vc.isKind(of: UIAlertController.self) else { return }
let alert = UIAlertController(title: title, message: message ?? error?.readableMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: alertHandler))
present(alert, animated: true, completion: nil)
}
func displayLoadingView(message: String) -> LoadingView {
return LoadingView.addAsSubview(to: view, withMessage: message)
}
func popBack() {
navigationController?.popViewController(animated: true)
}
func showToast(message: String, type: ToastView.ToastType = .success, dismissDelay: TimeInterval = 3.5, completion: @escaping () -> () = {}) {
ToastView.show(in: self.view, message: message, type: type, dismissDelay: dismissDelay, completion: completion)
}
}
| apache-2.0 | 2b277829b16151e9976b6502b1ca2ee8 | 28.681409 | 313 | 0.590685 | 2.967412 | false | false | false | false |
michalciurus/KatanaRouter | Pods/Katana/Katana/Plastic/EdgeInsets.swift | 1 | 4912 | //
// EdgeInsets.swift
// Katana
//
// Copyright © 2016 Bending Spoons.
// Distributed under the MIT License.
// See the LICENSE file for more information.
import CoreGraphics
/// `EdgeInsets` is the scalable counterpart of `UIEdgeInsets`
public struct EdgeInsets: Equatable {
/// the top inset
public let top: Value
/// the left inset
public let left: Value
/// the bottom inset
public let bottom: Value
/// the right inset
public let right: Value
/// an instance of `EdgeInsets` with all the insets equal to zero
public static let zero: EdgeInsets = .scalable(0, 0, 0, 0)
/**
Creates an instance of `EdgeInsets` where all the insets are not scalable
- parameter top: the value of the top inset
- parameter left: the value of the left inset
- parameter bottom: the value of the bottom inset
- parameter right: the value of the right inset
- returns: an instance of `EdgeInsets` where all the insets are not scalable
*/
public static func fixed(_ top: CGFloat, _ left: CGFloat, _ bottom: CGFloat, _ right: CGFloat) -> EdgeInsets {
return EdgeInsets(top: .fixed(top), left: .fixed(left), bottom: .fixed(bottom), right: .fixed(right))
}
/**
Creates an instance of `EdgeInsets` where all the insets are scalable
- parameter top: the value of the top inset
- parameter left: the value of the left inset
- parameter bottom: the value of the bottom inset
- parameter right: the value of the right inset
- returns: an instance of `EdgeInsets` where all the insets are scalable
*/
public static func scalable(_ top: CGFloat, _ left: CGFloat, _ bottom: CGFloat, _ right: CGFloat) -> EdgeInsets {
return EdgeInsets(top: .scalable(top), left: .scalable(left), bottom: .scalable(bottom), right: .scalable(right))
}
/**
Creates an instance of `EdgeInsets` with the given value
- parameter top: the value of the top inset
- parameter left: the value of the left inset
- parameter bottom: the value of the bottom inset
- parameter right: the value of the right inset
- returns: an instance of `EdgeInsets` with the given value
*/
public init(top: Value, left: Value, bottom: Value, right: Value) {
self.top = top
self.left = left
self.bottom = bottom
self.right = right
}
/**
Scales the insets using a multiplier
- parameter multiplier: the multiplier to use to scale the insets
- returns: an instance of `UIEdgeInsets` that is the result of the scaling process
*/
public func scale(by multiplier: CGFloat) -> FloatEdgeInsets {
return FloatEdgeInsets(
top: self.top.scale(by: multiplier),
left: self.left.scale(by: multiplier),
bottom: self.bottom.scale(by: multiplier),
right: self.right.scale(by: multiplier)
)
}
/**
Implements the multiplication for the `EdgeInsets` instances
- parameter lhs: the `EdgeInsets` instance
- parameter rhs: the the mutliplier to apply
- returns: an instance of `EdgeInsets` where the values are multiplied by `rhs`
- warning: this method is different from `scale(by:)` since it scales both
scalable and fixed values, whereas `scale(by:)` scales only the scalable
values
*/
public static func * (lhs: EdgeInsets, rhs: CGFloat) -> EdgeInsets {
return EdgeInsets(
top: lhs.top * rhs,
left: lhs.left * rhs,
bottom: lhs.bottom * rhs,
right: lhs.right * rhs
)
}
/**
Implements the addition for the `EdgeInsets` instances
- parameter lhs: the first instance
- parameter rhs: the second instance
- returns: an instance of `EdgeInsets` where the insets are the sum of the insets of the two operators
*/
public static func + (lhs: EdgeInsets, rhs: EdgeInsets) -> EdgeInsets {
return EdgeInsets(
top: lhs.top + rhs.top,
left: lhs.left + rhs.left,
bottom: lhs.bottom + rhs.bottom,
right: lhs.right + rhs.right
)
}
/**
Implements the division for the `EdgeInsets` instances
- parameter lhs: the first instance
- parameter rhs: the value that will be used in the division
- returns: an instance of `EdgeInsets` where the insets are divided by `rhs`
*/
public static func / (lhs: EdgeInsets, rhs: CGFloat) -> EdgeInsets {
return EdgeInsets(
top: lhs.top / rhs,
left: lhs.left / rhs,
bottom: lhs.bottom / rhs,
right: lhs.right / rhs
)
}
/**
Imlementation of the `Equatable` protocol.
- parameter lhs: the first instance
- parameter rhs: the second instance
- returns: true if the two instances are equal, which means all the insets are equal
*/
public static func == (lhs: EdgeInsets, rhs: EdgeInsets) -> Bool {
return lhs.top == rhs.top &&
lhs.left == rhs.left &&
lhs.bottom == rhs.bottom &&
lhs.right == rhs.right
}
}
| mit | cf1e8dd98a0bb0188e7f426b04c0127c | 30.88961 | 117 | 0.663816 | 4.144304 | false | false | false | false |
collegboi/DIT-Timetable-iOS | DIT-Timetable-V2/Controller/FileManager.swift | 1 | 15070 | //
// RCFileManager.swift
// Remote Config
//
// Created by Timothy Barnard on 29/10/2016.
// Copyright © 2016 Timothy Barnard. All rights reserved.
//
import Foundation
import UIKit
enum RCFile : String {
case saveConfigJSON = "configFile1.json"
case readConfigJSON = "configFile.json"
case saveLangJSON = "langFile1.json"
case readLangJSON = "langFile.json"
}
enum RCFileType {
case config
case language
}
class RCFileManager {
class func readPlistString( value: String, _ defaultStr: String = "") -> String {
var defaultURL = defaultStr
if let path = Bundle.main.path(forResource: "Info", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
guard let valueStr = dict[value] as? String else {
return defaultURL
}
defaultURL = valueStr
}
return defaultURL
}
class func readJSONFile( fileName: RCFile ) -> Data? {
var returnData : Data?
let file = fileName.rawValue
if let dir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first,
let path = NSURL(fileURLWithPath: dir).appendingPathComponent(file) {
returnData = NSData(contentsOf: path) as Data?
}
return returnData
}
class func getJSONDict( parseKey : String, keyVal : String ) -> [String:AnyObject] {
var returnStr = [String:AnyObject]()
guard let jsonData = RCFileManager.readJSONFile(fileName: .readConfigJSON) else {
return returnStr
}
do {
let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as! [String:AnyObject]
for( value ) in parsedData["controllers"] as! NSArray {
guard let dict = value as? [String:Any] else {
break
}
guard let controllerName = dict["name"] as? String else {
break
}
//print(value)
let trimmedString = parseKey.trimmingCharacters(in: .whitespaces)
//print(controllerName)
//print(trimmedString)
if controllerName.contains(trimmedString) {
//print(dict)
for ( object ) in dict["objectsList"] as! NSArray {
if let newobject = object as? [String: AnyObject ] {
guard let objectName = newobject["objectName"] as? String else {
break
}
//print(objectName)
//print(keyVal)
if objectName.contains(keyVal) {
guard let propertiesList = newobject["objectProperties"] as? [String:AnyObject] else {
break
}
//print(dict)
returnStr = propertiesList
}
}
}
}
}
} catch let error as NSError {
print(error)
}
return returnStr
}
class func getJSONClassProperties( parseKey : String ) -> [String:AnyObject] {
var returnStr = [String:AnyObject]()
guard let jsonData = RCFileManager.readJSONFile(fileName: .readConfigJSON) else {
return returnStr
}
do {
let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as! [String:AnyObject]
for( value ) in parsedData["controllers"] as! NSArray {
guard let dict = value as? [String:Any] else {
break
}
guard let controllerName = dict["name"] as? String else {
break
}
//print(value)
let trimmedString = parseKey.trimmingCharacters(in: .whitespaces)
//print(controllerName)
//print(trimmedString)
if controllerName.contains(trimmedString) {
guard let propertiesList = dict["classProperties"] as? [String:AnyObject] else {
break
}
//print(dict)
returnStr = propertiesList
break
}
}
} catch let error as NSError {
print(error)
}
return returnStr
}
class func readJSONColor( keyVal : String ) -> UIColor? {
var returnColor : UIColor?
guard let jsonData = RCFileManager.readJSONFile(fileName: .readConfigJSON) else {
return returnColor
}
do {
let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as! [String:Any]
for ( color ) in parsedData["colors"] as! NSArray {
guard let nextColor = color as? [String:Any] else {
break
}
guard let colorName = nextColor["name"] as? String else {
break
}
if colorName == keyVal {
guard let red = nextColor["red"] as? Float else {
break
}
guard let green = nextColor["green"] as? Float else {
break
}
guard let blue = nextColor["blue"] as? Float else {
break
}
guard let alpha = nextColor["alpha"] as? Float else {
break
}
//print(alpha)
returnColor = UIColor(red: CGFloat(red)/255, green: CGFloat(green)/255.0, blue: CGFloat(blue)/255.0, alpha: CGFloat(alpha))
break
}
}
} catch let error as NSError {
print(error)
}
return returnColor
}
class func readConfigVersion(_ key: String) -> String? {
var returnStr: String?
guard let jsonData = RCFileManager.readJSONFile(fileName: .readConfigJSON) else {
return returnStr
}
do {
let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as! [String:Any]
guard let configObject = parsedData["mainSettings"] as? [String:String] else {
return returnStr
}
guard let valueName = configObject[key] else {
return returnStr
}
returnStr = valueName
} catch let error as NSError {
print(error)
}
return returnStr
}
class func readJSONMainSettings( keyName: String ) -> String? {
var returnStr: String?
guard let jsonData = RCFileManager.readJSONFile(fileName: .readConfigJSON) else {
return returnStr
}
do {
let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as! [String:Any]
guard let translationList = parsedData["mainSettings"] as? [String:String] else {
return returnStr
}
guard let valueName = translationList[keyName] else {
return returnStr
}
returnStr = valueName
} catch let error as NSError {
print(error)
}
return returnStr
}
class func readJSONLanuageList() -> [String]? {
var returnStr: [String]?
guard let jsonData = RCFileManager.readJSONFile(fileName: .readConfigJSON) else {
return returnStr
}
do {
let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as! [String:Any]
guard let translationList = parsedData["languagesList"] as? [String] else {
return returnStr
}
returnStr = translationList
} catch let error as NSError {
print(error)
}
return returnStr
}
class func readJSONTranslation( keyName: String ) -> String? {
var returnStr: String?
guard let jsonData = RCFileManager.readJSONFile(fileName: .readLangJSON) else {
return returnStr
}
do {
let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as! [String:Any]
guard let translationList = parsedData["translationList"] as? [String:String] else {
return returnStr
}
guard let valueName = translationList[keyName] else {
return returnStr
}
returnStr = valueName
} catch let error as NSError {
print(error)
}
return returnStr
}
class func deleteJSONFileName( fileName: String ) -> Bool {
var returnBool = false
var fileNotFound = false
let fileManager = FileManager.default
let tempFolderPath = NSTemporaryDirectory()
do {
let filePaths = try fileManager.contentsOfDirectory(atPath: tempFolderPath)
for filePath in filePaths {
//print(filePath)
if filePath == fileName {
try fileManager.removeItem(atPath: NSTemporaryDirectory() + filePath)
returnBool = true
fileNotFound = false
break
} else {
fileNotFound = true
}
}
} catch {
print("Could not clear temp folder: \(error)")
}
return returnBool || fileNotFound
}
class func checkFilesExists( fileName: String) -> Bool {
//var fileFound = false
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String
let url = NSURL(fileURLWithPath: path)
let filePath = url.appendingPathComponent(fileName)?.path
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath!) {
return true
} else {
return false
}
/*if let dir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first,
let _ = NSURL(fileURLWithPath: dir).appendingPathComponent(fileName) {
fileFound = true
}
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
print(documentsUrl)
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let documentDirectory = URL(fileURLWithPath: path)
let originPath = documentDirectory.appendingPathComponent(fileName)
do {
let directoryContents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: [])
let jsonFiles = directoryContents.filter{ $0.pathExtension == "json" }
//let filePaths = try fileManager.contentsOfDirectory(atPath: tempFolderPath)
for filePath in jsonFiles {
print("list",filePath)
print("find", originPath)
if filePath == originPath {
fileFound = true
break
} else {
fileFound = false
}
}
} catch {
print("Could not clear temp folder: \(error)")
}*/
//return fileFound
}
class func changeJSONFileName(oldName: String, newName: String) {
if deleteJSONFileName(fileName: newName) {
do {
let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let documentDirectory = URL(fileURLWithPath: path)
let originPath = documentDirectory.appendingPathComponent(oldName)
let destinationPath = documentDirectory.appendingPathComponent(newName)
try FileManager.default.moveItem(at: originPath, to: destinationPath)
} catch {
print(error)
}
}
}
class func writeJSONFile( jsonData : NSData, fileType : RCFileType ) {
var fileName: String = ""
switch fileType {
case .language:
//if RCFileManager.checkFilesExists(fileName: RCFile.readLangJSON.rawValue) {
// fileName = RCFile.saveLangJSON.rawValue
//} else {
fileName = RCFile.readLangJSON.rawValue
//}
default:
//if RCFileManager.checkFilesExists(fileName: RCFile.readConfigJSON.rawValue) {
// fileName = RCFile.saveConfigJSON.rawValue
//} else {
fileName = RCFile.readConfigJSON.rawValue
//}
}
if let dir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first,
let path = NSURL(fileURLWithPath: dir).appendingPathComponent(fileName) {
//print("WritePath", path)
do {
try jsonData.write(to: path, options: .noFileProtection) //text.write(to: path, atomically: false, encoding: String.Encoding.utf8)
}
catch {/* error handling here */}
}
}
}
| mit | 779b48e8af955aa7a702d540b1ddfffd | 32.862921 | 171 | 0.506006 | 5.88403 | false | false | false | false |
Esri/arcgis-runtime-samples-ios | arcgis-ios-sdk-samples/Geometry/Geodesic operations/GeodesicOperationsViewController.swift | 1 | 4612 | // Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class GeodesicOperationsViewController: UIViewController, AGSGeoViewTouchDelegate {
@IBOutlet private var mapView: AGSMapView!
private let destinationGraphic: AGSGraphic
private let pathGraphic: AGSGraphic
private let graphicsOverlay = AGSGraphicsOverlay()
private let measurementFormatter = MeasurementFormatter()
private let JFKAirportLocation = AGSPoint(x: -73.7781, y: 40.6413, spatialReference: .wgs84())
/// Add graphics representing origin, destination, and path to a graphics overlay.
required init?(coder aDecoder: NSCoder) {
// Create graphic symbols.
let locationMarker = AGSSimpleMarkerSymbol(style: .circle, color: .blue, size: 10)
locationMarker.outline = AGSSimpleLineSymbol(style: .solid, color: .green, width: 5)
let pathSymbol = AGSSimpleLineSymbol(style: .dash, color: .blue, width: 5)
// Create an origin graphic.
let originGraphic = AGSGraphic(geometry: JFKAirportLocation, symbol: locationMarker, attributes: nil)
// Create a destination graphic.
destinationGraphic = AGSGraphic(geometry: nil, symbol: locationMarker, attributes: nil)
// Create a graphic to represent geodesic path between origin and destination.
pathGraphic = AGSGraphic(geometry: nil, symbol: pathSymbol, attributes: nil)
// Add graphics to the graphics overlay.
graphicsOverlay.graphics.addObjects(from: [originGraphic, destinationGraphic, pathGraphic])
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
// Add the source code button item to the right of navigation bar.
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["GeodesicOperationsViewController"]
// Assign map with imagery basemap to the map view.
mapView.map = AGSMap(basemapStyle: .arcGISImageryStandard)
// Add the graphics overlay to the map view.
mapView.graphicsOverlays.add(graphicsOverlay)
// Set touch delegate on map view as self.
mapView.touchDelegate = self
}
// MARK: - AGSGeoViewTouchDelegate
func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) {
// If callout is open, dismiss it.
if !mapView.callout.isHidden {
mapView.callout.dismiss()
}
// Get the tapped geometry projected to WGS84.
guard let destinationLocation = AGSGeometryEngine.projectGeometry(mapPoint, to: .wgs84()) as? AGSPoint else {
return
}
// Update geometry of the destination graphic.
destinationGraphic.geometry = destinationLocation
// Create a straight line path from origin to destination.
let path = AGSPolyline(points: [JFKAirportLocation, destinationLocation])
// Densify the polyline to show the geodesic curve.
guard let geodeticPath = AGSGeometryEngine.geodeticDensifyGeometry(path, maxSegmentLength: 1, lengthUnit: .kilometers(), curveType: .geodesic) else {
return
}
// Update geometry of the path graphic.
pathGraphic.geometry = geodeticPath
// Calculate geodetic distance between origin and destination.
let distance = AGSGeometryEngine.geodeticLength(of: geodeticPath, lengthUnit: .kilometers(), curveType: .geodesic)
// Display the distance in mapview's callout.
mapView.callout.title = "Distance"
let measurement = Measurement<UnitLength>(value: distance, unit: .kilometers)
mapView.callout.detail = measurementFormatter.string(from: measurement)
mapView.callout.isAccessoryButtonHidden = true
mapView.callout.show(at: mapPoint, screenOffset: .zero, rotateOffsetWithMap: false, animated: true)
}
}
| apache-2.0 | 5f851aa1932ccfe3f05f71b11c3cdc4a | 42.92381 | 157 | 0.682567 | 4.985946 | false | false | false | false |
animalsBeef/CF-TestDYZ | DYZB/DYZB/Classes/Home/Controller/HomeViewController.swift | 1 | 3542 | //
// HomeViewController.swift
// DYZB
//
// Created by 陈峰 on 16/9/18.
// Copyright © 2016年 陈峰. All rights reserved.
//
import UIKit
private let kTitleViewH : CGFloat = 40
class HomeViewController: UIViewController {
// MARK:- 懒加载属性
private lazy var pageTitleView : PageTitleView = {[weak self] in
let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH)
let titles = ["推荐", "游戏", "娱乐", "趣玩"]
let titleView = PageTitleView(frame: titleFrame, titles: titles)
titleView.delegate = self
return titleView
}()
private lazy var pageContentView : PageContentView = {[weak self] in
// 1.确定内容的frame
let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH - kTabbarH
let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH)
// 2.确定所有的子控制器
var childVcs = [UIViewController]()
childVcs.append(RecommendViewController())
for _ in 0..<3 {
let vc = UIViewController()
vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
childVcs.append(vc)
}
let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentViewController: self)
contentView.delegate = self
return contentView
}()
override func viewDidLoad() {
super.viewDidLoad()
//设置UI界面
setupUI()
}
}
// Mark: - 设置UI界面
extension HomeViewController{
private func setupUI(){
// 0.不需要调整UIScrollView的内边距
automaticallyAdjustsScrollViewInsets = false
// 1.设置导航栏
setupNavigationBar();
// 2.添加TitleView
view.addSubview(pageTitleView)
// 3.添加ContentView
view.addSubview(pageContentView)
}
private func setupNavigationBar(){
//设置左侧Item
let btn = UIButton()
btn.setImage(UIImage(named: "logo"), forState:.Normal)
btn.sizeToFit()
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
//设置右侧Item
let size = CGSize(width: 40, height: 40)
let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size)
let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size)
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size)
navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem]
}
}
// MARK:- 遵守PageTitleViewDelegate协议
extension HomeViewController : PageTitleViewDelegate {
func pageTitleView(titleView: PageTitleView, selectedIndex index: Int) {
pageContentView.setCurrentIndex(index)
}
}
// MARK:- 遵守PageContentViewDelegate协议
extension HomeViewController : PageContentViewDelegate {
func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleView.setTitleWithProgress(progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
| mit | 2567ff225d84d70d144cf2b0fb8f2433 | 31.009434 | 156 | 0.646625 | 5.041605 | false | false | false | false |
ZXVentures/ZXFoundation | Sources/ZXFoundation/Foundation/Date.swift | 1 | 2305 | //
// Date.swift
// ZXFoundation
//
// Created by Wyatt McBain on 10/12/16.
// Copyright © 2016 ZX Ventures. All rights reserved.
//
import Foundation
extension Date {
/**
Represents the date as a String in HH:mm format.
*/
public var hourMinute: String {
return DateFormatter.usLocale(with: "HH:mm").string(from: self)
}
/**
Represents the date in MMMM d, yyyy format.
*/
public var monthDayYear: String {
return DateFormatter.usLocale(with: "MMMM d, yyyy").string(from: self)
}
}
extension Date {
/**
Creates a Date from a IOS8601 formatted String. Attempts to represent the most
accurate potrayal of the time given a String. If a dat cannot be created it
will attempt to pare down the String information and create a partial representation.
- parameter from: The ISO8601 date string: `yyyy-MM-dd'T'HH:mm:ssZZZZZ`
- returns: The date formatted from the string. Nil if unable to parse.
*/
public static func iso8601Date(from string: String) -> Date? {
let formats = [
"yyyy-MM-dd'T'HH:mm:ssZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss",
"yyyy-MM-dd'T'HH:mm",
"yyyy-MM-dd'T'HH",
"yyyy-MM-dd",
"yyyy-MM",
"yyyy",
]
var mutableString = string
for index in 0..<formats.count {
let formatter = DateFormatter.usLocale(with: formats[index])
guard let date = formatter.date(from: mutableString) else {
guard (index + 1) != formats.count else { return nil }
// Make sure we want to strip characters off the string.
guard mutableString.characters.count > formats[index + 1].characters.count else {
continue
}
// If unable to create from formatted representation, fall back to simpler iso.
mutableString = mutableString.substring(to: mutableString.index(mutableString.startIndex, offsetBy: formats[index + 1].characters.count - 2))
continue
}
return date
}
return nil
}
}
| mit | fb54dca7e5d39d8d32e247e51c20c7c5 | 30.135135 | 157 | 0.561198 | 4.48249 | false | false | false | false |
airbnb/lottie-ios | Sources/Private/Model/DotLottie/DotLottieUtils.swift | 2 | 1410 | //
// DotLottieUtils.swift
// Lottie
//
// Created by Evandro Harrison Hoffmann on 27/06/2020.
//
import Foundation
// MARK: - DotLottieUtils
struct DotLottieUtils {
static let dotLottieExtension = "lottie"
static let jsonExtension = "json"
/// Temp folder to app directory
static var tempDirectoryURL: URL {
if #available(iOS 10.0, *) {
return FileManager.default.temporaryDirectory
}
return URL(fileURLWithPath: NSTemporaryDirectory())
}
}
extension URL {
/// Checks if url is a lottie file
var isDotLottie: Bool {
pathExtension == DotLottieUtils.dotLottieExtension
}
/// Checks if url is a json file
var isJsonFile: Bool {
pathExtension == DotLottieUtils.jsonExtension
}
var urls: [URL] {
FileManager.default.urls(for: self) ?? []
}
}
extension FileManager {
/// Lists urls for all files in a directory
/// - Parameters:
/// - url: URL of directory to search
/// - skipsHiddenFiles: If should or not show hidden files
/// - Returns: Returns urls of all files matching criteria in the directory
func urls(for url: URL, skipsHiddenFiles: Bool = true) -> [URL]? {
try? contentsOfDirectory(at: url, includingPropertiesForKeys: nil, options: skipsHiddenFiles ? .skipsHiddenFiles : [])
}
}
// MARK: - DotLottieError
public enum DotLottieError: Error {
case invalidFileFormat
case invalidData
case animationNotAvailable
}
| apache-2.0 | c4ea8c6daae87cf43938daa296e58830 | 23.310345 | 122 | 0.700709 | 4.147059 | false | false | false | false |
TG908/iOS | TUM Campus App/CalendarViewController.swift | 1 | 6529 | //
// CalendarViewController.swift
// TUM Campus App
//
// Created by Mathias Quintero on 12/7/15.
// Copyright © 2015 LS1 TUM. All rights reserved.
//
import UIKit
import ASWeekSelectorView
import CalendarLib
class CalendarViewController: UIViewController, DetailView {
@IBOutlet weak var dayPlannerView: MGCDayPlannerView!
var weekSelector: ASWeekSelectorView?
var items = [String:[CalendarRow]]()
var delegate: DetailViewDelegate?
var nextLectureItem: CalendarRow?
var scrolling = false
var firstTimeAppearing = true
func showToday(_ sender: AnyObject?) {
let now = Date()
weekSelector?.setSelectedDate(now, animated: true)
updateTitle(now)
scrolling = true
scrollTo(now)
dayPlannerView.reloadAllEvents()
}
func lecturesOfDate(_ date: Date) -> [CalendarRow] {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy MM dd"
let string = dateformatter.string(from: date)
return items[string] ?? []
}
func updateTitle(_ date: Date) {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "MMMM dd"
title = dateformatter.string(from: date)
}
}
extension CalendarViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = "My Caledar"
let size = CGSize(width: view.frame.width, height: 80.0)
let origin = CGPoint(x: view.frame.origin.x, y: view.frame.origin.y+64)
weekSelector = ASWeekSelectorView(frame: CGRect(origin: origin, size: size))
weekSelector?.firstWeekday = 2
weekSelector?.letterTextColor = UIColor(white: 0.5, alpha: 1.0)
weekSelector?.delegate = self
weekSelector?.selectedDate = Date()
delegate?.dataManager().getCalendar(self)
let barItem = UIBarButtonItem(title: "Today", style: UIBarButtonItemStyle.plain, target: self, action: #selector(CalendarViewController.showToday(_:)))
navigationItem.rightBarButtonItem = barItem
updateTitle(Date())
dayPlannerView.frame = CGRect(x: dayPlannerView.frame.origin.x, y: dayPlannerView.frame.origin.y, width: view.frame.width, height: dayPlannerView.frame.width)
dayPlannerView.dataSource = self
dayPlannerView.delegate = self
dayPlannerView.numberOfVisibleDays = 1
dayPlannerView.dayHeaderHeight = 0.0
dayPlannerView.showsAllDayEvents = false
self.view.addSubview(weekSelector!)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if firstTimeAppearing {
if let item = nextLectureItem {
let date = item.dtstart ?? Date()
weekSelector?.setSelectedDate(date, animated: true)
updateTitle(date)
goToTime(date)
} else {
let now = Date()
scrollTo(now, animated: false)
firstTimeAppearing = false
}
}
}
}
extension CalendarViewController {
func goToDay(_ date: Date) {
let newDate = lecturesOfDate(date).first?.dtstart ?? date
goToTime(newDate)
}
func goToTime(_ date: Date) {
scrolling = true
scrollTo(date)
}
func sameDay(_ a: Date, b: Date) -> Bool {
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy MM dd"
return dateformatter.string(from: a) == dateformatter.string(from: b)
}
func scrollTo(_ date: Date) {
scrollTo(date, animated: true)
}
func scrollTo(_ date: Date, animated: Bool) {
let interval = TimeInterval(-1200.0)
var newDate = Date(timeInterval: interval, since: date)
if !sameDay(newDate, b: date) {
newDate = date
}
dayPlannerView.scroll(to: newDate, options: .dateTime, animated: animated)
}
}
extension CalendarViewController: TumDataReceiver {
func receiveData(_ data: [DataElement]) {
items.removeAll()
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy MM dd"
for item in data {
if let lecture = item as? CalendarRow, let date = lecture.dtstart {
if let _ = items[dateformatter.string(from: date as Date)] {
items[dateformatter.string(from: date as Date)]?.append(lecture)
} else {
items[dateformatter.string(from: date as Date)] = [lecture]
}
}
}
let now = Date()
updateTitle(now)
}
}
extension CalendarViewController: ASWeekSelectorViewDelegate {
func weekSelector(_ weekSelector: ASWeekSelectorView!, didSelect date: Date!) {
updateTitle(date)
goToDay(date)
}
}
extension CalendarViewController: MGCDayPlannerViewDataSource, MGCDayPlannerViewDelegate {
func dayPlannerView(_ view: MGCDayPlannerView!, canCreateNewEventOf type: MGCEventType, at date: Date!) -> Bool {
return false
}
func dayPlannerView(_ view: MGCDayPlannerView!, numberOfEventsOf type: MGCEventType, at date: Date!) -> Int {
return lecturesOfDate(date).count
}
func dayPlannerView(_ view: MGCDayPlannerView!, canMoveEventOf type: MGCEventType, at index: UInt, date: Date!, to targetType: MGCEventType, date targetDate: Date!) -> Bool {
return false
}
func dayPlannerView(_ view: MGCDayPlannerView!, viewForEventOf type: MGCEventType, at index: UInt, date: Date!) -> MGCEventView! {
let eventView = MGCStandardEventView()
eventView.color = Constants.tumBlue
let item = lecturesOfDate(date)[(Int)(index)]
eventView.title = item.text
return eventView
}
func dayPlannerView(_ view: MGCDayPlannerView!, dateRangeForEventOf type: MGCEventType, at index: UInt, date: Date!) -> MGCDateRange! {
let item = lecturesOfDate(date)[(Int)(index)]
return MGCDateRange(start: item.dtstart! as Date!, end: item.dtend! as Date!)
}
func dayPlannerView(_ view: MGCDayPlannerView!, willDisplay date: Date!) {
if !scrolling {
weekSelector?.setSelectedDate(date, animated: true)
updateTitle(date)
} else if sameDay(date, b: (weekSelector?.selectedDate)!) {
scrolling = false
}
}
}
| gpl-3.0 | 922a6987843a948f05787430e0cf3e09 | 32.476923 | 178 | 0.624694 | 4.434783 | false | false | false | false |
DingSoung/CCExtension | Sources/UIKit/Array+UIImage.swift | 2 | 1256 | // Created by Songwen Ding on 2017/8/9.
// Copyright © 2017年 DingSoung. All rights reserved.
#if canImport(UIKit)
import UIKit
extension Array where Element: UIImage {
public func verticalImage(space: CGFloat, backgroundColor: UIColor?) -> UIImage? {
var size = CGSize.zero
for image in self {
let imgSize = image.size
size.height += imgSize.height
size.width = Swift.max(size.width, imgSize.width)
}
size.height += CGFloat(Swift.max(0, count - 1)) * space
var image: UIImage?
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
if let color = backgroundColor {
let path = UIBezierPath(rect: CGRect(origin: CGPoint.zero, size: size))
color.setFill()
path.fill()
}
var imgY: CGFloat = 0
for image in self {
image.draw(at: CGPoint(x: 0, y: imgY))
imgY += image.size.height
imgY += space
}
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
public var verticalImage: UIImage? {
return verticalImage(space: 0, backgroundColor: nil)
}
}
#endif
| mit | 28abd8444ff63f0450d35f34a0f5dcd5 | 31.973684 | 86 | 0.605746 | 4.507194 | false | false | false | false |
icaksama/Weathersama | WeathersamaDemo/WeathersamaDemo/Utilities/ExtentionCollections.swift | 1 | 3217 | //
// ExtentionCollections.swift
// WeathersamaDemo
//
// Created by Saiful I. Wicaksana on 10/4/17.
// Copyright © 2017 icaksama. All rights reserved.
//
import Foundation
import UIKit
extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
func imageFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloadedFrom(url: url, contentMode: mode)
}
}
extension UIApplication {
class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(base: selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(base: presented)
}
return base
}
}
extension UIView {
var parentViewController: UIViewController? {
var parentResponder: UIResponder? = self
while parentResponder != nil {
parentResponder = parentResponder!.next
if let viewController = parentResponder as? UIViewController {
return viewController
}
}
return nil
}
func clearConstraints() {
for subview in self.subviews {
subview.clearConstraints()
}
self.removeConstraints(self.constraints)
}
}
extension UINavigationController {
open override var shouldAutorotate: Bool {
return (visibleViewController?.shouldAutorotate)!
}
open override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return (visibleViewController?.supportedInterfaceOrientations)!
}
}
extension UIView {
func setX(x: CGFloat) {
var frame: CGRect = self.frame
frame.origin.x = x
self.frame = frame
}
func setY(y: CGFloat) {
var frame: CGRect = self.frame
frame.origin.y = y
self.frame = frame
}
func setZ(z: CGFloat) {
self.layer.zPosition = z
}
func setWidth(width: CGFloat) {
var frame: CGRect = self.frame
frame.size.width = width
self.frame = frame
}
func setHeight(height: CGFloat) {
var frame: CGRect = self.frame
frame.size.height = height
self.frame = frame
}
}
| mit | 7bbf4c7d32320ed1f344321cc919ba46 | 28.777778 | 133 | 0.612251 | 5.088608 | false | false | false | false |
wanghdnku/Whisper | Whisper/SendPostTableViewController.swift | 1 | 10854 | //
// SendPostTableViewController.swift
// Whisper
//
// Created by Hayden on 2016/10/16.
// Copyright © 2016年 unimelb. All rights reserved.
//
import UIKit
import Firebase
import KRProgressHUD
class SendPostTableViewController: UITableViewController {
var userArray = [User]()
var friendList = [String: Bool]()
var chatFunctions = ChatFunctions()
@IBOutlet var imageView: UIImageView!
var storageRef = FIRStorage.storage().reference()
var databaseRef = FIRDatabase.database().reference()
var passedImage: UIImage!
var passedTimeout: NSNumber!
override func viewDidLoad() {
super.viewDidLoad()
imageView.image = passedImage
fetchFriendList()
loadUsers()
}
func fetchFriendList() {
// 加载好友列表
let friendsRef = databaseRef.child("Friendships").child(FIRAuth.auth()!.currentUser!.uid)
friendsRef.observeSingleEvent(of: .value, with: { (snapshot) in
for friend in snapshot.children {
let snap = friend as! FIRDataSnapshot
self.friendList[snap.key] = true
//print(snap.key)
//print(friend)
}
}) { (error) in
// let alertView = SCLAlertView()
// alertView.showError("OOPS", subTitle: error.localizedDescription)
}
}
func loadUsers() {
let userRef = databaseRef.child("users")
userRef.observeSingleEvent(of: .value, with: { (snapshot) in
var allUsers = [User]()
for user in snapshot.children {
let newUser = User(snapshot: user as! FIRDataSnapshot)
if newUser.uid != FIRAuth.auth()!.currentUser!.uid {
if self.friendList[newUser.uid] == true {
allUsers.append(newUser)
}
}
}
self.userArray = allUsers.sorted(by: { (user1, user2) -> Bool in
user1.username < user2.username
})
self.tableView.reloadData()
}) { (error) in
// let alertView = SCLAlertView()
// alertView.showError("OOPS", subTitle: error.localizedDescription)
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return userArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath)
// Configure the cell...
cell.textLabel?.text = userArray[indexPath.row].username
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
KRProgressHUD.show()
let user = userArray[indexPath.row]
let userId1 = FIRAuth.auth()!.currentUser!.uid
let userId2 = user.uid
var chatRoomId = ""
let comparison = userId1.compare(userId2!).rawValue
if comparison < 0 {
chatRoomId = userId1.appending(userId2!)
} else {
chatRoomId = userId2!.appending(userId1)
}
let currentUser = User(username: FIRAuth.auth()!.currentUser!.displayName!, userId: FIRAuth.auth()!.currentUser!.uid, photoUrl: "\(FIRAuth.auth()!.currentUser!.photoURL!)")
chatFunctions.startChat(user1: currentUser, user2: userArray[indexPath.row])
if let image = passedImage {
let imagePath = "messageWithMedia\(chatRoomId + NSUUID().uuidString)/photo.jpg"
let imageRef = storageRef.child(imagePath)
let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpeg"
let imageData = UIImageJPEGRepresentation(image, 0.8)!
// 将图片数据存放进storage并且返回URL,把URL存Realtime database.
imageRef.put(imageData, metadata: metadata, completion: { (newMetaData, error) in
if error == nil {
let message = Message(text: "", senderId: currentUser.uid, username: currentUser.username, mediaType: "PHOTO", mediaUrl: "\(newMetaData!.downloadURL()!)")
let messageRef = self.databaseRef.child("ChatRooms").child(chatRoomId).child("Messages").childByAutoId()
// 将media message存入数据库
messageRef.setValue(message.toAnyObject(), withCompletionBlock: { (error, ref) in
if error == nil {
// 更新last message
let lastMessageRef = self.databaseRef.child("ChatRooms").child(chatRoomId).child("lastMessage")
let date = Date(timeIntervalSince1970: Double(NSDate().timeIntervalSince1970))
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "'Last Message: 'MM/dd hh:mm a"
let dateString = dateFormatter.string(from: date)
lastMessageRef.setValue(dateString, withCompletionBlock: { (error, ref) in
if error == nil {
// Send a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateDiscussion"), object: nil)
} else {
let alertView = SCLAlertView()
alertView.showError("Last Message Error", subTitle: error!.localizedDescription)
}
})
// 更新last time
let lastTimeRef = self.databaseRef.child("ChatRooms").child(chatRoomId).child("date")
lastTimeRef.setValue(NSDate().timeIntervalSince1970, withCompletionBlock: { (error, ref) in
if error == nil {
// Nothing
} else {
let alertView = SCLAlertView()
alertView.showError("Last Message Error", subTitle: error!.localizedDescription)
}
})
// let alertView = SCLAlertView()
// alertView.showSuccess("Success", subTitle: "Your photo has been sent to \(user.username) successfully!")
KRProgressHUD.showSuccess()
KRProgressHUD.dismiss()
self.dismiss(animated: true, completion: nil)
} else {
let alertView = SCLAlertView()
alertView.showError("Send Message Error", subTitle: error!.localizedDescription)
}
})
} else {
let alertView = SCLAlertView()
alertView.showError("Upload Image Error", subTitle: error!.localizedDescription)
}
})
}
}
@IBAction func sendtoMemory(_ sender: AnyObject) {
postImage(isPrivate: true)
}
@IBAction func sendToStory(_ sender: AnyObject) {
postImage(isPrivate: false)
}
func postImage(isPrivate: Bool) {
KRProgressHUD.show()
let user = FIRAuth.auth()!.currentUser!
let userId = user.uid
let username = user.displayName!
let imagePath = "Posts/post-\(userId + NSUUID().uuidString).jpg"
let imageRef = storageRef.child(imagePath)
let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpeg"
let imageData = UIImageJPEGRepresentation(passedImage, 0.8)!
// 将图片数据存放进storage并且返回URL,把URL存Realtime database.
imageRef.put(imageData, metadata: metadata, completion: { (newMetaData, error) in
if error == nil {
let post = Post(senderId: userId, username: username, timastamp: NSNumber(value: Int(Date().timeIntervalSince1970)), imageUrl: "\(newMetaData!.downloadURL()!)", isPrivate: isPrivate, timeout: self.passedTimeout)
let postRef = self.databaseRef.child("Posts").child(userId).childByAutoId()
postRef.setValue(post.toAnyObject(), withCompletionBlock: { (error, ref) in
if let error = error {
let alertView = SCLAlertView()
alertView.showError("Send Post Error", subTitle: error.localizedDescription)
} else {
DispatchQueue.main.async {
let alertView = SCLAlertView()
if isPrivate {
alertView.showSuccess("Success", subTitle: "Your post has been saved in memory!")
} else {
alertView.showSuccess("Success", subTitle: "Your post has been sent to story!")
}
}
// Back to the camera view.
self.dismiss(animated: true, completion: nil)
//self.performSegue(withIdentifier: "backToCam", sender: nil)
}
})
} else {
let alertView = SCLAlertView()
alertView.showError("Upload Image Error", subTitle: error!.localizedDescription)
}
})
KRProgressHUD.dismiss()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 4af81ff59ae566f84bf2d7a8c90d63d1 | 39.908745 | 227 | 0.532206 | 5.732019 | false | false | false | false |
hooman/swift | stdlib/public/Concurrency/AsyncFlatMapSequence.swift | 3 | 5638 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@available(SwiftStdlib 5.5, *)
extension AsyncSequence {
/// Creates an asynchronous sequence that concatenates the results of calling
/// the given transformation with each element of this sequence.
///
/// Use this method to receive a single-level asynchronous sequence when your
/// transformation produces an asynchronous sequence for each element.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `5`. The transforming closure takes the received `Int`
/// and returns a new `Counter` that counts that high. For example, when the
/// transform receives `3` from the base sequence, it creates a new `Counter`
/// that produces the values `1`, `2`, and `3`. The `flatMap(_:)` method
/// "flattens" the resulting sequence-of-sequences into a single
/// `AsyncSequence`.
///
/// let stream = Counter(howHigh: 5)
/// .flatMap { Counter(howHigh: $0) }
/// for await number in stream {
/// print("\(number)", terminator: " ")
/// }
/// // Prints: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
///
/// - Parameter transform: A mapping closure. `transform` accepts an element
/// of this sequence as its parameter and returns an `AsyncSequence`.
/// - Returns: A single, flattened asynchronous sequence that contains all
/// elements in all the asychronous sequences produced by `transform`.
@inlinable
public __consuming func flatMap<SegmentOfResult: AsyncSequence>(
_ transform: @escaping (Element) async -> SegmentOfResult
) -> AsyncFlatMapSequence<Self, SegmentOfResult> {
return AsyncFlatMapSequence(self, transform: transform)
}
}
/// An asynchronous sequence that concatenates the results of calling a given
/// transformation with each element of this sequence.
@available(SwiftStdlib 5.5, *)
@frozen
public struct AsyncFlatMapSequence<Base: AsyncSequence, SegmentOfResult: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let transform: (Base.Element) async -> SegmentOfResult
@inlinable
init(
_ base: Base,
transform: @escaping (Base.Element) async -> SegmentOfResult
) {
self.base = base
self.transform = transform
}
}
@available(SwiftStdlib 5.5, *)
extension AsyncFlatMapSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The flat map sequence produces the type of element in the asynchronous
/// sequence produced by the `transform` closure.
public typealias Element = SegmentOfResult.Element
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the flat map sequence.
@frozen
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
let transform: (Base.Element) async -> SegmentOfResult
@usableFromInline
var currentIterator: SegmentOfResult.AsyncIterator?
@usableFromInline
var finished = false
@inlinable
init(
_ baseIterator: Base.AsyncIterator,
transform: @escaping (Base.Element) async -> SegmentOfResult
) {
self.baseIterator = baseIterator
self.transform = transform
}
/// Produces the next element in the flat map sequence.
///
/// This iterator calls `next()` on its base iterator; if this call returns
/// `nil`, `next()` returns `nil`. Otherwise, `next()` calls the
/// transforming closure on the received element, takes the resulting
/// asynchronous sequence, and creates an asynchronous iterator from it.
/// `next()` then consumes values from this iterator until it terminates.
/// At this point, `next()` is ready to receive the next value from the base
/// sequence.
@inlinable
public mutating func next() async rethrows -> SegmentOfResult.Element? {
while !finished {
if var iterator = currentIterator {
do {
guard let element = try await iterator.next() else {
currentIterator = nil
continue
}
// restore the iterator since we just mutated it with next
currentIterator = iterator
return element
} catch {
finished = true
throw error
}
} else {
guard let item = try await baseIterator.next() else {
finished = true
return nil
}
do {
let segment = await transform(item)
var iterator = segment.makeAsyncIterator()
guard let element = try await iterator.next() else {
currentIterator = nil
continue
}
currentIterator = iterator
return element
} catch {
finished = true
throw error
}
}
}
return nil
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), transform: transform)
}
}
| apache-2.0 | eda44e6919f41211e82af63cde6c846c | 34.683544 | 89 | 0.641007 | 5.070144 | false | false | false | false |
hooman/swift | test/Concurrency/Runtime/async_task_locals_prevent_illegal_use.swift | 2 | 1516 | // RUN: %target-fail-simple-swift( -Xfrontend -disable-availability-checking -parse-as-library %import-libdispatch) 2>&1 | %FileCheck %s
//
// // TODO: could not figure out how to use 'not --crash' it never is used with target-run-simple-swift
// This test is intended to *crash*, so we're using target-fail-simple-swift
// which expects the exit code of the program to be non-zero;
// We then check stderr for the expected error message using filecheck as usual.
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
@available(SwiftStdlib 5.5, *)
enum TL {
@TaskLocal
static var number: Int = 2
}
// ==== ------------------------------------------------------------------------
@available(SwiftStdlib 5.5, *)
func bindAroundGroupSpawn() async {
await TL.$number.withValue(1111) { // ok
await withTaskGroup(of: Int.self) { group in
// CHECK: error: task-local: detected illegal task-local value binding at {{.*}}illegal_use.swift:[[# @LINE + 1]]
TL.$number.withValue(2222) { // bad!
print("Survived, inside withValue!") // CHECK-NOT: Survived, inside withValue!
group.spawn {
0 // don't actually perform the read, it would be unsafe.
}
}
print("Survived the illegal call!") // CHECK-NOT: Survived the illegal call!
}
}
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
await bindAroundGroupSpawn()
}
}
| apache-2.0 | 6db411b79fe70e7dcbc148eff9b7d17b | 33.454545 | 136 | 0.643799 | 3.857506 | false | false | false | false |
TruckMuncher/TruckMuncher-iOS | TruckMuncher/TableViewCells/TruckCollectionViewCell.swift | 1 | 1373 | //
// TruckCollectionViewCell.swift
// TruckMuncher
//
// Created by Andrew Moore on 4/17/15.
// Copyright (c) 2015 TruckMuncher. All rights reserved.
//
import UIKit
class TruckCollectionViewCell: UICollectionViewCell {
@IBOutlet var logoImageView: UIImageView!
@IBOutlet var truckNameField: UILabel!
@IBOutlet var isServingIndicator: UIView!
override func awakeFromNib() {
super.awakeFromNib()
}
func updateCellWithTruckInfo(truck: RTruck, isServing: Bool){
layoutIfNeeded()
getImageForTruck(truck)
truckNameField.text = truck.name
isServingIndicator.layer.cornerRadius = isServingIndicator.frame.size.width/2
isServingIndicator.backgroundColor = isServing == true ? UIColor(rgba: "#0f9d58") : UIColor.lightGrayColor()
}
func getImageForTruck(truck:RTruck) {
var imgURL: NSURL? = NSURL(string: truck.imageUrl)
logoImageView.layer.cornerRadius = logoImageView.frame.size.height / 2
logoImageView.layer.masksToBounds = true
logoImageView.layer.borderWidth = 0
self.logoImageView.sd_setImageWithURL(imgURL, placeholderImage: UIImage(named: "noImageAvailable"), completed: { (image, error, type, url) -> Void in
if error == nil {
self.reloadInputViews()
}
})
}
}
| gpl-2.0 | 6294033bacd1eb2aa188f4a6499c6362 | 31.690476 | 157 | 0.667152 | 4.607383 | false | false | false | false |
amcnary/cs147_instagator | instagator-prototype/instagator-prototype/Event.swift | 1 | 593 | //
// Event.swift
// instagator-prototype
//
// Created by Tanner Gilligan on 11/17/15.
// Copyright © 2015 ThePenguins. All rights reserved.
//
import Foundation
class Event: Activity {
var Name: String
var Description: String
var Cost: Float?
var StartDate: NSDate
var EndDate: NSDate
init(name: String, description: String = "", cost: Float? = nil, startDate: NSDate, endDate: NSDate) {
self.Name = name
self.Description = description
self.Cost = cost
self.StartDate = startDate
self.EndDate = endDate
}
} | apache-2.0 | 7c7fcbe7027030772f9701e93b00bfc1 | 21.807692 | 106 | 0.633446 | 3.946667 | false | false | false | false |
vermont42/Conjugar | Conjugar/StubCommunGetter.swift | 1 | 7776 | //
// StubCommunGetter.swift
// Conjugar
//
// Created by Joshua Adams on 12/14/20.
// Copyright © 2020 Josh Adams. All rights reserved.
//
import MessageUI
import UIKit
struct StubCommunGetter: CommunGetter {
func getCommunication(completion: @escaping (Commun) -> Void) {
let delay: TimeInterval = 2.0
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: {
// if let sendEmailClosure = Emailer.shared.sendEmailClosure {
// let commun = email(sendEmailClosure: sendEmailClosure)
// completion(commun, communVersion)
// }
completion(newVersion)
})
}
func email(sendEmailClosure: @escaping () -> ()) -> Commun {
Commun(
title: ["en": "Request for Feedback", "es": "Pedido"],
image: UIImage(named: "Dancer") ?? UIImage(),
imageLabel: ["en": "female flamenco dancer", "es": "bailaora de flamenco"],
content: [
"en": "The developer of Conjugar, Josh Adams, welcomes feedback on the app and suggestions for new features. To email him, tap the Email button below.",
"es": "El desarrollador de Conjugar, Josh Adams, agradece los comentarios sobre la aplicación y las sugerencias de nuevas características. Para enviarle un correo electrónico, toca el botón Enviar de abajo."
],
type: .email(actionTitle: ["en": "Email", "es": "Enviar"], cancelTitle: ["en": "No Thanks", "es": "No, Gracias"], action: sendEmailClosure),
identifier: 0
)
}
let information = Commun(
title: ["en": "History", "es": "Historia"],
image: UIImage(named: "Dancer") ?? UIImage(),
imageLabel: ["en": "female flamenco dancer", "es": "bailaora de flamenco"],
content: [
"en": """
Development of Conjugar began in March, 2017. But there is a backstory.
In 1994, while he was attending Dartmouth College, the future developer of Conjugar, Josh Adams, took a class called Intro to Computing. For his culminating project, Mr. Adams created a Hypercard "stack" (app) called Le Conjuguateur. This app was like Conjugar but for French verbs. The app won Dartmouth College's Kemeney Computing Prize (Honorable Mention) and inspired development of Conjugar twenty-three years later.
John Kemeney, inventor of the BASIC programming language, is the namesake of the Kemeney Computing Prize. Ironically, BASIC was the language that Mr. Adams used to teach himself to program at age nine.
""",
"es": """
El desarrollo de Conjugar comenzó en marzo de 2017. Pero hay una historia de fondo.
En 1994, mientras asistía a Dartmouth College, el eventual desarrollador de Conjugar, Josh Adams, tomó una clase llamada Introducción a la Computación. Para su proyecto culminante, el Sr. Adams creó una "stack" (aplicación) de Hypercard llamada Le Conjuguateur. Esta aplicación era como Conjugar pero para los verbos franceses. La aplicación ganó el Premio de Informática Kemeney de Dartmouth College (Mención de Honor) e inspiró el desarrollo de Conjugar veintitrés años después.
John Kemeney, inventor del lenguaje de programación BASIC, es el homónimo del Premio de Informática Kemeney. Irónicamente, BASIC era el lenguaje que el Sr. Adams usaba para aprender a programar a los nueve años.
"""
],
type: .information(okayTitle: ["en": "Awesome", "es": "Asombrosa"]),
identifier: 1
)
var newVersion: Commun {
let alreadyUpdated: Bool
// Change to higher than current app version to screen with action.
let appVersionFromCloudKit = 2.5
if
let appVersionString = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String,
let appVersion = Double(appVersionString),
appVersion < appVersionFromCloudKit
{
alreadyUpdated = false
} else {
alreadyUpdated = true
}
guard let openUrlClosure = openUrlClosure(urlString: "https://itunes.apple.com/\(Current.locale.regionCode)/app/conjugar/id1236500467") else {
fatalError("Could not initialize URL.")
}
return Commun(
title: ["en": "New Version", "es": "Nueva Versión"],
image: UIImage(named: "Dancer") ?? UIImage(),
imageLabel: ["en": "female flamenco dancer", "es": "bailaora de flamenco"],
content: [
"en": "Ordinarily, the only way for developers of iOS apps to communicate with users in an ad-hoc manner is via App Store release notes for a new version of the app. This manner of communication has two shortcomings. First, the communication is tied to a new release. Without a new release, the developer can't communicate. Second, many users, this developer included, don't regularly read release notes. Version 2.5 of Conjugar has an exciting new feature: the developer can communicate directly with users in Conjugar itself, without releasing a new version. He is doing that right now.",
"es": "Por lo general, la única forma en que los desarrolladores de aplicaciones iOS pueden comunicarse con los usuarios de manera ad-hoc es a través de las notas de la versión de la App Store para una nueva versión de la aplicación. Esta forma de comunicación tiene dos defectos. Primero, la comunicación está vinculada a una nueva versión. Sin una nueva versión, el desarrollador no puede comunicarse. En segundo lugar, muchos usuarios, incluido este desarrollador, no leen regularmente las notas de la versión. La versión 2.5 de Conjugar tiene una nueva característica interesante: el desarrollador puede comunicarse directamente con los usuarios en Conjugar mismo, sin lanzar una nueva versión. Él está haciendo eso ahora mismo."
],
type: .newVersion(okayTitle: ["en": "Cool, I Have It", "es": "Genial, Lo Tengo"], actionTitle: ["en": "Update", "es": "Actualizar"], cancelTitle: ["en": "No Thanks", "es": "No, Gracias"], action: openUrlClosure, alreadyUpdated: alreadyUpdated),
identifier: 2
)
}
var website: Commun {
guard let openUrlClosure = openUrlClosure(urlString: "https://racecondition.software/blog/programmatic-layout/") else {
fatalError("Could not initialize URL.")
}
return Commun(
title: ["en": "Technical Underpinnings", "es": "Fundamentos Técnicos"],
image: UIImage(named: "Dancer") ?? UIImage(),
imageLabel: ["en": "female flamenco dancer", "es": "bailaora de flamenco"],
content: [
"en": "In 2017, there were two approaches to creating user interfaces (UIs) in iOS apps. Developers could use a visual editor called Interface Builder (IB) or create UIs entirely in code, an approach called programmatic layout (PL). At that time, iOS developer Josh Adams was more comfortable with IB, but he had used PL while working on an app for San Francisco Airport taxi drivers. He created Conjugar using PL in order to increase his comfort with that technique. He then wrote a tutorial about converting an app from IB to PL. If this subject interests you, tap the Read button below.",
"es": "En 2017, hubo dos enfoques para crear las interfaces de usuario (IUes) en aplicaciones de iOS. Los desarrolladores pueden usar un editor visual llamado Interface Builder (IB) o crear las IUes completamente en código, un enfoque llamado diseño programático (DP). En ese momento, el desarrollador de iOS Josh Adams se sentía más cómodo con IB, pero había usado DP mientras trabajaba en una aplicación para las taxistas del Aeropuerto de San Francisco. Creó Conjugar usando DP para aumentar su comodidad con esa técnica. Luego escribió un tutorial sobre cómo convertir una aplicación de IB a DP. Si este tema le interesa, toca el botón Leer a continuación."
],
type: .website(actionTitle: ["en": "Read", "es": "Leer"], cancelTitle: ["en": "No Thanks", "es": "No, Gracias"], action: openUrlClosure),
identifier: 3
)
}
}
| agpl-3.0 | 5b52e5f0fefdd8a208353e2d81ae5541 | 69.798165 | 741 | 0.722301 | 3.652153 | false | false | false | false |
LoganWright/PolymerSwift | PolymerSwift/Source/Polymer.swift | 1 | 5209 | //
// PolymerSwift.swift
// PolymerSwift
//
// Created by Logan Wright on 5/29/15.
// Copyright (c) 2015 LowriDevs. All rights reserved.
//
import Foundation
import Polymer
import Genome
import AFNetworking
// MARK: TypeAliases
public typealias ResponseTransformer = (response: AnyObject?) -> GenomeMappableRawType?
public typealias SlugValidityCheck = (slugValue: AnyObject?, slugPath: String?) -> Bool
public typealias SlugValueForPath = (slug: AnyObject?, slugPath: String?) -> AnyObject?
// MARK: Response
public enum Response<T : GenomeObject> {
case Result([T])
case Error(NSError)
}
// MARK: Operation Type
public enum OperationType {
case Get
case Post
case Put
case Patch
case Delete
}
// MARK: Endpoint Descriptor
public class EndpointDescriptor {
public final private(set) var currentOperation: OperationType = .Get
// MARK: Required Properties
public var baseUrl: String { fatalError("Must Override") }
public var endpointUrl: String { fatalError("Must Override") }
// MARK: Optional Properties
public var responseKeyPath: String? { return nil }
public var acceptableContentTypes: Set<String>? { return nil }
public var headerFields: [String : AnyObject]? { return nil }
public var requestSerializer: AFHTTPRequestSerializer? { return nil }
public var responseSerializer: AFHTTPResponseSerializer? { return nil }
public var shouldAppendHeaderToResponse: Bool { return false }
// MARK: Response Transformer
public var responseTransformer: ResponseTransformer? { return nil }
// MARK: Slug Interaction
public var slugValidityCheck: SlugValidityCheck? { return nil }
public var slugValueForPath: SlugValueForPath? { return nil }
// MARK: Initialization
required public init() {}
}
// MARK: Endpoint
public class Endpoint<T,U where T : EndpointDescriptor, U : GenomeObject> {
// MARK: TypeAliases
public typealias ResponseBlock = (response: Response<U>) -> Void
private typealias ObjCResponseBlock = (result: AnyObject?, error: NSError?) -> Void
// MARK: Private Properties
final let descriptor = T()
final let slug: AnyObject?
final let parameters: PLYParameterEncodableType?
private final lazy var ep: BackingEndpoint! = BackingEndpoint(endpoint: self)
// MARK: Initialization
public convenience init() {
self.init(slug: nil, parameters: nil)
}
public convenience init(slug: AnyObject?) {
self.init(slug: slug, parameters: nil)
}
public convenience init(parameters: PLYParameterEncodableType?) {
self.init(slug: nil, parameters: parameters)
}
required public init(slug: AnyObject?, parameters: PLYParameterEncodableType?) {
self.slug = slug
self.parameters = parameters
}
// MARK: Networking
public func get(responseBlock: ResponseBlock) {
descriptor.currentOperation = .Get
let wrappedCompletion = objcResponseBlockForResponseBlock(responseBlock)
ep.getWithCompletion(wrappedCompletion)
}
public func post(responseBlock: ResponseBlock) {
descriptor.currentOperation = .Post
let wrappedCompletion = objcResponseBlockForResponseBlock(responseBlock)
ep.postWithCompletion(wrappedCompletion)
}
public func put(responseBlock: ResponseBlock) {
descriptor.currentOperation = .Put
let wrappedCompletion = objcResponseBlockForResponseBlock(responseBlock)
ep.putWithCompletion(wrappedCompletion)
}
public func patch(responseBlock: ResponseBlock) {
descriptor.currentOperation = .Patch
let wrappedCompletion = objcResponseBlockForResponseBlock(responseBlock)
ep.putWithCompletion(wrappedCompletion)
}
public func delete(responseBlock: ResponseBlock) {
descriptor.currentOperation = .Delete
let wrappedCompletion = objcResponseBlockForResponseBlock(responseBlock)
ep.deleteWithCompletion(wrappedCompletion)
}
/*!
Used to map the objc response to the swift response
:param: completion the completion passed by the user to call with the Result
*/
private func objcResponseBlockForResponseBlock(responseBlock: ResponseBlock) -> ObjCResponseBlock {
return { (result, error) -> Void in
let response: Response<U>
if let _result = result as? [U] {
response = .Result(_result)
} else if let _result = result as? U {
response = .Result([_result])
} else if let _error = error {
response = .Error(_error)
} else {
let err = NSError(message: "No Result: \(result) or Error: \(error). Unknown.")
response = .Error(err)
}
responseBlock(response: response)
}
}
}
// MARK: Error
private extension NSError {
convenience init(code: Int = 1, message: String) {
self.init(domain: "com.polymer.errordomain", code: 1, userInfo: [NSLocalizedDescriptionKey : message])
}
}
| mit | dc8196cc731dcf160b985773cec66b36 | 29.822485 | 110 | 0.66865 | 4.697024 | false | false | false | false |
mshhmzh/firefox-ios | Storage/SQL/BrowserDB.swift | 2 | 17671 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import XCGLogger
import Deferred
import Shared
import Deferred
public let NotificationDatabaseWasRecreated = "NotificationDatabaseWasRecreated"
private let log = Logger.syncLogger
public typealias Args = [AnyObject?]
protocol Changeable {
func run(sql: String, withArgs args: Args?) -> Success
func run(commands: [String]) -> Success
func run(commands: [(sql: String, args: Args?)]) -> Success
}
protocol Queryable {
func runQuery<T>(sql: String, args: Args?, factory: SDRow -> T) -> Deferred<Maybe<Cursor<T>>>
}
// Version 1 - Basic history table.
// Version 2 - Added a visits table, refactored the history table to be a GenericTable.
// Version 3 - Added a favicons table.
// Version 4 - Added a readinglist table.
// Version 5 - Added the clients and the tabs tables.
// Version 6 - Visit timestamps are now microseconds.
// Version 7 - Eliminate most tables. See BrowserTable instead.
public class BrowserDB {
private let db: SwiftData
// XXX: Increasing this should blow away old history, since we currently don't support any upgrades.
private let Version: Int = 7
private let files: FileAccessor
private let filename: String
private let secretKey: String?
private let schemaTable: SchemaTable
private var initialized = [String]()
// SQLITE_MAX_VARIABLE_NUMBER = 999 by default. This controls how many ?s can
// appear in a query string.
public static let MaxVariableNumber = 999
public init(filename: String, secretKey: String? = nil, files: FileAccessor) {
log.debug("Initializing BrowserDB: \(filename).")
self.files = files
self.filename = filename
self.schemaTable = SchemaTable()
self.secretKey = secretKey
let file = ((try! files.getAndEnsureDirectory()) as NSString).stringByAppendingPathComponent(filename)
self.db = SwiftData(filename: file, key: secretKey, prevKey: nil)
if AppConstants.BuildChannel == .Developer && secretKey != nil {
log.debug("Creating db: \(file) with secret = \(secretKey)")
}
// Create or update will also delete and create the database if our key was incorrect.
self.createOrUpdate(self.schemaTable)
}
// Creates a table and writes its table info into the table-table database.
private func createTable(conn: SQLiteDBConnection, table: SectionCreator) -> TableResult {
log.debug("Try create \(table.name) version \(table.version)")
if !table.create(conn) {
// If creating failed, we'll bail without storing the table info
log.debug("Creation failed.")
return .Failed
}
var err: NSError? = nil
return schemaTable.insert(conn, item: table, err: &err) > -1 ? .Created : .Failed
}
// Updates a table and writes its table into the table-table database.
// Exposed internally for testing.
func updateTable(conn: SQLiteDBConnection, table: SectionUpdater) -> TableResult {
log.debug("Trying update \(table.name) version \(table.version)")
var from = 0
// Try to find the stored version of the table
let cursor = schemaTable.query(conn, options: QueryOptions(filter: table.name))
if cursor.count > 0 {
if let info = cursor[0] as? TableInfoWrapper {
from = info.version
}
}
// If the versions match, no need to update
if from == table.version {
return .Exists
}
if !table.updateTable(conn, from: from) {
// If the update failed, we'll bail without writing the change to the table-table.
log.debug("Updating failed.")
return .Failed
}
var err: NSError? = nil
// Yes, we UPDATE OR INSERT… because we might be transferring ownership of a database table
// to a different Table. It'll trigger exists, and thus take the update path, but we won't
// necessarily have an existing schema entry -- i.e., we'll be updating from 0.
if schemaTable.update(conn, item: table, err: &err) > 0 ||
schemaTable.insert(conn, item: table, err: &err) > 0 {
return .Updated
}
return .Failed
}
// Utility for table classes. They should call this when they're initialized to force
// creation of the table in the database.
func createOrUpdate(tables: Table...) -> Bool {
var success = true
let doCreate = { (table: Table, connection: SQLiteDBConnection) -> () in
switch self.createTable(connection, table: table) {
case .Created:
success = true
return
case .Exists:
log.debug("Table already exists.")
success = true
return
default:
success = false
}
}
if let _ = self.db.transaction({ connection -> Bool in
let thread = NSThread.currentThread().description
// If the table doesn't exist, we'll create it.
for table in tables {
log.debug("Create or update \(table.name) version \(table.version) on \(thread).")
if !table.exists(connection) {
log.debug("Doesn't exist. Creating table \(table.name).")
doCreate(table, connection)
} else {
// Otherwise, we'll update it
switch self.updateTable(connection, table: table) {
case .Updated:
log.debug("Updated table \(table.name).")
success = true
break
case .Exists:
log.debug("Table \(table.name) already exists.")
success = true
break
default:
log.error("Update failed for \(table.name). Dropping and recreating.")
table.drop(connection)
var err: NSError? = nil
self.schemaTable.delete(connection, item: table, err: &err)
doCreate(table, connection)
}
}
if !success {
log.warning("Failed to configure multiple tables. Aborting.")
return false
}
}
return success
}) {
// Err getting a transaction
success = false
}
// If we failed, move the file and try again. This will probably break things that are already
// attached and expecting a working DB, but at least we should be able to restart.
var notify: NSNotification? = nil
if !success {
log.debug("Couldn't create or update \(tables.map { $0.name }).")
log.debug("Attempting to move \(self.filename) to another location.")
// Make sure that we don't still have open the files that we want to move!
// Note that we use sqlite3_close_v2, which might actually _not_ close the
// database file yet. For this reason we move the -shm and -wal files, too.
db.forceClose()
// Note that a backup file might already exist! We append a counter to avoid this.
var bakCounter = 0
var bak: String
repeat {
bakCounter += 1
bak = "\(self.filename).bak.\(bakCounter)"
} while self.files.exists(bak)
do {
try self.files.move(self.filename, toRelativePath: bak)
let shm = self.filename + "-shm"
let wal = self.filename + "-wal"
log.debug("Moving \(shm) and \(wal)…")
if self.files.exists(shm) {
log.debug("\(shm) exists.")
try self.files.move(shm, toRelativePath: bak + "-shm")
}
if self.files.exists(wal) {
log.debug("\(wal) exists.")
try self.files.move(wal, toRelativePath: bak + "-wal")
}
success = true
// Notify the world that we moved the database. This allows us to
// reset sync and start over in the case of corruption.
let notification = NotificationDatabaseWasRecreated
notify = NSNotification(name: notification, object: self.filename)
} catch _ {
success = false
}
assert(success)
// Do this after the relevant tables have been created.
defer {
if let notify = notify {
NSNotificationCenter.defaultCenter().postNotification(notify)
}
}
if let _ = db.transaction({ connection -> Bool in
for table in tables {
doCreate(table, connection)
if !success {
return false
}
}
return success
}) {
success = false;
}
}
return success
}
typealias IntCallback = (connection: SQLiteDBConnection, inout err: NSError?) -> Int
func withConnection<T>(flags flags: SwiftData.Flags, inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> T) -> T {
var res: T!
err = db.withConnection(flags) { connection in
// This should never occur. Make it fail hard in debug builds.
assert(!(connection is FailedSQLiteDBConnection))
var err: NSError? = nil
res = callback(connection: connection, err: &err)
return err
}
return res
}
func withWritableConnection<T>(inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> T) -> T {
return withConnection(flags: SwiftData.Flags.ReadWrite, err: &err, callback: callback)
}
func withReadableConnection<T>(inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> Cursor<T>) -> Cursor<T> {
return withConnection(flags: SwiftData.Flags.ReadOnly, err: &err, callback: callback)
}
func transaction(inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> Bool) -> NSError? {
return self.transaction(synchronous: true, err: &err, callback: callback)
}
func transaction(synchronous synchronous: Bool=true, inout err: NSError?, callback: (connection: SQLiteDBConnection, inout err: NSError?) -> Bool) -> NSError? {
return db.transaction(synchronous: synchronous) { connection in
var err: NSError? = nil
return callback(connection: connection, err: &err)
}
}
}
extension BrowserDB {
func vacuum() {
log.debug("Vacuuming a BrowserDB.")
db.withConnection(SwiftData.Flags.ReadWriteCreate, synchronous: true) { connection in
return connection.vacuum()
}
}
func checkpoint() {
log.debug("Checkpointing a BrowserDB.")
db.transaction(synchronous: true) { connection in
connection.checkpoint()
return true
}
}
}
extension BrowserDB {
public class func varlist(count: Int) -> String {
return "(" + Array(count: count, repeatedValue: "?").joinWithSeparator(", ") + ")"
}
enum InsertOperation: String {
case Insert = "INSERT"
case Replace = "REPLACE"
case InsertOrIgnore = "INSERT OR IGNORE"
case InsertOrReplace = "INSERT OR REPLACE"
case InsertOrRollback = "INSERT OR ROLLBACK"
case InsertOrAbort = "INSERT OR ABORT"
case InsertOrFail = "INSERT OR FAIL"
}
/**
* Insert multiple sets of values into the given table.
*
* Assumptions:
* 1. The table exists and contains the provided columns.
* 2. Every item in `values` is the same length.
* 3. That length is the same as the length of `columns`.
* 4. Every value in each element of `values` is non-nil.
*
* If there are too many items to insert, multiple individual queries will run
* in sequence.
*
* A failure anywhere in the sequence will cause immediate return of failure, but
* will not roll back — use a transaction if you need one.
*/
func bulkInsert(table: String, op: InsertOperation, columns: [String], values: [Args]) -> Success {
// Note that there's a limit to how many ?s can be in a single query!
// So here we execute 999 / (columns * rows) insertions per query.
// Note that we can't use variables for the column names, so those don't affect the count.
if values.isEmpty {
log.debug("No values to insert.")
return succeed()
}
let variablesPerRow = columns.count
// Sanity check.
assert(values[0].count == variablesPerRow)
let cols = columns.joinWithSeparator(", ")
let queryStart = "\(op.rawValue) INTO \(table) (\(cols)) VALUES "
let varString = BrowserDB.varlist(variablesPerRow)
let insertChunk: [Args] -> Success = { vals -> Success in
let valuesString = Array(count: vals.count, repeatedValue: varString).joinWithSeparator(", ")
let args: Args = vals.flatMap { $0 }
return self.run(queryStart + valuesString, withArgs: args)
}
let rowCount = values.count
if (variablesPerRow * rowCount) < BrowserDB.MaxVariableNumber {
return insertChunk(values)
}
log.debug("Splitting bulk insert across multiple runs. I hope you started a transaction!")
let rowsPerInsert = (999 / variablesPerRow)
let chunks = chunk(values, by: rowsPerInsert)
log.debug("Inserting in \(chunks.count) chunks.")
// There's no real reason why we can't pass the ArraySlice here, except that I don't
// want to keep fighting Swift.
return walk(chunks, f: { insertChunk(Array($0)) })
}
func runWithConnection<T>(block: (connection: SQLiteDBConnection, inout err: NSError?) -> T) -> Deferred<Maybe<T>> {
return DeferredDBOperation(db: self.db, block: block).start()
}
func write(sql: String, withArgs args: Args? = nil) -> Deferred<Maybe<Int>> {
return self.runWithConnection() { (connection, err) -> Int in
err = connection.executeChange(sql, withArgs: args)
if err == nil {
let modified = connection.numberOfRowsModified
log.debug("Modified rows: \(modified).")
return modified
}
return 0
}
}
public func forceClose() {
db.forceClose()
}
}
extension BrowserDB: Changeable {
func run(sql: String, withArgs args: Args? = nil) -> Success {
return run([(sql, args)])
}
func run(commands: [String]) -> Success {
return self.run(commands.map { (sql: $0, args: nil) })
}
/**
* Runs an array of SQL commands. Note: These will all run in order in a transaction and will block
* the caller's thread until they've finished. If any of them fail the operation will abort (no more
* commands will be run) and the transaction will roll back, returning a DatabaseError.
*/
func run(commands: [(sql: String, args: Args?)]) -> Success {
if commands.isEmpty {
return succeed()
}
var err: NSError? = nil
let errorResult = self.transaction(&err) { (conn, err) -> Bool in
for (sql, args) in commands {
err = conn.executeChange(sql, withArgs: args)
if let err = err {
log.warning("SQL operation failed: \(err.localizedDescription)")
return false
}
}
return true
}
if let err = err ?? errorResult {
return deferMaybe(DatabaseError(err: err))
}
return succeed()
}
}
extension BrowserDB: Queryable {
func runQuery<T>(sql: String, args: Args?, factory: SDRow -> T) -> Deferred<Maybe<Cursor<T>>> {
return runWithConnection { (connection, err) -> Cursor<T> in
return connection.executeQuery(sql, factory: factory, withArgs: args)
}
}
func queryReturnsResults(sql: String, args: Args?=nil) -> Deferred<Maybe<Bool>> {
return self.runQuery(sql, args: args, factory: { row in true })
>>== { deferMaybe($0[0] ?? false) }
}
func queryReturnsNoResults(sql: String, args: Args?=nil) -> Deferred<Maybe<Bool>> {
return self.runQuery(sql, args: nil, factory: { row in false })
>>== { deferMaybe($0[0] ?? true) }
}
}
extension SQLiteDBConnection {
func tablesExist(names: [String]) -> Bool {
let count = names.count
let inClause = BrowserDB.varlist(names.count)
let tablesSQL = "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN \(inClause)"
let res = self.executeQuery(tablesSQL, factory: StringFactory, withArgs: names.map { $0 as AnyObject })
log.debug("\(res.count) tables exist. Expected \(count)")
return res.count > 0
}
}
| mpl-2.0 | 4f070e5b87b3700fb2a91596fcabfb29 | 37.909692 | 164 | 0.586187 | 4.770456 | false | false | false | false |
srxboys/RXSwiftExtention | RXSwiftExtention/Tools/RXNetworkTools.swift | 1 | 3068 | //
// RXNetworkTools.swift
// RXSwiftExtention
//
// Created by srx on 2017/3/25.
// Copyright © 2017年 https://github.com/srxboys. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case get
case post
}
class RXNetworkTools {
class func postData(parameters : [String : Any]? = nil, finishedCallback : @escaping (_ result : Any, _ status:Bool, _ message:String) -> ()) {
guard (parameters?.keys.count)! > 0 else {
assert(false, "参数有误")
return;
}
printHttp(parameters!)
requestHttpData(.post, URLString: SERVER, parameters: parameters) { (result : Any) in
// 1.将result转成字典类型
guard let resultDict = result as? [String : NSObject] else {
finishedCallback("", false, "服务器错误")
return
}
// 2.1根据data该key,获取服务器信息
let dataDictModel = dictForKeyDict(resultDict, key: "data")
var dataDict = [String:Any]()
if(dataDictModel.isValue) {
dataDict = dataDictModel.object
}
else {
finishedCallback("", false, dictForKeyString(resultDict, key: "data"))
return
}
//一般直接打印就好,我是为了学习
// RXPrintJSON(printObject: dataDict)
//3.1根据data该key,获取服务器是否使用 https
let returnIsHttps = dictForKeyBool(dataDict, key: "is_https")
RXLog("服务器的请求接口头采用是否采用https= \(returnIsHttps)")
//3.2根据message,获取 接口信息
let returnMessage = dictForKeyString(dataDict, key: "message")
//3.3根据status,获取 接口信息的状态
let returnStatus = dictForKeyBool(dataDict, key: "status")
//3.4
let returnDataModel = dictForKey(dataDict, key: "returndata")
if(returnDataModel.isValue){
finishedCallback(returnDataModel.object, returnStatus, "")
}
else {
finishedCallback("", returnStatus, returnMessage)
}
}
}
fileprivate class func requestHttpData(_ type : MethodType, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping (_ result : Any) -> ()) {
// 1.获取类型
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
// 2.发送网络请求
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
// 3.获取结果
guard let result = response.result.value else {
RXLog(response.result.error)
return
}
// 4.将结果回调出去
finishedCallback(result)
}
}
}
| mit | 2fae3d0951a613ed8833ad21ac9caa45 | 29.967391 | 175 | 0.530713 | 4.63252 | false | false | false | false |
Urinx/SomeCodes | Swift/The Swift Programming Language/12.Subscripts.playground/section-1.swift | 1 | 1355 |
// P.422
// Subscripts
struct TimesTable {
let multiplier: Int
subscript(index: Int) -> Int {
return multiplier * index
}
}
let threeTimesTable = TimesTable(multiplier: 3)
println("six times three is \(threeTimesTable[6])")
struct TwoTable {
var n: Int
subscript(i: Int) -> Int {
get {
return n * i
}
set {
n = newValue * 2
}
}
}
var twoTable = TwoTable(n: 1)
twoTable[3]
twoTable[2] = 2
twoTable[2]
// Subscript Options
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: 0.0)
}
func indexIsValidForRow(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValidForRow(row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
var matrix = Matrix(rows: 2, columns: 2)
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2
| gpl-2.0 | a0a9d93740ef35fcb28846f9de2d159d | 21.583333 | 81 | 0.553506 | 3.702186 | false | false | false | false |
mutfak/MCalendarKit | Example/MCalendarKit/ViewController.swift | 1 | 3038 | //
// ViewController.swift
// MCalendarKit
//
// Created by Ridvan Kucuk on 08/01/2016.
// Copyright (c) 2016 Ridvan Kucuk. All rights reserved.
//
import UIKit
import MCalendarKit
import EventKit
class ViewController: UIViewController, CalendarViewDataSource, CalendarViewDelegate {
var viewCalendar: MCalendarView?
override func viewDidLoad() {
super.viewDidLoad()
var params = [Parameters : AnyObject]()
params[.CalendarBackgroundColor] = UIColor.whiteColor()
params[.AllowMultipleSelection] = true
params[.SelectedCellBackgroundColor] = UIColor.cyanColor()
params[.DeselectedCellBackgroundColor] = UIColor.lightGrayColor()
params[.TodayDeSelectedBackgroundColor] = UIColor.redColor()
params[.Circular] = true
viewCalendar = MCalendarView()
viewCalendar?.direction = .Horizontal
viewCalendar?.parameters = params
viewCalendar?.translatesAutoresizingMaskIntoConstraints = false
viewCalendar?.delegate = self
viewCalendar?.dataSource = self
view.addSubview(self.viewCalendar!)
let views = ["view_calendar" : viewCalendar!]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view_calendar]|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view_calendar(300)]", options: [], metrics: nil, views: views))
let dateComponents = NSDateComponents()
dateComponents.day = 0
let today = NSDate()
if let date = self.viewCalendar!.calendar.dateByAddingComponents(dateComponents, toDate: today, options: NSCalendarOptions()) {
self.viewCalendar?.selectDate(date)
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let width = view.frame.size.width - 16.0 * 2
let height = width + 30.0
viewCalendar?.frame = CGRect(x: 16.0, y: 32.0, width: width, height: height)
}
//MARK: RKCalendarViewDataSource
func startDate() -> NSDate? {
return NSDate()
}
func endDate() -> NSDate? {
let dateComponents = NSDateComponents()
dateComponents.year = 2;
let today = NSDate()
let twoYearsFromNow = self.viewCalendar!.calendar.dateByAddingComponents(dateComponents, toDate: today, options: NSCalendarOptions())
return twoYearsFromNow
}
//MARK: RKCalendarViewDelegate
func calendar(calendar: MCalendarView, didSelectDate date: NSDate, withEvents events: [EKEvent]) {
print(date)
}
func calendar(calendar: MCalendarView, didScrollToMonth date: NSDate) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | cdf146f7c729fcdbf8cbe497c154ba85 | 30.978947 | 143 | 0.639236 | 5.274306 | false | false | false | false |
Vostro162/VaporTelegram | Sources/App/Audio+Extensions.swift | 1 | 1176 | //
// Audio+Extensions.swift
// VaporTelegram
//
// Created by Marius Hartig on 11.05.17.
//
//
import Foundation
import Vapor
// MARK: - Audio
extension Audio: JSONInitializable {
public init(json: JSON) throws {
guard
let fileId = json["file_id"]?.string,
let duration = json["duration"]?.int
else { throw VaporTelegramError.parsing }
self.fileId = fileId
self.duration = duration
/*
*
* Optionals
*
*/
if let fileSize = json["file_size"]?.int {
self.fileSize = fileSize
} else {
self.fileSize = nil
}
if let mimeType = json["mime_type"]?.string {
self.mimeType = mimeType
} else {
self.mimeType = nil
}
if let title = json["title"]?.string {
self.title = title
} else {
self.title = nil
}
if let performer = json["performer"]?.string {
self.performer = performer
} else {
self.performer = nil
}
}
}
| mit | 1bf4533a55fce376c0523b01304724de | 20 | 54 | 0.471939 | 4.741935 | false | false | false | false |
jeanetienne/Bee | Bee/Modules/Spelling/SpellingView.swift | 1 | 2704 | //
// Bee
// Copyright © 2017 Jean-Étienne. All rights reserved.
//
import UIKit
class SpellingView: UIViewController {
@IBOutlet weak var phraseTextField: UITextField!
@IBOutlet weak var alphabetPicker: CollapsiblePicker!
@IBOutlet weak var spellingTableView: UITableView!
var controller: SpellingController!
override func viewDidLoad() {
super.viewDidLoad()
let cell = UINib(nibName: String(describing: SpelledCharacterTableViewCell.self), bundle: Bundle.main)
spellingTableView.register(cell, forCellOfClass: SpelledCharacterTableViewCell.self)
phraseTextField.delegate = self
UIViewController.observeKeyboardWillShowNotification { notification in
UIViewController.handleKeyboardWillShow(withNotification: notification,
onScrollView: self.spellingTableView)
}
UIViewController.observeKeyboardWillHideNotification { notification in
UIViewController.handleKeyboardWillHide(withNotification: notification,
onScrollView: self.spellingTableView)
}
alphabetPicker.delegate = self
controller.didLoadView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
controller.didPresentView()
}
// MARK: - Controller callbacks
func setSpellingTableViewManager(manager: SpellingTableViewManager) {
spellingTableView.dataSource = manager
spellingTableView.delegate = manager
}
func updateAlphabets(_ updatedAlphabets: [String]) {
alphabetPicker.items = updatedAlphabets
alphabetPicker.selectItem(atIndex: 0)
}
func updateSpelling(withNumberOfCharacters numberOfCharacters: Int) {
spellingTableView.reloadData()
phraseTextField.resignFirstResponder()
}
func deselectSpellingTableView() {
for rowNumber in 0..<spellingTableView.numberOfRows(inSection: 0) {
spellingTableView.deselectRow(at: IndexPath(row: rowNumber, section: 0), animated: true)
}
}
}
extension SpellingView: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
controller.didSelectSpell(phrase: textField.text)
return false
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
controller.didSelectClear()
return true
}
}
extension SpellingView: CollapsiblePickerDelegate {
func pickerDidSelectItem(withName name: String) {
controller.didSelectAlphabet(withName: name, phrase: phraseTextField.text)
}
}
| mit | 4b8bb18cc415002d5e2f6c39884b78be | 30.418605 | 110 | 0.685048 | 5.393214 | false | false | false | false |
narumolp/NMPAnchorOverlayView | NMPAnchorOverlayView_Demo/ViewController.swift | 1 | 10863 | //
// ViewController.swift
// NMPAnchorOverlayViewExample project
//
// Created by Narumol Pugkhem on 5/8/17.
// Copyright © 2017 Narumol. All rights reserved.
//
// This is the main viewController of NMPAnchorOverlayViewExample app.
// It's main purpose is to demonstrate usage of NMPAnchorOverlayView.
// It creates two NMPAnchorOverlayView instances as subviews; one is anchored
// to the top and the other to the bottom.
// some work done
// some more work done
import UIKit
class ViewController: UIViewController, NMPAnchorOverlayViewDelegate {
var slideView: NMPAnchorOverlayView!
internal let ImageNames = ["playful", "bark", "sweet"]
@IBOutlet weak var stbView: NMPAnchorOverlayView!
@IBOutlet weak var B4: UIButton!
// Constraints IBOutlets
@IBOutlet weak var heightCt: NSLayoutConstraint!
@IBOutlet weak var bottomCt: NSLayoutConstraint!
@IBOutlet weak var leftCt: NSLayoutConstraint!
@IBOutlet weak var rightCt: NSLayoutConstraint!
// MARK: - Private variables
private var button: UIButton!
/// Add two NMPAnchorOverlayView instances on ViewController's view
/// - Returns: n/a
override func viewDidLoad() {
super.viewDidLoad()
// 1 Create programatically
//
let size: CGSize = CGSize(width: view.frame.width - 20, height: view.bounds.height)
slideView = NMPAnchorOverlayView(size: size, anchorLocation: .top, maximumHeight: 500)
// Additional Properties
//
slideView.minHeight = 28.0
slideView.backgroundColor = UIColor.green
slideView.layer.cornerRadius = 12.0
// Set delegate and add view
slideView.delegate = self
self.view.addSubview(slideView)
// Add additional view to AanchorOverlayView
addStuffOnSlideView()
// 2 Create from storyboard, then call this method to add IBOutlets contraints on an
// NMPAnchorOverlayView instance
//
do {
try stbView.addIBOutletConstraintsFromParentViewController(leading: leftCt, trailing: rightCt, height: heightCt, topMargin: nil, bottomMargin: bottomCt)
} catch {
print("error add const")
}
// Set additional properties
stbView.maxHeight = 500
stbView.minHeight = 25
// stbView.animSpringDampingRatio = 0.2
// stbView.animClearance = 0.7
// Set delegate
stbView.delegate = self
// Optionally hide the NMPAnchorOverlayView instance's subviews
for v in stbView.subviews {
v.isHidden = true
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
/// Add a purple view on NMPAnchorOverlayView's instance
/// - Returns:
func addStuffOnSlideView() {
button = UIButton(frame: CGRect(x:0, y:0, width:150, height: (slideView.maxHeight)/3))
button.backgroundColor = UIColor.lightGray
button.isHidden = true
button.setTitle("BUTTON !", for: .normal)
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
button.layer.cornerRadius = 8.0
slideView.addSubview(button)
}
/// Close AnchorOverlay instance views when a finger touches outside the view
/// - Returns: n/a
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let point = touch.location(in: view)
if !( stbView.frame.contains(point) || slideView.frame.contains(point)) {
for v in view.subviews {
if v is NMPAnchorOverlayView {
(v as! NMPAnchorOverlayView).closeView()
}
}
}
}
// MARK: - AnchorOverlayView Delegate
/// Hide the button after the slideView close
/// - Returns: n/a
func NMPAnchorOverlayViewDidShrink(view: UIView) {
if view === slideView {
UIView.animate(withDuration: 0.5) {
self.button.alpha = 0.0
self.button.isHidden = true
}
}
}
/// Hide subviews of stbView
/// - Returns: n/a
func NMPAnchorOverlayViewWillShrink(view: UIView) {
if view === stbView {
UIView.animate(withDuration: 0.3) {
for v in self.stbView.subviews {
v.isHidden = true
}
}
}
}
/// Show the button and animate
/// - Returns: n/a
func NMPAnchorOverlayViewDidExpand(view: UIView) {
if view === slideView {
button.center.x = slideView.bounds.width/2
button.center.y = slideView.bounds.height/2
UIView.animate(withDuration: 0.5) {
self.button.alpha = 1.0
self.button.isHidden = false
}
}
}
/// Show stbView's subviews
/// - Returns: n/a
func NMPAnchorOverlayViewWillExpand(view: UIView) {
if view === stbView {
UIView.animate(withDuration: 0.3) {
for v in self.stbView.subviews {
v.isHidden = false
}
}
}
}
}
// Extra fun stuff
// ViewController extension includes button tapped action methods
// Watch the doc images fly to different directions when with animations.
extension ViewController {
@nonobjc static var b4Index = 2
/// Create an image view with dog image
/// - Returns: imageView: UIImage
func makeImageView(index: Int) -> UIImageView {
let imageView = UIImageView(image: UIImage(named: ImageNames[index]))
imageView.backgroundColor = UIColor.clear
imageView.layer.cornerRadius = 15.0
imageView.clipsToBounds = true
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
return imageView
}
/// Display image with animation when left button pressed
/// - Returns: n/a
@IBAction func b2Pressed(_ sender: Any) {
let imageView = makeImageView(index: 0)
view.addSubview(imageView)
let conX = imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
let conBottom = imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: imageView.frame.height + 200 )
let conWidth = imageView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.53, constant: 0.0)
let conHeight = imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor)
NSLayoutConstraint.activate([conX, conBottom, conWidth, conHeight])
view.layoutIfNeeded()
//Animate in
UIView.animate( withDuration: 0.8, delay: 0.0, usingSpringWithDamping: 0.6, initialSpringVelocity: 10.0, animations: {
conBottom.constant = -imageView.frame.size.height / 2
conWidth.constant = 0.0
self.view.layoutIfNeeded()
}, completion: nil)
//Animate out
UIView.animate( withDuration: 0.67, delay: 1.0, animations: {
conX.constant += 350
conWidth.constant = -20.0
self.view.layoutIfNeeded()
},completion: { _ in
imageView.removeFromSuperview()
})
}
/// Display image with animation when middle button pressed
/// - Returns: n/a
@IBAction func b3Pressed(_ sender: Any) {
let imageView = makeImageView(index: 1)
view.addSubview(imageView)
let conX = imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
let conTop = imageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 10)
let conWidth = imageView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.5, constant: 10.0)
let conHeight = imageView.heightAnchor.constraint(equalTo: imageView.widthAnchor)
NSLayoutConstraint.activate([conX, conTop, conWidth, conHeight])
view.layoutIfNeeded()
//Animate in
UIView.animate( withDuration: 3.8, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 5.0, animations: {
conTop.constant = imageView.frame.size.height * 2
conWidth.constant = imageView.frame.size.width * 0.7
self.view.layoutIfNeeded()
}, completion: nil)
//Animate ratation
UIView.animate( withDuration: 5.0, delay: 1.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 10, options: [], animations: {
let angle: CGFloat = .pi
imageView.transform = CGAffineTransform(rotationAngle: angle)
self.view.layoutIfNeeded()
})
//Animate out
UIView.animate( withDuration: 3.67, delay: 2.0, animations: {
conTop.constant = -imageView.frame.size.width / 3
conWidth.constant = -50.0
self.view.layoutIfNeeded()
}) { _ in
imageView.removeFromSuperview()
}
}
/// Display image with animation when right button pressed
/// - Returns: n/a
@IBAction func b4Pressed(_ sender: Any) {
let imageView = makeImageView(index: ViewController.b4Index)
view.addSubview(imageView)
let conX = imageView.centerXAnchor.constraint(equalTo: B4.centerXAnchor)
let conTop = imageView.topAnchor.constraint(equalTo: B4.topAnchor)
let conWidth = imageView.widthAnchor.constraint(equalTo: B4.widthAnchor)
let conHeight = imageView.heightAnchor.constraint(equalTo: B4.heightAnchor)
NSLayoutConstraint.activate([conX, conTop, conWidth, conHeight])
view.layoutIfNeeded()
let ratio:CGFloat = 2.0
//Animate in
UIView.animate( withDuration: 1.0, delay: 0.1, usingSpringWithDamping: 0.2, initialSpringVelocity: 3.0, animations: {
conWidth.constant = imageView.frame.size.width * ratio
conHeight.constant = imageView.frame.size.height * ratio
conX.constant -= abs(imageView.center.x - self.view.center.x)
self.view.layoutIfNeeded()
}) { _ in
UIView.transition(with: imageView, duration: 2.0, options: .transitionCrossDissolve, animations: {
imageView.transform = CGAffineTransform(rotationAngle: .pi/8)
imageView.image = UIImage(named: self.ImageNames[ViewController.b4Index])
ViewController.b4Index = (ViewController.b4Index + 1) % 3
})
}
//Animate out
UIView.animate( withDuration: 2.0, delay: 3.5, animations: {
conWidth.constant = 0.0
conHeight.constant = 0.0
conX.constant = 0.0
imageView.transform = CGAffineTransform(rotationAngle: -.pi)
self.view.layoutIfNeeded()
}) { _ in
imageView.removeFromSuperview()
self.B4.setImage(imageView.image, for: .normal)
}
}
}
| mit | ae05e0ddd216deffe6648f2f10d088d9 | 32.94375 | 161 | 0.645001 | 4.433469 | false | false | false | false |
Erickson0806/AVFoundationSwiftDemo | AVFoundation01-HelloAVF/AVFoundation01-HelloAVF/ViewController.swift | 1 | 2574 | //
// ViewController.swift
// AVFoundation01-HelloAVF
//
// Created by Erickson on 16/1/4.
// Copyright © 2016年 erickson. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UITableViewController {
let speechManager = SpeechManager()
var speechStrings = [String]()
override func viewDidLoad() {
speechManager.synthesizer.delegate = self
speechManager.beginConversation()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return speechStrings.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let id = indexPath.row % 2 == 0 ? "myCell" : "AVCell"
let cell = tableView.dequeueReusableCellWithIdentifier(id, forIndexPath: indexPath) as! BubbleCell
cell.messageLabel.text = speechStrings[indexPath.row]
return cell
}
}
extension ViewController:AVSpeechSynthesizerDelegate{
func speechSynthesizer(synthesizer: AVSpeechSynthesizer, didStartSpeechUtterance utterance: AVSpeechUtterance) {
speechStrings.append(utterance.speechString)
tableView.reloadData()
let index = NSIndexPath(forRow: speechStrings.count-1, inSection: 0)
tableView.scrollToRowAtIndexPath(index, atScrollPosition: .Bottom, animated: true)
}
}
class SpeechManager {
let synthesizer : AVSpeechSynthesizer
private let voices: [AVSpeechSynthesisVoice]
private let speechString: [String]
init(){
synthesizer = AVSpeechSynthesizer()
voices = [AVSpeechSynthesisVoice(language: "zh-TW")!,
AVSpeechSynthesisVoice(language: "zh-HK")!]
/*
*/
speechString = ["河水往哪里流啊","大河向东流啊","天上有多少颗星星阿","天上的星星参北斗阿","你给我滚出去","说走咱就走阿","你有病吧","你有我有全都有阿","你再唱一句试试","路见不平一生吼阿","你信不信我奏你","该出手时就出手阿","我让你退学","风风火火闯九洲阿"]
}
func beginConversation(){
for i in 0..<speechString.count {
let utterance = AVSpeechUtterance(string: speechString[i])
utterance.voice = voices[i%2]
utterance.rate = 0.5
utterance.pitchMultiplier = 0.8
utterance.postUtteranceDelay = 0.2
synthesizer.speakUtterance(utterance)
}
}
} | apache-2.0 | d389fecc8bea70fd14d621ef0e45a83e | 27.285714 | 164 | 0.658947 | 4.318182 | false | false | false | false |
jzucker2/SwiftyKit | Example/SwiftyKit/PlainViewController.swift | 1 | 1554 | //
// PlainViewController.swift
// SwiftyKit_Example
//
// Created by Jordan Zucker on 8/1/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import SwiftyKit
class PlainViewController: UIViewController {
let stackView: UIStackView = UIStackView(frame: .zero)
var count = 0
override func loadView() {
self.view = loadedView()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
edgesForExtendedLayout = []
title = "Stack"
navigationItem.title = "Stack"
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add View", style: .done, target: self, action: #selector(addArrangedSubViewButtonPressed(sender:)))
addArrangedSubview()
addArrangedSubview()
addArrangedSubview()
view.setNeedsLayout()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UI Actions
func addArrangedSubview() {
let countString = "SubView => \(count)"
count += 1
let label = UILabel(frame: .zero)
label.text = countString
stackView.addArrangedSubview(label)
stackView.setNeedsLayout()
view.setNeedsLayout()
}
@objc func addArrangedSubViewButtonPressed(sender: UIBarButtonItem) {
addArrangedSubview()
}
}
extension PlainViewController: StackingView {
}
| mit | 855682bed444dfa0024d50c06ed83225 | 24.459016 | 167 | 0.644559 | 5.091803 | false | false | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/Login Management/LoginListDataSourceHelper.swift | 2 | 3366 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Storage
import Shared
class LoginListDataSourceHelper {
private(set) var domainLookup = [GUID: (baseDomain: String?, host: String?, hostname: String)]()
// Precompute the baseDomain, host, and hostname values for sorting later on. At the moment
// baseDomain() is a costly call because of the ETLD lookup tables.
func setDomainLookup(_ logins: [LoginRecord]) {
self.domainLookup = [:]
logins.forEach { login in
self.domainLookup[login.id] = (
login.hostname.asURL?.baseDomain,
login.hostname.asURL?.host,
login.hostname
)
}
}
// Small helper method for using the precomputed base domain to determine the title/section of the
// given login.
func titleForLogin(_ login: LoginRecord) -> Character {
// Fallback to hostname if we can't extract a base domain.
let titleString = domainLookup[login.id]?.baseDomain?.uppercased() ?? login.hostname
return titleString.first ?? Character("")
}
// Rules for sorting login URLS:
// 1. Compare base domains
// 2. If bases are equal, compare hosts
// 3. If login URL was invalid, revert to full hostname
func sortByDomain(_ loginA: LoginRecord, loginB: LoginRecord) -> Bool {
guard let domainsA = domainLookup[loginA.id],
let domainsB = domainLookup[loginB.id] else {
return false
}
guard let baseDomainA = domainsA.baseDomain,
let baseDomainB = domainsB.baseDomain,
let hostA = domainsA.host,
let hostB = domainsB.host else {
return domainsA.hostname < domainsB.hostname
}
if baseDomainA == baseDomainB {
return hostA < hostB
} else {
return baseDomainA < baseDomainB
}
}
func computeSectionsFromLogins(_ logins: [LoginRecord]) -> Deferred<Maybe<([Character], [Character: [LoginRecord]])>> {
guard !logins.isEmpty else {
return deferMaybe( ([Character](), [Character: [LoginRecord]]()) )
}
var sections = [Character: [LoginRecord]]()
var titleSet = Set<Character>()
return deferDispatchAsync(DispatchQueue.global(qos: DispatchQoS.userInteractive.qosClass)) { [weak self] in
guard let self = self else {
return deferMaybe( ([Character](), [Character: [LoginRecord]]()) )
}
self.setDomainLookup(logins)
// 1. Temporarily insert titles into a Set to get duplicate removal for 'free'.
logins.forEach { titleSet.insert(self.titleForLogin($0)) }
// 2. Setup an empty list for each title found.
titleSet.forEach { sections[$0] = [LoginRecord]() }
// 3. Go through our logins and put them in the right section.
logins.forEach { sections[self.titleForLogin($0)]?.append($0) }
// 4. Go through each section and sort.
sections.forEach { sections[$0] = $1.sorted(by: self.sortByDomain) }
return deferMaybe( (Array(titleSet).sorted(), sections) )
}
}
}
| mpl-2.0 | ab289b7128fd6d45d8f6b214bf3e8c37 | 38.6 | 123 | 0.614676 | 4.720898 | false | false | false | false |
keygx/GradientCircularProgress | Sample/MyStyle.swift | 1 | 1362 | //
// MyStyle.swift
// GradientCircularProgress
//
// Created by keygx on 2015/11/25.
// Copyright (c) 2015年 keygx. All rights reserved.
//
import UIKit
import GradientCircularProgress
public struct MyStyle: StyleProperty {
/*** style properties **********************************************************************************/
// Progress Size
public var progressSize: CGFloat = 200
// Gradient Circular
public var arcLineWidth: CGFloat = 18.0
public var startArcColor: UIColor = UIColor.clear
public var endArcColor: UIColor = UIColor.orange
// Base Circular
public var baseLineWidth: CGFloat? = 19.0
public var baseArcColor: UIColor? = UIColor.darkGray
// Ratio
public var ratioLabelFont: UIFont? = UIFont(name: "Verdana-Bold", size: 16.0)
public var ratioLabelFontColor: UIColor? = UIColor.white
// Message
public var messageLabelFont: UIFont? = UIFont.systemFont(ofSize: 16.0)
public var messageLabelFontColor: UIColor? = UIColor.white
// Background
public var backgroundStyle: BackgroundStyles = .dark
// Dismiss
public var dismissTimeInterval: Double? = 0.0 // 'nil' for default setting.
/*** style properties **********************************************************************************/
public init() {}
}
| mit | 223d5d4fa54eb84f3116a250f4aa918a | 30.627907 | 109 | 0.592647 | 4.927536 | false | false | false | false |
4faramita/TweeBox | TweeBox/SingleTweetViewController.swift | 1 | 10620 | //
// SingleTweetViewController.swift
// TweeBox
//
// Created by 4faramita on 2017/8/21.
// Copyright © 2017年 4faramita. All rights reserved.
//
import UIKit
//import Kanna
import SafariServices
import VisualEffectView
import YYText
import PopupDialog
class SingleTweetViewController: UIViewController, TweetClickableContentProtocol {
private var retweet: Tweet?
private var clientLink: String?
public var tweet: Tweet! {
didSet {
if let originTweet = tweet.retweetedStatus, tweet.text.hasPrefix("RT @") {
retweet = tweet
tweet = originTweet
}
if tweetID == nil {
tweetID = tweet?.id
}
}
}
public var tweetID: String! {
didSet {
if tweet == nil {
setTweet()
}
}
}
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var screenNameLabel: UILabel!
@IBOutlet weak var textContentLabel: YYLabel!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var createdTimeLabel: UILabel!
@IBOutlet weak var clientButton: UIButton!
@IBOutlet weak var likeCountLabel: UILabel!
@IBOutlet weak var retweetCountButton: UIButton!
var keyword: String? {
didSet {
if let newKeyword = keyword, newKeyword.hasPrefix("@") || newKeyword.hasPrefix("#") {
let index = newKeyword.index(newKeyword.startIndex, offsetBy: 1)
keyword = String(newKeyword[index...])
}
}
}
var fetchedUser: TwitterUser?
func alertForNoSuchUser(viewController: UIViewController) {
print(">>> no user")
let popup = PopupDialog(title: "Cannot Find User @\(keyword ?? "")", message: "Please check your input.", image: nil)
let cancelButton = CancelButton(title: "OK") { }
popup.addButton(cancelButton)
viewController.present(popup, animated: true, completion: nil)
}
func setAndPerformSegueForHashtag() {
performSegue(withIdentifier: "Show Tweets with Hashtag", sender: self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if tweet != nil {
setTweetContent()
}
if tweetID != nil {
refreshReply()
}
}
private func addPlayLabel(to view: UIView, isGif: Bool) {
let visualEffectView = VisualEffectView(frame: view.bounds)
visualEffectView.blurRadius = 2
visualEffectView.colorTint = .white
visualEffectView.colorTintAlpha = 0.2
visualEffectView.isUserInteractionEnabled = false
visualEffectView.isOpaque = false
view.addSubview(visualEffectView)
let play = UIImageView(image: UIImage(named: "play_video"))
play.isUserInteractionEnabled = false
play.isOpaque = false
view.addSubview(play)
play.snp.makeConstraints { (make) in
make.center.equalTo(view)
make.height.equalTo(32)
make.width.equalTo(32)
}
if isGif {
let gif = UIImageView(image: UIImage(named: "play_gif"))
gif.isUserInteractionEnabled = false
gif.isOpaque = false
view.addSubview(gif)
gif.snp.makeConstraints { (make) in
make.trailing.equalTo(view).offset(-10)
make.bottom.equalTo(view)
make.height.equalTo(32)
make.width.equalTo(32)
}
}
}
@IBAction private func tapOnProfileImage(_ sender: UIGestureRecognizer) {
fetchedUser = tweet.user
performSegue(withIdentifier: "profileImageTapped", sender: sender)
}
private func setTweetContent() {
if (tweet.entities?.realMedia == nil) || (tweet.entities?.realMedia!.count == 0) {
containerView.removeFromSuperview()
} else if let media = tweet.entities?.realMedia, media.count == 1 {
if media[0].type != "photo" {
addPlayLabel(to: containerView, isGif: (media[0].type == "animated_gif"))
}
}
containerView.cutToRound(radius: 5)
profileImageView.kf.setImage(with: tweet.user.profileImageURL)
profileImageView.cutToRound(radius: nil)
profileImageView.isUserInteractionEnabled = true
let tapProfile = UITapGestureRecognizer(target: self, action: #selector(tapOnProfileImage(_:)))
tapProfile.numberOfTapsRequired = 1
tapProfile.numberOfTouchesRequired = 1
profileImageView.addGestureRecognizer(tapProfile)
nameLabel.text = tweet.user.name
screenNameLabel.text = "@\(tweet.user.screenName)"
textContentLabel.attributedText = TwitterAttributedContent(tweet).attributedString
textContentLabel.lineBreakMode = .byWordWrapping
textContentLabel.numberOfLines = 0
textContentLabel.textAlignment = .natural
textContentLabel.preferredMaxLayoutWidth = containerView.bounds.width
textContentLabel.font = UIFont.preferredFont(forTextStyle: .body)
print(">>> label >> \(textContentLabel.subviews)")
// FIXME: HTML parsing
// let clientHTMLString = tweet.source
// if let doc = HTML(html: clientHTMLString, encoding: .utf8) {
// for link in doc.css("a, link") {
// let attributedString = NSMutableAttributedString(string: (link.text ?? ""))
//
// let range = NSRange.init(location: 0, length: attributedString.length)
//
// attributedString.addAttribute(NSAttributedStringKey.link, value: (link["href"] ?? ""), range: range)
// clientLink = link["href"]
//
// let font = UIFont.preferredFont(forTextStyle: .caption2)
// attributedString.addAttribute(NSAttributedStringKey.font, value: font, range: range)
// attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.darkGray, range: range)
// clientButton.setAttributedTitle(attributedString, for: .normal)
//
// clientButton.addTarget(self, action: #selector(clickOnClient(_:)), for: .touchUpInside)
// }
// }
if let date = tweet.createdTime {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.timeZone = TimeZone.current
let dateString = dateFormatter.string(from: date)
createdTimeLabel.text = dateString
}
likeCountLabel.text = "\((tweet.favoriteCount ?? 0).shortExpression) like"
retweetCountButton.setTitle("\(tweet.retweetCount.shortExpression) retweet", for: .normal)
}
@IBAction private func clickOnClient(_ sender: Any?) {
if let url = URL(string: clientLink ?? "") {
let safariViewController = SFSafariViewController(url: url, entersReaderIfAvailable: true)
present(safariViewController, animated: true)
}
}
private func setTweet() {
SingleTweet(
params: TweetParams(of: tweetID!),
resourceURL: ResourceURL.statuses_show_id
).fetchData { [weak self] (tweet) in
if tweet != nil {
self?.tweet = tweet
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
switch identifier {
// case "Retweet List":
// if let userListViewController = segue.destination as? UserListTableViewController {
//
// let retweetIDListRetriever = RetweeterID(
// resourceURL: ResourceURL.statuses_retweeters_ids,
// retweetersIDParams: RetweetersIDParams(id: tweetID, cursor: nil),
// fetchOlder: nil,
// nextCursor: nil,
// previousCursor: nil
// )
// retweetIDListRetriever.fetchData({ (nextCursor, previousCursor, idList) in
// print(">>> idList >> \(idList)")
// userListViewController.resourceURL = ResourceURL.user_lookup
// userListViewController.userListParams = MultiUserParams(userID: idList, screenName: nil)
// userListViewController.previousCursor = previousCursor
// userListViewController.nextCursor = nextCursor
// })
// }
case "Media Container":
if let imageContainerViewController = segue.destination as? ImageContainerViewController {
imageContainerViewController.tweet = tweet
}
case "profileImageTapped":
if let profileViewController = segue.destination.content as? UserTimelineTableViewController {
if let user = fetchedUser {
profileViewController.user = user
profileViewController.navigationItem.rightBarButtonItem = nil
}
}
case "Show Tweets with Hashtag":
if let searchTimelineViewController = segue.destination.content as? SearchTimelineTableViewController,
let keyword = keyword {
searchTimelineViewController.query = "%23\(keyword)"
searchTimelineViewController.navigationItem.title = "#\(keyword)"
searchTimelineViewController.navigationItem.rightBarButtonItem = nil
}
default:
return
}
}
}
override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
if identifier == "Media Container" {
return (tweet.entities?.realMedia != nil)
}
// FIX THIS
if identifier == "Retweet List" {
return false
}
return true
}
private func refreshReply() {
}
}
| mit | 537f71c1d0f9d8cdf12ff6c9744a8b8d | 34.868243 | 125 | 0.577376 | 5.370258 | false | false | false | false |
apple/swift-syntax | Sources/SwiftParser/Declarations.swift | 1 | 77769 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_spi(RawSyntax) import SwiftSyntax
extension DeclarationModifier {
var canHaveParenthesizedArgument: Bool {
switch self {
case .__consuming, .__setter_access, ._const, ._local, .async,
.classKeyword, .convenience, .distributed, .dynamic, .final,
.indirect, .infix, .isolated, .lazy, .mutating, .nonisolated,
.nonmutating, .optional, .override, .postfix, .prefix, .reasync,
.required, .rethrows, .staticKeyword, .weak:
return false
case .fileprivateKeyword, .internalKeyword, .open, .privateKeyword,
.publicKeyword, .unowned:
return true
}
}
}
extension TokenConsumer {
func atStartOfDeclaration(
isAtTopLevel: Bool = false,
allowInitDecl: Bool = true,
allowRecovery: Bool = false
) -> Bool {
if self.at(anyIn: PoundDeclarationStart.self) != nil {
return true
}
var subparser = self.lookahead()
var hasAttribute = false
var attributeProgress = LoopProgressCondition()
while attributeProgress.evaluate(subparser.currentToken) && subparser.at(.atSign) {
hasAttribute = true
_ = subparser.consumeAttributeList()
}
if subparser.currentToken.isKeyword ||
subparser.currentToken.tokenKind == .identifier {
var modifierProgress = LoopProgressCondition()
while let (modifierKind, handle) = subparser.at(anyIn: DeclarationModifier.self),
modifierKind != .classKeyword,
modifierProgress.evaluate(subparser.currentToken) {
subparser.eat(handle)
if subparser.at(.leftParen) &&
modifierKind.canHaveParenthesizedArgument {
subparser.consumeAnyToken()
subparser.consume(to: .rightParen)
}
}
}
if hasAttribute {
if subparser.at(.rightBrace) || subparser.at(.eof) || subparser.at(.poundEndifKeyword) {
return true
}
}
if subparser.at(.poundIfKeyword) {
var attrLookahead = subparser.lookahead()
return attrLookahead.consumeIfConfigOfAttributes()
}
let declStartKeyword: DeclarationStart?
if allowRecovery {
declStartKeyword = subparser.canRecoverTo(
anyIn: DeclarationStart.self,
recoveryPrecedence: isAtTopLevel ? nil : .closingBrace
)?.0
} else {
declStartKeyword = subparser.at(anyIn: DeclarationStart.self)?.0
}
switch declStartKeyword {
case .actorContextualKeyword:
// actor Foo {}
if subparser.peek().tokenKind == .identifier {
return true
}
// actor may be somewhere in the modifier list. Eat the tokens until we get
// to something that isn't the start of a decl. If that is an identifier,
// it's an actor declaration, otherwise, it isn't.
var lookahead = subparser.lookahead()
repeat {
lookahead.consumeAnyToken()
} while lookahead.atStartOfDeclaration(allowInitDecl: allowInitDecl)
return lookahead.at(.identifier)
case .caseKeyword:
// When 'case' appears inside a function, it's probably a switch
// case, not an enum case declaration.
return false
case .initKeyword:
return allowInitDecl
case .some(_):
// All other decl start keywords unconditonally start a decl.
return true
case nil:
if subparser.at(anyIn: ContextualDeclKeyword.self)?.0 != nil {
subparser.consumeAnyToken()
return subparser.atStartOfDeclaration(
isAtTopLevel: isAtTopLevel, allowInitDecl: allowInitDecl, allowRecovery: allowRecovery)
}
return false
}
}
}
extension Parser {
@_spi(RawSyntax)
public struct DeclAttributes {
public var attributes: RawAttributeListSyntax?
public var modifiers: RawModifierListSyntax?
public init(attributes: RawAttributeListSyntax?, modifiers: RawModifierListSyntax?) {
self.attributes = attributes
self.modifiers = modifiers
}
}
/// Parse a declaration.
///
/// Grammar
/// =======
///
/// declaration → import-declaration
/// declaration → constant-declaration
/// declaration → variable-declaration
/// declaration → typealias-declaration
/// declaration → function-declaration
/// declaration → enum-declaration
/// declaration → struct-declaration
/// declaration → class-declaration
/// declaration → actor-declaration
/// declaration → protocol-declaration
/// declaration → initializer-declaration
/// declaration → deinitializer-declaration
/// declaration → extension-declaration
/// declaration → subscript-declaration
/// declaration → operator-declaration
/// declaration → precedence-group-declaration
///
/// declarations → declaration declarations?
///
/// If `inMemberDeclList` is `true`, we know that the next item must be a
/// declaration and thus start with a keyword. This allows futher recovery.
@_spi(RawSyntax)
public mutating func parseDeclaration(inMemberDeclList: Bool = false) -> RawDeclSyntax {
switch self.at(anyIn: PoundDeclarationStart.self) {
case (.poundIfKeyword, _)?:
let directive = self.parsePoundIfDirective { parser in
let parsedDecl = parser.parseDeclaration()
let semicolon = parser.consume(if: .semicolon)
return RawMemberDeclListItemSyntax(
decl: parsedDecl,
semicolon: semicolon,
arena: parser.arena)
} addSemicolonIfNeeded: { lastElement, newItemAtStartOfLine, parser in
if lastElement.semicolon == nil && !newItemAtStartOfLine {
return RawMemberDeclListItemSyntax(
lastElement.unexpectedBeforeDecl,
decl: lastElement.decl,
lastElement.unexpectedBetweenDeclAndSemicolon,
semicolon: parser.missingToken(.semicolon, text: nil),
lastElement.unexpectedAfterSemicolon,
arena: parser.arena)
} else {
return nil
}
} syntax: { parser, elements in
return .decls(RawMemberDeclListSyntax(elements: elements, arena: parser.arena))
}
return RawDeclSyntax(directive)
case (.poundWarningKeyword, _)?, (.poundErrorKeyword, _)?:
return self.parsePoundDiagnosticDeclaration()
case nil:
break
}
if (self.at(.pound)) {
// FIXME: If we can have attributes for macro expansions, handle this
// via DeclarationStart.
return RawDeclSyntax(self.parseMacroExpansionDeclaration())
}
let attrs = DeclAttributes(
attributes: self.parseAttributeList(),
modifiers: self.parseModifierList())
// If we are inside a memberDecl list, we don't want to eat closing braces (which most likely close the outer context)
// while recoverying to the declaration start.
let recoveryPrecedence = inMemberDeclList ? TokenPrecedence.closingBrace : nil
switch self.canRecoverTo(anyIn: DeclarationStart.self, recoveryPrecedence: recoveryPrecedence) {
case (.importKeyword, let handle)?:
return RawDeclSyntax(self.parseImportDeclaration(attrs, handle))
case (.classKeyword, let handle)?:
return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawClassDeclSyntax.self, attrs: attrs, introucerHandle: handle))
case (.enumKeyword, let handle)?:
return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawEnumDeclSyntax.self, attrs: attrs, introucerHandle: handle))
case (.caseKeyword, let handle)?:
return RawDeclSyntax(self.parseEnumCaseDeclaration(attrs, handle))
case (.structKeyword, let handle)?:
return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawStructDeclSyntax.self, attrs: attrs, introucerHandle: handle))
case (.protocolKeyword, let handle)?:
return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawProtocolDeclSyntax.self, attrs: attrs, introucerHandle: handle))
case (.associatedtypeKeyword, let handle)?:
return RawDeclSyntax(self.parseAssociatedTypeDeclaration(attrs, handle))
case (.typealiasKeyword, let handle)?:
return RawDeclSyntax(self.parseTypealiasDeclaration(attrs, handle))
case (.extensionKeyword, let handle)?:
return RawDeclSyntax(self.parseExtensionDeclaration(attrs, handle))
case (.funcKeyword, let handle)?:
return RawDeclSyntax(self.parseFuncDeclaration(attrs, handle))
case (.subscriptKeyword, let handle)?:
return RawDeclSyntax(self.parseSubscriptDeclaration(attrs, handle))
case (.letKeyword, let handle)?, (.varKeyword, let handle)?:
return RawDeclSyntax(self.parseLetOrVarDeclaration(attrs, handle, inMemberDeclList: inMemberDeclList))
case (.initKeyword, let handle)?:
return RawDeclSyntax(self.parseInitializerDeclaration(attrs, handle))
case (.deinitKeyword, let handle)?:
return RawDeclSyntax(self.parseDeinitializerDeclaration(attrs, handle))
case (.operatorKeyword, let handle)?:
return RawDeclSyntax(self.parseOperatorDeclaration(attrs, handle))
case (.precedencegroupKeyword, let handle)?:
return RawDeclSyntax(self.parsePrecedenceGroupDeclaration(attrs, handle))
case (.actorContextualKeyword, let handle)?:
return RawDeclSyntax(self.parseNominalTypeDeclaration(for: RawActorDeclSyntax.self, attrs: attrs, introucerHandle: handle))
case nil:
if inMemberDeclList {
let isProbablyVarDecl = self.at(any: [.identifier, .wildcardKeyword]) && self.peek().tokenKind.is(any: [.colon, .equal, .comma])
let isProbablyTupleDecl = self.at(.leftParen) && self.peek().tokenKind.is(any: [.identifier, .wildcardKeyword])
if isProbablyVarDecl || isProbablyTupleDecl {
return RawDeclSyntax(self.parseLetOrVarDeclaration(attrs, .missing(.varKeyword)))
}
let isProbablyFuncDecl = self.at(any: [.identifier, .wildcardKeyword]) || self.at(anyIn: Operator.self) != nil
if isProbablyFuncDecl {
return RawDeclSyntax(self.parseFuncDeclaration(attrs, .missing(.funcKeyword)))
}
}
return RawDeclSyntax(RawMissingDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
arena: self.arena
))
}
}
}
extension Parser {
/// Parse an import declaration.
///
/// Grammar
/// =======
///
/// import-declaration → attributes? 'import' import-kind? import-path
/// import-kind → 'typealias' | 'struct' | 'class' | 'enum' | 'protocol' | 'let' | 'var' | 'func'
/// import-path → identifier | identifier '.' import-path
@_spi(RawSyntax)
public mutating func parseImportDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawImportDeclSyntax {
let (unexpectedBeforeImportKeyword, importKeyword) = self.eat(handle)
let kind = self.parseImportKind()
let path = self.parseImportAccessPath()
return RawImportDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeImportKeyword,
importTok: importKeyword,
importKind: kind,
path: path,
arena: self.arena)
}
@_spi(RawSyntax)
public mutating func parseImportKind() -> RawTokenSyntax? {
return self.consume(ifAny: [.typealiasKeyword, .structKeyword, .classKeyword, .enumKeyword, .protocolKeyword, .varKeyword, .letKeyword, .funcKeyword])
}
@_spi(RawSyntax)
public mutating func parseImportAccessPath() -> RawAccessPathSyntax {
var elements = [RawAccessPathComponentSyntax]()
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
let name = self.parseAnyIdentifier()
keepGoing = self.consume(if: .period)
elements.append(RawAccessPathComponentSyntax(
name: name, trailingDot: keepGoing, arena: self.arena))
} while keepGoing != nil && loopProgress.evaluate(currentToken)
return RawAccessPathSyntax(elements: elements, arena: self.arena)
}
}
extension Parser {
/// Parse an extension declaration.
///
/// Grammar
/// =======
///
/// extension-declaration → attributes? access-level-modifier? 'extension' type-identifier type-inheritance-clause? generic-where-clause?t extension-body
/// extension-body → '{' extension-members? '}'
/// extension-members → extension-member extension-members?
/// extension-member → declaration | compiler-control-statement
@_spi(RawSyntax)
public mutating func parseExtensionDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawExtensionDeclSyntax {
let (unexpectedBeforeExtensionKeyword, extensionKeyword) = self.eat(handle)
let type = self.parseType()
let inheritance: RawTypeInheritanceClauseSyntax?
if self.at(.colon) {
inheritance = self.parseInheritance()
} else {
inheritance = nil
}
let whereClause: RawGenericWhereClauseSyntax?
if self.at(.whereKeyword) {
whereClause = self.parseGenericWhereClause()
} else {
whereClause = nil
}
let members = self.parseMemberDeclList(introducer: extensionKeyword)
return RawExtensionDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeExtensionKeyword,
extensionKeyword: extensionKeyword,
extendedType: type,
inheritanceClause: inheritance,
genericWhereClause: whereClause,
members: members,
arena: self.arena)
}
}
extension Parser {
/// Attempt to consume an ellipsis prefix, splitting the current token if
/// necessary.
mutating func tryConsumeEllipsisPrefix() -> RawTokenSyntax? {
// It is not sufficient to check currentToken.isEllipsis here, as we may
// have something like '...>'.
// TODO: Recovery for different numbers of dots (which also needs to be
// done for regular variadics).
guard self.at(anyIn: Operator.self) != nil else { return nil }
let text = self.currentToken.tokenText
guard text.hasPrefix("...") else { return nil }
return self.consumePrefix(
SyntaxText(rebasing: text.prefix(3)), as: .ellipsis)
}
@_spi(RawSyntax)
public mutating func parseGenericParameters() -> RawGenericParameterClauseSyntax {
if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() {
return RawGenericParameterClauseSyntax(
remainingTokens,
leftAngleBracket: missingToken(.leftAngle),
genericParameterList: RawGenericParameterListSyntax(elements: [], arena: self.arena),
genericWhereClause: nil,
rightAngleBracket: missingToken(.rightAngle),
arena: self.arena
)
}
assert(self.currentToken.starts(with: "<"))
let langle = self.consumeAnyToken(remapping: .leftAngle)
var elements = [RawGenericParameterSyntax]()
do {
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
let attributes = self.parseAttributeList()
let (unexpectedBeforeName, name) = self.expectIdentifier()
if attributes == nil && unexpectedBeforeName == nil && name.isMissing && elements.isEmpty {
break
}
// Parse the ellipsis for a type parameter pack 'T...'.
let ellipsis = tryConsumeEllipsisPrefix()
// Parse the ':' followed by a type.
let colon = self.consume(if: .colon)
let unexpectedBeforeInherited: RawUnexpectedNodesSyntax?
let inherited: RawTypeSyntax?
if colon != nil {
if self.at(any: [.identifier, .protocolKeyword, .anyKeyword]) {
unexpectedBeforeInherited = nil
inherited = self.parseType()
} else if let classKeyword = self.consume(if: .classKeyword) {
unexpectedBeforeInherited = RawUnexpectedNodesSyntax([classKeyword], arena: self.arena)
inherited = RawTypeSyntax(RawSimpleTypeIdentifierSyntax(
name: missingToken(.identifier, text: "AnyObject"),
genericArgumentClause: nil,
arena: self.arena
))
} else {
unexpectedBeforeInherited = nil
inherited = RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena))
}
} else {
unexpectedBeforeInherited = nil
inherited = nil
}
keepGoing = self.consume(if: .comma)
elements.append(RawGenericParameterSyntax(
attributes: attributes,
unexpectedBeforeName,
name: name,
ellipsis: ellipsis,
colon: colon,
unexpectedBeforeInherited,
inheritedType: inherited,
trailingComma: keepGoing,
arena: self.arena))
} while keepGoing != nil && loopProgress.evaluate(currentToken)
}
let whereClause: RawGenericWhereClauseSyntax?
if self.at(.whereKeyword) {
whereClause = self.parseGenericWhereClause()
} else {
whereClause = nil
}
let rangle: RawTokenSyntax
if self.currentToken.starts(with: ">") {
rangle = self.consumeAnyToken(remapping: .rightAngle)
} else {
rangle = RawTokenSyntax(missing: .rightAngle, arena: self.arena)
}
let parameters: RawGenericParameterListSyntax
if elements.isEmpty && rangle.isMissing {
parameters = RawGenericParameterListSyntax(elements: [], arena: self.arena)
} else {
parameters = RawGenericParameterListSyntax(elements: elements, arena: self.arena)
}
return RawGenericParameterClauseSyntax(
leftAngleBracket: langle,
genericParameterList: parameters,
genericWhereClause: whereClause,
rightAngleBracket: rangle,
arena: self.arena)
}
enum LayoutConstraint: SyntaxText, ContextualKeywords {
case trivialLayout = "_Trivial"
case trivialAtMostLayout = "_TrivialAtMost"
case unknownLayout = "_UnknownLayout"
case refCountedObjectLayout = "_RefCountedObject"
case nativeRefCountedObjectLayout = "_NativeRefCountedObject"
case classLayout = "_Class"
case nativeClassLayout = "_NativeClass"
var hasArguments: Bool {
switch self {
case .trivialLayout,
.trivialAtMostLayout:
return true
case .unknownLayout,
.refCountedObjectLayout,
.nativeRefCountedObjectLayout,
.classLayout,
.nativeClassLayout:
return false
}
}
}
@_spi(RawSyntax)
public mutating func parseGenericWhereClause() -> RawGenericWhereClauseSyntax {
let (unexpectedBeforeWhereKeyword, whereKeyword) = self.expect(.whereKeyword)
var elements = [RawGenericRequirementSyntax]()
do {
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
let firstType = self.parseType()
guard !firstType.is(RawMissingTypeSyntax.self) else {
keepGoing = self.consume(if: .comma)
elements.append(RawGenericRequirementSyntax(
body: .sameTypeRequirement(RawSameTypeRequirementSyntax(
leftTypeIdentifier: RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena)),
equalityToken: missingToken(.equal),
rightTypeIdentifier: RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena)),
arena: self.arena
)),
trailingComma: keepGoing,
arena: self.arena
))
continue
}
enum ExpectedTokenKind: RawTokenKindSubset {
case colon
case spacedBinaryOperator
case unspacedBinaryOperator
case postfixOperator
case prefixOperator
init?(lexeme: Lexer.Lexeme) {
switch (lexeme.tokenKind, lexeme.tokenText) {
case (.colon, _): self = .colon
case (.spacedBinaryOperator, "=="): self = .spacedBinaryOperator
case (.unspacedBinaryOperator, "=="): self = .unspacedBinaryOperator
case (.postfixOperator, "=="): self = .postfixOperator
case (.prefixOperator, "=="): self = .prefixOperator
default: return nil
}
}
var rawTokenKind: RawTokenKind {
switch self {
case .colon: return .colon
case .spacedBinaryOperator: return .spacedBinaryOperator
case .unspacedBinaryOperator: return .unspacedBinaryOperator
case .postfixOperator: return .postfixOperator
case .prefixOperator: return .prefixOperator
}
}
}
let requirement: RawGenericRequirementSyntax.Body
switch self.at(anyIn: ExpectedTokenKind.self) {
case (.colon, let handle)?:
let colon = self.eat(handle)
// A conformance-requirement.
if let (layoutConstraint, handle) = self.at(anyIn: LayoutConstraint.self) {
// Parse a layout constraint.
let constraint = self.eat(handle)
let unexpectedBeforeLeftParen: RawUnexpectedNodesSyntax?
let leftParen: RawTokenSyntax?
let size: RawTokenSyntax?
let comma: RawTokenSyntax?
let alignment: RawTokenSyntax?
let unexpectedBeforeRightParen: RawUnexpectedNodesSyntax?
let rightParen: RawTokenSyntax?
// Unlike the other layout constraints, _Trivial's argument list
// is optional.
if layoutConstraint.hasArguments && (layoutConstraint != .trivialLayout || self.at(.leftParen)) {
(unexpectedBeforeLeftParen, leftParen) = self.expect(.leftParen)
size = self.expectWithoutRecovery(.integerLiteral)
comma = self.consume(if: .comma)
if comma != nil {
alignment = self.expectWithoutRecovery(.integerLiteral)
} else {
alignment = nil
}
(unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen)
} else {
unexpectedBeforeLeftParen = nil
leftParen = nil
size = nil
comma = nil
alignment = nil
unexpectedBeforeRightParen = nil
rightParen = nil
}
requirement = .layoutRequirement(RawLayoutRequirementSyntax(
typeIdentifier: firstType,
colon: colon,
layoutConstraint: constraint,
unexpectedBeforeLeftParen,
leftParen: leftParen,
size: size,
comma: comma,
alignment: alignment,
unexpectedBeforeRightParen,
rightParen: rightParen,
arena: self.arena))
} else {
// Parse the protocol or composition.
let secondType = self.parseType()
requirement = .conformanceRequirement(RawConformanceRequirementSyntax(
leftTypeIdentifier: firstType,
colon: colon,
rightTypeIdentifier: secondType,
arena: self.arena))
}
case (.spacedBinaryOperator, let handle)?,
(.unspacedBinaryOperator, let handle)?,
(.postfixOperator, let handle)?,
(.prefixOperator, let handle)?:
let equal = self.eat(handle)
let secondType = self.parseType()
requirement = .sameTypeRequirement(RawSameTypeRequirementSyntax(
leftTypeIdentifier: firstType,
equalityToken: equal,
rightTypeIdentifier: secondType,
arena: self.arena))
case nil:
requirement = .sameTypeRequirement(RawSameTypeRequirementSyntax(
leftTypeIdentifier: firstType,
equalityToken: RawTokenSyntax(missing: .equal, arena: self.arena),
rightTypeIdentifier: RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena)),
arena: self.arena
))
}
keepGoing = self.consume(if: .comma)
elements.append(RawGenericRequirementSyntax(
body: requirement, trailingComma: keepGoing, arena: self.arena))
} while keepGoing != nil && loopProgress.evaluate(currentToken)
}
return RawGenericWhereClauseSyntax(
unexpectedBeforeWhereKeyword,
whereKeyword: whereKeyword,
requirementList: RawGenericRequirementListSyntax(elements: elements, arena: self.arena),
arena: self.arena)
}
}
extension Parser {
@_spi(RawSyntax)
public mutating func parseMemberDeclListItem() -> RawMemberDeclListItemSyntax? {
if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() {
let item = RawMemberDeclListItemSyntax(
remainingTokens,
decl: RawDeclSyntax(RawMissingDeclSyntax(attributes: nil, modifiers: nil, arena: self.arena)),
semicolon: nil,
arena: self.arena
)
return item
}
let decl: RawDeclSyntax
if self.at(.poundSourceLocationKeyword) {
decl = RawDeclSyntax(self.parsePoundSourceLocationDirective())
} else {
decl = self.parseDeclaration(inMemberDeclList: true)
}
let semi = self.consume(if: .semicolon)
var trailingSemis: [RawTokenSyntax] = []
while let trailingSemi = self.consume(if: .semicolon) {
trailingSemis.append(trailingSemi)
}
if decl.isEmpty && semi == nil && trailingSemis.isEmpty {
return nil
}
return RawMemberDeclListItemSyntax(
decl: decl,
semicolon: semi,
RawUnexpectedNodesSyntax(trailingSemis, arena: self.arena),
arena: self.arena
)
}
/// `introducer` is the `struct`, `class`, ... keyword that is the cause that the member decl block is being parsed.
/// If the left brace is missing, its indentation will be used to judge whether a following `}` was
/// indented to close this code block or a surrounding context. See `expectRightBrace`.
@_spi(RawSyntax)
public mutating func parseMemberDeclList(introducer: RawTokenSyntax? = nil) -> RawMemberDeclBlockSyntax {
var elements = [RawMemberDeclListItemSyntax]()
let (unexpectedBeforeLBrace, lbrace) = self.expect(.leftBrace)
do {
var loopProgress = LoopProgressCondition()
while !self.at(any: [.eof, .rightBrace]) && loopProgress.evaluate(currentToken) {
let newItemAtStartOfLine = self.currentToken.isAtStartOfLine
guard let newElement = self.parseMemberDeclListItem() else {
break
}
if let lastItem = elements.last, lastItem.semicolon == nil && !newItemAtStartOfLine {
elements[elements.count - 1] = RawMemberDeclListItemSyntax(
lastItem.unexpectedBeforeDecl,
decl: lastItem.decl,
lastItem.unexpectedBetweenDeclAndSemicolon,
semicolon: self.missingToken(.semicolon, text: nil),
lastItem.unexpectedAfterSemicolon,
arena: self.arena)
}
elements.append(newElement)
}
}
let (unexpectedBeforeRBrace, rbrace) = self.expectRightBrace(leftBrace: lbrace, introducer: introducer)
let members: RawMemberDeclListSyntax
if elements.isEmpty && (lbrace.isMissing || rbrace.isMissing) {
members = RawMemberDeclListSyntax(elements: [], arena: self.arena)
} else {
members = RawMemberDeclListSyntax(elements: elements, arena: self.arena)
}
return RawMemberDeclBlockSyntax(
unexpectedBeforeLBrace,
leftBrace: lbrace,
members: members,
unexpectedBeforeRBrace,
rightBrace: rbrace,
arena: self.arena)
}
}
extension Parser {
/// Parse an enum 'case' declaration.
///
/// Grammar
/// =======
///
/// union-style-enum-case-clause → attributes? 'indirect'? 'case' union-style-enum-case-list
/// union-style-enum-case-list → union-style-enum-case | union-style-enum-case ',' union-style-enum-case-list
/// union-style-enum-case → enum-case-name tuple-type?
///
/// raw-value-style-enum-case-clause → attributes? 'case' raw-value-style-enum-case-list
/// raw-value-style-enum-case-list → raw-value-style-enum-case | raw-value-style-enum-case ',' raw-value-style-enum-case-list
/// raw-value-style-enum-case → enum-case-name raw-value-assignment?
/// raw-value-assignment → = raw-value-literal
/// raw-value-literal → numeric-literal | static-string-literal | boolean-literal
@_spi(RawSyntax)
public mutating func parseEnumCaseDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawEnumCaseDeclSyntax {
let (unexpectedBeforeCaseKeyword, caseKeyword) = self.eat(handle)
var elements = [RawEnumCaseElementSyntax]()
do {
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
let unexpectedPeriod = self.consume(ifAny: [.period, .prefixPeriod])
let (unexpectedBeforeName, name) = self.expectIdentifier(allowIdentifierLikeKeywords: false, keywordRecovery: true)
let associatedValue: RawParameterClauseSyntax?
if self.at(.leftParen, where: { !$0.isAtStartOfLine }) {
associatedValue = self.parseParameterClause(for: .enumCase)
} else {
associatedValue = nil
}
// See if there's a raw value expression.
let rawValue: RawInitializerClauseSyntax?
if let eq = self.consume(if: .equal) {
let value = self.parseExpression()
rawValue = RawInitializerClauseSyntax(
equal: eq,
value: value,
arena: self.arena
)
} else {
rawValue = nil
}
// Continue through the comma-separated list.
keepGoing = self.consume(if: .comma)
elements.append(RawEnumCaseElementSyntax(
RawUnexpectedNodesSyntax(combining: unexpectedPeriod, unexpectedBeforeName, arena: self.arena),
identifier: name,
associatedValue: associatedValue,
rawValue: rawValue,
trailingComma: keepGoing,
arena: self.arena))
} while keepGoing != nil && loopProgress.evaluate(currentToken)
}
return RawEnumCaseDeclSyntax(
attributes: attrs.attributes, modifiers: attrs.modifiers,
unexpectedBeforeCaseKeyword,
caseKeyword: caseKeyword,
elements: RawEnumCaseElementListSyntax(elements: elements, arena: self.arena),
arena: self.arena)
}
/// Parse an associated type declaration.
///
/// Grammar
/// =======
///
/// protocol-associated-type-declaration → attributes? access-level-modifier? 'associatedtype' typealias-name type-inheritance-clause? typealias-assignment? generic-where-clause?
@_spi(RawSyntax)
public mutating func parseAssociatedTypeDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawAssociatedtypeDeclSyntax {
let (unexpectedBeforeAssocKeyword, assocKeyword) = self.eat(handle)
let (unexpectedBeforeName, name) = self.expectIdentifier(keywordRecovery: true)
if unexpectedBeforeName == nil && name.isMissing {
return RawAssociatedtypeDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeAssocKeyword,
associatedtypeKeyword: assocKeyword,
unexpectedBeforeName,
identifier: name,
inheritanceClause: nil,
initializer: nil,
genericWhereClause: nil,
arena: self.arena)
}
// Detect an attempt to use a type parameter pack.
let ellipsis = tryConsumeEllipsisPrefix()
// Parse optional inheritance clause.
let inheritance: RawTypeInheritanceClauseSyntax?
if self.at(.colon) {
inheritance = self.parseInheritance()
} else {
inheritance = nil
}
// Parse default type, if any.
let defaultType: RawTypeInitializerClauseSyntax?
if let equal = self.consume(if: .equal) {
let type = self.parseType()
defaultType = RawTypeInitializerClauseSyntax(
equal: equal,
value: type,
arena: self.arena
)
} else {
defaultType = nil
}
// Parse a 'where' clause if present.
let whereClause: RawGenericWhereClauseSyntax?
if self.at(.whereKeyword) {
whereClause = self.parseGenericWhereClause()
} else {
whereClause = nil
}
return RawAssociatedtypeDeclSyntax(
attributes: attrs.attributes, modifiers: attrs.modifiers,
unexpectedBeforeAssocKeyword,
associatedtypeKeyword: assocKeyword,
unexpectedBeforeName,
identifier: name,
RawUnexpectedNodesSyntax([ellipsis], arena: self.arena),
inheritanceClause: inheritance,
initializer: defaultType,
genericWhereClause: whereClause,
arena: self.arena)
}
}
extension Parser {
/// Parse an initializer declaration.
///
/// Grammar
/// =======
///
/// initializer-declaration → initializer-head generic-parameter-clause? parameter-clause 'async'? 'throws'? generic-where-clause? initializer-body
/// initializer-declaration → initializer-head generic-parameter-clause? parameter-clause 'async'? 'rethrows' generic-where-clause? initializer-body
///
/// initializer-head → attributes? declaration-modifiers? 'init'
/// initializer-head → attributes? declaration-modifiers? 'init' '?'
/// initializer-head → attributes? declaration-modifiers? 'init' '!'
/// initializer-body → code-block
@_spi(RawSyntax)
public mutating func parseInitializerDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawInitializerDeclSyntax {
let (unexpectedBeforeInitKeyword, initKeyword) = self.eat(handle)
// Parse the '!' or '?' for a failable initializer.
let failable: RawTokenSyntax?
if let parsedFailable = self.consume(ifAny: [.exclamationMark, .postfixQuestionMark, .infixQuestionMark]) {
failable = parsedFailable
} else if let parsedFailable = self.consumeIfContextualPunctuator("!") {
failable = parsedFailable
} else {
failable = nil
}
let generics: RawGenericParameterClauseSyntax?
if self.currentToken.starts(with: "<") {
generics = self.parseGenericParameters()
} else {
generics = nil
}
// Parse the signature.
let signature = self.parseFunctionSignature()
let whereClause: RawGenericWhereClauseSyntax?
if self.at(.whereKeyword) {
whereClause = self.parseGenericWhereClause()
} else {
whereClause = nil
}
let items = self.parseOptionalCodeBlock(allowInitDecl: false)
return RawInitializerDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeInitKeyword,
initKeyword: initKeyword,
optionalMark: failable,
genericParameterClause: generics,
signature: signature,
genericWhereClause: whereClause,
body: items,
arena: self.arena)
}
/// Parse a deinitializer declaration.
///
/// Grammar
/// =======
///
/// deinitializer-declaration → attributes? 'deinit' code-block
@_spi(RawSyntax)
public mutating func parseDeinitializerDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawDeinitializerDeclSyntax {
let (unexpectedBeforeDeinitKeyword, deinitKeyword) = self.eat(handle)
var unexpectedNameAndSignature: [RawSyntax?] = []
unexpectedNameAndSignature.append(self.consume(if: .identifier, where: { !$0.isAtStartOfLine }).map(RawSyntax.init))
if self.at(.leftParen) && !self.currentToken.isAtStartOfLine {
unexpectedNameAndSignature.append(RawSyntax(parseFunctionSignature()))
}
let items = self.parseOptionalCodeBlock()
return RawDeinitializerDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeDeinitKeyword,
deinitKeyword: deinitKeyword,
RawUnexpectedNodesSyntax(unexpectedNameAndSignature, arena: self.arena),
body: items,
arena: self.arena
)
}
}
extension Parser {
public enum ParameterSubject {
case closure
case enumCase
case functionParameters
case indices
var isClosure: Bool {
switch self {
case .closure: return true
case .enumCase: return false
case .functionParameters: return false
case .indices: return false
}
}
}
mutating func parseParameterModifiers(for subject: ParameterSubject) -> RawModifierListSyntax? {
var elements = [RawDeclModifierSyntax]()
var loopCondition = LoopProgressCondition()
MODIFIER_LOOP: while loopCondition.evaluate(currentToken) {
switch self.at(anyIn: ParameterModifier.self) {
case (._const, let handle)?:
elements.append(RawDeclModifierSyntax(name: self.eat(handle), detail: nil, arena: self.arena))
case (.isolated, let handle)? where self.withLookahead({ !$0.startsParameterName(isClosure: subject.isClosure, allowMisplacedSpecifierRecovery: false) }):
elements.append(RawDeclModifierSyntax(name: self.eat(handle), detail: nil, arena: self.arena))
default:
break MODIFIER_LOOP
}
}
if elements.isEmpty {
return nil
} else {
return RawModifierListSyntax(elements: elements, arena: self.arena)
}
}
@_spi(RawSyntax)
public mutating func parseFunctionParameter(for subject: ParameterSubject) -> RawFunctionParameterSyntax {
// Parse any declaration attributes. The exception here is enum cases
// which only allow types, so we do not consume attributes to allow the
// type attribute grammar a chance to examine them.
let attrs: RawAttributeListSyntax?
if case .enumCase = subject {
attrs = nil
} else {
attrs = self.parseAttributeList()
}
let modifiers = parseParameterModifiers(for: subject)
var misplacedSpecifiers: [RawTokenSyntax] = []
while let specifier = self.consume(ifAnyIn: TypeSpecifier.self) {
misplacedSpecifiers.append(specifier)
}
let unexpectedBeforeFirstName: RawUnexpectedNodesSyntax?
let firstName: RawTokenSyntax?
let unexpectedBeforeSecondName: RawUnexpectedNodesSyntax?
let secondName: RawTokenSyntax?
let unexpectedBeforeColon: RawUnexpectedNodesSyntax?
let colon: RawTokenSyntax?
let shouldParseType: Bool
if self.withLookahead({ $0.startsParameterName(isClosure: subject.isClosure, allowMisplacedSpecifierRecovery: false) }) {
if self.currentToken.canBeArgumentLabel(allowDollarIdentifier: true) {
(unexpectedBeforeFirstName, firstName) = self.parseArgumentLabel()
} else {
unexpectedBeforeFirstName = nil
firstName = nil
}
if self.currentToken.canBeArgumentLabel(allowDollarIdentifier: true) {
(unexpectedBeforeSecondName, secondName) = self.parseArgumentLabel()
} else {
unexpectedBeforeSecondName = nil
secondName = nil
}
if subject.isClosure {
unexpectedBeforeColon = nil
colon = self.consume(if: .colon)
shouldParseType = (colon != nil)
} else {
(unexpectedBeforeColon, colon) = self.expect(.colon)
shouldParseType = true
}
} else {
unexpectedBeforeFirstName = nil
firstName = nil
unexpectedBeforeSecondName = nil
secondName = nil
unexpectedBeforeColon = nil
colon = nil
shouldParseType = true
}
let type: RawTypeSyntax?
if shouldParseType {
type = self.parseType(misplacedSpecifiers: misplacedSpecifiers)
} else {
type = nil
}
let ellipsis: RawTokenSyntax?
if self.atContextualPunctuator("...") {
ellipsis = self.consumeAnyToken(remapping: .ellipsis)
} else {
ellipsis = nil
}
let defaultArgument: RawInitializerClauseSyntax?
if self.at(.equal) {
defaultArgument = self.parseDefaultArgument()
} else {
defaultArgument = nil
}
let trailingComma = self.consume(if: .comma)
return RawFunctionParameterSyntax(
attributes: attrs,
modifiers: modifiers,
RawUnexpectedNodesSyntax(combining: misplacedSpecifiers, unexpectedBeforeFirstName, arena: self.arena),
firstName: firstName,
unexpectedBeforeSecondName,
secondName: secondName,
unexpectedBeforeColon,
colon: colon,
type: type,
ellipsis: ellipsis,
defaultArgument: defaultArgument,
trailingComma: trailingComma,
arena: self.arena)
}
@_spi(RawSyntax)
public mutating func parseParameterClause(for subject: ParameterSubject) -> RawParameterClauseSyntax {
let (unexpectedBeforeLParen, lparen) = self.expect(.leftParen)
var elements = [RawFunctionParameterSyntax]()
// If we are missing the left parenthesis and the next token doesn't appear
// to be an argument label, don't parse any parameters.
let shouldSkipParameterParsing = lparen.isMissing && (!currentToken.canBeArgumentLabel(allowDollarIdentifier: true) || currentToken.isKeyword)
if !shouldSkipParameterParsing {
var keepGoing = true
var loopProgress = LoopProgressCondition()
while !self.at(any: [.eof, .rightParen])
&& keepGoing
&& loopProgress.evaluate(currentToken) {
let parameter = parseFunctionParameter(for: subject)
keepGoing = parameter.trailingComma != nil
elements.append(parameter)
}
}
let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen)
let parameters: RawFunctionParameterListSyntax
if elements.isEmpty && (lparen.isMissing || rparen.isMissing) {
parameters = RawFunctionParameterListSyntax(elements: [], arena: self.arena)
} else {
parameters = RawFunctionParameterListSyntax(elements: elements, arena: self.arena)
}
return RawParameterClauseSyntax(
unexpectedBeforeLParen,
leftParen: lparen,
parameterList: parameters,
unexpectedBeforeRParen,
rightParen: rparen,
arena: self.arena)
}
/// If a `throws` keyword appears right in front of the `arrow`, it is returned as `misplacedThrowsKeyword` so it can be synthesized in front of the arrow.
@_spi(RawSyntax)
public mutating func parseFunctionReturnClause() -> (returnClause: RawReturnClauseSyntax, misplacedThrowsKeyword: RawTokenSyntax?) {
let (unexpectedBeforeArrow, arrow) = self.expect(.arrow)
var misplacedThrowsKeyword: RawTokenSyntax? = nil
let unexpectedBeforeReturnType: RawUnexpectedNodesSyntax?
if let throwsKeyword = self.consume(ifAny: [.rethrowsKeyword, .throwsKeyword]) {
misplacedThrowsKeyword = throwsKeyword
unexpectedBeforeReturnType = RawUnexpectedNodesSyntax(elements: [RawSyntax(throwsKeyword)], arena: self.arena)
} else {
unexpectedBeforeReturnType = nil
}
let result = self.parseResultType()
let returnClause = RawReturnClauseSyntax(
unexpectedBeforeArrow,
arrow: arrow,
unexpectedBeforeReturnType,
returnType: result,
arena: self.arena)
return (returnClause, misplacedThrowsKeyword)
}
}
extension Parser {
/// Are we at a regular expression literal that could act as an operator?
private func atRegexLiteralThatCouldBeAnOperator() -> Bool {
guard self.at(.regexLiteral) else {
return false
}
/// Try to re-lex at regex literal as an operator. If it succeeds and
/// consumes the entire regex literal, we're done.
return self.currentToken.tokenText.withBuffer {
(buffer: UnsafeBufferPointer<UInt8>) -> Bool in
var cursor = Lexer.Cursor(input: buffer, previous: 0)
guard buffer[0] == UInt8(ascii: "/") else { return false }
switch (cursor.lexOperatorIdentifier(cursor, cursor)) {
case (.unknown, _):
return false
default:
return cursor.input.isEmpty
}
}
}
@_spi(RawSyntax)
public mutating func parseFuncDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawFunctionDeclSyntax {
let (unexpectedBeforeFuncKeyword, funcKeyword) = self.eat(handle)
let unexpectedBeforeIdentifier: RawUnexpectedNodesSyntax?
let identifier: RawTokenSyntax
if self.at(anyIn: Operator.self) != nil ||
self.at(any: [.exclamationMark, .prefixAmpersand]) ||
self.atRegexLiteralThatCouldBeAnOperator()
{
var name = self.currentToken.tokenText
if name.count > 1 && name.hasSuffix("<") && self.peek().tokenKind == .identifier {
name = SyntaxText(rebasing: name.dropLast())
}
unexpectedBeforeIdentifier = nil
identifier = self.consumePrefix(name, as: .spacedBinaryOperator)
} else {
(unexpectedBeforeIdentifier, identifier) = self.expectIdentifier(keywordRecovery: true)
}
let genericParams: RawGenericParameterClauseSyntax?
if self.currentToken.starts(with: "<") {
genericParams = self.parseGenericParameters()
} else {
genericParams = nil
}
let signature = self.parseFunctionSignature()
let generics: RawGenericWhereClauseSyntax?
if self.at(.whereKeyword) {
generics = self.parseGenericWhereClause()
} else {
generics = nil
}
let body = self.parseOptionalCodeBlock()
return RawFunctionDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeFuncKeyword,
funcKeyword: funcKeyword,
unexpectedBeforeIdentifier,
identifier: identifier,
genericParameterClause: genericParams,
signature: signature,
genericWhereClause: generics,
body: body,
arena: self.arena)
}
@_spi(RawSyntax)
public mutating func parseFunctionSignature() -> RawFunctionSignatureSyntax {
let input = self.parseParameterClause(for: .functionParameters)
let async: RawTokenSyntax?
if let asyncTok = self.consumeIfContextualKeyword("async") {
async = asyncTok
} else if let reasync = self.consumeIfContextualKeyword("reasync") {
async = reasync
} else {
async = nil
}
var throwsKeyword = self.consume(ifAny: [.throwsKeyword, .rethrowsKeyword])
let output: RawReturnClauseSyntax?
if self.at(.arrow) {
let result = self.parseFunctionReturnClause()
output = result.returnClause
if let misplacedThrowsKeyword = result.misplacedThrowsKeyword, throwsKeyword == nil {
throwsKeyword = RawTokenSyntax(missing: misplacedThrowsKeyword.tokenKind, arena: self.arena)
}
} else {
output = nil
}
return RawFunctionSignatureSyntax(
input: input,
asyncOrReasyncKeyword: async,
throwsOrRethrowsKeyword: throwsKeyword,
output: output,
arena: self.arena)
}
}
extension Parser {
/// Parse a subscript declaration.
///
/// Grammar
/// =======
///
/// subscript-declaration → subscript-head subscript-result generic-where-clause? code-block
/// subscript-declaration → subscript-head subscript-result generic-where-clause? getter-setter-block
/// subscript-declaration → subscript-head subscript-result generic-where-clause? getter-setter-keyword-block
/// subscript-head → attributes? declaration-modifiers? 'subscript' generic-parameter-clause? parameter-clause
/// subscript-result → '->' attributes? type
@_spi(RawSyntax)
public mutating func parseSubscriptDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawSubscriptDeclSyntax {
let (unexpectedBeforeSubscriptKeyword, subscriptKeyword) = self.eat(handle)
let unexpectedName: RawTokenSyntax?
if self.at(.identifier) && self.peek().starts(with: "<") || self.peek().tokenKind == .leftParen {
unexpectedName = self.consumeAnyToken()
} else {
unexpectedName = nil
}
let genericParameterClause: RawGenericParameterClauseSyntax?
if self.currentToken.starts(with: "<") {
genericParameterClause = self.parseGenericParameters()
} else {
genericParameterClause = nil
}
let indices = self.parseParameterClause(for: .indices)
let result = self.parseFunctionReturnClause().returnClause
// Parse a 'where' clause if present.
let genericWhereClause: RawGenericWhereClauseSyntax?
if self.at(.whereKeyword) {
genericWhereClause = self.parseGenericWhereClause()
} else {
genericWhereClause = nil
}
// Parse getter and setter.
let accessor: RawSubscriptDeclSyntax.Accessor?
if self.at(.leftBrace) || self.at(anyIn: AccessorKind.self) != nil {
accessor = self.parseGetSet()
} else {
accessor = nil
}
return RawSubscriptDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeSubscriptKeyword,
subscriptKeyword: subscriptKeyword,
RawUnexpectedNodesSyntax([unexpectedName], arena: self.arena),
genericParameterClause: genericParameterClause,
indices: indices,
result: result,
genericWhereClause: genericWhereClause,
accessor: accessor,
arena: self.arena)
}
}
extension Parser {
/// Parse a variable declaration starting with a leading 'let' or 'var' keyword.
///
/// Grammar
/// =======
///
/// constant-declaration → attributes? declaration-modifiers? 'let' pattern-initializer-list
/// pattern-initializer-list → pattern-initializer | pattern-initializer ',' pattern-initializer-list
/// pattern-initializer → pattern initializer?
/// initializer → = expression
///
/// If `inMemberDeclList` is `true`, we know that the next item needs to be a
/// declaration that is started by a keyword. Thus, we in the following case
/// we know that `set` can't start a new declaration and we can thus recover
/// by synthesizing a missing `{` in front of `set`.
/// ```
/// var x: Int
/// set {
/// }
/// }
/// ```
@_spi(RawSyntax)
public mutating func parseLetOrVarDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle,
inMemberDeclList: Bool = false
) -> RawVariableDeclSyntax {
let (unexpectedBeforeIntroducer, introducer) = self.eat(handle)
let hasTryBeforeIntroducer = unexpectedBeforeIntroducer?.containsToken(where: { $0.tokenKind == .tryKeyword }) ?? false
var elements = [RawPatternBindingSyntax]()
do {
var keepGoing: RawTokenSyntax? = nil
var loopProgress = LoopProgressCondition()
repeat {
var (pattern, typeAnnotation) = self.parseTypedPattern()
// Parse an initializer if present.
let initializer: RawInitializerClauseSyntax?
if let equal = self.consume(if: .equal) {
var value = self.parseExpression()
if hasTryBeforeIntroducer && !value.is(RawTryExprSyntax.self) {
value = RawExprSyntax(RawTryExprSyntax(
tryKeyword: missingToken(.tryKeyword, text: nil),
questionOrExclamationMark: nil,
expression: value,
arena: self.arena
))
}
initializer = RawInitializerClauseSyntax(
equal: equal,
value: value,
arena: self.arena
)
} else if self.at(.leftParen), !self.currentToken.isAtStartOfLine,
let typeAnnotationUnwrapped = typeAnnotation {
// If we have a '(' after the type in the annotation, the type annotation
// is probably a constructor call. Rewrite the nodes to remove the type
// annotation and form an initializer clause from it instead.
typeAnnotation = nil
let initExpr = parsePostfixExpressionSuffix(
RawExprSyntax(RawTypeExprSyntax(
type: typeAnnotationUnwrapped.type,
typeAnnotation?.unexpectedAfterType,
arena: self.arena
)),
.basic,
forDirective: false,
pattern: .none
)
initializer = RawInitializerClauseSyntax(
RawUnexpectedNodesSyntax(combining:
typeAnnotationUnwrapped.unexpectedBeforeColon,
typeAnnotationUnwrapped.colon,
typeAnnotationUnwrapped.unexpectedBetweenColonAndType,
arena: self.arena
),
equal: missingToken(.equal, text: nil),
value: initExpr,
arena: self.arena
)
} else {
initializer = nil
}
let accessor: RawPatternBindingSyntax.Accessor?
if self.at(.leftBrace) || (inMemberDeclList && self.at(anyIn: AccessorKind.self) != nil) {
switch self.parseGetSet() {
case .accessors(let accessors):
accessor = .accessors(accessors)
case .getter(let getter):
accessor = .getter(getter)
}
} else {
accessor = nil
}
keepGoing = self.consume(if: .comma)
elements.append(RawPatternBindingSyntax(
pattern: pattern,
typeAnnotation: typeAnnotation,
initializer: initializer,
accessor: accessor,
trailingComma: keepGoing,
arena: self.arena))
} while keepGoing != nil && loopProgress.evaluate(currentToken)
}
return RawVariableDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeIntroducer,
letOrVarKeyword: introducer,
bindings: RawPatternBindingListSyntax(elements: elements, arena: self.arena),
arena: self.arena)
}
struct AccessorIntroducer {
var attributes: RawAttributeListSyntax?
var modifier: RawDeclModifierSyntax?
var kind: AccessorKind
var token: RawTokenSyntax
}
mutating func parseAccessorIntroducer() -> AccessorIntroducer? {
// Check there is an identifier before consuming
var look = self.lookahead()
let _ = look.consumeAttributeList()
let hasModifier = look.consume(ifAny: [], contextualKeywords: ["mutating", "nonmutating", "__consuming"]) != nil
guard let (kind, handle) = look.at(anyIn: AccessorKind.self) else {
return nil
}
let attrs = self.parseAttributeList()
// Parse the contextual keywords for 'mutating' and 'nonmutating' before
// get and set.
let modifier: RawDeclModifierSyntax?
if hasModifier {
modifier = RawDeclModifierSyntax(
name: self.consumeAnyToken(),
detail: nil,
arena: self.arena
)
} else {
modifier = nil
}
let introducer = self.eat(handle)
return AccessorIntroducer(
attributes: attrs, modifier: modifier, kind: kind, token: introducer)
}
@_spi(RawSyntax)
public mutating func parseEffectsSpecifier() -> RawTokenSyntax? {
// 'async'
if let async = self.consumeIfContextualKeyword("async") {
return async
}
// 'reasync'
if let reasync = self.consumeIfContextualKeyword("reasync") {
return reasync
}
// 'throws'/'rethrows'
if let throwsRethrows = self.consume(ifAny: [.throwsKeyword, .rethrowsKeyword]) {
return throwsRethrows
}
// diagnose 'throw'/'try'.
if let throwTry = self.consume(ifAny: [.throwKeyword, .tryKeyword], where: { !$0.isAtStartOfLine }) {
return throwTry
}
return nil
}
@_spi(RawSyntax)
public mutating func parseEffectsSpecifiers() -> [RawTokenSyntax] {
var specifiers = [RawTokenSyntax]()
var loopProgress = LoopProgressCondition()
while let specifier = self.parseEffectsSpecifier(), loopProgress.evaluate(currentToken) {
specifiers.append(specifier)
}
return specifiers
}
/// Parse the body of a variable declaration. This can include explicit
/// getters, setters, and observers, or the body of a computed property.
///
/// Grammar
/// =======
///
/// getter-setter-block → code-block
/// getter-setter-block → { getter-clause setter-clause opt }
/// getter-setter-block → { setter-clause getter-clause }
/// getter-clause → attributes opt mutation-modifier opt get code-block
/// setter-clause → attributes opt mutation-modifier opt set setter-name opt code-block
/// setter-name → ( identifier )
/// getter-setter-keyword-block → { getter-keyword-clause setter-keyword-clause opt }
/// getter-setter-keyword-block → { setter-keyword-clause getter-keyword-clause }
/// getter-keyword-clause → attributes opt mutation-modifier opt get
/// setter-keyword-clause → attributes opt mutation-modifier opt set
/// willSet-didSet-block → { willSet-clause didSet-clause opt }
/// willSet-didSet-block → { didSet-clause willSet-clause opt }
/// willSet-clause → attributes opt willSet setter-name opt code-block
/// didSet-clause → attributes opt didSet setter-name opt code-block
@_spi(RawSyntax)
public mutating func parseGetSet() -> RawSubscriptDeclSyntax.Accessor {
// Parse getter and setter.
let unexpectedBeforeLBrace: RawUnexpectedNodesSyntax?
let lbrace: RawTokenSyntax
if self.at(anyIn: AccessorKind.self) != nil {
unexpectedBeforeLBrace = nil
lbrace = missingToken(.leftBrace, text: nil)
} else {
(unexpectedBeforeLBrace, lbrace) = self.expect(.leftBrace)
}
// Collect all explicit accessors to a list.
var elements = [RawAccessorDeclSyntax]()
do {
var loopProgress = LoopProgressCondition()
while !self.at(any: [.eof, .rightBrace]) && loopProgress.evaluate(currentToken) {
guard let introducer = self.parseAccessorIntroducer() else {
// There can only be an implicit getter if no other accessors were
// seen before this one.
guard elements.isEmpty else {
let (unexpectedBeforeRBrace, rbrace) = self.expect(.rightBrace)
return .accessors(RawAccessorBlockSyntax(
unexpectedBeforeLBrace,
leftBrace: lbrace,
accessors: RawAccessorListSyntax(elements: elements, arena: self.arena),
unexpectedBeforeRBrace,
rightBrace: rbrace,
arena: self.arena))
}
var body = [RawCodeBlockItemSyntax]()
var codeBlockProgress = LoopProgressCondition()
while !self.at(.rightBrace),
let newItem = self.parseCodeBlockItem(),
codeBlockProgress.evaluate(currentToken) {
body.append(newItem)
}
let (unexpectedBeforeRBrace, rbrace) = self.expect(.rightBrace)
return .getter(RawCodeBlockSyntax(
unexpectedBeforeLBrace,
leftBrace: lbrace,
statements: RawCodeBlockItemListSyntax(elements: body, arena: self.arena),
unexpectedBeforeRBrace,
rightBrace: rbrace,
arena: self.arena))
}
// 'set' and 'willSet' can have an optional name. This isn't valid in a
// protocol, but we parse and then reject it for better QoI.
//
// set-name ::= '(' identifier ')'
let parameter: RawAccessorParameterSyntax?
if [ AccessorKind.set, .willSet, .didSet ].contains(introducer.kind), let lparen = self.consume(if: .leftParen) {
let (unexpectedBeforeName, name) = self.expectIdentifier()
let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen)
parameter = RawAccessorParameterSyntax(
leftParen: lparen,
unexpectedBeforeName,
name: name,
unexpectedBeforeRParen,
rightParen: rparen,
arena: self.arena
)
} else {
parameter = nil
}
// Next, parse effects specifiers. While it's only valid to have them
// on 'get' accessors, we also emit diagnostics if they show up on others.
let asyncKeyword: RawTokenSyntax?
let throwsKeyword: RawTokenSyntax?
if self.at(anyIn: EffectsSpecifier.self) != nil {
asyncKeyword = self.parseEffectsSpecifier()
throwsKeyword = self.parseEffectsSpecifier()
} else {
asyncKeyword = nil
throwsKeyword = nil
}
let body = self.parseOptionalCodeBlock()
elements.append(RawAccessorDeclSyntax(
attributes: introducer.attributes,
modifier: introducer.modifier,
accessorKind: introducer.token,
parameter: parameter,
asyncKeyword: asyncKeyword,
throwsKeyword: throwsKeyword,
body: body,
arena: self.arena))
}
}
let (unexpectedBeforeRBrace, rbrace) = self.expect(.rightBrace)
return .accessors(RawAccessorBlockSyntax(
unexpectedBeforeLBrace,
leftBrace: lbrace,
accessors: RawAccessorListSyntax(elements: elements, arena: self.arena),
unexpectedBeforeRBrace,
rightBrace: rbrace,
arena: self.arena))
}
}
extension Parser {
/// Parse a typealias declaration.
///
/// Grammar
/// =======
///
/// typealias-declaration → attributes? access-level-modifier? 'typealias' typealias-name generic-parameter-clause? typealias-assignment
/// typealias-name → identifier
/// typealias-assignment → '=' type
@_spi(RawSyntax)
public mutating func parseTypealiasDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawTypealiasDeclSyntax {
let (unexpectedBeforeTypealiasKeyword, typealiasKeyword) = self.eat(handle)
let (unexpectedBeforeName, name) = self.expectIdentifier(keywordRecovery: true)
// Parse a generic parameter list if it is present.
let generics: RawGenericParameterClauseSyntax?
if self.currentToken.starts(with: "<") {
generics = self.parseGenericParameters()
} else {
generics = nil
}
// Parse the binding alias.
let unexpectedBeforeEqual: RawUnexpectedNodesSyntax?
let equal: RawTokenSyntax
if let colon = self.consume(if: .colon) {
unexpectedBeforeEqual = RawUnexpectedNodesSyntax(elements: [RawSyntax(colon)], arena: self.arena)
equal = missingToken(.equal, text: nil)
} else {
(unexpectedBeforeEqual, equal) = self.expect(.equal)
}
let value = self.parseType()
let initializer = RawTypeInitializerClauseSyntax(
unexpectedBeforeEqual,
equal: equal,
value: value,
arena: self.arena
)
// Parse a 'where' clause if present.
let genericWhereClause: RawGenericWhereClauseSyntax?
if self.at(.whereKeyword) {
genericWhereClause = self.parseGenericWhereClause()
} else {
genericWhereClause = nil
}
return RawTypealiasDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeTypealiasKeyword,
typealiasKeyword: typealiasKeyword,
unexpectedBeforeName,
identifier: name,
genericParameterClause: generics,
initializer: initializer,
genericWhereClause: genericWhereClause,
arena: self.arena)
}
}
extension Parser {
/// Parse an operator declaration.
///
/// Grammar
/// =======
///
/// operator-declaration → prefix-operator-declaration | postfix-operator-declaration | infix-operator-declaration
/// prefix-operator-declaration → 'prefix' 'operator' operator
/// postfix-operator-declaration → 'postfix' 'operator' operator
/// infix-operator-declaration → 'infix' 'operator' operator infix-operator-group?
/// infix-operator-group → ':' precedence-group-name
@_spi(RawSyntax)
public mutating func parseOperatorDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawOperatorDeclSyntax {
let (unexpectedBeforeOperatorKeyword, operatorKeyword) = self.eat(handle)
let unexpectedBeforeName: RawUnexpectedNodesSyntax?
let name: RawTokenSyntax
switch self.canRecoverTo(anyIn: OperatorLike.self) {
case (_, let handle)?:
(unexpectedBeforeName, name) = self.eat(handle)
default:
if let identifier = self.consume(ifAny: [.identifier, .dollarIdentifier], where: { !$0.isAtStartOfLine }) {
// Recover if the developer tried to use an identifier as the operator name
unexpectedBeforeName = RawUnexpectedNodesSyntax([identifier], arena: self.arena)
} else {
unexpectedBeforeName = nil
}
name = missingToken(.spacedBinaryOperator, text: nil)
}
// Eat any subsequent tokens that are not separated to the operator by trivia.
// The developer most likely intended these to be part of the operator name.
var identifiersAfterOperatorName: [RawTokenSyntax] = []
var loopProgress = LoopProgressCondition()
while (identifiersAfterOperatorName.last ?? name).trailingTriviaByteLength == 0,
self.currentToken.leadingTriviaByteLength == 0,
!self.at(any: [.colon, .leftBrace, .eof]),
loopProgress.evaluate(self.currentToken) {
identifiersAfterOperatorName.append(consumeAnyToken())
}
// Parse (or diagnose) a specified precedence group and/or
// designated protocol. These both look like identifiers, so we
// parse them both as identifiers here and sort it out in type
// checking.
let precedenceAndTypes: RawOperatorPrecedenceAndTypesSyntax?
if let colon = self.consume(if: .colon) {
let (unexpectedBeforeIdentifier, identifier) = self.expectIdentifier(keywordRecovery: true)
var types = [RawDesignatedTypeElementSyntax]()
while let comma = self.consume(if: .comma) {
// FIXME: The compiler accepts... anything here. This is a bug.
// let (unexpectedBeforeDesignatedType, designatedType) = self.expectIdentifier()
let designatedType = self.consumeAnyToken()
types.append(RawDesignatedTypeElementSyntax(
leadingComma: comma,
name: designatedType,
arena: self.arena))
}
precedenceAndTypes = RawOperatorPrecedenceAndTypesSyntax(
colon: colon,
unexpectedBeforeIdentifier,
precedenceGroup: identifier,
designatedTypes: RawDesignatedTypeListSyntax(
elements: types, arena: self.arena),
arena: self.arena)
} else {
precedenceAndTypes = nil
}
let unexpectedAtEnd: RawUnexpectedNodesSyntax?
if let leftBrace = self.consume(if: .leftBrace) {
let attributeList = self.parsePrecedenceGroupAttributeListSyntax()
let rightBrace = self.consume(if: .rightBrace)
unexpectedAtEnd = RawUnexpectedNodesSyntax(
elements: [
RawSyntax(leftBrace),
RawSyntax(attributeList),
rightBrace.map(RawSyntax.init)
].compactMap({ $0 }),
arena: self.arena
)
} else {
unexpectedAtEnd = nil
}
return RawOperatorDeclSyntax(
attributes: attrs.attributes,
modifiers: attrs.modifiers,
unexpectedBeforeOperatorKeyword,
operatorKeyword: operatorKeyword,
unexpectedBeforeName,
identifier: name,
RawUnexpectedNodesSyntax(identifiersAfterOperatorName, arena: self.arena),
operatorPrecedenceAndTypes: precedenceAndTypes,
unexpectedAtEnd,
arena: self.arena
)
}
/// Parse a precedence group declaration.
///
/// Grammar
/// =======
///
/// precedence-group-declaration → precedencegroup precedence-group-name '{' precedence-group-attributes? '}'
///
/// precedence-group-attributes → precedence-group-attribute precedence-group-attributes?
/// precedence-group-attribute → precedence-group-relation
/// precedence-group-attribute → precedence-group-assignment
/// precedence-group-attribute → precedence-group-associativity
///
/// precedence-group-relation → 'higherThan' ':' precedence-group-names
/// precedence-group-relation → 'lowerThan' ':' precedence-group-names
///
/// precedence-group-assignment → 'assignment' ':' boolean-literal
///
/// precedence-group-associativity → 'associativity' ':' 'left'
/// precedence-group-associativity → 'associativity' ':' 'right'
/// precedence-group-associativity → 'associativity' ':' 'none'
///
/// precedence-group-names → precedence-group-name | precedence-group-name ',' precedence-group-names
/// precedence-group-name → identifier
@_spi(RawSyntax)
public mutating func parsePrecedenceGroupDeclaration(
_ attrs: DeclAttributes,
_ handle: RecoveryConsumptionHandle
) -> RawPrecedenceGroupDeclSyntax {
let (unexpectedBeforeGroup, group) = self.eat(handle)
let (unexpectedBeforeIdentifier, identifier) = self.expectIdentifier(keywordRecovery: true)
let (unexpectedBeforeLBrace, lbrace) = self.expect(.leftBrace)
let groupAttributes = self.parsePrecedenceGroupAttributeListSyntax()
let (unexpectedBeforeRBrace, rbrace) = self.expect(.rightBrace)
return RawPrecedenceGroupDeclSyntax(
attributes: attrs.attributes, modifiers: attrs.modifiers,
unexpectedBeforeGroup,
precedencegroupKeyword: group,
unexpectedBeforeIdentifier,
identifier: identifier,
unexpectedBeforeLBrace,
leftBrace: lbrace,
groupAttributes: groupAttributes,
unexpectedBeforeRBrace,
rightBrace: rbrace,
arena: self.arena)
}
@_spi(RawSyntax)
public mutating func parsePrecedenceGroupAttributeListSyntax() -> RawPrecedenceGroupAttributeListSyntax {
enum LabelText: SyntaxText, ContextualKeywords {
case associativity = "associativity"
case assignment = "assignment"
case higherThan = "higherThan"
case lowerThan = "lowerThan"
}
var elements = [RawPrecedenceGroupAttributeListSyntax.Element]()
do {
var attributesProgress = LoopProgressCondition()
LOOP: while !self.at(any: [.eof, .rightBrace]) && attributesProgress.evaluate(currentToken) {
switch self.at(anyIn: LabelText.self) {
case (.associativity, let handle)?:
let associativity = self.eat(handle)
let (unexpectedBeforeColon, colon) = self.expect(.colon)
let (unexpectedBeforeValue, value) = self.expectIdentifier()
elements.append(.precedenceGroupAssociativity(RawPrecedenceGroupAssociativitySyntax(
associativityKeyword: associativity,
unexpectedBeforeColon,
colon: colon,
unexpectedBeforeValue,
value: value,
arena: self.arena
)))
case (.assignment, let handle)?:
let assignmentKeyword = self.eat(handle)
let (unexpectedBeforeColon, colon) = self.expect(.colon)
let (unexpectedBeforeFlag, flag) = self.expectAny([.trueKeyword, .falseKeyword], default: .trueKeyword)
let unexpectedAfterFlag: RawUnexpectedNodesSyntax?
if flag.isMissing, let unexpectedIdentifier = self.consume(if: .identifier, where: { !$0.isAtStartOfLine }) {
unexpectedAfterFlag = RawUnexpectedNodesSyntax([unexpectedIdentifier], arena: self.arena)
} else {
unexpectedAfterFlag = nil
}
elements.append(.precedenceGroupAssignment(RawPrecedenceGroupAssignmentSyntax(
assignmentKeyword: assignmentKeyword,
unexpectedBeforeColon,
colon: colon,
unexpectedBeforeFlag,
flag: flag,
unexpectedAfterFlag,
arena: self.arena
)))
case (.higherThan, let handle)?,
(.lowerThan, let handle)?:
// "lowerThan" and "higherThan" are contextual keywords.
let level = self.eat(handle)
let (unexpectedBeforeColon, colon) = self.expect(.colon)
var names = [RawPrecedenceGroupNameElementSyntax]()
do {
var keepGoing: RawTokenSyntax? = nil
var namesProgress = LoopProgressCondition()
repeat {
let (unexpectedBeforeName, name) = self.expectIdentifier()
keepGoing = self.consume(if: .comma)
names.append(RawPrecedenceGroupNameElementSyntax(
unexpectedBeforeName,
name: name,
trailingComma: keepGoing,
arena: self.arena
))
} while keepGoing != nil && namesProgress.evaluate(currentToken)
}
elements.append(.precedenceGroupRelation(RawPrecedenceGroupRelationSyntax(
higherThanOrLowerThan: level,
unexpectedBeforeColon,
colon: colon,
otherNames: RawPrecedenceGroupNameListSyntax(elements: names, arena: self.arena),
arena: self.arena)))
case nil:
break LOOP
}
}
}
return RawPrecedenceGroupAttributeListSyntax(elements: elements, arena: self.arena)
}
}
extension Parser {
enum PoundDiagnosticKind {
case error(poundError: RawTokenSyntax)
case warning(poundWarning: RawTokenSyntax)
}
@_spi(RawSyntax)
public mutating func parsePoundDiagnosticDeclaration() -> RawDeclSyntax {
enum ExpectedTokenKind: RawTokenKindSubset {
case poundErrorKeyword
case poundWarningKeyword
init?(lexeme: Lexer.Lexeme) {
switch lexeme.tokenKind {
case .poundErrorKeyword: self = .poundErrorKeyword
case .poundWarningKeyword: self = .poundWarningKeyword
default: return nil
}
}
var rawTokenKind: RawTokenKind {
switch self {
case .poundErrorKeyword: return .poundErrorKeyword
case .poundWarningKeyword: return .poundWarningKeyword
}
}
}
let directive: PoundDiagnosticKind
switch self.at(anyIn: ExpectedTokenKind.self) {
case (.poundErrorKeyword, let handle)?:
directive = .error(poundError: self.eat(handle))
case (.poundWarningKeyword, let handle)?:
directive = .warning(poundWarning: self.eat(handle))
case nil:
directive = .error(poundError: RawTokenSyntax(missing: .poundErrorKeyword, arena: self.arena))
}
let (unexpectedBeforeLeftParen, leftParen) = self.expect(.leftParen)
let stringLiteral: RawStringLiteralExprSyntax
if self.at(.stringLiteral) {
stringLiteral = self.parseStringLiteral()
} else {
stringLiteral = RawStringLiteralExprSyntax(
openDelimiter: nil,
openQuote: RawTokenSyntax(missing: .stringQuote, arena: self.arena),
segments: RawStringLiteralSegmentsSyntax(elements: [], arena: self.arena),
closeQuote: RawTokenSyntax(missing: .stringQuote, arena: self.arena),
closeDelimiter: nil,
arena: self.arena
)
}
let (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen)
switch directive {
case .error(let tok):
return RawDeclSyntax(RawPoundErrorDeclSyntax(
poundError: tok,
unexpectedBeforeLeftParen,
leftParen: leftParen,
message: stringLiteral,
unexpectedBeforeRightParen,
rightParen: rightParen,
arena: self.arena))
case .warning(let tok):
return RawDeclSyntax(RawPoundWarningDeclSyntax(
poundWarning: tok,
unexpectedBeforeLeftParen,
leftParen: leftParen,
message: stringLiteral,
unexpectedBeforeRightParen,
rightParen: rightParen,
arena: self.arena))
}
}
/// Parse a macro expansion as an declaration.
///
///
/// Grammar
/// =======
///
/// macro-expansion-declaration → '#' identifier expr-call-suffix?
mutating func parseMacroExpansionDeclaration() -> RawMacroExpansionDeclSyntax {
let poundKeyword = self.consumeAnyToken()
let (unexpectedBeforeMacro, macro) = self.expectIdentifier()
// Parse the optional generic argument list.
let generics: RawGenericArgumentClauseSyntax?
if self.lookahead().canParseAsGenericArgumentList() {
generics = self.parseGenericArguments()
} else {
generics = nil
}
// Parse the optional parenthesized argument list.
let leftParen = self.consume(if: .leftParen, where: { !$0.isAtStartOfLine })
let args: [RawTupleExprElementSyntax]
let unexpectedBeforeRightParen: RawUnexpectedNodesSyntax?
let rightParen: RawTokenSyntax?
if leftParen != nil {
args = parseArgumentListElements(pattern: .none)
(unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen)
} else {
args = []
unexpectedBeforeRightParen = nil
rightParen = nil
}
// Parse the optional trailing closures.
let trailingClosure: RawClosureExprSyntax?
let additionalTrailingClosures: RawMultipleTrailingClosureElementListSyntax?
if self.at(.leftBrace),
self.lookahead().isValidTrailingClosure(.trailingClosure) {
(trailingClosure, additionalTrailingClosures) =
self.parseTrailingClosures(.trailingClosure)
} else {
trailingClosure = nil
additionalTrailingClosures = nil
}
return RawMacroExpansionDeclSyntax(
poundToken: poundKeyword,
unexpectedBeforeMacro,
macro: macro,
genericArguments: generics,
leftParen: leftParen,
argumentList: RawTupleExprElementListSyntax(
elements: args, arena: self.arena
),
unexpectedBeforeRightParen,
rightParen: rightParen,
trailingClosure: trailingClosure,
additionalTrailingClosures: additionalTrailingClosures,
arena: self.arena
)
}
}
| apache-2.0 | 0b84778fb6f8ef201ac5c05329ecbbe7 | 36.469338 | 184 | 0.667509 | 4.874309 | false | false | false | false |
andersonlucasg3/Swift.Binary | Sources/SwiftBinary/IvarArray.swift | 1 | 3793 | //
// Created by Anderson Lucas C. Ramos on 11/04/17.
//
import Foundation
public class IvarArray<T> : IvarToken<Array<T>> {
public override func findType() throws {
let type = T.self
if type is Int.Type || type is Int64.Type {
self.type = .arrayInt64
} else if type is Int8.Type {
self.type = .arrayInt8
} else if type is Int16.Type {
self.type = .arrayInt16
} else if type is Int32.Type {
self.type = .arrayInt32
} else if type is Float.Type {
self.type = .arrayFloat
} else if type is Double.Type {
self.type = .arrayDouble
} else if type is String.Type {
self.type = .arrayString
} else if type is Data.Type {
self.type = .arrayData
} else if type is Bool.Type {
self.type = .arrayBool
} else if type is IvarObject.Type {
self.type = .arrayObject
} else {
throw NSError(domain: "Type [[[\(T.self)]]] not supported yet.", code: -1)
}
}
// MARK: encoding implementations
public override func encode() throws -> Data {
var data = Data()
self.writeOther(self.type.rawValue, info: &data)
self.writeString(self.name, into: &data)
try self.writeValue(into: &data)
return data
}
public override func writeValue(into data: inout Data) throws {
self.writeOther(Int32(self.value.count), info: &data)
if DataType.isFixedSize(type: T.self) {
for fixed in self.value {
self.writeOther(fixed, info: &data)
}
} else if DataType.isSizeable(type: T.self) {
for sizable in self.value {
if sizable is String || sizable is NSString {
self.writeString(sizable as! String, into: &data)
} else {
self.writeData(sizable as! Data, into: &data)
}
}
} else {
for token in self.value {
data.append(try (token as! Token).encode())
}
}
}
// MARK: decoding implementations
public override func decode(data: Data) throws {
var bytes = data.withUnsafeBytes({ $0 as UnsafePointer<UInt8> })
try self.decode(bytes: &bytes)
}
public override func decode(bytes: inout UnsafePointer<UInt8>) throws {
self.type = DataType(rawValue: self.readOther(from: &bytes))
self.name = self.readString(from: &bytes)
try self.readValue(from: &bytes)
}
public override func readValue(from bytes: inout UnsafePointer<UInt8>) throws {
let count = Int(self.readOther(from: &bytes) as Int32)
self.value = self.getTypedArray() as! [T]
if DataType.isFixedSize(type: T.self) {
for _ in 0..<count {
self.value.append(self.readOther(from: &bytes))
}
} else if DataType.isSizeable(type: T.self) {
for _ in 0..<count {
let type = DataType(rawValue: self.readOther(from: &bytes, advance: false))
if type == .string {
self.value.append(self.readString(from: &bytes) as! T)
} else {
self.value.append(self.readData(from: &bytes) as! T)
}
}
} else {
for _ in 0..<count {
let type = DataType(rawValue: self.readOther(from: &bytes, advance: false))
let decodable = try type!.getIvarInstance()
try decodable.decode(bytes: &bytes)
self.value.append(decodable as! T)
}
}
}
fileprivate func getTypedArray() -> [AnyObject] {
switch self.type {
case .arrayInt8: return Array<IvarToken<Int8>>() as [AnyObject]
case .arrayInt16: return Array<IvarToken<Int16>>() as [AnyObject]
case .arrayInt32: return Array<IvarToken<Int32>>() as [AnyObject]
case .arrayInt64: return Array<IvarToken<Int64>>() as [AnyObject]
case .arrayFloat: return Array<IvarToken<Float>>() as [AnyObject]
case .arrayDouble: return Array<IvarToken<Double>>() as [AnyObject]
case .arrayString: return Array<IvarToken<String>>() as [AnyObject]
case .arrayData: return Array<IvarToken<Data>>() as [AnyObject]
case .arrayBool: return Array<IvarToken<Bool>>() as [AnyObject]
default:
return Array<AnyObject>()
}
}
}
| mit | dac2fd988c62452e79528eeacb200d22 | 30.347107 | 80 | 0.669655 | 3.155574 | false | false | false | false |
milseman/swift | stdlib/public/core/Mirror.swift | 4 | 34761 | //===--- Mirror.swift -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// FIXME: ExistentialCollection needs to be supported before this will work
// without the ObjC Runtime.
/// Representation of the sub-structure and optional "display style"
/// of any arbitrary subject instance.
///
/// Describes the parts---such as stored properties, collection
/// elements, tuple elements, or the active enumeration case---that
/// make up a particular instance. May also supply a "display style"
/// property that suggests how this structure might be rendered.
///
/// Mirrors are used by playgrounds and the debugger.
public struct Mirror {
/// Representation of descendant classes that don't override
/// `customMirror`.
///
/// Note that the effect of this setting goes no deeper than the
/// nearest descendant class that overrides `customMirror`, which
/// in turn can determine representation of *its* descendants.
internal enum _DefaultDescendantRepresentation {
/// Generate a default mirror for descendant classes that don't
/// override `customMirror`.
///
/// This case is the default.
case generated
/// Suppress the representation of descendant classes that don't
/// override `customMirror`.
///
/// This option may be useful at the root of a class cluster, where
/// implementation details of descendants should generally not be
/// visible to clients.
case suppressed
}
/// Representation of ancestor classes.
///
/// A `CustomReflectable` class can control how its mirror will
/// represent ancestor classes by initializing the mirror with a
/// `AncestorRepresentation`. This setting has no effect on mirrors
/// reflecting value type instances.
public enum AncestorRepresentation {
/// Generate a default mirror for all ancestor classes.
///
/// This case is the default.
///
/// - Note: This option generates default mirrors even for
/// ancestor classes that may implement `CustomReflectable`'s
/// `customMirror` requirement. To avoid dropping an ancestor class
/// customization, an override of `customMirror` should pass
/// `ancestorRepresentation: .Customized(super.customMirror)` when
/// initializing its `Mirror`.
case generated
/// Use the nearest ancestor's implementation of `customMirror` to
/// create a mirror for that ancestor. Other classes derived from
/// such an ancestor are given a default mirror.
///
/// The payload for this option should always be
/// "`{ super.customMirror }`":
///
/// var customMirror: Mirror {
/// return Mirror(
/// self,
/// children: ["someProperty": self.someProperty],
/// ancestorRepresentation: .Customized({ super.customMirror })) // <==
/// }
case customized(() -> Mirror)
/// Suppress the representation of all ancestor classes. The
/// resulting `Mirror`'s `superclassMirror` is `nil`.
case suppressed
}
/// Reflect upon the given `subject`.
///
/// If the dynamic type of `subject` conforms to `CustomReflectable`,
/// the resulting mirror is determined by its `customMirror` property.
/// Otherwise, the result is generated by the language.
///
/// - Note: If the dynamic type of `subject` has value semantics,
/// subsequent mutations of `subject` will not observable in
/// `Mirror`. In general, though, the observability of such
/// mutations is unspecified.
public init(reflecting subject: Any) {
if case let customized as CustomReflectable = subject {
self = customized.customMirror
} else {
self = Mirror(
legacy: _reflect(subject),
subjectType: type(of: subject))
}
}
/// An element of the reflected instance's structure. The optional
/// `label` may be used when appropriate, e.g. to represent the name
/// of a stored property or of an active `enum` case, and will be
/// used for lookup when `String`s are passed to the `descendant`
/// method.
public typealias Child = (label: String?, value: Any)
/// The type used to represent sub-structure.
///
/// Depending on your needs, you may find it useful to "upgrade"
/// instances of this type to `AnyBidirectionalCollection` or
/// `AnyRandomAccessCollection`. For example, to display the last
/// 20 children of a mirror if they can be accessed efficiently, you
/// might write:
///
/// if let b = AnyBidirectionalCollection(someMirror.children) {
/// var i = xs.index(b.endIndex, offsetBy: -20,
/// limitedBy: b.startIndex) ?? b.startIndex
/// while i != xs.endIndex {
/// print(b[i])
/// b.formIndex(after: &i)
/// }
/// }
public typealias Children = AnyCollection<Child>
/// A suggestion of how a `Mirror`'s `subject` is to be interpreted.
///
/// Playgrounds and the debugger will show a representation similar
/// to the one used for instances of the kind indicated by the
/// `DisplayStyle` case name when the `Mirror` is used for display.
public enum DisplayStyle {
case `struct`, `class`, `enum`, tuple, optional, collection
case dictionary, `set`
}
static func _noSuperclassMirror() -> Mirror? { return nil }
/// Returns the legacy mirror representing the part of `subject`
/// corresponding to the superclass of `staticSubclass`.
internal static func _legacyMirror(
_ subject: AnyObject, asClass targetSuperclass: AnyClass) -> _Mirror? {
// get a legacy mirror and the most-derived type
var cls: AnyClass = type(of: subject)
var clsMirror = _reflect(subject)
// Walk up the chain of mirrors/classes until we find staticSubclass
while let superclass: AnyClass = _getSuperclass(cls) {
guard let superclassMirror = clsMirror._superMirror() else { break }
if superclass == targetSuperclass { return superclassMirror }
clsMirror = superclassMirror
cls = superclass
}
return nil
}
@_semantics("optimize.sil.specialize.generic.never")
@inline(never)
@_versioned
internal static func _superclassIterator<Subject>(
_ subject: Subject, _ ancestorRepresentation: AncestorRepresentation
) -> () -> Mirror? {
if let subjectClass = Subject.self as? AnyClass,
let superclass = _getSuperclass(subjectClass) {
switch ancestorRepresentation {
case .generated:
return {
self._legacyMirror(_unsafeDowncastToAnyObject(fromAny: subject), asClass: superclass).map {
Mirror(legacy: $0, subjectType: superclass)
}
}
case .customized(let makeAncestor):
return {
Mirror(_unsafeDowncastToAnyObject(fromAny: subject), subjectClass: superclass,
ancestor: makeAncestor())
}
case .suppressed:
break
}
}
return Mirror._noSuperclassMirror
}
/// Represent `subject` with structure described by `children`,
/// using an optional `displayStyle`.
///
/// If `subject` is not a class instance, `ancestorRepresentation`
/// is ignored. Otherwise, `ancestorRepresentation` determines
/// whether ancestor classes will be represented and whether their
/// `customMirror` implementations will be used. By default, a
/// representation is automatically generated and any `customMirror`
/// implementation is bypassed. To prevent bypassing customized
/// ancestors, `customMirror` overrides should initialize the
/// `Mirror` with:
///
/// ancestorRepresentation: .customized({ super.customMirror })
///
/// - Note: The traversal protocol modeled by `children`'s indices
/// (`ForwardIndex`, `BidirectionalIndex`, or
/// `RandomAccessIndex`) is captured so that the resulting
/// `Mirror`'s `children` may be upgraded later. See the failable
/// initializers of `AnyBidirectionalCollection` and
/// `AnyRandomAccessCollection` for details.
public init<Subject, C : Collection>(
_ subject: Subject,
children: C,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
) where C.Element == Child
// FIXME(ABI) (Revert Where Clauses): Remove these
, C.SubSequence : Collection, C.SubSequence.Indices : Collection, C.Indices : Collection
{
self.subjectType = Subject.self
self._makeSuperclassMirror = Mirror._superclassIterator(
subject, ancestorRepresentation)
self.children = Children(children)
self.displayStyle = displayStyle
self._defaultDescendantRepresentation
= subject is CustomLeafReflectable ? .suppressed : .generated
}
/// Represent `subject` with child values given by
/// `unlabeledChildren`, using an optional `displayStyle`. The
/// result's child labels will all be `nil`.
///
/// This initializer is especially useful for the mirrors of
/// collections, e.g.:
///
/// extension MyArray : CustomReflectable {
/// var customMirror: Mirror {
/// return Mirror(self, unlabeledChildren: self, displayStyle: .collection)
/// }
/// }
///
/// If `subject` is not a class instance, `ancestorRepresentation`
/// is ignored. Otherwise, `ancestorRepresentation` determines
/// whether ancestor classes will be represented and whether their
/// `customMirror` implementations will be used. By default, a
/// representation is automatically generated and any `customMirror`
/// implementation is bypassed. To prevent bypassing customized
/// ancestors, `customMirror` overrides should initialize the
/// `Mirror` with:
///
/// ancestorRepresentation: .Customized({ super.customMirror })
///
/// - Note: The traversal protocol modeled by `children`'s indices
/// (`ForwardIndex`, `BidirectionalIndex`, or
/// `RandomAccessIndex`) is captured so that the resulting
/// `Mirror`'s `children` may be upgraded later. See the failable
/// initializers of `AnyBidirectionalCollection` and
/// `AnyRandomAccessCollection` for details.
public init<Subject, C : Collection>(
_ subject: Subject,
unlabeledChildren: C,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
)
// FIXME(ABI) (Revert Where Clauses): Remove these two clauses
where C.SubSequence : Collection, C.Indices : Collection
{
self.subjectType = Subject.self
self._makeSuperclassMirror = Mirror._superclassIterator(
subject, ancestorRepresentation)
let lazyChildren =
unlabeledChildren.lazy.map { Child(label: nil, value: $0) }
self.children = Children(lazyChildren)
self.displayStyle = displayStyle
self._defaultDescendantRepresentation
= subject is CustomLeafReflectable ? .suppressed : .generated
}
/// Represent `subject` with labeled structure described by
/// `children`, using an optional `displayStyle`.
///
/// Pass a dictionary literal with `String` keys as `children`. Be
/// aware that although an *actual* `Dictionary` is
/// arbitrarily-ordered, the ordering of the `Mirror`'s `children`
/// will exactly match that of the literal you pass.
///
/// If `subject` is not a class instance, `ancestorRepresentation`
/// is ignored. Otherwise, `ancestorRepresentation` determines
/// whether ancestor classes will be represented and whether their
/// `customMirror` implementations will be used. By default, a
/// representation is automatically generated and any `customMirror`
/// implementation is bypassed. To prevent bypassing customized
/// ancestors, `customMirror` overrides should initialize the
/// `Mirror` with:
///
/// ancestorRepresentation: .customized({ super.customMirror })
///
/// - Note: The resulting `Mirror`'s `children` may be upgraded to
/// `AnyRandomAccessCollection` later. See the failable
/// initializers of `AnyBidirectionalCollection` and
/// `AnyRandomAccessCollection` for details.
public init<Subject>(
_ subject: Subject,
children: DictionaryLiteral<String, Any>,
displayStyle: DisplayStyle? = nil,
ancestorRepresentation: AncestorRepresentation = .generated
) {
self.subjectType = Subject.self
self._makeSuperclassMirror = Mirror._superclassIterator(
subject, ancestorRepresentation)
let lazyChildren = children.lazy.map { Child(label: $0.0, value: $0.1) }
self.children = Children(lazyChildren)
self.displayStyle = displayStyle
self._defaultDescendantRepresentation
= subject is CustomLeafReflectable ? .suppressed : .generated
}
/// The static type of the subject being reflected.
///
/// This type may differ from the subject's dynamic type when `self`
/// is the `superclassMirror` of another mirror.
public let subjectType: Any.Type
/// A collection of `Child` elements describing the structure of the
/// reflected subject.
public let children: Children
/// Suggests a display style for the reflected subject.
public let displayStyle: DisplayStyle?
public var superclassMirror: Mirror? {
return _makeSuperclassMirror()
}
internal let _makeSuperclassMirror: () -> Mirror?
internal let _defaultDescendantRepresentation: _DefaultDescendantRepresentation
}
/// A type that explicitly supplies its own mirror.
///
/// You can create a mirror for any type using the `Mirror(reflect:)`
/// initializer, but if you are not satisfied with the mirror supplied for
/// your type by default, you can make it conform to `CustomReflectable` and
/// return a custom `Mirror` instance.
public protocol CustomReflectable {
/// The custom mirror for this instance.
///
/// If this type has value semantics, the mirror should be unaffected by
/// subsequent mutations of the instance.
var customMirror: Mirror { get }
}
/// A type that explicitly supplies its own mirror, but whose
/// descendant classes are not represented in the mirror unless they
/// also override `customMirror`.
public protocol CustomLeafReflectable : CustomReflectable {}
//===--- Addressing -------------------------------------------------------===//
/// A protocol for legitimate arguments to `Mirror`'s `descendant`
/// method.
///
/// Do not declare new conformances to this protocol; they will not
/// work as expected.
// FIXME(ABI)#49 (Sealed Protocols): this protocol should be "non-open" and you shouldn't be able to
// create conformances.
public protocol MirrorPath {}
extension Int : MirrorPath {}
extension String : MirrorPath {}
extension Mirror {
internal struct _Dummy : CustomReflectable {
var mirror: Mirror
var customMirror: Mirror { return mirror }
}
/// Return a specific descendant of the reflected subject, or `nil`
/// Returns a specific descendant of the reflected subject, or `nil`
/// if no such descendant exists.
///
/// A `String` argument selects the first `Child` with a matching label.
/// An integer argument *n* select the *n*th `Child`. For example:
///
/// var d = Mirror(reflecting: x).descendant(1, "two", 3)
///
/// is equivalent to:
///
/// var d = nil
/// let children = Mirror(reflecting: x).children
/// if let p0 = children.index(children.startIndex,
/// offsetBy: 1, limitedBy: children.endIndex) {
/// let grandChildren = Mirror(reflecting: children[p0].value).children
/// SeekTwo: for g in grandChildren {
/// if g.label == "two" {
/// let greatGrandChildren = Mirror(reflecting: g.value).children
/// if let p1 = greatGrandChildren.index(
/// greatGrandChildren.startIndex,
/// offsetBy: 3, limitedBy: greatGrandChildren.endIndex) {
/// d = greatGrandChildren[p1].value
/// }
/// break SeekTwo
/// }
/// }
/// }
///
/// As you can see, complexity for each element of the argument list
/// depends on the argument type and capabilities of the collection
/// used to initialize the corresponding subject's parent's mirror.
/// Each `String` argument results in a linear search. In short,
/// this function is suitable for exploring the structure of a
/// `Mirror` in a REPL or playground, but don't expect it to be
/// efficient.
public func descendant(
_ first: MirrorPath, _ rest: MirrorPath...
) -> Any? {
var result: Any = _Dummy(mirror: self)
for e in [first] + rest {
let children = Mirror(reflecting: result).children
let position: Children.Index
if case let label as String = e {
position = children.index { $0.label == label } ?? children.endIndex
}
else if let offset = (e as? Int).map({ Int64($0) }) ?? (e as? Int64) {
position = children.index(children.startIndex,
offsetBy: offset,
limitedBy: children.endIndex) ?? children.endIndex
}
else {
_preconditionFailure(
"Someone added a conformance to MirrorPath; that privilege is reserved to the standard library")
}
if position == children.endIndex { return nil }
result = children[position].value
}
return result
}
}
//===--- Legacy _Mirror Support -------------------------------------------===//
extension Mirror.DisplayStyle {
/// Construct from a legacy `_MirrorDisposition`
internal init?(legacy: _MirrorDisposition) {
switch legacy {
case .`struct`: self = .`struct`
case .`class`: self = .`class`
case .`enum`: self = .`enum`
case .tuple: self = .tuple
case .aggregate: return nil
case .indexContainer: self = .collection
case .keyContainer: self = .dictionary
case .membershipContainer: self = .`set`
case .container: preconditionFailure("unused!")
case .optional: self = .optional
case .objCObject: self = .`class`
}
}
}
internal func _isClassSuperMirror(_ t: Any.Type) -> Bool {
#if _runtime(_ObjC)
return t == _ClassSuperMirror.self || t == _ObjCSuperMirror.self
#else
return t == _ClassSuperMirror.self
#endif
}
extension _Mirror {
internal func _superMirror() -> _Mirror? {
if self.count > 0 {
let childMirror = self[0].1
if _isClassSuperMirror(type(of: childMirror)) {
return childMirror
}
}
return nil
}
}
/// When constructed using the legacy reflection infrastructure, the
/// resulting `Mirror`'s `children` collection will always be
/// upgradable to `AnyRandomAccessCollection` even if it doesn't
/// exhibit appropriate performance. To avoid this pitfall, convert
/// mirrors to use the new style, which only present forward
/// traversal in general.
internal extension Mirror {
/// An adapter that represents a legacy `_Mirror`'s children as
/// a `Collection` with integer `Index`. Note that the performance
/// characteristics of the underlying `_Mirror` may not be
/// appropriate for random access! To avoid this pitfall, convert
/// mirrors to use the new style, which only present forward
/// traversal in general.
internal struct LegacyChildren : RandomAccessCollection {
typealias Indices = CountableRange<Int>
init(_ oldMirror: _Mirror) {
self._oldMirror = oldMirror
}
var startIndex: Int {
return _oldMirror._superMirror() == nil ? 0 : 1
}
var endIndex: Int { return _oldMirror.count }
subscript(position: Int) -> Child {
let (label, childMirror) = _oldMirror[position]
return (label: label, value: childMirror.value)
}
internal let _oldMirror: _Mirror
}
/// Initialize for a view of `subject` as `subjectClass`.
///
/// - parameter ancestor: A Mirror for a (non-strict) ancestor of
/// `subjectClass`, to be injected into the resulting hierarchy.
///
/// - parameter legacy: Either `nil`, or a legacy mirror for `subject`
/// as `subjectClass`.
internal init(
_ subject: AnyObject,
subjectClass: AnyClass,
ancestor: Mirror,
legacy legacyMirror: _Mirror? = nil
) {
if ancestor.subjectType == subjectClass
|| ancestor._defaultDescendantRepresentation == .suppressed {
self = ancestor
}
else {
let legacyMirror = legacyMirror ?? Mirror._legacyMirror(
subject, asClass: subjectClass)!
self = Mirror(
legacy: legacyMirror,
subjectType: subjectClass,
makeSuperclassMirror: {
_getSuperclass(subjectClass).map {
Mirror(
subject,
subjectClass: $0,
ancestor: ancestor,
legacy: legacyMirror._superMirror())
}
})
}
}
internal init(
legacy legacyMirror: _Mirror,
subjectType: Any.Type,
makeSuperclassMirror: (() -> Mirror?)? = nil
) {
if let makeSuperclassMirror = makeSuperclassMirror {
self._makeSuperclassMirror = makeSuperclassMirror
}
else if let subjectSuperclass = _getSuperclass(subjectType) {
self._makeSuperclassMirror = {
legacyMirror._superMirror().map {
Mirror(legacy: $0, subjectType: subjectSuperclass) }
}
}
else {
self._makeSuperclassMirror = Mirror._noSuperclassMirror
}
self.subjectType = subjectType
self.children = Children(LegacyChildren(legacyMirror))
self.displayStyle = DisplayStyle(legacy: legacyMirror.disposition)
self._defaultDescendantRepresentation = .generated
}
}
//===--- QuickLooks -------------------------------------------------------===//
/// The sum of types that can be used as a Quick Look representation.
public enum PlaygroundQuickLook {
/// Plain text.
case text(String)
/// An integer numeric value.
case int(Int64)
/// An unsigned integer numeric value.
case uInt(UInt64)
/// A single precision floating-point numeric value.
case float(Float32)
/// A double precision floating-point numeric value.
case double(Float64)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// An image.
case image(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A sound.
case sound(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A color.
case color(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A bezier path.
case bezierPath(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// An attributed string.
case attributedString(Any)
// FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type.
/// A rectangle.
case rectangle(Float64, Float64, Float64, Float64)
// FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type.
/// A point.
case point(Float64, Float64)
// FIXME: Uses explicit coordinates to avoid coupling a particular Cocoa type.
/// A size.
case size(Float64, Float64)
/// A boolean value.
case bool(Bool)
// FIXME: Uses explicit values to avoid coupling a particular Cocoa type.
/// A range.
case range(Int64, Int64)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A GUI view.
case view(Any)
// FIXME: Uses an Any to avoid coupling a particular Cocoa type.
/// A graphical sprite.
case sprite(Any)
/// A Uniform Resource Locator.
case url(String)
/// Raw data that has already been encoded in a format the IDE understands.
case _raw([UInt8], String)
}
extension PlaygroundQuickLook {
/// Initialize for the given `subject`.
///
/// If the dynamic type of `subject` conforms to
/// `CustomPlaygroundQuickLookable`, returns the result of calling
/// its `customPlaygroundQuickLook` property. Otherwise, returns
/// a `PlaygroundQuickLook` synthesized for `subject` by the
/// language. Note that in some cases the result may be
/// `.Text(String(reflecting: subject))`.
///
/// - Note: If the dynamic type of `subject` has value semantics,
/// subsequent mutations of `subject` will not observable in
/// `Mirror`. In general, though, the observability of such
/// mutations is unspecified.
public init(reflecting subject: Any) {
if let customized = subject as? CustomPlaygroundQuickLookable {
self = customized.customPlaygroundQuickLook
}
else if let customized = subject as? _DefaultCustomPlaygroundQuickLookable {
self = customized._defaultCustomPlaygroundQuickLook
}
else {
if let q = _reflect(subject).quickLookObject {
self = q
}
else {
self = .text(String(reflecting: subject))
}
}
}
}
/// A type that explicitly supplies its own playground Quick Look.
///
/// A Quick Look can be created for an instance of any type by using the
/// `PlaygroundQuickLook(reflecting:)` initializer. If you are not satisfied
/// with the representation supplied for your type by default, you can make it
/// conform to the `CustomPlaygroundQuickLookable` protocol and provide a
/// custom `PlaygroundQuickLook` instance.
public protocol CustomPlaygroundQuickLookable {
/// A custom playground Quick Look for this instance.
///
/// If this type has value semantics, the `PlaygroundQuickLook` instance
/// should be unaffected by subsequent mutations.
var customPlaygroundQuickLook: PlaygroundQuickLook { get }
}
// A workaround for <rdar://problem/26182650>
// FIXME(ABI)#50 (Dynamic Dispatch for Class Extensions) though not if it moves out of stdlib.
public protocol _DefaultCustomPlaygroundQuickLookable {
var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook { get }
}
//===--- General Utilities ------------------------------------------------===//
// This component could stand alone, but is used in Mirror's public interface.
/// A lightweight collection of key-value pairs.
///
/// Use a `DictionaryLiteral` instance when you need an ordered collection of
/// key-value pairs and don't require the fast key lookup that the
/// `Dictionary` type provides. Unlike key-value pairs in a true dictionary,
/// neither the key nor the value of a `DictionaryLiteral` instance must
/// conform to the `Hashable` protocol.
///
/// You initialize a `DictionaryLiteral` instance using a Swift dictionary
/// literal. Besides maintaining the order of the original dictionary literal,
/// `DictionaryLiteral` also allows duplicates keys. For example:
///
/// let recordTimes: DictionaryLiteral = ["Florence Griffith-Joyner": 10.49,
/// "Evelyn Ashford": 10.76,
/// "Evelyn Ashford": 10.79,
/// "Marlies Gohr": 10.81]
/// print(recordTimes.first!)
/// // Prints "("Florence Griffith-Joyner", 10.49)"
///
/// Some operations that are efficient on a dictionary are slower when using
/// `DictionaryLiteral`. In particular, to find the value matching a key, you
/// must search through every element of the collection. The call to
/// `index(where:)` in the following example must traverse the whole
/// collection to find the element that matches the predicate:
///
/// let runner = "Marlies Gohr"
/// if let index = recordTimes.index(where: { $0.0 == runner }) {
/// let time = recordTimes[index].1
/// print("\(runner) set a 100m record of \(time) seconds.")
/// } else {
/// print("\(runner) couldn't be found in the records.")
/// }
/// // Prints "Marlies Gohr set a 100m record of 10.81 seconds."
///
/// Dictionary Literals as Function Parameters
/// ------------------------------------------
///
/// When calling a function with a `DictionaryLiteral` parameter, you can pass
/// a Swift dictionary literal without causing a `Dictionary` to be created.
/// This capability can be especially important when the order of elements in
/// the literal is significant.
///
/// For example, you could create an `IntPairs` structure that holds a list of
/// two-integer tuples and use an initializer that accepts a
/// `DictionaryLiteral` instance.
///
/// struct IntPairs {
/// var elements: [(Int, Int)]
///
/// init(_ elements: DictionaryLiteral<Int, Int>) {
/// self.elements = Array(elements)
/// }
/// }
///
/// When you're ready to create a new `IntPairs` instance, use a dictionary
/// literal as the parameter to the `IntPairs` initializer. The
/// `DictionaryLiteral` instance preserves the order of the elements as
/// passed.
///
/// let pairs = IntPairs([1: 2, 1: 1, 3: 4, 2: 1])
/// print(pairs.elements)
/// // Prints "[(1, 2), (1, 1), (3, 4), (2, 1)]"
public struct DictionaryLiteral<Key, Value> : ExpressibleByDictionaryLiteral {
/// Creates a new `DictionaryLiteral` instance from the given dictionary
/// literal.
///
/// The order of the key-value pairs is kept intact in the resulting
/// `DictionaryLiteral` instance.
public init(dictionaryLiteral elements: (Key, Value)...) {
self._elements = elements
}
internal let _elements: [(Key, Value)]
}
/// `Collection` conformance that allows `DictionaryLiteral` to
/// interoperate with the rest of the standard library.
extension DictionaryLiteral : RandomAccessCollection {
public typealias Indices = CountableRange<Int>
/// The position of the first element in a nonempty collection.
///
/// If the `DictionaryLiteral` instance is empty, `startIndex` is equal to
/// `endIndex`.
public var startIndex: Int { return 0 }
/// The collection's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the `DictionaryLiteral` instance is empty, `endIndex` is equal to
/// `startIndex`.
public var endIndex: Int { return _elements.endIndex }
// FIXME(ABI)#174 (Type checker): a typealias is needed to prevent <rdar://20248032>
/// The element type of a `DictionaryLiteral`: a tuple containing an
/// individual key-value pair.
public typealias Element = (key: Key, value: Value)
/// Accesses the element at the specified position.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the collection that is not equal to the
/// `endIndex` property.
/// - Returns: The key-value pair at position `position`.
public subscript(position: Int) -> Element {
return _elements[position]
}
}
extension String {
/// Creates a string representing the given value.
///
/// Use this initializer to convert an instance of any type to its preferred
/// representation as a `String` instance. The initializer creates the
/// string representation of `instance` in one of the following ways,
/// depending on its protocol conformance:
///
/// - If `instance` conforms to the `TextOutputStreamable` protocol, the
/// result is obtained by calling `instance.write(to: s)` on an empty
/// string `s`.
/// - If `instance` conforms to the `CustomStringConvertible` protocol, the
/// result is `instance.description`.
/// - If `instance` conforms to the `CustomDebugStringConvertible` protocol,
/// the result is `instance.debugDescription`.
/// - An unspecified result is supplied automatically by the Swift standard
/// library.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library.
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(describing: p))
/// // Prints "Point(x: 21, y: 30)"
///
/// After adding `CustomStringConvertible` conformance by implementing the
/// `description` property, `Point` provides its own custom representation.
///
/// extension Point: CustomStringConvertible {
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// print(String(describing: p))
/// // Prints "(21, 30)"
public init<Subject>(describing instance: Subject) {
self.init()
_print_unlocked(instance, &self)
}
/// Creates a string with a detailed representation of the given value,
/// suitable for debugging.
///
/// Use this initializer to convert an instance of any type to its custom
/// debugging representation. The initializer creates the string
/// representation of `instance` in one of the following ways, depending on
/// its protocol conformance:
///
/// - If `subject` conforms to the `CustomDebugStringConvertible` protocol,
/// the result is `subject.debugDescription`.
/// - If `subject` conforms to the `CustomStringConvertible` protocol, the
/// result is `subject.description`.
/// - If `subject` conforms to the `TextOutputStreamable` protocol, the
/// result is obtained by calling `subject.write(to: s)` on an empty
/// string `s`.
/// - An unspecified result is supplied automatically by the Swift standard
/// library.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library.
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(reflecting: p))
/// // Prints "p: Point = {
/// // x = 21
/// // y = 30
/// // }"
///
/// After adding `CustomDebugStringConvertible` conformance by implementing
/// the `debugDescription` property, `Point` provides its own custom
/// debugging representation.
///
/// extension Point: CustomDebugStringConvertible {
/// var debugDescription: String {
/// return "Point(x: \(x), y: \(y))"
/// }
/// }
///
/// print(String(reflecting: p))
/// // Prints "Point(x: 21, y: 30)"
public init<Subject>(reflecting subject: Subject) {
self.init()
_debugPrint_unlocked(subject, &self)
}
}
/// Reflection for `Mirror` itself.
extension Mirror : CustomStringConvertible {
public var description: String {
return "Mirror for \(self.subjectType)"
}
}
extension Mirror : CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [:])
}
}
@available(*, unavailable, renamed: "MirrorPath")
public typealias MirrorPathType = MirrorPath
| apache-2.0 | c0403252cbf161dfbdb13d469a8c9252 | 36.377419 | 106 | 0.662898 | 4.705699 | false | false | false | false |
caicai0/ios_demo | load/thirdpart/SwiftSoup/ParseErrorList.swift | 5 | 1313 | //
// ParseErrorList.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 19/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
public class ParseErrorList {
private static let INITIAL_CAPACITY: Int = 16
private let maxSize: Int
private let initialCapacity: Int
private var array: Array<ParseError?> = Array<ParseError>()
init(_ initialCapacity: Int, _ maxSize: Int) {
self.maxSize = maxSize
self.initialCapacity = initialCapacity
array = Array(repeating: nil, count: maxSize)
}
func canAddError() -> Bool {
return array.count < maxSize
}
func getMaxSize() -> Int {
return maxSize
}
static func noTracking() -> ParseErrorList {
return ParseErrorList(0, 0)
}
static func tracking(_ maxSize: Int) -> ParseErrorList {
return ParseErrorList(INITIAL_CAPACITY, maxSize)
}
// // you need to provide the Equatable functionality
// static func ==(leftFoo: Foo, rightFoo: Foo) -> Bool {
// return ObjectIdentifier(leftFoo) == ObjectIdentifier(rightFoo)
// }
open func add(_ e: ParseError) {
array.append(e)
}
open func add(_ index: Int, _ element: ParseError) {
array.insert(element, at: index)
}
}
| mit | cb3de38308e04e2eb471104f5a6794ee | 24.230769 | 76 | 0.625762 | 4.205128 | false | false | false | false |
aiwalle/LiveProject | LiveProject/Home/LJWaterFallView/LJWaterFallLayout.swift | 1 | 2481 | //
// LJWaterFallLayout.swift
// LiveProject
//
// Created by liang on 2017/7/28.
// Copyright © 2017年 liang. All rights reserved.
//
import UIKit
protocol LJWaterFallLayoutDataSource : class {
func waterFallLayout(_ layout : LJWaterFallLayout, itemIndex : Int) -> CGFloat
}
class LJWaterFallLayout: UICollectionViewFlowLayout {
var cols : Int = 2
weak var dataSource : LJWaterFallLayoutDataSource?
fileprivate lazy var attributes : [UICollectionViewLayoutAttributes] = [UICollectionViewLayoutAttributes]()
fileprivate lazy var maxHeight : CGFloat = self.sectionInset.top + self.sectionInset.bottom
fileprivate lazy var heights : [CGFloat] = Array(repeating: self.sectionInset.top, count: self.cols)
}
extension LJWaterFallLayout {
override func prepare() {
super.prepare()
guard let collectionView = self.collectionView else { return }
// 获取cell对应的attributes --> 一个cell对应一个attribute
let cellCount = collectionView.numberOfItems(inSection: 0)
let colNumber = cols
let itemW = (collectionView.bounds.width - sectionInset.left - sectionInset.right - (CGFloat(colNumber) - 1) * minimumInteritemSpacing) / CGFloat(colNumber)
for i in attributes.count..<cellCount {
let indexPath = IndexPath(item: i, section: 0)
let attribute = UICollectionViewLayoutAttributes(forCellWith: indexPath)
guard let itemH = dataSource?.waterFallLayout(self, itemIndex: i) else {
fatalError("请设置数据源")
}
let minH = heights.min()!
let minIndex = heights.index(of: minH)!
let itemX = sectionInset.left + (minimumInteritemSpacing + itemW) * CGFloat(minIndex)
let itemY = minH
attribute.frame = CGRect(x: itemX, y: itemY, width: itemW, height: CGFloat(itemH))
attributes.append(attribute)
heights[minIndex] = attribute.frame.maxY + minimumLineSpacing
}
maxHeight = heights.max()! - minimumLineSpacing
}
}
extension LJWaterFallLayout {
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
return attributes
}
}
extension LJWaterFallLayout {
override var collectionViewContentSize: CGSize {
return CGSize(width: 0, height: maxHeight + sectionInset.bottom)
}
}
| mit | d3c28d9f49d3270540f3ac25c223c031 | 35.477612 | 164 | 0.665303 | 4.937374 | false | false | false | false |
OlegNovosad/Sample | iOS/Severenity/Services/PlacesService.swift | 2 | 5051 | //
// LocationsServerManager.swift
// severenityProject
//
// Created by Yura Yasinskyy on 13.09.16.
// Copyright © 2016 severenity. All rights reserved.
//
import UIKit
import Alamofire
import RealmSwift
import FBSDKLoginKit
class PlacesService: NSObject {
private var realm: Realm?
// MARK: Init
override init() {
super.init()
do {
realm = try Realm()
} catch {
Log.error(message: "Realm error: \(error.localizedDescription)", sender: self)
}
}
// MARK: Methods
/**- This method returns Array with data in callback.
It checks whether data is already in Realm. If yes than it goes to getDataFromRealm method
if no than it calls requestDataFromServer to get data from server.*/
func provideData(_ completion: @escaping (_ result: NSArray) -> Void) {
if checkIfRealmIsEmpty() {
Log.info(message: "Realm is empty, asking server for data", sender: self)
requestDataFromServer {
self.getDataFromRealm { data in
completion(data)
}
}
} else {
Log.info(message: "Realm is not empty, loading data", sender: self)
getDataFromRealm { data in
completion(data)
}
}
}
private func checkIfRealmIsEmpty() -> Bool {
let realmReadQuery = realm?.objects(RealmPlace.self)
return realmReadQuery?.isEmpty ?? false
}
/**- requestDataFromServer gets called when Realm is empty. It than perform request to server,
gets JSON response, parse it and set to Realm. When completed, returns to provideData method.*/
private func requestDataFromServer(_ completion: @escaping () -> Void) {
guard let serverURL = URL.init(string: kPlacesServerURL) else {
Log.error(message: "Cannot create server url", sender: self)
return
}
let serverRequest = URLRequest.init(url: serverURL)
Alamofire.request(serverRequest).responseJSON { response in
guard let places = response.result.value as? [[String: Any]] else {
Log.error(message: "Response does not contain places.", sender: self)
return
}
for place in places {
guard let owners = place["owners"] as? [String] else {
Log.error(message: "Can't find owners in place item.", sender: self)
return
}
for owner in owners where owner == FBSDKAccessToken.current().userID {
// Adding data to Realm DB
let placeInRealm = RealmPlace(place: place)
for object in owners {
let placeOwner = RealmPlaceOwner()
placeOwner.owner = object
placeInRealm.owners.append(placeOwner)
}
placeInRealm.addToDB()
}
}
completion()
}
}
/**- This method makes query to Realm data model and gets all needed data
that is than returned in Array. */
private func getDataFromRealm(_ completion: (_ data: NSArray) -> Void) {
let realmReadQuery = realm?.objects(RealmPlace.self)
var dataFromRealm: [AnyObject] = []
var ownersArray: [AnyObject] = []
var isRightOwnerFound = false
guard let query = realmReadQuery else {
Log.error(message: "Error creating Realm read query", sender: self)
return
}
for place in query {
let tempArray = Array(place.owners)
for owner in tempArray {
ownersArray.append(owner.owner as AnyObject)
isRightOwnerFound = owner.owner == FBSDKAccessToken.current().userID
}
if isRightOwnerFound {
let dictionaryWithPlace: [String: AnyObject] = [
"placeId" : place.placeId as AnyObject,
"name" : place.name as AnyObject,
"type" : place.type as AnyObject,
"createdDate" : place.createdDate as AnyObject,
"owners" : ownersArray as AnyObject,
"lat" : place.lat as AnyObject,
"lng" : place.lng as AnyObject
]
dataFromRealm.append(dictionaryWithPlace as AnyObject)
}
ownersArray.removeAll()
}
completion(dataFromRealm as NSArray)
}
// Try to drop data by type 'Location' etc., not all data
private func dropDataInRealm() {
do {
try realm?.write {
realm?.deleteAll()
}
} catch {
Log.error(message: "Realm error: \(error.localizedDescription)", sender: self)
}
}
}
| apache-2.0 | a048ac2b00de9d2d687068024c8cea1e | 34.314685 | 100 | 0.544158 | 5.121704 | false | false | false | false |
skarppi/cavok | CAVOK/Weather/Layers/ColorRamp.swift | 1 | 3019 | //
// ColorRamp.swift
// CAVOK
//
// Created by Juho Kolehmainen on 18.09.16.
// Copyright © 2016 Juho Kolehmainen. All rights reserved.
//
import Foundation
struct GridStep {
var lower: Int32
var upper: Int32
var fromHue: Int32
var toHue: Int32
func int4() -> [Int32] {
return [lower, upper, fromHue, toHue]
}
}
let purple: [Int32] = [300, 359]
let red: [Int32] = [0, 45]
let orange: [Int32] = [45, 60]
let yellow: [Int32] = [60, 75]
let green: [Int32] = [75, 190]
let blue: [Int32] = [190, 200]
let hues: [[Int32]] = [ purple, red, orange, yellow, green, blue]
let brightness: CGFloat = 0.81
class ColorRamp {
let unit: String
let steps: [GridStep]
let titles: [String]
init(module: Module) {
unit = module.unit
let sorted = Array(module.legend).sorted(by: {$0.key < $1.key})
let keys = sorted.map { (key, _) in Int32(key)! }
titles = sorted.map { (_, value) in value }
steps = keys.enumerated().map { (i, step) in
let next = (i + 1) < keys.count ? keys[i + 1] : Int32.max
return GridStep(lower: step, upper: next, fromHue: hues[i][0], toHue: hues[i][1])
}
}
func color(for value: Int32, alpha: CGFloat = 1) -> UIColor {
if let step = steps.reversed().first(where: { value >= $0.lower}) {
// Point-Slope Equation of a Line: y - y1 = m(x - x1)
let slope = CGFloat(step.toHue - step.fromHue) / CGFloat(step.upper - step.lower)
let hue = slope * CGFloat(value - step.lower) + CGFloat(step.fromHue)
return UIColor(hue: hue/360, saturation: 1, brightness: brightness, alpha: alpha)
} else {
return UIColor.black
}
}
class func color(for date: Date, alpha: CGFloat = 1) -> UIColor {
let minutes = Int(-date.timeIntervalSinceNow / 60)
return ColorRamp.color(forMinutes: minutes, alpha: alpha)
}
class func color(forMinutes minutes: Int, alpha: CGFloat = 1) -> UIColor {
if minutes < 0 {
return UIColor(hue: CGFloat(blue[0])/360, saturation: 1, brightness: brightness, alpha: alpha)
} else if minutes <= 30 {
return ColorRamp.color(for: .VFR, alpha: alpha)
} else if minutes <= 90 {
return ColorRamp.color(for: .MVFR, alpha: alpha)
} else {
return ColorRamp.color(for: .IFR, alpha: alpha)
}
}
class func color(for condition: WeatherConditions, alpha: CGFloat = 1) -> UIColor {
switch condition {
case .VFR:
return UIColor(hue: 120/360, saturation: 1, brightness: brightness, alpha: alpha)
case .MVFR:
return UIColor(hue: CGFloat(orange[0])/360, saturation: 1, brightness: brightness, alpha: alpha)
case .IFR:
return UIColor(hue: 0, saturation: 1, brightness: 0.61, alpha: alpha)
default:
return UIColor(hue: 0, saturation: 0, brightness: 0.1, alpha: alpha)
}
}
}
| mit | 1d8f2c27e8d181dc79d2593d4b647870 | 31.106383 | 108 | 0.58383 | 3.453089 | false | false | false | false |
dankogai/swift-interval | macOS.playground/Pages/Quadratic Equasion.xcplaygroundpage/Contents.swift | 1 | 387 | //: [Previous](@previous)
import Interval
//: cf http://verifiedby.me/adiary/070
func det<T:IntervalElement>(_ a:Interval<T>, _ b:Interval<T>, _ c:Interval<T>)->Interval<T> {
return Interval<T>.sqrt(b*b - T(4)*a*c)
}
let a = Interval(1.0)
let b = Interval(1e15)
let c = Interval(1e14)
let x = (-b + det(a,b,c)) / (2.0 * a)
let y = (2.0 * c) / (-b - det(a,b,c))
//: [Next](@next)
| mit | 1e701d5c5d928ff5ab7913fe34ee983d | 23.1875 | 93 | 0.583979 | 2.317365 | false | false | false | false |
acegreen/Bitcoin-Sample-iOS-App | BitLive/Generics/QueryHelper.swift | 1 | 1068 | //
// QueryHelper.swift
// BitLive
//
// Created by Ace Green on 7/14/16.
// Copyright © 2016 Ace Green. All rights reserved.
//
import UIKit
open class QueryHelper {
static let sharedInstance = QueryHelper()
open func queryWith(_ queryString: String, completionHandler: @escaping (_ result: () throws -> Data) -> Void) -> Void {
if let queryUrl: URL = URL(string: queryString) {
let session = URLSession.shared
let task = session.dataTask(with: queryUrl, completionHandler: { (queryData, response, error) -> Void in
guard error == nil else { return completionHandler({throw Constants.Errors.errorQueryingForData}) }
guard queryData != nil, let queryData = queryData else {
return completionHandler({throw Constants.Errors.queryDataEmpty})
}
return completionHandler({ queryData })
})
task.resume()
}
}
}
| mit | 5ab0d27090486008cd9849873fb9828f | 30.382353 | 124 | 0.557638 | 5.033019 | false | false | false | false |
iMemon/ISYSSnapStoryViewController | ISYSSnapStoryViewController/Classes/SnapTimer/SnapTimer/SnapTimerCircleLayer.swift | 1 | 2010 | //
// SnapTimerCircleLayer.swift
// SnapTimer
//
// Created by Andres on 8/29/16.
// Copyright © 2016 Andres. All rights reserved.
//
import UIKit
@objc
public class SnapTimerCircleLayer: CALayer {
@NSManaged var circleColor: CGColor
@NSManaged var startAngle: CGFloat
@NSManaged var radius: CGFloat
override init(layer: Any) {
super.init(layer: layer)
if let layer = layer as? SnapTimerCircleLayer {
startAngle = layer.startAngle
circleColor = layer.circleColor
radius = layer.radius
} else {
startAngle = 0
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init() {
super.init()
}
func animation(_ key: String) -> CAAnimation {
let animation = CABasicAnimation(keyPath: key)
if let pLayer = self.presentation(), let value = pLayer.value(forKey: key) {
animation.fromValue = value
}
let animationTiming = CATransaction.animationTimingFunction() ?? CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
let duration = CATransaction.animationDuration()
animation.timingFunction = animationTiming
animation.duration = duration
return animation
}
override public func action(forKey key: String) -> CAAction? {
if key == "startAngle" {
return self.animation(key)
}
return super.action(forKey: key)
}
override public class func needsDisplay(forKey key: String) -> Bool {
if key == "startAngle" || key == "circleColor" || key == "radius" {
return true
}
return super.needsDisplay(forKey: key)
}
override public func draw(in ctx: CGContext) {
let center = CGPoint(x:bounds.width/2, y: bounds.height/2)
ctx.beginPath()
ctx.setLineWidth(0)
ctx.move(to: CGPoint(x: center.x, y: center.y))
ctx.addArc(
center: center,
radius: self.radius,
startAngle: self.startAngle,
endAngle: SnapTimerView.endAngle,
clockwise: false
)
ctx.setFillColor(self.circleColor)
ctx.drawPath(using: .fillStroke)
}
}
| mit | 75219f1c2d8e3e5de91799417cb441ce | 24.43038 | 124 | 0.690891 | 3.659381 | false | false | false | false |
liuweihaocool/iOS_06_liuwei | 新浪微博_swift/新浪微博_swift/class/Main/Model/LWStatus.swift | 1 | 2988 | //
// LWStatus.swift
// 新浪微博_swift
//
// Created by LiuWei on 15/12/3.
// Copyright © 2015年 liuwei. All rights reserved.
//
import UIKit
class LWStatus: NSObject {
/// 创建时间
var created_at: String?//"created_at": Wed Nov 25 18:53:55 +0800 2015,
/// 创建ID
var id: Int = 0
/// 微博内容
var text: String?
/// 消息来源
var source: String?
/// 微博 缩略图 图片地址数组: 数组里面存放的是字典
var pic_urls: [[String: AnyObject]]?
/*用户模型,如果不做特殊处理,kvc将返回数据中的字典赋值给user ,
普通的属性使用kvc赋值,如果user属性我们拦截,不使用kvc赋值
我们自己来字典转模型,在赋值给user
*/
/// 用户模型,如果不做特殊处理,KVC会将返回数据中 的字典赋值给 user
var user:LWUser?
/// 转发数
var reposts_count: Int = 0
/// 评论数
var comments_count: Int = 0
/// 表态数
var attitudes_count: Int = 0
/// kvc设置值
init(dict: [String:AnyObject]){
super.init()
setValuesForKeysWithDictionary(dict)
}
/// 重写赋值方法
override func setValue(value: AnyObject?, forKey key: String) {
if key == "user" {
print("user: \(user) value: \(value)")
}
super.setValue(value, forKey: key)
}
/// kvc 字典转模型时 如个nil会报错
override func setValue(value: AnyObject?, forUndefinedKey key: String) {
}
override var description: String {
let properties = ["created_at", "id", "text", "source", "pic_urls", "reposts_count", "comments_count", "attitudes_count", "user"]
// 根据传人的数组作为字典的key value会从模型里面自动获取
return "\n \t 模型:\(dictionaryWithValuesForKeys(properties))"
}
/// 获取微博数据
class func loadStatus(finished: (statuses: [LWStatus]?, error: NSError?) ->()) {
// 调用网络工具类获取Status
LWNetworkTools.sharedInstance.loadStatus { (result, error) -> () in
// 没有加载到数据
if error != nil || result == nil{
print("error:\(error)")
finished(statuses: nil, error: error)
return
}
// 加载到了 数据
if let arr = result!["statuses"] as? [[String: AnyObject]] {
// 能来到这里 status 数据没有问
// 创建一个数字来存放转好的模型
var statuses = [LWStatus]()
for dict in arr {
let status = LWStatus(dict: dict)
statuses.append(status)
}
finished(statuses: statuses, error: nil)
}else{ // arr 为空
finished(statuses: nil, error: nil)
}
}
}
}
| apache-2.0 | 583d325f8e4e791a8c6450fde313d64c | 27.465909 | 137 | 0.53014 | 3.871716 | false | false | false | false |
soapyigu/LeetCode_Swift | DFS/CourseSchedule.swift | 1 | 2497 | /**
* Question Link: https://leetcode.com/problems/course-schedule/
* Primary idea: Kahn's Algorithms
* 1) Create the graph
* 2) Decorate each vertex with its in-degree
* 3) Create a set of all sources
* 4) While the set isn’t empty,
* i. Remove a vertex from the set and add it to the sorted list
* ii. For every edge from that vertex:
* - Decrement the in-degree of the destination node
* - Check all of its destination vertices and add them to the set if they have no incoming edges
* Time Complexity: O(|E| + |V|), Space Complexity: O(n^2)
* Recommand Reading: http://cs.brown.edu/courses/csci0160/lectures/14.pdf
*/
class CourseSchedule {
func canFinish(_ numCourses: Int, _ prerequisites: [[Int]]) -> Bool {
// ATTENTION: if graph use [[Int]], will get 'memory limited exceed'
var graph = [[UInt8]](repeatElement([UInt8](repeatElement(0, count: numCourses)), count: numCourses))
var indegree = [Int](repeatElement(0, count: numCourses))
// 1. Create the graph
for i in 0..<prerequisites.count {
let course = prerequisites[i][0]
let pre = prerequisites[i][1]
// 2. Decorate each vertex with its in-degree
// Eliminate duplicate case
if graph[pre][course] == 0 {
indegree[course] += 1
}
graph[pre][course] = 1
}
// 3. Create a array of sources
var sources = [Int]()
for i in 0..<numCourses {
if indegree[i] == 0 {
sources.append(i)
}
}
//var topoSortedList = [Int]()
var count = 0
while !sources.isEmpty {
// 4.i. Remove a vertex from the set and add it to the sorted list
let source = sources.popLast()
//topoSortedList.append(source!)
count += 1
// 4.ii. Decrement the in-degree of the destination node
for i in 0..<numCourses {
if graph[source!][i] == 1 {
indegree[i] -= 1
// Check all of its destination vertices and add them to the set if they have no incoming edges
if indegree[i] == 0 {
sources.append(i)
}
}
}
}
//return topoSortedList.count == numCourses
return count == numCourses
}
}
| mit | f99e227e30e67e3d6728bcffd9ce7cce | 36.80303 | 115 | 0.537876 | 4.286942 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet | SwiftGL-Demo/Source/GetPointColorInView.swift | 1 | 1105 | //
// GetPointColorInView.swift
// SwiftGL
//
// Created by jerry on 2015/9/12.
// Copyright © 2015年 Jerry Chan. All rights reserved.
//
import UIKit
extension UIView
{
func getColorFromPoint(_ point:CGPoint) -> UIColor {
let colorSpace:CGColorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
var pixelData:[UInt8] = [0, 0, 0, 0]
let context = CGContext(data: &pixelData, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
context?.translateBy(x: -point.x, y: -point.y);
self.layer.render(in: context!)
let red:CGFloat = CGFloat(pixelData[0])/CGFloat(255.0)
let green:CGFloat = CGFloat(pixelData[1])/CGFloat(255.0)
let blue:CGFloat = CGFloat(pixelData[2])/CGFloat(255.0)
let alpha:CGFloat = CGFloat(pixelData[3])/CGFloat(255.0)
let color:UIColor = UIColor(red: red, green: green, blue: blue, alpha: alpha)
return color
}
}
| mit | 7fd5fec746a10a6767f4471062970a84 | 34.548387 | 159 | 0.649728 | 3.992754 | false | false | false | false |
antonvmironov/PhysicalValue | PhysicalValue/Types/Length.swift | 1 | 4161 | //
// Length.swift
// PhysicalValue
//
// Created by Anton Mironov on 14.03.16.
// Copyright © 2016 Anton Mironov. All rights reserved.
//
import Foundation
public struct Length: PhysicalValue {
public typealias Unit = LengthUnit
// MARK: Properties - Owned
public var amount: MathValue
public var unit: Unit
// MARK: Properties - Derived
public var meters: MathValue {
get { return self.amount(unit: .metre) }
set { self.setAmount(newValue, unit: .metre) }
}
// MARK: Initializers
public init(amount: MathValue, unit: Unit) {
self.amount = amount
self.unit = unit
}
public init(meters: MathValue) {
self.amount = meters
self.unit = .metre
}
}
// MARK: -
public enum LengthUnit: LinearPhysicalUnit, AtomicPhysicalUnit {
public typealias Value = Length
// MARK: SI
case metre
case kilometre
case centimetre
case millimetre
case micrometre
case nanometre
// MARK: Imperial
case yard
case mile
case foot
case inch
// MARK: Astronomical
case parsec
case lightYear
case lightSecond
case astronomicalUnit
// MARK: -
public var kind: PhysicalUnitKind { return .length(self) }
public var unitOfNormal: LengthUnit { return .metre }
public var fractionOfNormal: MathValue {
switch self {
case .metre: return 1.0
case .kilometre: return 1000.0
case .centimetre: return 0.01
case .millimetre: return pow(1.0, -3.0)
case .micrometre: return pow(1.0, -6.0)
case .nanometre: return pow(1.0, -9.0)
case .yard: return LengthUnit.yardInMeters
case .mile: return LengthUnit.yardInMeters * 1760.0
case .foot: return LengthUnit.yardInMeters / 3.0
case .inch: return LengthUnit.yardInMeters / 36.0
case .parsec: return LengthUnit.parsecInMeters
case .lightYear: return LengthUnit.lightYearInMeters
case .lightSecond: return LengthUnit.lightSecondInMeters
case .astronomicalUnit: return LengthUnit.astronomicalUnitInMeters
}
}
public var name: String {
switch self {
case .metre: return "metre"
case .kilometre: return "kilometre"
case .centimetre: return "centimetre"
case .millimetre: return "millimetre"
case .micrometre: return "micrometre"
case .nanometre: return "nanometre"
case .yard: return "yard"
case .mile: return "mile"
case .foot: return "foot"
case .inch: return "inch"
case .parsec: return "parsec"
case .lightYear: return "light year"
case .lightSecond: return "light second"
case .astronomicalUnit: return "Astronomical Unit"
}
}
public var symbol: String {
switch self {
case .metre: return "m"
case .kilometre: return "km"
case .centimetre: return "cm"
case .millimetre: return "mm"
case .micrometre: return "\u{03BC}m"
case .nanometre: return "nm"
case .yard: return "yd"
case .mile: return "mi"
case .foot: return "ft"
case .inch: return "in"
case .parsec: return "parsec"
case .lightYear: return "light year"
case .lightSecond: return "light second"
case .astronomicalUnit: return "AU"
}
}
public var wantsSpaceBetweenAmountAndSymbol: Bool {
switch self {
case .metre: return false
case .kilometre: return false
case .centimetre: return false
case .millimetre: return false
case .micrometre: return false
case .nanometre: return false
case .yard: return false
case .mile: return false
case .foot: return false
case .inch: return false
case .parsec: return true
case .lightYear: return true
case .lightSecond: return true
case .astronomicalUnit: return false
}
}
// MARK: Meta
private static let astronomicalUnitInMeters: MathValue = 149_597_870_700.0
private static let lightSecondInMeters: MathValue = 299_792_458.0
private static let lightYearInMeters: MathValue = LengthUnit.lightSecondInMeters * Time(amount: 1.0, unit: .year).seconds
private static let parsecInMeters = (648_000.0 / M_PI) * LengthUnit.astronomicalUnitInMeters
private static let yardInMeters: MathValue = 0.9144
}
| mit | d565677e319d229d5d278bc5c6ad42ea | 26.012987 | 123 | 0.677644 | 3.678161 | false | false | false | false |
ryan-blunden/ga-mobile | Recipes/Recipes/SwiftyJSONViewController.swift | 2 | 929 | //
// SwiftyJSONViewController.swift
// Recipes
//
// Created by Ryan Blunden on 11/06/2015.
// Copyright (c) 2015 RabbitBird Pty Ltd. All rights reserved.
//
import Foundation
import UIKit
class SwiftyJSONViewController:UIViewController {
// This means, set it to nil initially, but TRUST ME, by the time
// someone goes to access it, it WON'T be nil.
// USE WITH CAUTION!!!
var newsArticle:Article! = nil
@IBOutlet weak var newsArticleTitle: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let newsArticles = FakeNewsFeedManager().getAllArticles()
if let firstNewsArticle = newsArticles.first {
newsArticle = firstNewsArticle
newsArticleTitle.text = newsArticle.title
}
}
@IBAction func onButtonTapped(sender: AnyObject) {
if newsArticle != nil {
UIApplication.sharedApplication().openURL(NSURL(string:newsArticle.link)!)
}
}
}
| gpl-3.0 | 106afb8df0895cd40f0ef630f16cb611 | 24.108108 | 80 | 0.697524 | 4.110619 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.