repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
seanperez29/GifMaker_PortingObjC | GifMaker_Swift_Template/PreviewViewController.swift | 1 | 1542 | //
// PreviewViewController.swift
// GifMaker_Swift_Template
//
// Created by Sean Perez on 10/10/16.
// Copyright © 2016 Gabrielle Miller-Messner. All rights reserved.
//
import UIKit
class PreviewViewController: UIViewController {
var gif: Gif?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
@IBAction func shareGif(sender: AnyObject) {
let url: URL = (self.gif?.url)!
let animatedGif = NSData(contentsOf: url)
let itemsToShare = [animatedGif]
let activityVC = UIActivityViewController(activityItems: itemsToShare, applicationActivities: nil)
activityVC.completionWithItemsHandler = {(activity, completed, items, error) in
if completed {
self.navigationController?.popToRootViewController(animated: true)
}
}
navigationController?.present(activityVC, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | acd7d333c2d2c6aae1cc7e74d1ccd347 | 28.634615 | 106 | 0.658014 | 5.171141 | false | false | false | false |
IngmarStein/swift | test/attr/attr_objc.swift | 1 | 88832 | // RUN: %target-parse-verify-swift
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module | %FileCheck %s
// RUN: not %target-swift-frontend -parse -dump-ast -disable-objc-attr-requires-foundation-module %s 2> %t.dump
// RUN: %FileCheck -check-prefix CHECK-DUMP %s < %t.dump
// REQUIRES: objc_interop
import Foundation
class PlainClass {}
struct PlainStruct {}
enum PlainEnum {}
protocol PlainProtocol {} // expected-note {{protocol 'PlainProtocol' declared here}}
enum ErrorEnum : Error {
case failed
}
@objc class Class_ObjC1 {}
protocol Protocol_Class1 : class {} // expected-note {{protocol 'Protocol_Class1' declared here}}
protocol Protocol_Class2 : class {}
@objc protocol Protocol_ObjC1 {}
@objc protocol Protocol_ObjC2 {}
//===--- Subjects of @objc attribute.
@objc extension PlainClass { } // expected-error{{@objc cannot be applied to this declaration}}{{1-7=}}
@objc
var subject_globalVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
var subject_getterSetter: Int {
@objc
get { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
return 0
}
@objc
set { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
}
var subject_global_observingAccessorsVar1: Int = 0 {
@objc
willSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
}
@objc
didSet { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
}
}
class subject_getterSetter1 {
var instanceVar1: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
}
var instanceVar2: Int {
get {
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var instanceVar3: Int {
@objc
get { // expected-error {{'@objc' getter for non-'@objc' property}}
return 0
}
@objc
set { // expected-error {{'@objc' setter for non-'@objc' property}}
}
}
var observingAccessorsVar1: Int = 0 {
@objc
willSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
@objc
didSet { // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
}
}
class subject_staticVar1 {
@objc
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
@objc
class var staticVar2: Int { return 42 }
}
@objc
func subject_freeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}}
@objc
var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_nestedFreeFunc() { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
}
@objc
func subject_genericFunc<T>(t: T) { // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-6=}}
@objc
var subject_localVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
func subject_funcParam(a: @objc Int) { // expected-error {{attribute can only be applied to declarations, not types}} {{1-1=@objc }} {{27-33=}}
}
@objc // expected-error {{@objc cannot be applied to this declaration}} {{1-7=}}
struct subject_struct {
@objc
var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
@objc // expected-error {{@objc cannot be applied to this declaration}} {{1-7=}}
struct subject_genericStruct<T> {
@objc
var subject_instanceVar: Int // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
@objc
class subject_class1 { // no-error
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no-error
}
@objc
class subject_class2 : Protocol_Class1, PlainProtocol { // no-error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{1-7=}}
class subject_genericClass<T> {
@objc
var subject_instanceVar: Int // no-error
@objc
init() {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{1-7=}}
class subject_genericClass2<T> : Class_ObjC1 {
@objc
var subject_instanceVar: Int // no-error
@objc
init(foo: Int) {} // no-error
@objc
func subject_instanceFunc() {} // no_error
}
extension subject_genericClass where T : Hashable {
@objc var prop: Int { return 0 } // expected-error{{members of constrained extensions cannot be declared @objc}}
}
extension subject_genericClass {
@objc var extProp: Int { return 0 } // expected-error{{@objc is not supported within extensions of generic classes}}
@objc func extFoo() {} // expected-error{{@objc is not supported within extensions of generic classes}}
}
@objc
enum subject_enum: Int {
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement1
@objc(subject_enumElement2)
case subject_enumElement2
@objc(subject_enumElement3)
case subject_enumElement3, subject_enumElement4 // expected-error {{'@objc' enum case declaration defines multiple enum cases with the same Objective-C name}}{{3-8=}}
@objc // expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement5, subject_enumElement6
@nonobjc // expected-error {{@nonobjc cannot be applied to this declaration}}
case subject_enumElement7
@objc
init() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
@objc
func subject_instanceFunc() {} // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-8=}}
}
enum subject_enum2 {
@objc(subject_enum2Element1)
case subject_enumElement1 // expected-error{{'@objc' enum case is not allowed outside of an '@objc' enum}}{{3-8=}}
}
@objc
protocol subject_protocol1 {
@objc
var subject_instanceVar: Int { get }
@objc
func subject_instanceFunc()
}
@objc protocol subject_protocol2 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol2 {
@objc protocol subject_protocol3 {} // no-error
// CHECK-LABEL: @objc protocol subject_protocol3 {
@objc
protocol subject_protocol4 : PlainProtocol {} // expected-error {{@objc protocol 'subject_protocol4' cannot refine non-@objc protocol 'PlainProtocol'}}
@objc
protocol subject_protocol5 : Protocol_Class1 {} // expected-error {{@objc protocol 'subject_protocol5' cannot refine non-@objc protocol 'Protocol_Class1'}}
@objc
protocol subject_protocol6 : Protocol_ObjC1 {}
protocol subject_containerProtocol1 {
@objc
var subject_instanceVar: Int { get } // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc
func subject_instanceFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc
static func subject_staticFunc() // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
@objc
protocol subject_containerObjCProtocol1 {
func func_FunctionReturn1() -> PlainStruct
// expected-error@-1 {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_FunctionParam1(a: PlainStruct)
// expected-error@-1 {{method cannot be a member of an @objc protocol because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_Variadic(_: AnyObject...)
// expected-error @-1{{method cannot be a member of an @objc protocol because it has a variadic parameter}}
// expected-note @-2{{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
subscript(a: PlainStruct) -> Int { get }
// expected-error@-1 {{subscript cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
var varNonObjC1: PlainStruct { get }
// expected-error@-1 {{property cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
}
@objc
protocol subject_containerObjCProtocol2 {
init(a: Int)
@objc init(a: Double)
func func1() -> Int
@objc func func1_() -> Int
var instanceVar1: Int { get set }
@objc var instanceVar1_: Int { get set }
subscript(i: Int) -> Int { get set }
@objc subscript(i: String) -> Int { get set}
}
protocol nonObjCProtocol {
@objc func objcRequirement() // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
func concreteContext1() {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext2 {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext3 {
func dynamicSelf1() -> Self { return self }
@objc func dynamicSelf1_() -> Self { return self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func genericParams<T: NSObject>() -> [T] { return [] }
// expected-error@-1{{method cannot be marked @objc because it has generic parameters}}
@objc func returnObjCProtocolMetatype() -> NSCoding.Protocol { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias AnotherNSCoding = NSCoding
typealias MetaNSCoding1 = NSCoding.Protocol
typealias MetaNSCoding2 = AnotherNSCoding.Protocol
@objc func returnObjCAliasProtocolMetatype1() -> AnotherNSCoding.Protocol { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnObjCAliasProtocolMetatype2() -> MetaNSCoding1 { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnObjCAliasProtocolMetatype3() -> MetaNSCoding2 { return NSCoding.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias Composition = NSCopying & NSCoding
@objc func returnCompositionMetatype1() -> Composition.Protocol { return Composition.self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc func returnCompositionMetatype2() -> (NSCopying & NSCoding).Protocol { return (NSCopying & NSCoding).self }
// expected-error@-1{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias NSCodingExistential = NSCoding.Type
@objc func metatypeOfExistentialMetatypePram1(a: NSCodingExistential.Protocol) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
@objc func metatypeOfExistentialMetatypePram2(a: NSCoding.Type.Protocol) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
}
func genericContext1<T>(_: T) {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {} // expected-error{{type 'subject_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{type 'subject_inGenericContext2' cannot be nested in generic function 'genericContext1'}}
class subject_constructor_inGenericContext { // expected-error{{type 'subject_constructor_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
init() {} // no-error
}
class subject_var_inGenericContext { // expected-error{{type 'subject_var_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
var subject_instanceVar: Int = 0 // no-error
}
class subject_func_inGenericContext { // expected-error{{type 'subject_func_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
func f() {} // no-error
}
}
class GenericContext2<T> {
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {} // expected-error{{nested in generic type}}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{nested in generic type}}
@objc
func f() {} // no-error
}
class GenericContext3<T> {
class MoreNested { // expected-error{{nested in generic type}}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{5-11=}}
class subject_inGenericContext {} // expected-error{{nested in generic type}}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{5-11=}}
class subject_inGenericContext2 : Class_ObjC1 {} // expected-error{{nested in generic type}}
@objc
func f() {} // no-error
}
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute because they are not directly visible from Objective-C}} {{1-7=}}
class ConcreteSubclassOfGeneric : GenericContext3<Int> {}
extension ConcreteSubclassOfGeneric {
@objc func foo() {} // expected-error {{@objc is not supported within extensions of generic classes}}
}
@objc // expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' attribute}} {{1-7=}}
class ConcreteSubclassOfGeneric2 : subject_genericClass2<Int> {}
extension ConcreteSubclassOfGeneric2 {
@objc func foo() {} // expected-error {{@objc is not supported within extensions of generic classes}}
}
class subject_subscriptIndexed1 {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed2 {
@objc
subscript(a: Int8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed3 {
@objc
subscript(a: UInt8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed1 {
@objc
subscript(a: String) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed2 {
@objc
subscript(a: Class_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed3 {
@objc
subscript(a: Class_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed4 {
@objc
subscript(a: Protocol_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed5 {
@objc
subscript(a: Protocol_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed6 {
@objc
subscript(a: Protocol_ObjC1 & Protocol_ObjC2) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed7 {
@objc
subscript(a: (Protocol_ObjC1 & Protocol_ObjC2).Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptBridgedFloat {
@objc
subscript(a: Float32) -> Int {
get { return 0 }
}
}
class subject_subscriptGeneric<T> {
@objc
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptInvalid2 {
@objc
subscript(a: PlainClass) -> Int {
// expected-error@-1 {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid3 {
@objc
subscript(a: PlainClass.Type) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid4 {
@objc
subscript(a: PlainStruct) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{Swift structs cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid5 {
@objc
subscript(a: PlainEnum) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{enums cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid6 {
@objc
subscript(a: PlainProtocol) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol 'PlainProtocol' is not '@objc'}}
get { return 0 }
}
}
class subject_subscriptInvalid7 {
@objc
subscript(a: Protocol_Class1) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol 'Protocol_Class1' is not '@objc'}}
get { return 0 }
}
}
class subject_subscriptInvalid8 {
@objc
subscript(a: Protocol_Class1 & Protocol_Class2) -> Int { // expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol 'Protocol_Class1' is not '@objc'}}
get { return 0 }
}
}
//===--- Tests for @objc inference.
@objc
class infer_instanceFunc1 {
// CHECK-LABEL: @objc class infer_instanceFunc1 {
func func1() {}
// CHECK-LABEL: @objc func func1() {
@objc func func1_() {} // no-error
func func2(a: Int) {}
// CHECK-LABEL: @objc func func2(a: Int) {
@objc func func2_(a: Int) {} // no-error
func func3(a: Int) -> Int {}
// CHECK-LABEL: @objc func func3(a: Int) -> Int {
@objc func func3_(a: Int) -> Int {} // no-error
func func4(a: Int, b: Double) {}
// CHECK-LABEL: @objc func func4(a: Int, b: Double) {
@objc func func4_(a: Int, b: Double) {} // no-error
func func5(a: String) {}
// CHECK-LABEL: @objc func func5(a: String) {
@objc func func5_(a: String) {} // no-error
func func6() -> String {}
// CHECK-LABEL: @objc func func6() -> String {
@objc func func6_() -> String {} // no-error
func func7(a: PlainClass) {}
// CHECK-LABEL: {{^}} func func7(a: PlainClass) {
@objc func func7_(a: PlainClass) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func7m(a: PlainClass.Type) {}
// CHECK-LABEL: {{^}} func func7m(a: PlainClass.Type) {
@objc func func7m_(a: PlainClass.Type) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
func func8() -> PlainClass {}
// CHECK-LABEL: {{^}} func func8() -> PlainClass {
@objc func func8_() -> PlainClass {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func8m() -> PlainClass.Type {}
// CHECK-LABEL: {{^}} func func8m() -> PlainClass.Type {
@objc func func8m_() -> PlainClass.Type {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
func func9(a: PlainStruct) {}
// CHECK-LABEL: {{^}} func func9(a: PlainStruct) {
@objc func func9_(a: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func10() -> PlainStruct {}
// CHECK-LABEL: {{^}} func func10() -> PlainStruct {
@objc func func10_() -> PlainStruct {}
// expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func11(a: PlainEnum) {}
// CHECK-LABEL: {{^}} func func11(a: PlainEnum) {
@objc func func11_(a: PlainEnum) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
func func12(a: PlainProtocol) {}
// CHECK-LABEL: {{^}} func func12(a: PlainProtocol) {
@objc func func12_(a: PlainProtocol) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
func func13(a: Class_ObjC1) {}
// CHECK-LABEL: @objc func func13(a: Class_ObjC1) {
@objc func func13_(a: Class_ObjC1) {} // no-error
func func14(a: Protocol_Class1) {}
// CHECK-LABEL: {{^}} func func14(a: Protocol_Class1) {
@objc func func14_(a: Protocol_Class1) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
func func15(a: Protocol_ObjC1) {}
// CHECK-LABEL: @objc func func15(a: Protocol_ObjC1) {
@objc func func15_(a: Protocol_ObjC1) {} // no-error
func func16(a: AnyObject) {}
// CHECK-LABEL: @objc func func16(a: AnyObject) {
@objc func func16_(a: AnyObject) {} // no-error
func func17(a: @escaping () -> ()) {}
// CHECK-LABEL: {{^}} @objc func func17(a: @escaping () -> ()) {
@objc func func17_(a: @escaping () -> ()) {}
func func18(a: @escaping (Int) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func18(a: @escaping (Int) -> (), b: Int)
@objc func func18_(a: @escaping (Int) -> (), b: Int) {}
func func19(a: @escaping (String) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func19(a: @escaping (String) -> (), b: Int) {
@objc func func19_(a: @escaping (String) -> (), b: Int) {}
func func_FunctionReturn1() -> () -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn1() -> () -> () {
@objc func func_FunctionReturn1_() -> () -> () {}
func func_FunctionReturn2() -> (Int) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn2() -> (Int) -> () {
@objc func func_FunctionReturn2_() -> (Int) -> () {}
func func_FunctionReturn3() -> () -> Int {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn3() -> () -> Int {
@objc func func_FunctionReturn3_() -> () -> Int {}
func func_FunctionReturn4() -> (String) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn4() -> (String) -> () {
@objc func func_FunctionReturn4_() -> (String) -> () {}
func func_FunctionReturn5() -> () -> String {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn5() -> () -> String {
@objc func func_FunctionReturn5_() -> () -> String {}
func func_ZeroParams1() {}
// CHECK-LABEL: @objc func func_ZeroParams1() {
@objc func func_ZeroParams1a() {} // no-error
func func_OneParam1(a: Int) {}
// CHECK-LABEL: @objc func func_OneParam1(a: Int) {
@objc func func_OneParam1a(a: Int) {} // no-error
func func_TupleStyle1(a: Int, b: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle1(a: Int, b: Int) {
@objc func func_TupleStyle1a(a: Int, b: Int) {}
func func_TupleStyle2(a: Int, b: Int, c: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle2(a: Int, b: Int, c: Int) {
@objc func func_TupleStyle2a(a: Int, b: Int, c: Int) {}
// Check that we produce diagnostics for every parameter and return type.
@objc func func_MultipleDiags(a: PlainStruct, b: PlainEnum) -> Any {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter 1 cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-error@-3 {{method cannot be marked @objc because the type of the parameter 2 cannot be represented in Objective-C}}
// expected-note@-4 {{non-'@objc' enums cannot be represented in Objective-C}}
@objc func func_UnnamedParam1(_: Int) {} // no-error
@objc func func_UnnamedParam2(_: PlainStruct) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
@objc func func_varParam1(a: AnyObject) {
var a = a
let b = a; a = b
}
func func_varParam2(a: AnyObject) {
var a = a
let b = a; a = b
}
// CHECK-LABEL: @objc func func_varParam2(a: AnyObject) {
}
@objc
class infer_constructor1 {
// CHECK-LABEL: @objc class infer_constructor1
init() {}
// CHECK: @objc init()
init(a: Int) {}
// CHECK: @objc init(a: Int)
init(a: PlainStruct) {}
// CHECK: {{^}} init(a: PlainStruct)
init(malice: ()) {}
// CHECK: @objc init(malice: ())
init(forMurder _: ()) {}
// CHECK: @objc init(forMurder _: ())
}
@objc
class infer_destructor1 {
// CHECK-LABEL: @objc class infer_destructor1
deinit {}
// CHECK: @objc deinit
}
// @!objc
class infer_destructor2 {
// CHECK-LABEL: {{^}}class infer_destructor2
deinit {}
// CHECK: @objc deinit
}
@objc
class infer_instanceVar1 {
// CHECK-LABEL: @objc class infer_instanceVar1 {
init() {}
var instanceVar1: Int
// CHECK: @objc var instanceVar1: Int
var (instanceVar2, instanceVar3): (Int, PlainProtocol)
// CHECK: @objc var instanceVar2: Int
// CHECK: {{^}} var instanceVar3: PlainProtocol
@objc var (instanceVar1_, instanceVar2_): (Int, PlainProtocol)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var intstanceVar4: Int {
// CHECK: @objc var intstanceVar4: Int {
get {}
// CHECK-NEXT: @objc get {}
}
var intstanceVar5: Int {
// CHECK: @objc var intstanceVar5: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
@objc var instanceVar5_: Int {
// CHECK: @objc var instanceVar5_: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
var observingAccessorsVar1: Int {
// CHECK: @objc var observingAccessorsVar1: Int {
willSet {}
// CHECK-NEXT: {{^}} final willSet {}
didSet {}
// CHECK-NEXT: {{^}} final didSet {}
}
@objc var observingAccessorsVar1_: Int {
// CHECK: {{^}} @objc var observingAccessorsVar1_: Int {
willSet {}
// CHECK-NEXT: {{^}} final willSet {}
didSet {}
// CHECK-NEXT: {{^}} final didSet {}
}
var var_Int: Int
// CHECK-LABEL: @objc var var_Int: Int
var var_Bool: Bool
// CHECK-LABEL: @objc var var_Bool: Bool
var var_CBool: CBool
// CHECK-LABEL: @objc var var_CBool: CBool
var var_String: String
// CHECK-LABEL: @objc var var_String: String
var var_Float: Float
var var_Double: Double
// CHECK-LABEL: @objc var var_Float: Float
// CHECK-LABEL: @objc var var_Double: Double
var var_Char: UnicodeScalar
// CHECK-LABEL: @objc var var_Char: UnicodeScalar
//===--- Tuples.
var var_tuple1: ()
// CHECK-LABEL: {{^}} var var_tuple1: ()
@objc var var_tuple1_: ()
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple2: Void
// CHECK-LABEL: {{^}} var var_tuple2: Void
@objc var var_tuple2_: Void
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple3: (Int)
// CHECK-LABEL: @objc var var_tuple3: (Int)
@objc var var_tuple3_: (Int) // no-error
var var_tuple4: (Int, Int)
// CHECK-LABEL: {{^}} var var_tuple4: (Int, Int)
@objc var var_tuple4_: (Int, Int)
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{tuples cannot be represented in Objective-C}}
//===--- Stdlib integer types.
var var_Int8: Int8
var var_Int16: Int16
var var_Int32: Int32
var var_Int64: Int64
// CHECK-LABEL: @objc var var_Int8: Int8
// CHECK-LABEL: @objc var var_Int16: Int16
// CHECK-LABEL: @objc var var_Int32: Int32
// CHECK-LABEL: @objc var var_Int64: Int64
var var_UInt8: UInt8
var var_UInt16: UInt16
var var_UInt32: UInt32
var var_UInt64: UInt64
// CHECK-LABEL: @objc var var_UInt8: UInt8
// CHECK-LABEL: @objc var var_UInt16: UInt16
// CHECK-LABEL: @objc var var_UInt32: UInt32
// CHECK-LABEL: @objc var var_UInt64: UInt64
var var_OpaquePointer: OpaquePointer
// CHECK-LABEL: @objc var var_OpaquePointer: OpaquePointer
var var_PlainClass: PlainClass
// CHECK-LABEL: {{^}} var var_PlainClass: PlainClass
@objc var var_PlainClass_: PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
var var_PlainStruct: PlainStruct
// CHECK-LABEL: {{^}} var var_PlainStruct: PlainStruct
@objc var var_PlainStruct_: PlainStruct
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
var var_PlainEnum: PlainEnum
// CHECK-LABEL: {{^}} var var_PlainEnum: PlainEnum
@objc var var_PlainEnum_: PlainEnum
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
var var_PlainProtocol: PlainProtocol
// CHECK-LABEL: {{^}} var var_PlainProtocol: PlainProtocol
@objc var var_PlainProtocol_: PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_ClassObjC: Class_ObjC1
// CHECK-LABEL: @objc var var_ClassObjC: Class_ObjC1
@objc var var_ClassObjC_: Class_ObjC1 // no-error
var var_ProtocolClass: Protocol_Class1
// CHECK-LABEL: {{^}} var var_ProtocolClass: Protocol_Class1
@objc var var_ProtocolClass_: Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
var var_ProtocolObjC: Protocol_ObjC1
// CHECK-LABEL: @objc var var_ProtocolObjC: Protocol_ObjC1
@objc var var_ProtocolObjC_: Protocol_ObjC1 // no-error
var var_PlainClassMetatype: PlainClass.Type
// CHECK-LABEL: {{^}} var var_PlainClassMetatype: PlainClass.Type
@objc var var_PlainClassMetatype_: PlainClass.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainStructMetatype: PlainStruct.Type
// CHECK-LABEL: {{^}} var var_PlainStructMetatype: PlainStruct.Type
@objc var var_PlainStructMetatype_: PlainStruct.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainEnumMetatype: PlainEnum.Type
// CHECK-LABEL: {{^}} var var_PlainEnumMetatype: PlainEnum.Type
@objc var var_PlainEnumMetatype_: PlainEnum.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainExistentialMetatype: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_PlainExistentialMetatype: PlainProtocol.Type
@objc var var_PlainExistentialMetatype_: PlainProtocol.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ClassObjCMetatype: Class_ObjC1.Type
// CHECK-LABEL: @objc var var_ClassObjCMetatype: Class_ObjC1.Type
@objc var var_ClassObjCMetatype_: Class_ObjC1.Type // no-error
var var_ProtocolClassMetatype: Protocol_Class1.Type
// CHECK-LABEL: {{^}} var var_ProtocolClassMetatype: Protocol_Class1.Type
@objc var var_ProtocolClassMetatype_: Protocol_Class1.Type
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
@objc var var_ProtocolObjCMetatype1_: Protocol_ObjC1.Type // no-error
var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
@objc var var_ProtocolObjCMetatype2_: Protocol_ObjC2.Type // no-error
var var_AnyObject1: AnyObject
var var_AnyObject2: AnyObject.Type
// CHECK-LABEL: @objc var var_AnyObject1: AnyObject
// CHECK-LABEL: @objc var var_AnyObject2: AnyObject.Type
var var_Existential0: Any
// CHECK-LABEL: @objc var var_Existential0: Any
@objc var var_Existential0_: Any
var var_Existential1: PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential1: PlainProtocol
@objc var var_Existential1_: PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_Existential2: PlainProtocol & PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential2: PlainProtocol
@objc var var_Existential2_: PlainProtocol & PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_Existential3: PlainProtocol & Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential3: PlainProtocol & Protocol_Class1
@objc var var_Existential3_: PlainProtocol & Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_Existential4: PlainProtocol & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential4: PlainProtocol & Protocol_ObjC1
@objc var var_Existential4_: PlainProtocol & Protocol_ObjC1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'PlainProtocol' is not '@objc'}}
var var_Existential5: Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential5: Protocol_Class1
@objc var var_Existential5_: Protocol_Class1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
var var_Existential6: Protocol_Class1 & Protocol_Class2
// CHECK-LABEL: {{^}} var var_Existential6: Protocol_Class1 & Protocol_Class2
@objc var var_Existential6_: Protocol_Class1 & Protocol_Class2
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
var var_Existential7: Protocol_Class1 & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential7: Protocol_Class1 & Protocol_ObjC1
@objc var var_Existential7_: Protocol_Class1 & Protocol_ObjC1
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol 'Protocol_Class1' is not '@objc'}}
var var_Existential8: Protocol_ObjC1
// CHECK-LABEL: @objc var var_Existential8: Protocol_ObjC1
@objc var var_Existential8_: Protocol_ObjC1 // no-error
var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
@objc var var_Existential9_: Protocol_ObjC1 & Protocol_ObjC2 // no-error
var var_ExistentialMetatype0: Any.Type
var var_ExistentialMetatype1: PlainProtocol.Type
var var_ExistentialMetatype2: (PlainProtocol & PlainProtocol).Type
var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
var var_ExistentialMetatype5: (Protocol_Class1).Type
var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
var var_ExistentialMetatype8: Protocol_ObjC1.Type
var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype0: Any.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype1: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype2: (PlainProtocol).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype5: (Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
// CHECK-LABEL: @objc var var_ExistentialMetatype8: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
// CHECK-LABEL: var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
var var_Optional1: Class_ObjC1?
var var_Optional2: Protocol_ObjC1?
var var_Optional3: Class_ObjC1.Type?
var var_Optional4: Protocol_ObjC1.Type?
var var_Optional5: AnyObject?
var var_Optional6: AnyObject.Type?
var var_Optional7: String?
var var_Optional8: Protocol_ObjC1?
var var_Optional9: Protocol_ObjC1.Type?
var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
var var_Optional12: OpaquePointer?
var var_Optional13: UnsafeMutablePointer<Int>?
var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
// CHECK-LABEL: @objc var var_Optional1: Class_ObjC1?
// CHECK-LABEL: @objc var var_Optional2: Protocol_ObjC1?
// CHECK-LABEL: @objc var var_Optional3: Class_ObjC1.Type?
// CHECK-LABEL: @objc var var_Optional4: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc var var_Optional5: AnyObject?
// CHECK-LABEL: @objc var var_Optional6: AnyObject.Type?
// CHECK-LABEL: @objc var var_Optional7: String?
// CHECK-LABEL: @objc var var_Optional8: Protocol_ObjC1?
// CHECK-LABEL: @objc var var_Optional9: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
// CHECK-LABEL: @objc var var_Optional12: OpaquePointer?
// CHECK-LABEL: @objc var var_Optional13: UnsafeMutablePointer<Int>?
// CHECK-LABEL: @objc var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional5: AnyObject!
var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
var var_ImplicitlyUnwrappedOptional7: String!
var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional5: AnyObject!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional7: String!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
// CHECK-LABEL: @objc var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
var var_Optional_fail1: PlainClass?
var var_Optional_fail2: PlainClass.Type?
var var_Optional_fail3: PlainClass!
var var_Optional_fail4: PlainStruct?
var var_Optional_fail5: PlainStruct.Type?
var var_Optional_fail6: PlainEnum?
var var_Optional_fail7: PlainEnum.Type?
var var_Optional_fail8: PlainProtocol?
var var_Optional_fail10: PlainProtocol?
var var_Optional_fail11: (PlainProtocol & Protocol_ObjC1)?
var var_Optional_fail12: Int?
var var_Optional_fail13: Bool?
var var_Optional_fail14: CBool?
var var_Optional_fail20: AnyObject??
var var_Optional_fail21: AnyObject.Type??
var var_Optional_fail22: ComparisonResult? // a non-bridged imported value type
var var_Optional_fail23: NSRange? // a bridged struct imported from C
// CHECK-NOT: @objc{{.*}}Optional_fail
// CHECK-LABEL: @objc var var_CFunctionPointer_1: @convention(c) () -> ()
var var_CFunctionPointer_1: @convention(c) () -> ()
// CHECK-LABEL: @objc var var_CFunctionPointer_invalid_1: Int
var var_CFunctionPointer_invalid_1: @convention(c) Int // expected-error {{@convention attribute only applies to function types}}
// CHECK-LABEL: {{^}} var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int
var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int // expected-error {{'(PlainStruct) -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
// <rdar://problem/20918869> Confusing diagnostic for @convention(c) throws
var var_CFunctionPointer_invalid_3 : @convention(c) (Int) throws -> Int // expected-error {{'(Int) throws -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
weak var var_Weak1: Class_ObjC1?
weak var var_Weak2: Protocol_ObjC1?
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//weak var var_Weak3: Class_ObjC1.Type?
//weak var var_Weak4: Protocol_ObjC1.Type?
weak var var_Weak5: AnyObject?
//weak var var_Weak6: AnyObject.Type?
weak var var_Weak7: Protocol_ObjC1?
weak var var_Weak8: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc weak var var_Weak1: @sil_weak Class_ObjC1
// CHECK-LABEL: @objc weak var var_Weak2: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc weak var var_Weak5: @sil_weak AnyObject
// CHECK-LABEL: @objc weak var var_Weak7: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc weak var var_Weak8: @sil_weak (Protocol_ObjC1 & Protocol_ObjC2)?
weak var var_Weak_fail1: PlainClass?
weak var var_Weak_bad2: PlainStruct?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
weak var var_Weak_bad3: PlainEnum?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
weak var var_Weak_bad4: String?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Weak_fail
unowned var var_Unowned1: Class_ObjC1
unowned var var_Unowned2: Protocol_ObjC1
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//unowned var var_Unowned3: Class_ObjC1.Type
//unowned var var_Unowned4: Protocol_ObjC1.Type
unowned var var_Unowned5: AnyObject
//unowned var var_Unowned6: AnyObject.Type
unowned var var_Unowned7: Protocol_ObjC1
unowned var var_Unowned8: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc unowned var var_Unowned1: @sil_unowned Class_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned2: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned5: @sil_unowned AnyObject
// CHECK-LABEL: @objc unowned var var_Unowned7: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned8: @sil_unowned Protocol_ObjC1 & Protocol_ObjC2
unowned var var_Unowned_fail1: PlainClass
unowned var var_Unowned_bad2: PlainStruct
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
unowned var var_Unowned_bad3: PlainEnum
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
unowned var var_Unowned_bad4: String
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Unowned_fail
var var_FunctionType1: () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType1: () -> ()
var var_FunctionType2: (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType2: (Int) -> ()
var var_FunctionType3: (Int) -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionType3: (Int) -> Int
var var_FunctionType4: (Int, Double) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType4: (Int, Double) -> ()
var var_FunctionType5: (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType5: (String) -> ()
var var_FunctionType6: () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionType6: () -> String
var var_FunctionType7: (PlainClass) -> ()
// CHECK-NOT: @objc var var_FunctionType7: (PlainClass) -> ()
var var_FunctionType8: () -> PlainClass
// CHECK-NOT: @objc var var_FunctionType8: () -> PlainClass
var var_FunctionType9: (PlainStruct) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType9: (PlainStruct) -> ()
var var_FunctionType10: () -> PlainStruct
// CHECK-LABEL: {{^}} var var_FunctionType10: () -> PlainStruct
var var_FunctionType11: (PlainEnum) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType11: (PlainEnum) -> ()
var var_FunctionType12: (PlainProtocol) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType12: (PlainProtocol) -> ()
var var_FunctionType13: (Class_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType13: (Class_ObjC1) -> ()
var var_FunctionType14: (Protocol_Class1) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType14: (Protocol_Class1) -> ()
var var_FunctionType15: (Protocol_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType15: (Protocol_ObjC1) -> ()
var var_FunctionType16: (AnyObject) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType16: (AnyObject) -> ()
var var_FunctionType17: (() -> ()) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType17: (() -> ()) -> ()
var var_FunctionType18: ((Int) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType18: ((Int) -> (), Int) -> ()
var var_FunctionType19: ((String) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType19: ((String) -> (), Int) -> ()
var var_FunctionTypeReturn1: () -> () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn1: () -> () -> ()
@objc var var_FunctionTypeReturn1_: () -> () -> () // no-error
var var_FunctionTypeReturn2: () -> (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn2: () -> (Int) -> ()
@objc var var_FunctionTypeReturn2_: () -> (Int) -> () // no-error
var var_FunctionTypeReturn3: () -> () -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn3: () -> () -> Int
@objc var var_FunctionTypeReturn3_: () -> () -> Int // no-error
var var_FunctionTypeReturn4: () -> (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn4: () -> (String) -> ()
@objc var var_FunctionTypeReturn4_: () -> (String) -> () // no-error
var var_FunctionTypeReturn5: () -> () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn5: () -> () -> String
@objc var var_FunctionTypeReturn5_: () -> () -> String // no-error
var var_BlockFunctionType1: @convention(block) () -> ()
// CHECK-LABEL: @objc var var_BlockFunctionType1: @convention(block) () -> ()
@objc var var_BlockFunctionType1_: @convention(block) () -> () // no-error
var var_ArrayType1: [AnyObject]
// CHECK-LABEL: {{^}} @objc var var_ArrayType1: [AnyObject]
@objc var var_ArrayType1_: [AnyObject] // no-error
var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject]
@objc var var_ArrayType2_: [@convention(block) (AnyObject) -> AnyObject] // no-error
var var_ArrayType3: [PlainStruct]
// CHECK-LABEL: {{^}} var var_ArrayType3: [PlainStruct]
@objc var var_ArrayType3_: [PlainStruct]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType4: [(AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType4: [(AnyObject) -> AnyObject]
@objc var var_ArrayType4_: [(AnyObject) -> AnyObject]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType5: [Protocol_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType5: [Protocol_ObjC1]
@objc var var_ArrayType5_: [Protocol_ObjC1] // no-error
var var_ArrayType6: [Class_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType6: [Class_ObjC1]
@objc var var_ArrayType6_: [Class_ObjC1] // no-error
var var_ArrayType7: [PlainClass]
// CHECK-LABEL: {{^}} var var_ArrayType7: [PlainClass]
@objc var var_ArrayType7_: [PlainClass]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType8: [PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType8: [PlainProtocol]
@objc var var_ArrayType8_: [PlainProtocol]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType9: [Protocol_ObjC1 & PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType9: [PlainProtocol & Protocol_ObjC1]
@objc var var_ArrayType9_: [Protocol_ObjC1 & PlainProtocol]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
// CHECK-LABEL: {{^}} @objc var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
@objc var var_ArrayType10_: [Protocol_ObjC1 & Protocol_ObjC2]
// no-error
var var_ArrayType11: [Any]
// CHECK-LABEL: @objc var var_ArrayType11: [Any]
@objc var var_ArrayType11_: [Any]
var var_ArrayType13: [Any?]
// CHECK-LABEL: {{^}} var var_ArrayType13: [Any?]
@objc var var_ArrayType13_: [Any?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType15: [AnyObject?]
// CHECK-LABEL: {{^}} var var_ArrayType15: [AnyObject?]
@objc var var_ArrayType15_: [AnyObject?]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType16: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType16: {{\[}}[@convention(block) (AnyObject) -> AnyObject]]
@objc var var_ArrayType16_: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
var var_ArrayType17: [[(AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType17: {{\[}}[(AnyObject) -> AnyObject]]
@objc var var_ArrayType17_: [[(AnyObject) -> AnyObject]]
// expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
}
@objc
class ObjCBase {}
class infer_instanceVar2<
GP_Unconstrained,
GP_PlainClass : PlainClass,
GP_PlainProtocol : PlainProtocol,
GP_Class_ObjC : Class_ObjC1,
GP_Protocol_Class : Protocol_Class1,
GP_Protocol_ObjC : Protocol_ObjC1> : ObjCBase {
// CHECK-LABEL: class infer_instanceVar2<{{.*}}> : ObjCBase {
override init() {}
var var_GP_Unconstrained: GP_Unconstrained
// CHECK-LABEL: {{^}} var var_GP_Unconstrained: GP_Unconstrained
@objc var var_GP_Unconstrained_: GP_Unconstrained
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainClass: GP_PlainClass
// CHECK-LABEL: {{^}} var var_GP_PlainClass: GP_PlainClass
@objc var var_GP_PlainClass_: GP_PlainClass
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainProtocol: GP_PlainProtocol
// CHECK-LABEL: {{^}} var var_GP_PlainProtocol: GP_PlainProtocol
@objc var var_GP_PlainProtocol_: GP_PlainProtocol
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Class_ObjC: GP_Class_ObjC
// CHECK-LABEL: {{^}} var var_GP_Class_ObjC: GP_Class_ObjC
@objc var var_GP_Class_ObjC_: GP_Class_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_Class: GP_Protocol_Class
// CHECK-LABEL: {{^}} var var_GP_Protocol_Class: GP_Protocol_Class
@objc var var_GP_Protocol_Class_: GP_Protocol_Class
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_ObjC: GP_Protocol_ObjC
// CHECK-LABEL: {{^}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC
@objc var var_GP_Protocol_ObjCa: GP_Protocol_ObjC
// expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
func func_GP_Unconstrained(a: GP_Unconstrained) {}
// CHECK-LABEL: {{^}} func func_GP_Unconstrained(a: GP_Unconstrained) {
@objc func func_GP_Unconstrained_(a: GP_Unconstrained) {}
// expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
}
class infer_instanceVar3 : Class_ObjC1 {
// CHECK-LABEL: @objc class infer_instanceVar3 : Class_ObjC1 {
var v1: Int = 0
// CHECK-LABEL: @objc var v1: Int
}
@objc
protocol infer_instanceVar4 {
// CHECK-LABEL: @objc protocol infer_instanceVar4 {
var v1: Int { get }
// CHECK-LABEL: @objc var v1: Int { get }
}
// @!objc
class infer_instanceVar5 {
// CHECK-LABEL: {{^}}class infer_instanceVar5 {
@objc
var intstanceVar1: Int {
// CHECK: @objc var intstanceVar1: Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
class infer_staticVar1 {
// CHECK-LABEL: @objc class infer_staticVar1 {
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
// CHECK: @objc class var staticVar1: Int
}
// @!objc
class infer_subscript1 {
// CHECK-LABEL: class infer_subscript1
@objc
subscript(i: Int) -> Int {
// CHECK: @objc subscript(i: Int) -> Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc
protocol infer_throughConformanceProto1 {
// CHECK-LABEL: @objc protocol infer_throughConformanceProto1 {
func funcObjC1()
var varObjC1: Int { get }
var varObjC2: Int { get set }
// CHECK: @objc func funcObjC1()
// CHECK: @objc var varObjC1: Int { get }
// CHECK: @objc var varObjC2: Int { get set }
}
class infer_class1 : PlainClass {}
// CHECK-LABEL: {{^}}class infer_class1 : PlainClass {
class infer_class2 : Class_ObjC1 {}
// CHECK-LABEL: @objc class infer_class2 : Class_ObjC1 {
class infer_class3 : infer_class2 {}
// CHECK-LABEL: @objc class infer_class3 : infer_class2 {
class infer_class4 : Protocol_Class1 {}
// CHECK-LABEL: {{^}}class infer_class4 : Protocol_Class1 {
class infer_class5 : Protocol_ObjC1 {}
// CHECK-LABEL: {{^}}class infer_class5 : Protocol_ObjC1 {
//
// If a protocol conforms to an @objc protocol, this does not infer @objc on
// the protocol itself, or on the newly introduced requirements. Only the
// inherited @objc requirements get @objc.
//
// Same rule applies to classes.
//
protocol infer_protocol1 {
// CHECK-LABEL: {{^}}protocol infer_protocol1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol2 : Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol2 : Protocol_Class1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol3 : Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol3 : Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
class C {
// Don't crash.
@objc func foo(x: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}}
@IBAction func myAction(sender: Undeclared) {} // expected-error {{use of undeclared type 'Undeclared'}}
}
//===---
//===--- @IBOutlet implies @objc
//===---
class HasIBOutlet {
// CHECK-LABEL: {{^}}class HasIBOutlet {
init() {}
@IBOutlet weak var goodOutlet: Class_ObjC1!
// CHECK-LABEL: {{^}} @IBOutlet @objc weak var goodOutlet: @sil_weak Class_ObjC1!
@IBOutlet var badOutlet: PlainStruct
// expected-error@-1 {{@IBOutlet property cannot have non-object type 'PlainStruct'}} {{3-13=}}
// CHECK-LABEL: {{^}} @IBOutlet var badOutlet: PlainStruct
}
//===---
//===--- @IBAction implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBAction {
class HasIBAction {
@IBAction func goodAction(_ sender: AnyObject?) { }
// CHECK: {{^}} @IBAction @objc func goodAction(_ sender: AnyObject?) {
@IBAction func badAction(_ sender: PlainStruct?) { }
// expected-error@-1{{argument to @IBAction method cannot have non-object type 'PlainStruct?'}}
// expected-error@-2{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
}
//===---
//===--- @NSManaged implies @objc
//===---
class HasNSManaged {
// CHECK-LABEL: {{^}}class HasNSManaged {
init() {}
@NSManaged
var goodManaged: Class_ObjC1
// CHECK-LABEL: {{^}} @NSManaged @objc dynamic var goodManaged: Class_ObjC1
@NSManaged
var badManaged: PlainStruct
// expected-error@-1 {{property cannot be marked @NSManaged because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// CHECK-LABEL: {{^}} @NSManaged var badManaged: PlainStruct
}
//===---
//===--- Pointer argument types
//===---
@objc class TakesCPointers {
// CHECK-LABEL: {{^}}@objc class TakesCPointers {
func constUnsafeMutablePointer(p: UnsafePointer<Int>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointer(p: UnsafePointer<Int>) {
func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {
func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {
func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {}
// CHECK-LABEL: @objc func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {
func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {
func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {
}
// @objc with nullary names
@objc(NSObjC2)
class Class_ObjC2 {
// CHECK-LABEL: @objc(NSObjC2) class Class_ObjC2
@objc(initWithMalice)
init(foo: ()) { }
@objc(initWithIntent)
init(bar _: ()) { }
@objc(initForMurder)
init() { }
@objc(isFoo)
func foo() -> Bool {}
// CHECK-LABEL: @objc(isFoo) func foo() -> Bool {
}
@objc() // expected-error{{expected name within parentheses of @objc attribute}}
class Class_ObjC3 {
}
// @objc with selector names
extension PlainClass {
// CHECK-LABEL: @objc(setFoo:) dynamic func
@objc(setFoo:)
func foo(b: Bool) { }
// CHECK-LABEL: @objc(setWithRed:green:blue:alpha:) dynamic func set
@objc(setWithRed:green:blue:alpha:)
func set(_: Float, green: Float, blue: Float, alpha: Float) { }
// CHECK-LABEL: @objc(createWithRed:green:blue:alpha:) dynamic class func createWith
@objc(createWithRed:green blue:alpha)
class func createWithRed(_: Float, green: Float, blue: Float, alpha: Float) { }
// expected-error@-2{{missing ':' after selector piece in @objc attribute}}{{28-28=:}}
// expected-error@-3{{missing ':' after selector piece in @objc attribute}}{{39-39=:}}
// CHECK-LABEL: @objc(::) dynamic func badlyNamed
@objc(::)
func badlyNamed(_: Int, y: Int) {}
}
@objc(Class:) // expected-error{{'@objc' class must have a simple name}}{{12-13=}}
class BadClass1 { }
@objc(Protocol:) // expected-error{{'@objc' protocol must have a simple name}}{{15-16=}}
protocol BadProto1 { }
@objc(Enum:) // expected-error{{'@objc' enum must have a simple name}}{{11-12=}}
enum BadEnum1: Int { case X }
@objc
enum BadEnum2: Int {
@objc(X:) // expected-error{{'@objc' enum case must have a simple name}}{{10-11=}}
case X
}
class BadClass2 {
@objc(badprop:foo:wibble:) // expected-error{{'@objc' property must have a simple name}}{{16-28=}}
var badprop: Int = 5
@objc(foo) // expected-error{{'@objc' subscript cannot have a name; did you mean to put the name on the getter or setter?}}
subscript (i: Int) -> Int {
get {
return i
}
}
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam(x: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam2(_: Int) { }
@objc(foo) // expected-error{{'@objc' method name provides names for 0 arguments, but method has 2 parameters}}
func noArgNamesTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 2 parameters}}
func oneArgNameTwoParams(_: Int, y: Int) { }
@objc(foo:) // expected-error{{'@objc' method name provides one argument name, but method has 0 parameters}}
func oneArgNameNoParams() { }
@objc(foo:) // expected-error{{'@objc' initializer name provides one argument name, but initializer has 0 parameters}}
init() { }
var _prop = 5
@objc var prop: Int {
@objc(property) get { return _prop }
@objc(setProperty:) set { _prop = newValue }
}
var prop2: Int {
@objc(property) get { return _prop } // expected-error{{'@objc' getter for non-'@objc' property}}
@objc(setProperty:) set { _prop = newValue } // expected-error{{'@objc' setter for non-'@objc' property}}
}
var prop3: Int {
@objc(setProperty:) didSet { } // expected-error{{observing accessors are not allowed to be marked @objc}} {{5-10=}}
}
@objc
subscript (c: Class_ObjC1) -> Class_ObjC1 {
@objc(getAtClass:) get {
return c
}
@objc(setAtClass:class:) set {
}
}
}
// Swift overrides that aren't also @objc overrides.
class Super {
@objc(renamedFoo)
var foo: Int { get { return 3 } } // expected-note 2{{overridden declaration is here}}
@objc func process(i: Int) -> Int { } // expected-note {{overriding '@objc' method 'process(i:)' here}}
}
class Sub1 : Super {
@objc(foo) // expected-error{{Objective-C property has a different name from the property it overrides ('foo' vs. 'renamedFoo')}}{{9-12=renamedFoo}}
override var foo: Int { get { return 5 } }
override func process(i: Int?) -> Int { } // expected-error{{method cannot be an @objc override because the type of the parameter cannot be represented in Objective-C}}
}
class Sub2 : Super {
@objc
override var foo: Int { get { return 5 } }
}
class Sub3 : Super {
override var foo: Int { get { return 5 } }
}
class Sub4 : Super {
@objc(renamedFoo)
override var foo: Int { get { return 5 } }
}
class Sub5 : Super {
@objc(wrongFoo) // expected-error{{Objective-C property has a different name from the property it overrides ('wrongFoo' vs. 'renamedFoo')}} {{9-17=renamedFoo}}
override var foo: Int { get { return 5 } }
}
enum NotObjCEnum { case X }
struct NotObjCStruct {}
// Closure arguments can only be @objc if their parameters and returns are.
// CHECK-LABEL: @objc class ClosureArguments
@objc class ClosureArguments {
// CHECK: @objc func foo
@objc func foo(f: (Int) -> ()) {}
// CHECK: @objc func bar
@objc func bar(f: (NotObjCEnum) -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func bas
@objc func bas(f: (NotObjCEnum) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zim
@objc func zim(f: () -> NotObjCStruct) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zang
@objc func zang(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
@objc func zangZang(f: (Int...) -> ()) {} // expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func fooImplicit
func fooImplicit(f: (Int) -> ()) {}
// CHECK: {{^}} func barImplicit
func barImplicit(f: (NotObjCEnum) -> NotObjCStruct) {}
// CHECK: {{^}} func basImplicit
func basImplicit(f: (NotObjCEnum) -> ()) {}
// CHECK: {{^}} func zimImplicit
func zimImplicit(f: () -> NotObjCStruct) {}
// CHECK: {{^}} func zangImplicit
func zangImplicit(f: (NotObjCEnum, NotObjCStruct) -> ()) {}
// CHECK: {{^}} func zangZangImplicit
func zangZangImplicit(f: (Int...) -> ()) {}
}
typealias GoodBlock = @convention(block) (Int) -> ()
typealias BadBlock = @convention(block) (NotObjCEnum) -> () // expected-error{{'(NotObjCEnum) -> ()' is not representable in Objective-C, so it cannot be used with '@convention(block)'}}
@objc class AccessControl {
// CHECK: @objc func foo
func foo() {}
// CHECK: {{^}} private func bar
private func bar() {}
// CHECK: @objc private func baz
@objc private func baz() {}
}
//===--- Ban @objc +load methods
class Load1 {
// Okay: not @objc
class func load() { }
class func alloc() {}
class func allocWithZone(_: Int) {}
}
@objc class Load2 {
class func load() { } // expected-error{{method 'load()' defines Objective-C class method 'load', which is not permitted by Swift}}
class func alloc() {} // expected-error{{method 'alloc()' defines Objective-C class method 'alloc', which is not permitted by Swift}}
class func allocWithZone(_: Int) {} // expected-error{{method 'allocWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
}
@objc class Load3 {
class var load: Load3 {
get { return Load3() } // expected-error{{getter for 'load' defines Objective-C class method 'load', which is not permitted by Swift}}
set { }
}
@objc(alloc) class var prop: Int { return 0 } // expected-error{{getter for 'prop' defines Objective-C class method 'alloc', which is not permitted by Swift}}
@objc(allocWithZone:) class func fooWithZone(_: Int) {} // expected-error{{method 'fooWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
}
// Members of protocol extensions cannot be @objc
extension PlainProtocol {
@objc final var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc final subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc final func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
@objc final var property: Int { return 5 } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc final subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
@objc final func fun() { } // expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
}
extension Protocol_ObjC1 {
// Don't infer @objc for extensions of @objc protocols.
// CHECK: {{^}} var propertyOK: Int
final var propertyOK: Int { return 5 }
}
//===---
//===--- Error handling
//===---
class ClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
@objc func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
@objc func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
@objc func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
@objc func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: @objc init(degrees: Double) throws
@objc init(degrees: Double) throws { }
// Errors
@objc func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type 'Class_ObjC1?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsOptionalArray() throws -> [String]? { return nil } // expected-error{{throwing method cannot be marked @objc because it returns a value of optional type '[String]?'; 'nil' indicates failure to Objective-C}}
@objc func methodReturnsInt() throws -> Int { return 0 } // expected-error{{throwing method cannot be marked @objc because it returns a value of type 'Int'; return 'Void' or a type that bridges to an Objective-C class}}
@objc func methodAcceptsThrowingFunc(fn: (String) throws -> Int) { }
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{throwing function types cannot be represented in Objective-C}}
@objc init?(radians: Double) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc init!(string: String) throws { } // expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc func fooWithErrorEnum1(x: ErrorEnum) {}
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{non-'@objc' enums cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorEnum2(x: ErrorEnum)
func fooWithErrorEnum2(x: ErrorEnum) {}
@objc func fooWithErrorProtocolComposition1(x: Error & Protocol_ObjC1) { }
// expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{protocol composition involving 'Error' cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1)
func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1) { }
}
// CHECK-DUMP-LABEL: class_decl "ImplicitClassThrows1"
@objc class ImplicitClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
// CHECK-DUMP: func_decl "methodReturnsVoid()"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
// CHECK-DUMP: func_decl "methodReturnsObjCClass()" {{.*}}foreign_error=NilResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: {{^}} func methodReturnsOptionalObjCClass() throws -> Class_ObjC1?
func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil }
// CHECK: @objc func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int)
// CHECK-DUMP: func_decl "methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int) throws { }
// CHECK: @objc init(degrees: Double) throws
// CHECK-DUMP: constructor_decl "init(degrees:)"{{.*}}foreign_error=NilResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
init(degrees: Double) throws { }
// CHECK: {{^}} func methodReturnsBridgedValueType() throws -> NSRange
func methodReturnsBridgedValueType() throws -> NSRange { return NSRange() }
@objc func methodReturnsBridgedValueType2() throws -> NSRange {
return NSRange()
}
// expected-error@-3{{throwing method cannot be marked @objc because it returns a value of type 'NSRange' (aka '_NSRange'); return 'Void' or a type that bridges to an Objective-C class}}
// CHECK: {{^}} @objc func methodReturnsError() throws -> Error
func methodReturnsError() throws -> Error { return ErrorEnum.failed }
// CHECK: @objc func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int)
func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int) {
func add(x: Int) -> (Int) -> Int {
return { x + $0 }
}
}
}
// CHECK-DUMP-LABEL: class_decl "SubclassImplicitClassThrows1"
@objc class SubclassImplicitClassThrows1 : ImplicitClassThrows1 {
// CHECK: @objc override func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping ((Int) -> Int), fn3: @escaping ((Int) -> Int))
// CHECK-DUMP: func_decl "methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: (@escaping (Int) -> Int), fn3: (@escaping (Int) -> Int)) throws { }
}
class ThrowsRedecl1 {
@objc func method1(_ x: Int, error: Class_ObjC1) { } // expected-note{{declared here}}
@objc func method1(_ x: Int) throws { } // expected-error{{with Objective-C selector 'method1:error:'}}
@objc func method2AndReturnError(_ x: Int) { } // expected-note{{declared here}}
@objc func method2() throws { } // expected-error{{with Objective-C selector 'method2AndReturnError:'}}
@objc func method3(_ x: Int, error: Int, closure: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc func method3(_ x: Int, closure: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'method3:error:closure:'}}
@objc(initAndReturnError:) func initMethod1(error: Int) { } // expected-note{{declared here}}
@objc init() throws { } // expected-error{{with Objective-C selector 'initAndReturnError:'}}
@objc(initWithString:error:) func initMethod2(string: String, error: Int) { } // expected-note{{declared here}}
@objc init(string: String) throws { } // expected-error{{with Objective-C selector 'initWithString:error:'}}
@objc(initAndReturnError:fn:) func initMethod3(error: Int, fn: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc init(fn: (Int) -> Int) throws { } // expected-error{{with Objective-C selector 'initAndReturnError:fn:'}}
}
class ThrowsObjCName {
@objc(method4:closure:error:) func method4(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method5AndReturnError:x:closure:) func method5(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method6) func method6() throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has one parameter (the error parameter)}}
@objc(method7) func method7(x: Int) throws { } // expected-error{{@objc' method name provides names for 0 arguments, but method has 2 parameters (including the error parameter)}}
// CHECK-DUMP: func_decl "method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method8:fn1:error:fn2:)
func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl "method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method9AndReturnError:s:fn1:fn2:)
func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
class SubclassThrowsObjCName : ThrowsObjCName {
// CHECK-DUMP: func_decl "method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl "method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
@objc protocol ProtocolThrowsObjCName {
@objc optional func doThing(_ x: String) throws -> String // expected-note{{requirement 'doThing' declared here}}
}
class ConformsToProtocolThrowsObjCName1 : ProtocolThrowsObjCName {
@objc func doThing(_ x: String) throws -> String { return x } // okay
}
class ConformsToProtocolThrowsObjCName2 : ProtocolThrowsObjCName {
@objc func doThing(_ x: Int) throws -> String { return "" }
// expected-warning@-1{{instance method 'doThing' nearly matches optional requirement 'doThing' of protocol 'ProtocolThrowsObjCName'}}
// expected-note@-2{{move 'doThing' to an extension to silence this warning}}
// expected-note@-3{{make 'doThing' private to silence this warning}}{{9-9=private }}
// expected-note@-4{{candidate has non-matching type '(Int) throws -> String'}}
}
@objc class DictionaryTest {
// CHECK-LABEL: @objc func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>)
func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
// CHECK-LABEL: @objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>)
@objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
func func_dictionary2a(x: Dictionary<String, Int>) { }
@objc func func_dictionary2b(x: Dictionary<String, Int>) { }
}
@objc class ObjC_Class1 : Hashable {
var hashValue: Int { return 0 }
}
func ==(lhs: ObjC_Class1, rhs: ObjC_Class1) -> Bool {
return true
}
// CHECK-LABEL: @objc class OperatorInClass
@objc class OperatorInClass {
// CHECK: {{^}} static func ==(lhs: OperatorInClass, rhs: OperatorInClass) -> Bool
static func ==(lhs: OperatorInClass, rhs: OperatorInClass) -> Bool {
return true
}
// CHECK: {{^}} @objc static func +(lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass
@objc static func +(lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass { // expected-error {{operator methods cannot be declared @objc}}
return lhs
}
} // CHECK: {{^}$}}
@objc protocol OperatorInProtocol {
static func +(lhs: Self, rhs: Self) -> Self // expected-error {{@objc protocols may not have operator requirements}}
}
//===--- @objc inference for witnesses
@objc protocol InferFromProtocol {
@objc(inferFromProtoMethod1:)
optional func method1(value: Int)
}
// Infer when in the same declaration context.
// CHECK-LABEL: ClassInfersFromProtocol1
class ClassInfersFromProtocol1 : InferFromProtocol{
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
// Infer when in a different declaration context of the same class.
// CHECK-LABEL: ClassInfersFromProtocol2a
class ClassInfersFromProtocol2a {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
extension ClassInfersFromProtocol2a : InferFromProtocol { }
// Infer when in a different declaration context of the same class.
class ClassInfersFromProtocol2b : InferFromProtocol { }
// CHECK-LABEL: ClassInfersFromProtocol2b
extension ClassInfersFromProtocol2b {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
// Don't infer when there is a signature mismatch.
// CHECK-LABEL: ClassInfersFromProtocol3
class ClassInfersFromProtocol3 : InferFromProtocol {
}
extension ClassInfersFromProtocol3 {
// CHECK: {{^}} func method1(value: String)
func method1(value: String) { }
}
// Inference for subclasses.
class SuperclassImplementsProtocol : InferFromProtocol { }
class SubclassInfersFromProtocol1 : SuperclassImplementsProtocol {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
class SubclassInfersFromProtocol2 : SuperclassImplementsProtocol {
}
extension SubclassInfersFromProtocol2 {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
| apache-2.0 | eb1a1ff4f60690af3f0783100b8753eb | 39.433318 | 293 | 0.701785 | 3.866632 | false | false | false | false |
LynxTipSoftware/BTHeartrate | BTHeartRate/AppDelegate.swift | 1 | 2493 | //
// AppDelegate.swift
// BTHeartRate
//
// Created on 4/17/16.
// Copyright © 2016 LynxTip Software. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let navigationController = self.window?.rootViewController as! UINavigationController
let heartRateViewController = navigationController.topViewController as! HeartRateViewController
let bluetoothManager = BluetoothManager()
let heartRateViewModel = HeartRateViewModel(bluetoothManager: bluetoothManager)
heartRateViewController.viewModel = heartRateViewModel
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 7fd622bdd4bab4302c6c95f120c33a88 | 46.018868 | 285 | 0.753612 | 5.836066 | false | false | false | false |
zonble/MRTSwift | Sources/MRTLib/MRTRoute.swift | 1 | 1163 | import Foundation
public class MRTRoute {
public private(set) var from: MRTExit
public private(set) var links: [MRTLink]
public private(set) var transitions = [[(String, MRTExit, MRTExit)]]()
init(from: MRTExit, links: [MRTLink]) {
self.from = from
self.links = links
var transitionsArray = [[(String, MRTExit, MRTExit)]]()
var currentSection = [(String, MRTExit, MRTExit)]()
var lastLineID = links[0].lineID
currentSection.append((self.links[0].lineID, from, self.links[0].to))
for i in 1..<self.links.count {
let link = self.links[i]
if link.lineID != lastLineID {
var connected = false
switch link.lineID {
case "4":
connected = (lastLineID == "4A" || lastLineID == "4B")
case "4A":
connected = lastLineID == "4"
case "4B":
connected = lastLineID == "4"
default:
break
}
if (!connected) {
transitionsArray.append(currentSection)
currentSection = [(String, MRTExit, MRTExit)]()
}
}
currentSection.append((link.lineID, links[i - 1].to, link.to))
lastLineID = link.lineID
}
transitionsArray.append(currentSection)
self.transitions = transitionsArray
}
}
| mit | 3c5da81487dfb59b51154fac2fa6464e | 27.365854 | 71 | 0.653482 | 3.31339 | false | false | false | false |
Minecodecraft/50DaysOfSwift | Day 3 - ShowMyLocation/ShowMyLocation/ShowMyLocation/ViewController.swift | 1 | 2876 | //
// ViewController.swift
// ShowMyLocation
//
// Created by Minecode on 2017/6/29.
// Copyright © 2017年 org.minecode. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
// Widget
@IBOutlet weak var showButton: UIButton!
@IBOutlet weak var locationLabel: UILabel!
// Data
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// 由于采用深色背景,状态栏设置浅色
UIApplication.shared.statusBarStyle = .lightContent
}
@IBAction func showAction(_ sender: Any) {
// 初始化地图框架
locationManager = CLLocationManager()
locationManager.delegate = self
// 设置精度
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
// 遵守CLLocationManager协议
extension ViewController {
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
self.locationLabel.text = "Error while updating location: " + error.localizedDescription
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// 将经纬度转化成地址
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {
(placemarks, error) -> Void in
if error != nil {
self.locationLabel.text = "Reverse geocoder failed with error: " + error!.localizedDescription
return
}
if placemarks!.count > 0 {
let pm = placemarks![0]
self.displayLocationInfo(pm)
}
else {
self.locationLabel.text = "Error existed in the data received from geocoder"
}
})
}
func displayLocationInfo(_ placemark: CLPlacemark?) {
guard let containsPlacemark = placemark else {return}
locationManager.stopUpdatingLocation()
let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
let adminstrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
self.locationLabel.text = postalCode! + " " + locality!
self.locationLabel.text?.append("\n")
self.locationLabel.text?.append(adminstrativeArea! + ", " + country!)
}
}
| mit | e6cd445f74276136ab2309a2a6162a0d | 30.382022 | 121 | 0.621912 | 5.688391 | false | false | false | false |
mixalich7b/SwiftTBot | Pods/ObjectMapper/Sources/Mappable.swift | 3 | 4611 | //
// Mappable.swift
// ObjectMapper
//
// Created by Scott Hoyt on 10/25/15.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2018 Tristan Himmelman
//
// 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
/// BaseMappable should not be implemented directly. Mappable or StaticMappable should be used instead
public protocol BaseMappable {
/// This function is where all variable mappings should occur. It is executed by Mapper during the mapping (serialization and deserialization) process.
mutating func mapping(map: Map)
}
public protocol Mappable: BaseMappable {
/// This function can be used to validate JSON prior to mapping. Return nil to cancel mapping at this point
init?(map: Map)
}
public protocol StaticMappable: BaseMappable {
/// This is function that can be used to:
/// 1) provide an existing cached object to be used for mapping
/// 2) return an object of another class (which conforms to BaseMappable) to be used for mapping. For instance, you may inspect the JSON to infer the type of object that should be used for any given mapping
static func objectForMapping(map: Map) -> BaseMappable?
}
public extension BaseMappable {
/// Initializes object from a JSON String
public init?(JSONString: String, context: MapContext? = nil) {
if let obj: Self = Mapper(context: context).map(JSONString: JSONString) {
self = obj
} else {
return nil
}
}
/// Initializes object from a JSON Dictionary
public init?(JSON: [String: Any], context: MapContext? = nil) {
if let obj: Self = Mapper(context: context).map(JSON: JSON) {
self = obj
} else {
return nil
}
}
/// Returns the JSON Dictionary for the object
public func toJSON() -> [String: Any] {
return Mapper().toJSON(self)
}
/// Returns the JSON String for the object
public func toJSONString(prettyPrint: Bool = false) -> String? {
return Mapper().toJSONString(self, prettyPrint: prettyPrint)
}
}
public extension Array where Element: BaseMappable {
/// Initialize Array from a JSON String
public init?(JSONString: String, context: MapContext? = nil) {
if let obj: [Element] = Mapper(context: context).mapArray(JSONString: JSONString) {
self = obj
} else {
return nil
}
}
/// Initialize Array from a JSON Array
public init(JSONArray: [[String: Any]], context: MapContext? = nil) {
let obj: [Element] = Mapper(context: context).mapArray(JSONArray: JSONArray)
self = obj
}
/// Returns the JSON Array
public func toJSON() -> [[String: Any]] {
return Mapper().toJSONArray(self)
}
/// Returns the JSON String for the object
public func toJSONString(prettyPrint: Bool = false) -> String? {
return Mapper().toJSONString(self, prettyPrint: prettyPrint)
}
}
public extension Set where Element: BaseMappable {
/// Initializes a set from a JSON String
public init?(JSONString: String, context: MapContext? = nil) {
if let obj: Set<Element> = Mapper(context: context).mapSet(JSONString: JSONString) {
self = obj
} else {
return nil
}
}
/// Initializes a set from JSON
public init?(JSONArray: [[String: Any]], context: MapContext? = nil) {
guard let obj = Mapper(context: context).mapSet(JSONArray: JSONArray) as Set<Element>? else {
return nil
}
self = obj
}
/// Returns the JSON Set
public func toJSON() -> [[String: Any]] {
return Mapper().toJSONSet(self)
}
/// Returns the JSON String for the object
public func toJSONString(prettyPrint: Bool = false) -> String? {
return Mapper().toJSONString(self, prettyPrint: prettyPrint)
}
}
| gpl-3.0 | b33810c5d249f531711cfd2da0b086d6 | 32.904412 | 208 | 0.713728 | 3.964746 | false | false | false | false |
iException/garage | Garage/Sources/Extension/UIImage+Garage.swift | 1 | 3200 | //
// UIImage+Garage.swift
// Garage
//
// Created by Yiming Tang on 10/27/17.
// Copyright © 2017 Baixing. All rights reserved.
//
import UIKit
// MARK: - Alpha
extension UIImage {
/// Returns whether the image contains an alpha component.
var gar_containsAlphaComponent: Bool {
let alphaInfo = cgImage?.alphaInfo
return (
alphaInfo == .first ||
alphaInfo == .last ||
alphaInfo == .premultipliedFirst ||
alphaInfo == .premultipliedLast
)
}
/// Returns whether the image is opaque.
var gar_isOpaque: Bool { return !gar_containsAlphaComponent }
}
// MARK: - Scaling
extension UIImage {
func gar_imageScaled(to size: CGSize) -> UIImage {
assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height")
UIGraphicsBeginImageContextWithOptions(size, gar_isOpaque, 0.0)
draw(in: CGRect(origin: .zero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
UIGraphicsEndImageContext()
return scaledImage
}
func gar_imageAspectScaled(toFit size: CGSize) -> UIImage {
assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height")
let imageAspectRatio = self.size.width / self.size.height
let canvasAspectRatio = size.width / size.height
var resizeFactor: CGFloat
if imageAspectRatio > canvasAspectRatio {
resizeFactor = size.width / self.size.width
} else {
resizeFactor = size.height / self.size.height
}
let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor)
let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0)
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
draw(in: CGRect(origin: origin, size: scaledSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
UIGraphicsEndImageContext()
return scaledImage
}
func gar_imageAspectScaled(toFill size: CGSize) -> UIImage {
assert(size.width > 0 && size.height > 0, "You cannot safely scale an image to a zero width or height")
let imageAspectRatio = self.size.width / self.size.height
let canvasAspectRatio = size.width / size.height
var resizeFactor: CGFloat
if imageAspectRatio > canvasAspectRatio {
resizeFactor = size.height / self.size.height
} else {
resizeFactor = size.width / self.size.width
}
let scaledSize = CGSize(width: self.size.width * resizeFactor, height: self.size.height * resizeFactor)
let origin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0)
UIGraphicsBeginImageContextWithOptions(size, gar_isOpaque, 0.0)
draw(in: CGRect(origin: origin, size: scaledSize))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext() ?? self
UIGraphicsEndImageContext()
return scaledImage
}
}
| mit | e133c066aeb7fcd835e7596a3a9104f6 | 32.322917 | 114 | 0.650203 | 4.71134 | false | false | false | false |
BlenderSleuth/Circles | Circles/ValueTypes/Enums.swift | 1 | 1011 | //
// Enums.swift
// Circles
//
// Created by Ben Sutherland on 20/06/2016.
// Copyright © 2016 blendersleuthgraphics. All rights reserved.
//
import SpriteKit
/**
This method will generate a closed CGPath polygon from a given number of sides and radius.
- Note:
1 or 2 sides will not work
- parameters:
- numberOfSides: The number of sides to make the polygon
- radius: Radius of polygon to generate
*/
func createPolygonWithSides(_ numberOfSides: Int, radius: CGFloat) -> CGPath {
let path = CGMutablePath()
path.move(to: CGPoint.zero)
let oneSegment = π * 2 / CGFloat(numberOfSides)
var points = [CGPoint]()
for i in 1...numberOfSides {
let point = CGPoint(x: sin(oneSegment * CGFloat(i)) * radius,
y: cos(oneSegment * CGFloat(i)) * radius)
points.append(point)
}
path.addLines(between: points)
path.closeSubpath()
return path
}
enum LayerZposition: CGFloat {
case background = -5
case circleLayer = 0
case towerLayer = 5
case ui = 10
}
| gpl-3.0 | d98baf7d7d13c1405fc36fc42880bada | 20.934783 | 90 | 0.683845 | 3.515679 | false | false | false | false |
CharlinFeng/Reflect | Reflect/Reflect/Reflect/Reflect+Type.swift | 1 | 5280 | //
// Reflect+Type.swift
// Reflect
//
// Created by 冯成林 on 15/8/19.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
class ReflectType {
var typeName: String!
var typeClass: Any.Type!
var displayStyle: Mirror.DisplayStyle!
var displayStyleDesc: String!
var belongType: Any.Type!
var isOptional: Bool = false
var isArray: Bool = false
var isReflect:Bool = false
var realType: RealType = .None
var propertyMirrorType: Mirror
init(propertyMirrorType: Mirror, belongType: Any.Type){
self.propertyMirrorType = propertyMirrorType
self.belongType = belongType
parseBegin()
}
}
extension ReflectType{
func parseBegin(){
parseTypeName()
parseTypeClass()
parseTypedisplayStyle()
parseTypedisplayStyleDesc()
}
func parseTypeName(){
typeName = "\(propertyMirrorType.subjectType)".deleteSpecialStr()
}
func parseTypeClass(){
typeClass = propertyMirrorType.subjectType
}
func parseTypedisplayStyle(){
displayStyle = propertyMirrorType.displayStyle
if displayStyle == nil && basicTypes.contains(typeName) {displayStyle = .struct}
if extraTypes.contains(typeName) {displayStyle = .struct}
// guard displayStyle != nil else {fatalError("[Charlin Feng]: DisplayStyle Must Have Value")}
}
func parseTypedisplayStyleDesc(){
if displayStyle == nil {return}
switch displayStyle! {
case .struct: displayStyleDesc = "Struct"
case .class: displayStyleDesc = "Class"
case .optional: displayStyleDesc = "Optional"; isOptional = true;
case .enum: displayStyleDesc = "Enum"
case .tuple: displayStyleDesc = "Tuple"
default: displayStyleDesc = "Other: Collection/Dictionary/Set"
}
fetchRealType()
}
}
extension ReflectType{
enum BasicType: String{
case String
case Int
case Float
case Double
case Bool
case NSNumber
}
enum RealType: String{
case None = "None"
case Int = "Int"
case Float = "Float"
case Double = "Double"
case String = "String"
case Bool = "Bool"
case Class = "Class"
}
}
extension ReflectType{
var basicTypes: [String] {return ["String", "Int", "Float", "Double", "Bool"]}
var extraTypes: [String] {return ["__NSCFNumber", "_NSContiguousString", "NSTaggedPointerString"]}
var sdkTypes: [String] {return ["__NSCFNumber", "NSNumber", "_NSContiguousString", "UIImage", "_NSZeroData"]}
var aggregateTypes: [String: Any.Type] {return ["String": String.self, "Int": Int.self, "Float": Float.self, "Double": Double.self, "Bool": Bool.self, "NSNumber": NSNumber.self]}
func fetchRealType(){
if typeName.contain(subStr: "Array") {isArray = true}
if typeName.contain(subStr: "Int") {realType = RealType.Int}
else if typeName.contain(subStr: "Float") {realType = RealType.Float}
else if typeName.contain(subStr: "Double") {realType = RealType.Double}
else if typeName.contain(subStr: "String") {realType = RealType.String}
else if typeName.contain(subStr: "Bool") {realType = RealType.Bool}
else if typeName.contain(subStr: "NSNumber") {realType = RealType.Bool}
else {realType = RealType.Class}
if .Class == realType && !sdkTypes.contains(typeName) {
isReflect = true
}
}
class func makeClass(type: ReflectType) -> AnyClass {
let arrayString = type.typeName
var clsString = arrayString?.replacingOccurrencesOfString(target: "Array<", withString: "").replacingOccurrencesOfString(target: "Optional<", withString: "").replacingOccurrencesOfString(target: ">", withString: "") ?? ""
clsString = arrayString?.replacingOccurrencesOfString(target: "Array<", withString: "") ?? ""
clsString = clsString.replacingOccurrencesOfString(target: "Optional", withString: "")
clsString = clsString.replacingOccurrencesOfString(target: "ImplicitlyUnwrapped", withString: "")
var cls: AnyClass? = ClassFromString(str: clsString)
if cls == nil && type.isReflect {
var nameSpaceString = "\(type.belongType ?? Any.self).\(clsString)" ?? ""
cls = ClassFromString(str: nameSpaceString)
}
return cls!
}
func isAggregate() -> Any!{
var res: Any! = nil
for (typeStr, type) in aggregateTypes {
if typeName.contain(subStr: typeStr) {res = type}
}
return res
}
func check() -> Bool{
if isArray {return true}
return self.realType != RealType.Int && self.realType != RealType.Float && self.realType != RealType.Double
}
}
| mit | 6b90411d1cbee0e9986e67011c7da6bb | 26.14433 | 229 | 0.581086 | 4.944601 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Authentication/Authentication/AuthenticationInterfaceBuilder.swift | 1 | 7281 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
/**
* A type of view controller that can be managed by an authentication coordinator.
*/
typealias AuthenticationStepViewController = UIViewController & AuthenticationCoordinatedViewController
/**
* An object that builds view controllers for authentication steps.
*/
class AuthenticationInterfaceBuilder {
/**
* Returns the view controller that displays the interface of the authentication step.
*
* - note: When new steps are added to the list of steps, you need to handle them here,
* otherwise the method will return `nil`.
*
* - parameter step: The step to create an interface for.
* - returns: The view controller to use for this step, or `nil` if the interface builder
* does not support this step.
*/
func makeViewController(for step: AuthenticationFlowStep) -> AuthenticationStepViewController? {
switch step {
case .landingScreen:
return LandingViewController()
case .reauthenticate(let credentials, let numberOfAccounts):
let registrationViewController = RegistrationViewController(authenticationFlow: .onlyLogin)
registrationViewController.shouldHideCancelButton = numberOfAccounts < 2
registrationViewController.loginCredentials = credentials
return registrationViewController
case .provideCredentials:
#if ALLOW_ONLY_EMAIL_LOGIN
let loginViewController = RegistrationViewController(authenticationFlow: .onlyLogin)
#else
let loginViewController = RegistrationViewController(authenticationFlow: .login)
#endif
loginViewController.shouldHideCancelButton = true
return loginViewController
case .createCredentials:
let registrationViewController = RegistrationViewController(authenticationFlow: .registration)
registrationViewController.shouldHideCancelButton = true
return registrationViewController
case .clientManagement(let clients, let credentials):
let emailCredentials = credentials.map { ZMEmailCredentials(email: $0.email!, password: $0.password!) }
let flow = ClientUnregisterFlowViewController(clientsList: clients, credentials: emailCredentials)
return AdaptiveFormViewController(childViewController: flow)
case .noHistory(_, let type):
let noHistory = NoHistoryViewController(contextType: type)
return AdaptiveFormViewController(childViewController: noHistory)
case .enterLoginCode(let phoneNumber):
let verification = VerificationCodeStepViewController(credential: phoneNumber)
return AdaptiveFormViewController(childViewController: verification)
case .addEmailAndPassword(_, _, let canSkip):
let addEmailPasswordViewController = AddEmailPasswordViewController()
addEmailPasswordViewController.canSkipStep = canSkip
return AdaptiveFormViewController(childViewController: addEmailPasswordViewController)
case .enterActivationCode(let credentials, _):
let verification = VerificationCodeStepViewController(credential: credentials.rawValue)
return AdaptiveFormViewController(childViewController: verification)
case .pendingEmailLinkVerification(let emailCredentials):
let verification = EmailLinkVerificationViewController(credentials: emailCredentials)
return AdaptiveFormViewController(childViewController: verification)
case .incrementalUserCreation(let user, let registrationStep):
return makeRegistrationStepViewController(for: registrationStep, user: user).map {
AdaptiveFormViewController(childViewController: $0)
}
case .teamCreation(let state):
return makeTeamCreationStepViewController(for: state)
default:
return nil
}
}
/**
* Returns the view controller that displays the interface for the given intermediate
* registration step.
*
* - parameter step: The step to create an interface for.
* - parameter user: The unregistered user that is being created.
* - returns: The view controller to use for this step, or `nil` if the interface builder
* does not support this step.
*/
private func makeRegistrationStepViewController(for step: IntermediateRegistrationStep, user: UnregisteredUser) -> AuthenticationStepViewController? {
switch step {
case .start:
return nil
case .provideMarketingConsent:
return nil
case .setName:
return NameStepViewController()
}
}
/**
* Returns the view controller that displays the interface for the given team creation step.
*
* - parameter step: The step to create an interface for.
* - returns: The view controller to use for this step, or `nil` if the interface builder
* does not support this step.
*/
private func makeTeamCreationStepViewController(for state: TeamCreationState) -> AuthenticationStepViewController? {
var stepDescription: TeamCreationStepDescription
switch state {
case .setTeamName:
stepDescription = SetTeamNameStepDescription()
case .setEmail:
stepDescription = SetEmailStepDescription()
case let .verifyEmail(teamName: _, email: email):
stepDescription = VerifyEmailStepDescription(email: email)
case .setFullName:
stepDescription = SetFullNameStepDescription()
case .setPassword:
stepDescription = SetPasswordStepDescription()
case .inviteMembers:
return TeamMemberInviteViewController()
default:
return nil
}
return createViewController(for: stepDescription)
}
/// Creates the view controller for team description.
private func createViewController(for description: TeamCreationStepDescription) -> TeamCreationStepController {
let controller = TeamCreationStepController(description: description)
let mainView = description.mainView
mainView.valueSubmitted = controller.valueSubmitted
mainView.valueValidated = { (error: TextFieldValidator.ValidationError) in
switch error {
case .none:
controller.clearError()
default:
controller.displayError(error)
}
}
return controller
}
}
| gpl-3.0 | 32afc4282424e964acda7fd737e109ad | 39.45 | 154 | 0.696882 | 5.820144 | false | false | false | false |
tqtifnypmb/armature | Sources/Armature/InputStream/RawInputStream.swift | 1 | 2125 | //
// BufferedInputStream.swift
// Armature
//
// The MIT License (MIT)
//
// Copyright (c) 2016 tqtifnypmb
//
// 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
final class RawInputStream: InputStream {
private let sock: Int32
required init(sock: Int32) {
self.sock = sock
}
func readInto(inout buffer: [UInt8]) throws -> Int {
let nread = read(self.sock, &buffer , Int(buffer.count))
if nread == -1 {
throw SocketError.ReadFailed(Socket.getErrorDescription())
} else if nread == 0 {
throw SocketError.ReadFailed("Trying to read a closed socket")
}
return nread
}
func readN(buffer: UnsafeMutablePointer<Void>, n: UInt32) throws {
var remain = n
let ptr = buffer
while remain > 0 {
let nread = read(sock, ptr.advancedBy(Int(n - remain)) , Int(remain))
if (nread == -1) {
throw SocketError.ReadFailed(Socket.getErrorDescription())
}
remain -= UInt32(nread)
}
}
}
| mit | f633a5b12c4901534d86b2455df63318 | 36.946429 | 82 | 0.668706 | 4.319106 | false | false | false | false |
icylydia/PlayWithLeetCode | 144. Binary Tree Preorder Traversal/iterative.swift | 1 | 899 | /**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
func preorderTraversal(root: TreeNode?) -> [Int] {
var stack = Stack<TreeNode?>()
stack.push(root)
var ans = [Int]()
while !stack.isEmpty {
if let head = stack.pop() {
ans.append(head.val)
stack.push(head.right)
stack.push(head.left)
}
}
return ans
}
}
struct Stack<E> {
private var elements = [E]()
var isEmpty: Bool {
return elements.count == 0
}
mutating func push(element: E) {
elements.append(element)
}
mutating func pop() -> E {
return elements.removeLast()
}
} | mit | 42aa07ca413211984bb3bef1c9b9b9a7 | 21.5 | 54 | 0.54505 | 3.418251 | false | false | false | false |
FandyLiu/FDDemoCollection | Swift/iOSCoreAnimationDemo/iOSCoreAnimationDemo/LayerTreeViewController.swift | 1 | 826 | //
// LayerTreeViewController.swift
// iOSCoreAnimationDemo
//
// Created by QianTuFD on 2017/4/24.
// Copyright © 2017年 fandy. All rights reserved.
//
import UIKit
class LayerTreeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.gray
let rect = CGRect(x: 100, y: 100, width: 100, height: 100)
let layerView = UIView(frame: rect)
view.addSubview(layerView)
let blueLayer = CALayer()
blueLayer.frame = CGRect(x: 50, y: 50, width: 100, height: 100)
blueLayer.backgroundColor = UIColor.blue.cgColor
layerView.layer .addSublayer(blueLayer)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 13199ec9ffff95ad4584ff5baeac2e94 | 23.939394 | 71 | 0.63548 | 4.546961 | false | false | false | false |
Hexaville/HexavilleAuth | Sources/HexavilleAuth/HexavilleAuth+Router.swift | 1 | 3073 | //
// HexavilleAuth+Router.swift
// HexavilleAuth
//
// Created by Yuki Takei on 2017/06/25.
//
//
import Foundation
import HexavilleFramework
extension HexavilleAuth {
func asRouter() -> Router {
var router = Router()
for type in providers {
switch type {
case .oauth1(let provider):
router.use(.GET, provider.path) { request, context in
let requestToken = try provider.getRequestToken(for: request)
context.session?["hexaville.oauth_token_secret"] = requestToken.oauthTokenSecret
context.session?["hexaville.oauth_token"] = requestToken.oauthToken
let location = try provider.createAuthorizeURL(requestToken: requestToken).absoluteString
var headers = context.responseHeaders
headers.add(name: "Location", value: location)
return Response(status: .found, headers: headers)
}
router.use(.GET, provider.oauth.callbackURL.path) { request, context in
guard let secret = context.session?["hexaville.oauth_token_secret"] as? String else {
throw OAuth1Error.accessTokenIsMissingInSession
}
guard let token = context.session?["hexaville.oauth_token"] as? String else {
throw OAuth1Error.accessTokenIsMissingInSession
}
let requestToken = RequestToken(
oauthToken: token,
oauthTokenSecret: secret,
oauthCallbackConfirmed: nil
)
let (cred, user) = try provider.authorize(request: request, requestToken: requestToken)
context.session?[AuthenticationMiddleware.sessionKey] = user.serialize()
return try provider.callback(cred, user, request, context)
}
case .oauth2(let provider):
router.use(.GET, provider.path) { request, context in
return Response(
status: .found,
headers: [
"Location": try provider.createAuthorizeURL(for: request).absoluteString
]
)
}
router.use(.GET, provider.oauth.callbackURL.path) { request, context in
let (cred, user) = try provider.authorize(for: request)
context.session?[AuthenticationMiddleware.sessionKey] = user.serialize()
return try provider.callback(cred, user, request, context)
}
}
}
return router
}
}
extension HexavilleFramework {
public func use(_ auth: HexavilleAuth) {
self.use(auth.asRouter())
}
}
| mit | 75c6b19ba5cc0aceb6e2428bfe441478 | 39.434211 | 109 | 0.516759 | 5.809074 | false | false | false | false |
didinozka/DreamsDiary | dreamsDiary/Controller/FeedViewController.swift | 1 | 5507 | //
// FeedViewController.swift
// dreamsDiary
//
// Created by Dusan Drabik on 05/06/16.
// Copyright © 2016 drabik. All rights reserved.
//
import UIKit
import Firebase
class FeedViewController: UIViewController {
@IBOutlet var feedTable: UITableView!
@IBOutlet var newFeedDescriptionTextField: UITextField!
@IBOutlet var picturePickerPickedImage: UIImageView!
var imagePicker: UIImagePickerController!
var pickedImage: UIImage?
var feeds: [Feed] = [Feed]()
// static var imageCache: NSCache = NSCache()
}
extension FeedViewController {
@IBAction func picturePickerTapped(sender: UITapGestureRecognizer) {
self.presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func newFeedAddBtnPressed(sender: AnyObject) {
// let image = picturePickerPickedImage.image
self.resignFirstResponder()
view.endEditing(true)
if newFeedDescriptionTextField == "" {
print("No feed description entered")
return
}
let image = pickedImage
DataManipulationRemote.createNewFeed(image, feedDescription: newFeedDescriptionTextField.text!)
newFeedDescriptionTextField.text = nil
resetPickerImage()
}
}
extension FeedViewController {
override func viewDidLoad() {
feedTable.dataSource = self
feedTable.delegate = self
imagePicker = UIImagePickerController()
imagePicker.delegate = self
addListenerOnFeedsChange()
feedTable.estimatedRowHeight = 352
}
}
extension FeedViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Data.sharedInstance.feeds.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if let cell = feedTable.dequeueReusableCellWithIdentifier("feedCell") as? FeedCell {
let feed = Data.sharedInstance.feeds[indexPath.row]
// if request in cell is created, cancel it
// cell.reqest?.cancel()
var img: UIImage?
if feed.ImgURL != "" {
img = Data.sharedInstance.imageCache.objectForKey(feed.ImgURL) as? UIImage
Data.sharedInstance.feeds[indexPath.row].Image = img
}
// cell.configureCell(feed, image: img)
cell.configureCell(indexPath.row, image: img)
return cell
}
return UITableViewCell()
}
}
extension FeedViewController: UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let feed = Data.sharedInstance.feeds[indexPath.row]
if feed.ImgURL == "" {
return 150
} else {
return feedTable.estimatedRowHeight
}
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let feedIndex = indexPath.row
performSegueWithIdentifier("feedDetailSegue", sender: feedIndex)
}
}
extension FeedViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
picturePickerPickedImage.image = image
pickedImage = image
}
}
// Helpers - need to refactor
extension FeedViewController {
func addListenerOnFeedsChange() {
let feedRef = k.Firebase.FIR_DATABASE_REF.child(k.Firebase.FIBDataStorageKeys.FEEDS)
feedRef.observeEventType(FIRDataEventType.Value) {
(snapshot: FIRDataSnapshot) in
print(snapshot.value)
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
Data.sharedInstance.feeds = []
for snap in snapshots {
print("SNAP: \(snap)")
if let snapDict = snap.value as? Dictionary<String,AnyObject> {
let feedID = snap.key
let feed = Feed(feedID: feedID, fromDictionary: snapDict)
Data.sharedInstance.feeds.append(feed)
self.feeds.append(feed)
}
}
self.feedTable.reloadData()
}
}
}
func resetPickerImage() {
picturePickerPickedImage.image = UIImage(named: "picChoserIcon")
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let targetVC = segue.destinationViewController as? FeedDetailsViewController {
if let index = sender as? Int {
targetVC.feedIndex = index
}
}
}
}
extension FeedViewController: UITextFieldDelegate {
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.resignFirstResponder()
view.endEditing(true)
}
}
| gpl-3.0 | 4c4ae63fa5150e5a62c3329e8fa3d066 | 23.471111 | 139 | 0.618235 | 5.561616 | false | false | false | false |
marknote/GoTao | GoTao/GoTao/Models/MoveGroup.swift | 1 | 780 | /**
*
* Copyright (c) 2015, MarkNote. (MIT Licensed)
* https://github.com/marknote/GoTao
*/
import Foundation
class MoveGroup:NSObject{
var type:StoneType = .black
var sequence:Int = 0
var name = ""
var allMoves: [Move] = [Move]()
var isDead = false
func addMove(_ m:Move){
m.groupName = name
allMoves.append(m)
}
func calculateLiberty(_ occupied:[Location])->Int{
return allMoves.reduce(0, {$0 + $1.calculateLiberty(occupied)} )
}
func mergeTo(_ groupToMerge:MoveGroup) {
for move in allMoves {
groupToMerge.addMove(move)
}
allMoves.removeAll()
}
override var description: String {
return name
}
}
| mit | 9bfbb4d54274d78de5e0e70a891d8ff0 | 19 | 72 | 0.553846 | 4.020619 | false | false | false | false |
practicalswift/Pythonic.swift | src/Pythonic.re.swift | 1 | 5436 | // Python docs: https://docs.python.org/2/library/re.html
//
// Most frequently used:
// 346 re.search
// 252 re.match
// 218 re.compile
// 217 re.sub
// 28 re.split
// 26 re.findall
// 26 re.IGNORECASE
// 17 re.escape
// 16 re.VERBOSE
// 9 re.finditer
//
// >>> filter(lambda s: not s.startswith("_"), dir(re))
// DEBUG
// DOTALL
// I
// IGNORECASE
// L
// LOCALE
// M
// MULTILINE
// S
// Scanner
// T
// TEMPLATE
// U
// UNICODE
// VERBOSE
// X
// compile
// copy_reg
// error
// escape
// findall
// finditer
// match
// purge
// search
// split
// sre_compile
// sre_parse
// sub
// subn
// sys
// template
import Foundation
public class RegularExpressionMatch: BooleanType {
private var matchedStrings = [String]()
public init(_ matchedStrings: [String]) {
self.matchedStrings.appendContentsOf(matchedStrings)
}
public func groups() -> [String] {
return Array(self.matchedStrings.dropFirst())
}
public func group(i: Int) -> String? {
return self.matchedStrings[i]
}
public var boolValue: Bool {
return self.matchedStrings.count != 0
}
public subscript (index: Int) -> String? {
return self.group(index)
}
}
public class re {
public class func search(pattern: String, _ string: String) -> RegularExpressionMatch {
var matchedStrings = [String]()
if pattern == "" {
return RegularExpressionMatch(matchedStrings)
}
// NOTE: Must use NSString:s below to avoid off-by-one issues when countElements(swiftString) != nsString.length.
// Example case: countElements("\r\n") [1] != ("\r\n" as NSString).length [2]
guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
return RegularExpressionMatch(matchedStrings)
}
let matches = regex.matchesInString(string, options: [], range: NSRange(location: 0, length: (string as NSString).length))
for match in matches {
for i in 0..<match.numberOfRanges {
let range = match.rangeAtIndex(i)
var matchString = ""
if range.location != Int.max {
matchString = (string as NSString).substringWithRange(range)
}
matchedStrings += [matchString]
}
}
return RegularExpressionMatch(matchedStrings)
}
public class func match(pattern: String, _ string: String) -> RegularExpressionMatch {
return re.search(pattern.startsWith("^") ? pattern : "^" + pattern, string)
}
public class func split(pattern: String, _ string: String) -> [String] {
if pattern == "" {
return [string]
}
var returnedMatches = [String]()
// NOTE: Must use NSString:s below to avoid off-by-one issues when countElements(swiftString) != nsString.length.
// Example case: countElements("\r\n") [1] != ("\r\n" as NSString).length [2]
if let regex = try? NSRegularExpression(pattern: pattern, options: []) {
let matches = regex.matchesInString(string, options: [], range: NSMakeRange(0, (string as NSString).length))
var includeDelimiters = false
// Heuristic detection of capture group(s) to try matching behaviour of Python's re.split. Room for improvement.
if "(".`in`(pattern.replace("\\(", "").replace("(?", "")) {
includeDelimiters = true
}
var previousRange: NSRange?
var lastLocation = 0
for match in matches {
if includeDelimiters {
if let previousRange = previousRange {
let previousString: String = (string as NSString).substringWithRange(NSMakeRange(previousRange.location, previousRange.length))
returnedMatches += [previousString]
}
}
let matchedString: String = (string as NSString).substringWithRange(NSMakeRange(lastLocation, match.range.location - lastLocation))
returnedMatches += [matchedString]
lastLocation = match.range.location + match.range.length
previousRange = match.range
}
if includeDelimiters {
if let previousRange = previousRange {
let previousString: String = (string as NSString).substringWithRange(NSMakeRange(previousRange.location, previousRange.length))
returnedMatches += [previousString]
}
}
let matchedString: String = (string as NSString).substringWithRange(NSMakeRange(lastLocation, (string as NSString).length - lastLocation))
returnedMatches += [matchedString]
}
return returnedMatches
}
public class func sub(pattern: String, _ repl: String, _ string: String) -> String {
var replaceWithString = repl
for i in 0...9 {
replaceWithString = replaceWithString.replace("\\\(i)", "$\(i)")
}
if let regex = try? NSRegularExpression(pattern: pattern, options: []) {
return regex.stringByReplacingMatchesInString(string, options: [], range: NSMakeRange(0, (string as NSString).length), withTemplate: replaceWithString)
}
return string
}
}
| mit | 4674b2c3d15a9b12a64b5ef650ab8217 | 34.298701 | 163 | 0.591428 | 4.598985 | false | false | false | false |
pccole/GitHubJobs-iOS | GitHubJobs/Extensions/UIFont+Extensions.swift | 1 | 2354 | //
// UIFont+Extensions.swift
// GitHubJobs
//
// Created by Phil Cole on 5/3/20.
// Copyright © 2020 Cole LLC. All rights reserved.
//
import Foundation
import UIKit
extension UIFont {
}
enum FontStyle {
case largeTitle
case title1
case title2
case title3
case headline
case body
case callout
case subhead
case footnote
case caption1
case caption2
var font: UIFont? {
let sizeCategory = UITraitCollection.current.preferredContentSizeCategory
switch sizeCategory {
case .extraSmall, .small, .medium, .extraLarge, .extraExtraLarge, .extraExtraExtraLarge, .accessibilityMedium, .accessibilityLarge, .accessibilityExtraLarge, .accessibilityExtraExtraLarge, .accessibilityExtraExtraLarge, .unspecified:
return nil
case .large:
switch self {
case .largeTitle, .body, .title1, .title2, .title3, .callout, .footnote, .caption1, .caption2:
return UIFont(name: FontWeight.regular.rawValue, size: size)
case .headline:
return UIFont(name: FontWeight.bold.rawValue, size: size)
case .subhead:
return UIFont(name: FontWeight.semiBold.rawValue, size: size)
}
default:
return nil
}
}
var size: CGFloat {
switch self {
case .largeTitle:
return 34
case .title1:
return 28
case .title2:
return 22
case .title3:
return 20
case .headline, .body:
return 17
case .callout:
return 16
case .subhead:
return 15
case .footnote:
return 13
case .caption1:
return 12
case .caption2:
return 11
}
}
enum FontWeight: String {
case bold = "OpenSans-Bold"
case boldItalic = "OpenSans-BoldItalic"
case extraBlod = "OpenSans-ExtraBold"
case extraBlodItalic = "OpenSans-ExtraBoldItalic"
case italic = "OpenSans-Italic"
case light = "OpenSans-Light"
case lightItalic = "OpenSans-LightItalic"
case regular = "OpenSans-Regular"
case semiBold = "OpenSans-SemiBold"
case semiBoldItalic = "OpenSans-SemiBoldItalic"
}
}
| mit | d91d0f43cc5e056fe31e996845114ceb | 26.360465 | 241 | 0.587335 | 4.7249 | false | false | false | false |
gossipgeek/gossipgeek | GossipGeek/GossipGeek/GGTime.swift | 1 | 983 | //
// GGTime.swift
// GossipGeek
//
// Created by Weidong Gu on 16/05/2017.
// Copyright © 2017 application. All rights reserved.
//
import UIKit
import SwiftDate
extension Date {
func toGGTime(baseTime: Date?) -> String {
let oneDay: Double = 24*60*60
let oneWeek: Double = 7*24*60*60
let oneMonth: Double = 30*24*60*60
if nil == baseTime && baseTime?.compare(self) == .orderedDescending{ return "" }
if self.timeIntervalSince(baseTime!) > -oneDay{
return String(format: "%02d:%02d", self.hour, self.minute)
}
if self.timeIntervalSince(baseTime!) > -oneWeek {
return "\(Int(-self.timeIntervalSince(baseTime!) / oneDay))天前"
}
if self.timeIntervalSince(baseTime!) > -oneMonth{
return "\(Int(-self.timeIntervalSince(baseTime!) / oneWeek))周前"
}
return String(format: "%04d年%02d月%02d日", self.year, self.month, self.day)
}
}
| mit | cb875ed0d07b96e6d1f2d7c8c68f7eae | 31.266667 | 88 | 0.605372 | 3.625468 | false | false | false | false |
zhangao0086/DKImagePickerController | Example/DKImagePickerControllerDemo/CustomCamera/CustomCameraExtension.swift | 2 | 2344 | //
// CustomCamera.swift
// DKImagePickerControllerDemo
//
// Created by ZhangAo on 03/01/2017.
// Copyright © 2017 ZhangAo. All rights reserved.
//
import UIKit
import MobileCoreServices
import DKImagePickerController
open class CustomCameraExtension: DKImageBaseExtension, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var didCancel: (() -> Void)?
var didFinishCapturingImage: ((_ image: UIImage, _ metadata: [AnyHashable : Any]?) -> Void)?
var didFinishCapturingVideo: ((_ videoURL: URL) -> Void)?
open override func perform(with extraInfo: [AnyHashable : Any]) {
guard let didFinishCapturingImage = extraInfo["didFinishCapturingImage"] as? ((UIImage, [AnyHashable : Any]?) -> Void)
, let didFinishCapturingVideo = extraInfo["didFinishCapturingVideo"] as? ((URL) -> Void)
, let didCancel = extraInfo["didCancel"] as? (() -> Void) else { return }
self.didFinishCapturingImage = didFinishCapturingImage
self.didFinishCapturingVideo = didFinishCapturingVideo
self.didCancel = didCancel
let camera = UIImagePickerController()
camera.delegate = self
camera.videoQuality = .typeHigh
camera.sourceType = .camera
camera.mediaTypes = [kUTTypeImage as String, kUTTypeMovie as String]
self.context.imagePickerController.present(camera)
}
open override func finish() {
self.context.imagePickerController.dismiss(animated: true)
}
// MARK: - UIImagePickerControllerDelegate methods
open func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
let mediaType = info[.mediaType] as! String
if mediaType == kUTTypeImage as String {
let metadata = info[.mediaMetadata] as! [AnyHashable : Any]
let image = info[.originalImage] as! UIImage
self.didFinishCapturingImage?(image, metadata)
} else if mediaType == kUTTypeMovie as String {
let videoURL = info[.mediaURL] as! URL
self.didFinishCapturingVideo?(videoURL)
}
}
open func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.didCancel?()
}
}
| mit | 27e3e3874fb6c14560852edc23afe554 | 38.05 | 149 | 0.672642 | 5.632212 | false | false | false | false |
therealbnut/swift | stdlib/private/SwiftReflectionTest/SwiftReflectionTest.swift | 1 | 16846 | //===--- SwiftReflectionTest.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
//
//===----------------------------------------------------------------------===//
//
// This file provides infrastructure for introspecting type information in a
// remote swift executable by swift-reflection-test, using pipes and a
// request-response protocol to communicate with the test tool.
//
//===----------------------------------------------------------------------===//
// FIXME: Make this work with Linux
import MachO
import Darwin
let RequestInstanceKind = "k"
let RequestInstanceAddress = "i"
let RequestReflectionInfos = "r"
let RequestReadBytes = "b"
let RequestSymbolAddress = "s"
let RequestStringLength = "l"
let RequestDone = "d"
let RequestPointerSize = "p"
internal func debugLog(_ message: String) {
#if DEBUG_LOG
fputs("Child: \(message)\n", stderr)
fflush(stderr)
#endif
}
public enum InstanceKind : UInt8 {
case None
case Object
case Existential
case ErrorExistential
case Closure
}
/// Represents a section in a loaded image in this process.
internal struct Section {
/// The absolute start address of the section's data in this address space.
let startAddress: UnsafeRawPointer
/// The size of the section in bytes.
let size: UInt
}
/// Holds the addresses and sizes of sections related to reflection
internal struct ReflectionInfo : Sequence {
/// The name of the loaded image
internal let imageName: String
/// Reflection metadata sections
internal let fieldmd: Section?
internal let assocty: Section?
internal let builtin: Section?
internal let capture: Section?
internal let typeref: Section?
internal let reflstr: Section?
internal func makeIterator() -> AnyIterator<Section?> {
return AnyIterator([
fieldmd,
assocty,
builtin,
capture,
typeref,
reflstr
].makeIterator())
}
}
#if arch(x86_64) || arch(arm64)
typealias MachHeader = mach_header_64
#else
typealias MachHeader = mach_header
#endif
/// Get the location and size of a section in a binary.
///
/// - Parameter name: The name of the section
/// - Parameter imageHeader: A pointer to the Mach header describing the
/// image.
/// - Returns: A `Section` containing the address and size, or `nil` if there
/// is no section by the given name.
internal func getSectionInfo(_ name: String,
_ imageHeader: UnsafePointer<MachHeader>) -> Section? {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
var size: UInt = 0
let address = getsectiondata(imageHeader, "__TEXT", name, &size)
guard let nonNullAddress = address else { return nil }
guard size != 0 else { return nil }
return Section(startAddress: nonNullAddress, size: size)
}
/// Get the Swift Reflection section locations for a loaded image.
///
/// An image of interest must have the following sections in the __DATA
/// segment:
/// - __swift3_fieldmd
/// - __swift3_assocty
/// - __swift3_builtin
/// - __swift3_capture
/// - __swift3_typeref
/// - __swift3_reflstr (optional, may have been stripped out)
///
/// - Parameter i: The index of the loaded image as reported by Dyld.
/// - Returns: A `ReflectionInfo` containing the locations of all of the
/// needed sections, or `nil` if the image doesn't contain all of them.
internal func getReflectionInfoForImage(atIndex i: UInt32) -> ReflectionInfo? {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let header = unsafeBitCast(_dyld_get_image_header(i),
to: UnsafePointer<MachHeader>.self)
let imageName = _dyld_get_image_name(i)!
let fieldmd = getSectionInfo("__swift3_fieldmd", header)
let assocty = getSectionInfo("__swift3_assocty", header)
let builtin = getSectionInfo("__swift3_builtin", header)
let capture = getSectionInfo("__swift3_capture", header)
let typeref = getSectionInfo("__swift3_typeref", header)
let reflstr = getSectionInfo("__swift3_reflstr", header)
return ReflectionInfo(imageName: String(validatingUTF8: imageName)!,
fieldmd: fieldmd,
assocty: assocty,
builtin: builtin,
capture: capture,
typeref: typeref,
reflstr: reflstr)
}
internal func sendBytes<T>(from address: UnsafePointer<T>, count: Int) {
var source = address
var bytesLeft = count
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
while bytesLeft > 0 {
let bytesWritten = fwrite(source, 1, bytesLeft, stdout)
fflush(stdout)
guard bytesWritten > 0 else {
fatalError("Couldn't write to parent pipe")
}
bytesLeft -= bytesWritten
source = source.advanced(by: bytesWritten)
}
}
/// Send the address of an object to the parent.
internal func sendAddress(of instance: AnyObject) {
debugLog("BEGIN \(#function)")
defer { debugLog("END \(#function)") }
var address = Unmanaged.passUnretained(instance).toOpaque()
sendBytes(from: &address, count: MemoryLayout<UInt>.size)
}
/// Send the `value`'s bits to the parent.
internal func sendValue<T>(_ value: T) {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
var value = value
sendBytes(from: &value, count: MemoryLayout<T>.size)
}
/// Read a word-sized unsigned integer from the parent.
internal func readUInt() -> UInt {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
var value: UInt = 0
fread(&value, MemoryLayout<UInt>.size, 1, stdin)
return value
}
/// Send all known `ReflectionInfo`s for all images loaded in the current
/// process.
internal func sendReflectionInfos() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let infos = (0..<_dyld_image_count()).flatMap(getReflectionInfoForImage)
var numInfos = infos.count
debugLog("\(numInfos) reflection info bundles.")
precondition(numInfos >= 1)
sendBytes(from: &numInfos, count: MemoryLayout<UInt>.size)
for info in infos {
debugLog("Sending info for \(info.imageName)")
for section in info {
sendValue(section?.startAddress)
sendValue(section?.size ?? 0)
}
}
}
internal func printErrnoAndExit() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let errorCString = strerror(errno)!
let message = String(validatingUTF8: errorCString)! + "\n"
let bytes = Array(message.utf8)
fwrite(bytes, 1, bytes.count, stderr)
fflush(stderr)
exit(EXIT_FAILURE)
}
/// Retrieve the address and count from the parent and send the bytes back.
internal func sendBytes() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let address = readUInt()
let count = Int(readUInt())
debugLog("Parent requested \(count) bytes from \(address)")
var totalBytesWritten = 0
var pointer = unsafeBitCast(address, to: UnsafeMutableRawPointer.self)
while totalBytesWritten < count {
let bytesWritten = Int(fwrite(pointer, 1, Int(count), stdout))
fflush(stdout)
if bytesWritten == 0 {
printErrnoAndExit()
}
totalBytesWritten += bytesWritten
pointer = pointer.advanced(by: bytesWritten)
}
}
/// Send the address of a symbol loaded in this process.
internal func sendSymbolAddress() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let name = readLine()!
name.withCString {
let handle = unsafeBitCast(Int(-2), to: UnsafeMutableRawPointer.self)
let symbol = dlsym(handle, $0)
let symbolAddress = unsafeBitCast(symbol, to: UInt.self)
sendValue(symbolAddress)
}
}
/// Send the length of a string to the parent.
internal func sendStringLength() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let address = readUInt()
let cString = unsafeBitCast(address, to: UnsafePointer<CChar>.self)
let count = String(validatingUTF8: cString)!.utf8.count
sendValue(count)
}
/// Send the size of this architecture's pointer type.
internal func sendPointerSize() {
debugLog("BEGIN \(#function)"); defer { debugLog("END \(#function)") }
let pointerSize = UInt8(MemoryLayout<UnsafeRawPointer>.size)
sendValue(pointerSize)
}
/// Hold an `instance` and wait for the parent to query for information.
///
/// This is the main "run loop" of the test harness.
///
/// The parent will necessarily need to:
/// - Get the addresses of all of the reflection sections for any swift dylibs
/// that are loaded, where applicable.
/// - Get the address of the `instance`
/// - Get the pointer size of this process, which affects assumptions about the
/// the layout of runtime structures with pointer-sized fields.
/// - Read raw bytes out of this process's address space.
///
/// The parent sends a Done message to indicate that it's done
/// looking at this instance. It will continue to ask for instances,
/// so call doneReflecting() when you don't have any more instances.
internal func reflect(instanceAddress: UInt, kind: InstanceKind) {
while let command = readLine(strippingNewline: true) {
switch command {
case String(validatingUTF8: RequestInstanceKind)!:
sendValue(kind.rawValue)
case String(validatingUTF8: RequestInstanceAddress)!:
sendValue(instanceAddress)
case String(validatingUTF8: RequestReflectionInfos)!:
sendReflectionInfos()
case String(validatingUTF8: RequestReadBytes)!:
sendBytes()
case String(validatingUTF8: RequestSymbolAddress)!:
sendSymbolAddress()
case String(validatingUTF8: RequestStringLength)!:
sendStringLength()
case String(validatingUTF8: RequestPointerSize)!:
sendPointerSize()
case String(validatingUTF8: RequestDone)!:
return
default:
fatalError("Unknown request received: '\(Array(command.utf8))'!")
}
}
}
/// Reflect a class instance.
///
/// This reflects the stored properties of the immediate class.
/// The superclass is not (yet?) visited.
public func reflect(object: AnyObject) {
defer { _fixLifetime(object) }
let address = Unmanaged.passUnretained(object).toOpaque()
let addressValue = UInt(bitPattern: address)
reflect(instanceAddress: addressValue, kind: .Object)
}
/// Reflect any type at all by boxing it into an existential container (an `Any`)
///
/// Given a class, this will reflect the reference value, and not the contents
/// of the instance. Use `reflect(object:)` for that.
///
/// This function serves to exercise the projectExistential function of the
/// SwiftRemoteMirror API.
///
/// It tests the three conditions of existential layout:
///
/// ## Class existentials
///
/// For example, a `MyClass as Any`:
/// ```
/// [Pointer to class instance]
/// [Witness table 1]
/// [Witness table 2]
/// ...
/// [Witness table n]
/// ```
///
/// ## Existentials whose contained type fits in the 3-word buffer
///
/// For example, a `(1, 2) as Any`:
/// ```
/// [Tuple element 1: Int]
/// [Tuple element 2: Int]
/// [-Empty_]
/// [Metadata Pointer]
/// [Witness table 1]
/// [Witness table 2]
/// ...
/// [Witness table n]
/// ```
///
/// ## Existentials whose contained type has to be allocated into a
/// heap buffer.
///
/// For example, a `LargeStruct<T> as Any`:
/// ```
/// [Pointer to unmanaged heap container] --> [Large struct]
/// [-Empty-]
/// [-Empty-]
/// [Metadata Pointer]
/// [Witness table 1]
/// [Witness table 2]
/// ...
/// [Witness table n]
/// ```
///
/// The test doesn't care about the witness tables - we only care
/// about what's in the buffer, so we always put these values into
/// an Any existential.
public func reflect<T>(any: T) {
let any: Any = any
let anyPointer = UnsafeMutablePointer<Any>.allocate(capacity: MemoryLayout<Any>.size)
anyPointer.initialize(to: any)
let anyPointerValue = unsafeBitCast(anyPointer, to: UInt.self)
reflect(instanceAddress: anyPointerValue, kind: .Existential)
anyPointer.deallocate(capacity: MemoryLayout<Any>.size)
}
// Reflect an `Error`, a.k.a. an "error existential".
//
// These are always boxed on the heap, with the following layout:
//
// - Word 0: Metadata Pointer
// - Word 1: 2x 32-bit reference counts
//
// If Objective-C interop is available, an Error is also an
// `NSError`, and so has:
//
// - Word 2: code (NSInteger)
// - Word 3: domain (NSString *)
// - Word 4: userInfo (NSDictionary *)
//
// Then, always follow:
//
// - Word 2 or 5: Instance type metadata pointer
// - Word 3 or 6: Instance witness table for conforming
// to `Swift.Error`.
//
// Following that is the instance that conforms to `Error`,
// rounding up to its alignment.
public func reflect<T: Error>(error: T) {
let error: Error = error
let errorPointerValue = unsafeBitCast(error, to: UInt.self)
reflect(instanceAddress: errorPointerValue, kind: .ErrorExistential)
}
/// Wraps a thick function with arity 0.
struct ThickFunction0 {
var function: () -> Void
}
/// Wraps a thick function with arity 1.
struct ThickFunction1 {
var function: (Int) -> Void
}
/// Wraps a thick function with arity 2.
struct ThickFunction2 {
var function: (Int, String) -> Void
}
/// Wraps a thick function with arity 3.
struct ThickFunction3 {
var function: (Int, String, AnyObject?) -> Void
}
struct ThickFunctionParts {
var function: UnsafeRawPointer
var context: Optional<UnsafeRawPointer>
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping () -> Void) {
let fn = UnsafeMutablePointer<ThickFunction0>.allocate(
capacity: MemoryLayout<ThickFunction0>.size)
fn.initialize(to: ThickFunction0(function: function))
let parts = unsafeBitCast(fn, to: UnsafePointer<ThickFunctionParts>.self)
let contextPointer = unsafeBitCast(parts.pointee.context, to: UInt.self)
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate(capacity: MemoryLayout<ThickFunction0>.size)
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping (Int) -> Void) {
let fn =
UnsafeMutablePointer<ThickFunction1>.allocate(
capacity: MemoryLayout<ThickFunction1>.size)
fn.initialize(to: ThickFunction1(function: function))
let parts = unsafeBitCast(fn, to: UnsafePointer<ThickFunctionParts>.self)
let contextPointer = unsafeBitCast(parts.pointee.context, to: UInt.self)
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate(capacity: MemoryLayout<ThickFunction1>.size)
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping (Int, String) -> Void) {
let fn = UnsafeMutablePointer<ThickFunction2>.allocate(
capacity: MemoryLayout<ThickFunction2>.size)
fn.initialize(to: ThickFunction2(function: function))
let parts = unsafeBitCast(fn, to: UnsafePointer<ThickFunctionParts>.self)
let contextPointer = unsafeBitCast(parts.pointee.context, to: UInt.self)
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate(capacity: MemoryLayout<ThickFunction2>.size)
}
/// Reflect a closure context. The given function must be a Swift-native
/// @convention(thick) function value.
public func reflect(function: @escaping (Int, String, AnyObject?) -> Void) {
let fn = UnsafeMutablePointer<ThickFunction3>.allocate(
capacity: MemoryLayout<ThickFunction3>.size)
fn.initialize(to: ThickFunction3(function: function))
let parts = unsafeBitCast(fn, to: UnsafePointer<ThickFunctionParts>.self)
let contextPointer = unsafeBitCast(parts.pointee.context, to: UInt.self)
reflect(instanceAddress: contextPointer, kind: .Object)
fn.deallocate(capacity: MemoryLayout<ThickFunction3>.size)
}
/// Call this function to indicate to the parent that there are
/// no more instances to look at.
public func doneReflecting() {
reflect(instanceAddress: UInt(InstanceKind.None.rawValue), kind: .None)
}
/* Example usage
public protocol P {
associatedtype Index
var startIndex: Index { get }
}
public struct Thing : P {
public let startIndex = 1010
}
public enum E<T: P> {
case B(T)
case C(T.Index)
}
public class A<T: P> : P {
public let x: T?
public let y: T.Index
public let b = true
public let t = (1, 1.0)
private let type: NSObject.Type
public let startIndex = 1010
public init(x: T) {
self.x = x
self.y = x.startIndex
self.type = NSObject.self
}
}
let instance = A(x: A(x: Thing()))
reflect(A(x: Thing()))
*/
| apache-2.0 | bb454a05380826eed455591d67a9f4a8 | 31.458574 | 87 | 0.692687 | 4.110786 | false | false | false | false |
DStorck/SwiftNewsApp | Pods/RealmSwift/RealmSwift/Util.swift | 8 | 2600 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
// MARK: Internal Helpers
internal func notFoundToNil(index: UInt) -> Int? {
if index == UInt(NSNotFound) {
return nil
}
return Int(index)
}
#if swift(>=3.0)
internal func throwRealmException(_ message: String, userInfo: [String:AnyObject] = [:]) {
NSException(name: NSExceptionName(rawValue: RLMExceptionName), reason: message, userInfo: userInfo).raise()
}
internal func throwForNegativeIndex(_ int: Int, parameterName: String = "index") {
if int < 0 {
throwRealmException("Cannot pass a negative value for '\(parameterName)'.")
}
}
internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? {
let regex = try? RegularExpression(pattern: pattern, options: [])
return regex?.stringByReplacingMatches(in: string, options: [],
range: NSRange(location: 0, length: string.utf16.count),
withTemplate: template)
}
#else
internal func throwRealmException(message: String, userInfo: [String:AnyObject] = [:]) {
NSException(name: RLMExceptionName, reason: message, userInfo: userInfo).raise()
}
internal func throwForNegativeIndex(int: Int, parameterName: String = "index") {
if int < 0 {
throwRealmException("Cannot pass a negative value for '\(parameterName)'.")
}
}
internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? {
let regex = try? NSRegularExpression(pattern: pattern, options: [])
return regex?.stringByReplacingMatchesInString(string, options: [],
range: NSRange(location: 0, length: string.utf16.count),
withTemplate: template)
}
#endif
| mit | be03ac966c6487afe310b9e2db828c43 | 36.681159 | 111 | 0.624231 | 4.814815 | false | false | false | false |
joshc89/DeclarativeLayout | DeclarativeLayout/Collections/CollectionModification.swift | 1 | 3186 | //
// CollectionModification.swift
// DeclarativeLayout
//
// Created by Joshua Campion on 16/09/2016.
// Copyright © 2016 Josh Campion. All rights reserved.
//
import Foundation
/**
Struct that can be used to encapsulate the changes that can be applied to one collection to transform it to another.
- seealso: `UITableView`.`apply(modifications:animated:)`
*/
public struct CollectionModification {
/// The `IndexPath`s of items to be inserted.
let rowInsertions: [IndexPath]
/// The `IndexPath`s of items to be deleted.
let rowDeletions: [IndexPath]
/// Pairs of `IndexPath`s for the rows to be moved.
let rowMoves: [(from: IndexPath, to: IndexPath)]
/// The `IndexPath`s of items to be reloaded, typically because they represent a model object that has been updated.
let rowReloads: [IndexPath]
/// The indexes of entire sections to be inserted.
let sectionInsertions: IndexSet
/// The indexes of entire sections to be deleted.
let sectionDeletions: IndexSet
/// Pairs of indexes for the entire sections to be moved.
let sectionMoves: [(from: Int, to: Int)]
/// The indexes of entire sections to be reloaded.
let sectionReloads: IndexSet
/**
Default initialiser setting all properties. Each has a default value of an empty Array or IndexSet as appropriate.
*/
public init(rowInsertions: [IndexPath] = [],
rowDeletions: [IndexPath] = [],
rowMoves: [(from: IndexPath, to: IndexPath)] = [],
rowReloads: [IndexPath] = [],
sectionInsertions: IndexSet = IndexSet(),
sectionDeletions: IndexSet = IndexSet(),
sectionMoves: [(from: Int, to: Int)] = [],
sectionReloads: IndexSet = IndexSet()) {
self.rowInsertions = rowInsertions
self.rowDeletions = rowDeletions
self.rowMoves = rowMoves
self.rowReloads = rowReloads
self.sectionInsertions = sectionInsertions
self.sectionDeletions = sectionDeletions
self.sectionMoves = sectionMoves
self.sectionReloads = sectionReloads
}
/**
Convenience method for creating the opposite of a modification. This can be used to create an undo stack for a series of changes to a collection.
- returns: The modification the would return the collection resulting from this modification to its original state.
*/
func makeInverse() -> CollectionModification {
return CollectionModification(rowInsertions: rowDeletions,
rowDeletions: rowInsertions,
rowMoves: rowMoves.map { ($0.to, $0.from) },
rowReloads: rowReloads,
sectionInsertions: sectionDeletions,
sectionDeletions: sectionInsertions,
sectionMoves: sectionMoves.map { ($0.to, $0.from) },
sectionReloads: sectionReloads)
}
}
| mit | 4acc09300273c70f0efa7a56d3023ca9 | 35.609195 | 150 | 0.604082 | 5.587719 | false | false | false | false |
cruisediary/Diving | Diving/Models/Realm/RealmUser.swift | 1 | 901 | //
// User.swift
// Diving
//
// Created by CruzDiary on 5/24/16.
// Copyright © 2016 DigitalNomad. All rights reserved.
//
import RealmSwift
class RealmUser: Object {
static let EXPENSES:String = "expenses"
dynamic var id = ""
dynamic var name = ""
//Relation
let expenses = List<RealmExpense>()
let travel = LinkingObjects(fromType: RealmTravel.self, property: RealmTravel.USERS)
let transactions = LinkingObjects(fromType: RealmExpense.self, property: RealmExpense.COMPANIONS)
let receipt = LinkingObjects(fromType: RealmExpense.self, property: RealmExpense.RECEIVER)
//Key
override static func primaryKey() -> String? {
return RealmCommonObject.ID
}
// Specify properties to ignore (Realm won't persist these)
// override static func ignoredProperties() -> [String] {
// return []
// }
}
| mit | 10238ed49cf9732cfd183b68db8939c5 | 22.684211 | 101 | 0.66 | 4.186047 | false | false | false | false |
katopz/Kingfisher | Kingfisher/UIImageView+Kingfisher.swift | 9 | 10538 | //
// UIImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - Set Images
/**
* Set image to use from web.
*/
public extension UIImageView {
/**
Set an image with a URL.
It will ask for Kingfisher's manager to get the image for the URL.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at this URL and store it for next use.
:param: URL The URL of image.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image with a URL and a placeholder image.
:param: URL The URL of image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image with a URL, a placaholder image and options.
:param: URL The URL of image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image with a URL, a placeholder image, options and completion handler.
:param: URL The URL of image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image with a URL, a placeholder image, options, progress handler and completion handler.
:param: URL The URL of image.
:param: placeholderImage A placeholder image when retrieving the image at URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: progressBlock Called when the image downloading progress gets updated.
:param: completionHandler Called when the image retrieved and set.
:returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
let showIndicatorWhenLoading = kf_showIndicatorWhenLoading
var indicator: UIActivityIndicatorView? = nil
if showIndicatorWhenLoading {
indicator = kf_indicator
indicator?.hidden = false
indicator?.startAnimating()
}
image = placeholderImage
kf_setWebURL(URL)
let task = KingfisherManager.sharedManager.retrieveImageWithURL(URL, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in
if let progressBlock = progressBlock {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
})
}
}, completionHandler: {[weak self] (image, error, cacheType, imageURL) -> () in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let sSelf = self where imageURL == sSelf.kf_webURL && image != nil {
sSelf.image = image;
indicator?.stopAnimating()
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
})
})
return task
}
}
// MARK: - Associated Object
private var lastURLKey: Void?
private var indicatorKey: Void?
private var showIndicatorWhenLoadingKey: Void?
public extension UIImageView {
/// Get the image URL binded to this image view.
public var kf_webURL: NSURL? {
get {
return objc_getAssociatedObject(self, &lastURLKey) as? NSURL
}
}
private func kf_setWebURL(URL: NSURL) {
objc_setAssociatedObject(self, &lastURLKey, URL, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
/// Whether show an animating indicator when the image view is loading an image or not.
/// Default is false.
public var kf_showIndicatorWhenLoading: Bool {
get {
if let result = objc_getAssociatedObject(self, &showIndicatorWhenLoadingKey) as? NSNumber {
return result.boolValue
} else {
return false
}
}
set {
if kf_showIndicatorWhenLoading == newValue {
return
} else {
if newValue {
let indicator = UIActivityIndicatorView(activityIndicatorStyle:.Gray)
indicator.center = center
indicator.autoresizingMask = .FlexibleLeftMargin | .FlexibleRightMargin | .FlexibleBottomMargin | .FlexibleTopMargin
indicator.hidden = true
indicator.hidesWhenStopped = true
self.addSubview(indicator)
kf_setIndicator(indicator)
} else {
kf_indicator?.removeFromSuperview()
kf_setIndicator(nil)
}
objc_setAssociatedObject(self, &showIndicatorWhenLoadingKey, NSNumber(bool: newValue), UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
}
/// The indicator view showing when loading. This will be `nil` if `kf_showIndicatorWhenLoading` is false.
/// You may want to use this to set the indicator style or color when you set `kf_showIndicatorWhenLoading` to true.
public var kf_indicator: UIActivityIndicatorView? {
get {
return objc_getAssociatedObject(self, &indicatorKey) as? UIActivityIndicatorView
}
}
private func kf_setIndicator(indicator: UIActivityIndicatorView?) {
objc_setAssociatedObject(self, &indicatorKey, indicator, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
}
}
// MARK: - Deprecated
public extension UIImageView {
@availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo: instead.")
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
options: KingfisherOptions) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: nil)
}
@availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
options: KingfisherOptions,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: completionHandler)
}
@availability(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: progressBlock, completionHandler: completionHandler)
}
}
| mit | 22b43923b312358e3ea364034397e4f7 | 42.188525 | 176 | 0.641108 | 5.566825 | false | false | false | false |
cristiannomartins/Tree-Sets | Tree Sets/PokemonSet+Extension.swift | 1 | 5179 | //
// PokemonSet+Extension.swift
// Tree Sets
//
// Created by Cristianno Vieira on 22/01/17.
// Copyright © 2017 Cristianno Vieira. All rights reserved.
//
import Foundation
import CoreData
extension PokemonSet {
static func getPokemonSets(_ fromDex: Dex? = nil) -> [PokemonSet] {
if let dex = fromDex {
return dex.contains?.allObjects as! [PokemonSet]
}
//let fetch = NSFetchRequest(entityName: "PokemonSet")
let fetch = NSFetchRequest<PokemonSet>(entityName: "PokemonSet")
do {
let pokemons = try PopulateDB.CDWrapper.managedObjectContext.fetch(fetch)
return pokemons
} catch {
print("Failed to retrieve record: \(error)")
}
return []
}
fileprivate func getEVs(_ category: PkmnStats) -> Int16 {
// switch category {
// case .hp: return evhp
// case .atk: return evatk
// case .def: return evdef
// case .spa: return evspa
// case .spd: return evspd
// default: return evspe
// }
for ev in evs?.allObjects as! [Stats] {
if ev.id == category.rawValue {
return ev.value
}
}
abort()
}
fileprivate func getMultiplier (_ nature: Nature, first: Int, last: Int, divisor: Int, remainder: Int) -> Double {
let rawValue = nature.rawValue
if rawValue >= first && rawValue <= last {
return 1.1
} else if rawValue % divisor == remainder {
return 0.9
} else {
return 1.0
}
}
fileprivate func natureBonus(_ stat: PkmnStats) -> Double {
//NSLog(self.nature!)
let nature = Nature.getNatureFromString(self.nature!)!
if nature.rawValue >= 20 {
return 1.0
}
switch stat {
case PkmnStats.atk:
return getMultiplier(nature, first: 0, last: 3, divisor: 4, remainder: 0)
case PkmnStats.def:
return getMultiplier(nature, first: 4, last: 7, divisor: 4, remainder: 1)
case PkmnStats.spe:
return getMultiplier(nature, first: 8, last: 11, divisor: 4, remainder: 2)
case PkmnStats.spd:
return getMultiplier(nature, first: 12, last: 15, divisor: 4, remainder: 3)
default: // diagonal of NATURES
return getMultiplier(nature, first: 16, last: 19, divisor: 5, remainder: 0)
}
}
func getBaseStatValue(_ category: PkmnStats) -> Int16 {
// switch category {
// case .hp:
// return species!.baseStats!.hp
// case .atk:
// return species!.baseStats!.atk
// case .def:
// return species!.baseStats!.def
// case .spa:
// return species!.baseStats!.spa
// case .spd:
// return species!.baseStats!.spd
// default:
// return species!.baseStats!.spe
// }
for base in species?.baseStats?.allObjects as! [Stats] {
if base.id == category.rawValue {
return base.value
}
}
abort()
}
fileprivate func calcHPTotalStat() -> Int {
let doubleBase = 2.0*Double(getBaseStatValue(PkmnStats.hp))
let level = 50.0
let percentageLvl = level/100.0
let baseTotal = doubleBase +
31.0 +
floor(Double(getEVs(PkmnStats.hp))/4.0)
return Int(floor(baseTotal*percentageLvl + level + 10.0))
}
func getStatValue(_ category: PkmnStats) -> Int {
if category == PkmnStats.hp {
return calcHPTotalStat()
}
let doubleBase = 2.0*Double(getBaseStatValue(category))
let level = 50.0 // All maison pkm are set to level 50
let percentageLvl = level/100.0
let baseTotal = doubleBase +
31.0 + // considering 30+ battle streak
floor(Double(getEVs(category))/4.0)
let baseWONature = floor(baseTotal*percentageLvl + 5.0)
return Int(floor(baseWONature * natureBonus(category)))
}
func getChangedStats() -> (decreased: PkmnStats, increased: PkmnStats) {
var stats = (decreased: PkmnStats.hp, increased: PkmnStats.hp)
for stat:PkmnStats in [.atk, .def, .spa, .spd, .spe] {
let bonus = natureBonus(stat)
if bonus > 1.0 {
stats.increased = stat
} else {
if bonus < 1.0 {
stats.decreased = stat
}
}
}
return stats
}
enum PkmnStats: Int16 {
case hp = 0, atk, def, spa, spd, spe
}
enum Nature: Int {
case adamant = 0, lonely, brave, naughty, // +Atk (-SpA, -Def, -Spe, -SpD) 0 - 3
bold, impish, relaxed, lax, // +Def (-Atk, -SpA, -Spe, -SpD) 4 - 7
timid, hasty, jolly, naive, // +Spe (-Atk, -Def, -SpA, -SpD) 8 - 11
calm, gentle, sassy, careful, // +SpD (-Atk, -Def, -Spe, -SpA) 12 - 15
modest, mild, rash, quiet, // +SpA (-Atk, -Def, -Spe, -SpD) 16 - 19
hardy, docile, serious, bashful, quirky // None 20 - 24
static func count() -> Int {
return quirky.rawValue + 1
}
static func getNatureFromString(_ name: String) -> Nature? {
let lowercased = name.lowercased()
for i in 0 ..< count() {
let nature = Nature(rawValue: i)!
if lowercased == "\(nature)" {
return nature
}
}
return nil
}
}
}
| mit | 269ec86ce1ee16921eaadab5480d0648 | 27.141304 | 116 | 0.581306 | 3.765818 | false | false | false | false |
PlutoMa/SwiftProjects | 029.Beauty Contest/BeautyContest/BeautyContest/ViewController.swift | 1 | 3140 | //
// ViewController.swift
// BeautyContest
//
// Created by Dareway on 2017/11/8.
// Copyright © 2017年 Pluto. All rights reserved.
//
import UIKit
import Koloda
import SnapKit
class ViewController: UIViewController {
let kolodaView = KolodaView()
lazy var dataSource: [UIImage] = {
var dataSource = [UIImage]()
for index in 1...10 {
dataSource.append(UIImage(named: "Photo\(index)")!)
}
return dataSource
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(red: 1, green: 0, blue: 0, alpha: 0.5)
kolodaView.delegate = self
kolodaView.dataSource = self
view.addSubview(kolodaView)
kolodaView.snp.makeConstraints { (maker) in
maker.top.equalTo(self.view.snp.top).offset(100)
maker.leading.equalTo(self.view.snp.leading).offset(20)
maker.bottom.equalTo(self.view.snp.bottom).offset(-100)
maker.trailing.equalTo(self.view.snp.trailing).offset(-20)
}
let dislikeButton = UIButton(type: .custom)
dislikeButton.setImage(UIImage(named: "ic_skip"), for: .normal)
dislikeButton.addTarget(self, action: #selector(dislikeAction), for: .touchUpInside)
view.addSubview(dislikeButton)
dislikeButton.snp.makeConstraints { (maker) in
maker.bottom.equalTo(self.view.snp.bottom).offset(-20)
maker.leading.equalTo(self.view.snp.leading).offset(90)
maker.width.equalTo(30)
maker.height.equalTo(30)
}
let likeButton = UIButton(type: .custom)
likeButton.setImage(UIImage(named: "ic_like"), for: .normal)
likeButton.addTarget(self, action: #selector(likeAction), for: .touchUpInside)
view.addSubview(likeButton)
likeButton.snp.makeConstraints { (maker) in
maker.bottom.equalTo(self.view.snp.bottom).offset(-20)
maker.trailing.equalTo(self.view.snp.trailing).offset(-90)
maker.width.equalTo(30)
maker.height.equalTo(30)
}
}
@objc func dislikeAction() -> Void {
kolodaView.swipe(.left)
}
@objc func likeAction() -> Void {
kolodaView.swipe(.right)
}
}
extension ViewController: KolodaViewDelegate {
func kolodaDidRunOutOfCards(_ koloda: KolodaView) {
}
func koloda(_ koloda: KolodaView, didSelectCardAt index: Int) {
}
}
extension ViewController: KolodaViewDataSource {
func kolodaSpeedThatCardShouldDrag(_ koloda: KolodaView) -> DragSpeed {
return .`default`
}
func kolodaNumberOfCards(_ koloda: KolodaView) -> Int {
return dataSource.count
}
func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {
return UIImageView(image: dataSource[index])
}
func koloda(_ koloda: KolodaView, viewForCardOverlayAt index: Int) -> OverlayView? {
let overlayView = BeautyContestOverlayView(frame: self.kolodaView.frame)
return overlayView
}
}
| mit | 029c28d8292e1b88a7560ef3f999d75e | 29.754902 | 92 | 0.625757 | 4.314993 | false | false | false | false |
uptech/Constraid | Sources/Constraid/ProxyExtensions/ConstraidProxy+ManageSize.swift | 1 | 6632 | #if os(iOS)
import UIKit
#else
import AppKit
#endif
extension ConstraidProxy {
/**
Set width of receiver using a constraint in auto-layout
- parameter constant: The value to set the width to
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraid proxy containing the generated constraint
*/
public func setWidth(to constant: CGFloat, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self {
self.constraintCollection.append(contentsOf: Constraid.setWidth(of: self.base, to: constant, priority: priority))
return self
}
/**
Expand width of receiver using a constraint in auto-layout
- parameter constant: The minimum width to expand from
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraid proxy containing the generated constraint
*/
public func expandWidth(from constant: CGFloat, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self {
self.constraintCollection.append(contentsOf: Constraid.expandWidth(of: self.base, from: constant, priority: priority))
return self
}
/**
Limit width of receiver using a constraint in auto-layout
- parameter constant: The maximum width to limit by
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraid proxy containing the generated constraint
*/
public func limitWidth(by constant: CGFloat, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self {
self.constraintCollection.append(contentsOf: Constraid.limitWidth(of: self.base, by: constant, priority: priority))
return self
}
/**
Set height of receiver using a constraint in auto-layout
- parameter item: The `item` you want to constrain
- parameter constant: The value to set the height to
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraid proxy containing the generated constraint
*/
public func setHeight(to constant: CGFloat, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self {
self.constraintCollection.append(contentsOf: Constraid.setHeight(of: self.base, to: constant, priority: priority))
return self
}
/**
Expand height of receiver using a constraint in auto-layout
- parameter constant: The minimum height to expand from
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraid proxy containing the generated constraint
*/
public func expandHeight(from constant: CGFloat, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self {
self.constraintCollection.append(contentsOf: Constraid.expandHeight(of: self.base, from: constant, priority: priority))
return self
}
/**
Limit height of receiver using a constraint in auto-layout
- parameter constant: The maximum height to limit by
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraid proxy containing the generated constraint
*/
public func limitHeight(by constant: CGFloat, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self {
self.constraintCollection.append(contentsOf: Constraid.limitHeight(of: self.base, by: constant, priority: priority))
return self
}
/**
Set width of receiver to width of `item`
- parameter item: The `item` you want to constrain itemA against
- parameter multiplier: The ratio altering the constraint relative to
the item
- parameter constant: The amount to adjust the constraint by
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraid proxy containing the generated constraint
*/
public func matchWidth(to item: Any?,
times multiplier: CGFloat = 1.0,
by constant: CGFloat = 0.0,
priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self {
self.constraintCollection.append(contentsOf: Constraid.matchWidth(of: self.base, to: item, times: multiplier, by: constant, priority: priority))
return self
}
/**
Set height of receiver to heigt of `item`
- parameter item: The `item` you want to constrain itemA against
- parameter multiplier: The ratio altering the constraint relative to
the item
- parameter constant: The amount to adjust the constraint by
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraid proxy containing the generated constraint
*/
public func matchHeight(to item: Any?,
times multiplier: CGFloat = 1.0,
by constant: CGFloat = 0.0,
priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self {
self.constraintCollection.append(contentsOf: Constraid.matchHeight(of: self.base, to: item, times: multiplier, by: constant, priority: priority))
return self
}
/**
Add constraint to receiver declaring it square
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraid proxy containing the generated constraint
*/
public func equalize(priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self {
self.constraintCollection.append(contentsOf: Constraid.equalize(self.base, priority: priority))
return self
}
/**
Set aspect ratio of receiver using a constraint in auto-layout
- parameter size: The CGSize of your height and width used to calculate the ratio
- parameter priority: The priority this constraint uses when being
evaluated against other constraints
- returns: Constraid proxy containing the generated constraint
*/
public func setAspectRatio(toSize size: CGSize, priority: Constraid.LayoutPriority = Constraid.LayoutPriorityRequired) -> Self {
self.constraintCollection.append(contentsOf: Constraid.setAspectRatio(of: self.base, toSize: size, priority: priority))
return self
}
}
| mit | d63f5a220b0e718e8af9c98f87b2794c | 40.710692 | 153 | 0.718938 | 5.318364 | false | false | false | false |
FedeCugliandolo/hayFulBot | Sources/App/Model.swift | 1 | 5586 | //
// Model.swift
// hayFulBot
//
// Created by Fede Cugliandolo on 8/1/17.
//
//
import Foundation
import FluentProvider
struct Data {
var lists: [Int : [User]]
var captains: [Int : [Captain]]
var maxPlayers: [Int : Int]
}
struct Players {
var list: [User] {
get {
return data.lists[chatID] ?? []
}
set (newList) {
data.lists[chatID] = newList
}
}
var maxPlayers: Int {
get {
return data.maxPlayers[chatID] ?? 10
}
set {
data.maxPlayers[chatID] = newValue
}
}
var capitanes : [Captain] {
get {
return data.captains[chatID] ?? []
}
set {
data.captains[chatID] = newValue
}
}
var chatID: Int
private var data : Data
init(chatID: Int, list: [User], maxPlayers: Int, capitanes : [Captain] = [Captain(team: .none,user: User(), chatID: 0)]) {
self.chatID = chatID
self.data = Data(lists: [chatID : list], captains: [chatID : capitanes], maxPlayers: [chatID : maxPlayers])
}
func areComplete () -> Bool { return list.count >= maxPlayers }
mutating func addGuest(player: User) { list.append(player) }
mutating func add(player:User) -> Bool {
if !list.contains(where: { $0.id == player.id }) {
list.append(player)
return true
} else { return false }
}
mutating func remove(player:User, _ byName: Bool?) -> Bool {
if list.contains(where: { byName == true ? $0.completeName() == player.completeName() : $0.id == player.id }),
let idx = list.index(where: { byName == true ? $0.completeName() == player.completeName() : $0.id == player.id }) {
list.remove(at: idx)
return true
} else { return false }
}
func show() -> String {
var listMessage = "\n"
for (index,player) in list.enumerated() {
if (index + 1) == self.maxPlayers + 1 {
listMessage.append("\n\n_Pueden ir a filmar:_\n")
}
let captainTeam = isCaptain(player).answer ? "©️\(isCaptain(player).team)": ""
listMessage.append("\n \(index + 1). \(player.firstName) \(player.lastName) \(captainTeam)")
}
return listMessage
}
mutating func setCapitanes() -> Bool {
guard areComplete() && capitanes.count == 0 else { return false }
let capitanNegro = list[Int.random(min: 0, max: maxPlayers - 1)]
var capitanBlanco = list[Int.random(min: 0, max: maxPlayers - 1)]
while list.count > 1 && capitanNegro.alias == capitanBlanco.alias {
capitanBlanco = list[Int.random(min: 0, max: maxPlayers - 1)]
}
capitanes = [Captain.init(team: .negro, user: capitanNegro, chatID: chatID),
Captain.init(team: .blanco, user: capitanBlanco, chatID: chatID)]
return true
}
func showCaptains() -> String {
return "\(capitanes[0].team.rawValue) \(capitanes[0].user.firstName) \n\(capitanes[1].team.rawValue) \(capitanes[1].user.firstName)"
}
func isCaptain(_ player: User) -> (answer: Bool, team: Team.RawValue) {
guard capitanes.count > 0 else { return (false, Team.none.rawValue) }
let cap = capitanes.filter({ $0.user.completeName() == player.completeName() })
return (capitanes.contains(where: { $0.user.completeName() == player.completeName()}),
cap.count > 0 ? cap[0].team.rawValue : Team.none.rawValue )
}
}
struct User {
var id: String
var firstName: String
var lastName: String
var alias: String
var chatID: Int
public func completeName() -> String { return "\(firstName) " + " \(lastName)" }
init(row: Row) throws {
id = try row.get("id")
firstName = try row.get("firstName")
lastName = try row.get("lastName")
alias = try row.get("alias")
chatID = try row.get("chatID")
}
init(_ id: String = "", firstName: String = "", lastName: String = "", alias: String = "", chatID: Int = 0) {
self.id = id
self.firstName = firstName
self.lastName = lastName
self.alias = alias
self.chatID = chatID
}
func makeRow() throws -> Row {
var row = Row()
try row.set("id", id)
try row.set("firstName", firstName)
try row.set("lastName", lastName)
try row.set("alias", alias)
try row.set("chatID", chatID)
return row
}
}
enum CallbackType: String {
case Juego = "juego"
case Cancel = "cancel"
case Baja = "baja"
case Cancha = "cancha"
case Capitanes = "capitanes"
case NuevaLista = "nuevalista"
}
enum Team : String {
case none = ""
case negro = "👨🏿✈️"
case blanco = "👨🏻✈️"
}
final class Captain: Model {
var team : Team = .none
var user = User()
var chatID : Int = 0
let storage = Storage()
init(team: Team, user: User, chatID: Int) {
self.team = team
self.user = user
self.chatID = chatID
}
init(row: Row) throws {
team = try row.get("team")
user = try row.get("user")
chatID = try row.get("cahtID")
}
func makeRow() throws -> Row {
var row = Row()
try row.set("team", team)
try row.set("user", user)
try row.set("chatID", chatID)
return row
}
}
| mit | 0205d4e498910bbead0a4a92fe84602d | 28.104712 | 140 | 0.544343 | 3.807534 | false | false | false | false |
JGiola/swift | test/Constraints/patterns.swift | 1 | 13239 | // RUN: %target-typecheck-verify-swift
// Leaf expression patterns are matched to corresponding pieces of a switch
// subject (TODO: or ~= expression) using ~= overload resolution.
switch (1, 2.5, "three") {
case (1, _, _):
()
// Double is ExpressibleByIntegerLiteral
case (_, 2, _),
(_, 2.5, _),
(_, _, "three"):
()
// ~= overloaded for (Range<Int>, Int)
case (0..<10, _, _),
(0..<10, 2.5, "three"),
(0...9, _, _),
(0...9, 2.5, "three"):
()
default:
()
}
switch (1, 2) {
case (var a, a): // expected-error {{cannot find 'a' in scope}}
()
}
// 'is' patterns can perform the same checks that 'is' expressions do.
protocol P { func p() }
class B : P {
init() {}
func p() {}
func b() {}
}
class D : B {
override init() { super.init() }
func d() {}
}
class E {
init() {}
func e() {}
}
struct S : P {
func p() {}
func s() {}
}
// Existential-to-concrete.
var bp : P = B()
switch bp {
case is B,
is D,
is S:
()
case is E:
()
default:
()
}
switch bp {
case let b as B:
b.b()
case let d as D:
d.b()
d.d()
case let s as S:
s.s()
case let e as E:
e.e()
default:
()
}
// Super-to-subclass.
var db : B = D()
switch db {
case is D:
()
case is E: // expected-warning {{always fails}}
()
default:
()
}
// Raise an error if pattern productions are used in expressions.
var b = var x // expected-error{{expected initial value after '='}} expected-error {{type annotation missing in pattern}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
var c = is Int // expected-error{{expected initial value after '='}} expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
// TODO: Bad recovery in these cases. Although patterns are never valid
// expr-unary productions, it would be good to parse them anyway for recovery.
//var e = 2 + var y
//var e = var y + 2
// 'E.Case' can be used in a dynamic type context as an equivalent to
// '.Case as E'.
protocol HairType {}
enum MacbookHair: HairType {
case HairSupply(S)
}
enum iPadHair<T>: HairType {
case HairForceOne
}
enum Watch {
case Sport, Watch, Edition
}
let hair: HairType = MacbookHair.HairSupply(S())
switch hair {
case MacbookHair.HairSupply(let s):
s.s()
case iPadHair<S>.HairForceOne:
()
case iPadHair<E>.HairForceOne:
()
case iPadHair.HairForceOne: // expected-error{{generic enum type 'iPadHair' is ambiguous without explicit generic parameters when matching value of type 'any HairType'}}
()
case Watch.Edition: // expected-warning {{cast from 'any HairType' to unrelated type 'Watch' always fails}}
()
case .HairForceOne: // expected-error{{type 'any HairType' has no member 'HairForceOne'}}
()
default:
break
}
// <rdar://problem/19382878> Introduce new x? pattern
switch Optional(42) {
case let x?: break // expected-warning{{immutable value 'x' was never used; consider replacing with '_' or removing it}} {{10-11=_}}
case nil: break
}
func SR2066(x: Int?) {
// nil literals should still work when wrapped in parentheses
switch x {
case (nil): break
case _?: break
}
switch x {
case ((nil)): break
case _?: break
}
switch (x, x) {
case ((nil), _): break
case (_?, _): break
}
}
// Test x???? patterns.
switch (nil as Int???) {
case let x???: print(x, terminator: "")
case let x??: print(x as Any, terminator: "")
case let x?: print(x as Any, terminator: "")
case 4???: break
case nil??: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
case nil?: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
default: break
}
switch ("foo" as String?) {
case "what": break
default: break
}
// Test some value patterns.
let x : Int?
extension Int {
func method() -> Int { return 42 }
}
func ~= <T : Equatable>(lhs: T?, rhs: T?) -> Bool {
return lhs == rhs
}
switch 4 as Int? {
case x?.method(): break // match value
default: break
}
switch 4 {
case x ?? 42: break // match value
default: break
}
for (var x) in 0...100 {} // expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}}
for var x in 0...100 {} // rdar://20167543 expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}}
for (let x) in 0...100 { _ = x} // expected-error {{'let' pattern cannot appear nested in an already immutable context}}
var (let y) = 42 // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}}
let (var z) = 42 // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}}
// Crash when re-typechecking EnumElementPattern.
// FIXME: This should actually type-check -- the diagnostics are bogus. But
// at least we don't crash anymore.
protocol PP {
associatedtype E
}
struct A<T> : PP {
typealias E = T
}
extension PP {
func map<T>(_ f: (Self.E) -> T) -> T {}
}
enum EE {
case A
case B
}
func good(_ a: A<EE>) -> Int {
return a.map {
switch $0 {
case .A:
return 1
default:
return 2
}
}
}
func bad(_ a: A<EE>) {
let _ = a.map {
let _: EE = $0
return 1
}
}
func ugly(_ a: A<EE>) {
let _ = a.map {
switch $0 {
case .A:
return 1
default:
return 2
}
}
}
// SR-2057
enum SR2057 {
case foo
}
let sr2057: SR2057?
if case .foo = sr2057 { } // Ok
// Invalid 'is' pattern
class SomeClass {}
if case let doesNotExist as SomeClass:AlsoDoesNotExist {}
// expected-error@-1 {{cannot find type 'AlsoDoesNotExist' in scope}}
// expected-error@-2 {{variable binding in a condition requires an initializer}}
// `.foo` and `.bar(...)` pattern syntax should also be able to match
// static members as expr patterns
struct StaticMembers: Equatable {
init() {}
init(_: Int) {}
init?(opt: Int) {}
static var prop = StaticMembers()
static var optProp: Optional = StaticMembers()
static func method(_: Int) -> StaticMembers { return prop }
static func method(withLabel: Int) -> StaticMembers { return prop }
static func optMethod(_: Int) -> StaticMembers? { return optProp }
static func ==(x: StaticMembers, y: StaticMembers) -> Bool { return true }
}
let staticMembers = StaticMembers()
let optStaticMembers: Optional = StaticMembers()
switch staticMembers {
case .init: break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}}
case .init(opt:): break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}}
case .init(): break
case .init(0): break
case .init(_): break // expected-error{{'_' can only appear in a pattern}}
case .init(let x): break // expected-error{{cannot appear in an expression}}
case .init(opt: 0): break // expected-error{{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}}
// expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
// expected-note@-2 {{coalesce using '??' to provide a default when the optional value contains 'nil'}}
case .prop: break
case .optProp: break
case .method: break // expected-error{{member 'method' expects argument of type 'Int'}}
case .method(0): break
case .method(_): break // expected-error{{'_' can only appear in a pattern}}
case .method(let x): break // expected-error{{cannot appear in an expression}}
case .method(withLabel:): break // expected-error{{member 'method(withLabel:)' expects argument of type 'Int'}}
case .method(withLabel: 0): break
case .method(withLabel: _): break // expected-error{{'_' can only appear in a pattern}}
case .method(withLabel: let x): break // expected-error{{cannot appear in an expression}}
case .optMethod: break // expected-error{{member 'optMethod' expects argument of type 'Int'}}
case .optMethod(0): break
}
_ = 0
// rdar://problem/32241441 - Add fix-it for cases in switch with optional chaining
struct S_32241441 {
enum E_32241441 {
case foo
case bar
}
var type: E_32241441 = E_32241441.foo
}
func rdar32241441() {
let s: S_32241441? = S_32241441()
switch s?.type { // expected-error {{switch must be exhaustive}} expected-note {{add missing case: '.none'}}
case .foo: // Ok
break;
case .bar: // Ok
break;
}
}
// SR-6100
struct One<Two> { // expected-note{{'Two' declared as parameter to type 'One'}}
public enum E: Error {
// if you remove associated value, everything works
case SomeError(String)
}
}
func testOne() {
do {
} catch let error { // expected-warning{{'catch' block is unreachable because no errors are thrown in 'do' block}}
if case One.E.SomeError = error {} // expected-error{{generic parameter 'Two' could not be inferred}}
}
}
// SR-8347
// constrain initializer expressions of optional some pattern bindings to be optional
func test8347() -> String {
struct C {
subscript (s: String) -> String? {
return ""
}
subscript (s: String) -> [String] {
return [""]
}
func f() -> String? {
return ""
}
func f() -> Int {
return 3
}
func g() -> String {
return ""
}
func h() -> String {
return ""
}
func h() -> Double {
return 3.0
}
func h() -> Int? { //expected-note{{found this candidate}}
return 2
}
func h() -> Float? { //expected-note{{found this candidate}}
return nil
}
}
let c = C()
if let s = c[""] {
return s
}
if let s = c.f() {
return s
}
if let s = c.g() { //expected-error{{initializer for conditional binding must have Optional type, not 'String'}}
return s
}
if let s = c.h() { //expected-error{{ambiguous use of 'h()'}}
return s
}
}
enum SR_7799 {
case baz
case bar
}
let sr7799: SR_7799? = .bar
switch sr7799 {
case .bar?: break // Ok
case .baz: break // Ok
default: break
}
let sr7799_1: SR_7799?? = .baz
switch sr7799_1 {
case .bar?: break // Ok
case .baz: break // Ok
default: break
}
if case .baz = sr7799_1 {} // Ok
if case .bar? = sr7799_1 {} // Ok
// rdar://problem/60048356 - `if case` fails when `_` pattern doesn't have a label
func rdar_60048356() {
typealias Info = (code: ErrorCode, reason: String)
enum ErrorCode {
case normalClosure
}
enum Failure {
case closed(Info) // expected-note {{'closed' declared here}}
}
enum Reason {
case close(Failure)
}
func test(_ reason: Reason) {
if case .close(.closed((code: .normalClosure, _))) = reason { // Ok
}
}
// rdar://problem/60061646
func test(e: Failure) {
if case .closed(code: .normalClosure, _) = e { // Ok
// expected-warning@-1 {{enum case 'closed' has one associated value that is a tuple of 2 elements}}
}
}
enum E {
case foo((x: Int, y: Int)) // expected-note {{declared here}}
case bar(x: Int, y: Int) // expected-note {{declared here}}
}
func test_destructing(e: E) {
if case .foo(let x, let y) = e { // Ok (destructring)
// expected-warning@-1 {{enum case 'foo' has one associated value that is a tuple of 2 elements}}
_ = x == y
}
if case .bar(let tuple) = e { // Ok (matching via tuple)
// expected-warning@-1 {{enum case 'bar' has 2 associated values; matching them as a tuple is deprecated}}
_ = tuple.0 == tuple.1
}
}
}
// rdar://problem/63510989 - valid pattern doesn't type-check
func rdar63510989() {
enum Value : P {
func p() {}
}
enum E {
case single(P?)
case double(P??)
case triple(P???)
}
func test(e: E) {
if case .single(_) = e {} // Ok
if case .single(_ as Value) = e {} // Ok
if case .single(let v as Value) = e {} // Ok
// expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}}
if case .double(_ as Value) = e {} // Ok
if case .double(let v as Value) = e {} // Ok
// expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}}
if case .double(let v as Value?) = e {} // Ok
// expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}}
if case .triple(_ as Value) = e {} // Ok
if case .triple(let v as Value) = e {} // Ok
// expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}}
if case .triple(let v as Value?) = e {} // Ok
// expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}}
if case .triple(let v as Value??) = e {} // Ok
// expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}}
}
}
// rdar://problem/64157451 - compiler crash when using undefined type in pattern
func rdar64157451() {
enum E {
case foo(Int)
}
func test(e: E) {
if case .foo(let v as DoeNotExist) = e {} // expected-error {{cannot find type 'DoeNotExist' in scope}}
}
}
// rdar://80797176 - circular reference incorrectly diagnosed while reaching for a type of a pattern.
func rdar80797176 () {
for x: Int in [1, 2] where x.bitWidth == 32 { // Ok
}
}
| apache-2.0 | dcc153bbc774cfaeda72172a05291ece | 24.313576 | 208 | 0.625047 | 3.535113 | false | false | false | false |
ahoppen/swift | test/SILGen/foreach_async.swift | 4 | 8799 | // RUN: %target-swift-emit-silgen %s -module-name foreach_async -swift-version 5 -disable-availability-checking | %FileCheck %s
// REQUIRES: concurrency
//////////////////
// Declarations //
//////////////////
class C {}
@_silgen_name("loopBodyEnd")
func loopBodyEnd() -> ()
@_silgen_name("condition")
func condition() -> Bool
@_silgen_name("loopContinueEnd")
func loopContinueEnd() -> ()
@_silgen_name("loopBreakEnd")
func loopBreakEnd() -> ()
@_silgen_name("funcEnd")
func funcEnd() -> ()
struct TrivialStruct {
var value: Int32
}
struct NonTrivialStruct {
var value: C
}
struct GenericStruct<T> {
var value: T
var value2: C
}
protocol P {}
protocol ClassP : AnyObject {}
protocol GenericCollection : Collection {
}
struct AsyncLazySequence<S: Sequence>: AsyncSequence {
typealias Element = S.Element
typealias AsyncIterator = Iterator
struct Iterator: AsyncIteratorProtocol {
typealias Element = S.Element
var iterator: S.Iterator?
mutating func next() async -> S.Element? {
return iterator?.next()
}
}
var sequence: S
func makeAsyncIterator() -> Iterator {
return Iterator(iterator: sequence.makeIterator())
}
}
///////////
// Tests //
///////////
//===----------------------------------------------------------------------===//
// Trivial Struct
//===----------------------------------------------------------------------===//
// CHECK-LABEL: sil hidden [ossa] @$s13foreach_async13trivialStructyyAA17AsyncLazySequenceVySaySiGGYaF : $@convention(thin) @async (@guaranteed AsyncLazySequence<Array<Int>>) -> () {
// CHECK: bb0([[SOURCE:%.*]] : @guaranteed $AsyncLazySequence<Array<Int>>):
// CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var AsyncLazySequence<Array<Int>>.Iterator }, var, name "$x$generator"
// CHECK: [[ITERATOR_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[ITERATOR_BOX]]
// CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_LIFETIME]]
// CHECK: br [[LOOP_DEST:bb[0-9]+]]
// CHECK: [[LOOP_DEST]]:
// CHECK: [[NEXT_RESULT:%.*]] = alloc_stack $Optional<Int>
// CHECK: [[MUTATION:%.*]] = begin_access
// CHECK: [[WITNESS_METHOD:%.*]] = witness_method $AsyncLazySequence<Array<Int>>.Iterator, #AsyncIteratorProtocol.next : <Self where Self : AsyncIteratorProtocol> (inout Self) -> () async throws -> Self.Element? : $@convention(witness_method: AsyncIteratorProtocol) @async <τ_0_0 where τ_0_0 : AsyncIteratorProtocol> (@inout τ_0_0) -> (@out Optional<τ_0_0.Element>, @error Error)
// CHECK: try_apply [[WITNESS_METHOD]]<AsyncLazySequence<[Int]>.Iterator>([[NEXT_RESULT]], [[MUTATION]]) : $@convention(witness_method: AsyncIteratorProtocol) @async <τ_0_0 where τ_0_0 : AsyncIteratorProtocol> (@inout τ_0_0) -> (@out Optional<τ_0_0.Element>, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]([[VAR:%.*]] : $()):
// CHECK: end_access [[MUTATION]]
// CHECK: switch_enum [[IND_VAR:%.*]] : $Optional<Int>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int):
// CHECK: loopBodyEnd
// CHECK: br [[LOOP_DEST]]
// CHECK: [[NONE_BB]]:
// CHECK: funcEnd
// CHECK return
// CHECK: [[ERROR_BB]]([[VAR:%.*]] : @owned $Error):
// CHECK: unreachable
// CHECK: } // end sil function '$s13foreach_async13trivialStructyyAA17AsyncLazySequenceVySaySiGGYaF'
func trivialStruct(_ xx: AsyncLazySequence<[Int]>) async {
for await x in xx {
loopBodyEnd()
}
funcEnd()
}
// CHECK-LABEL: sil hidden [ossa] @$s13foreach_async21trivialStructContinueyyAA17AsyncLazySequenceVySaySiGGYaF : $@convention(thin) @async (@guaranteed AsyncLazySequence<Array<Int>>) -> () {
// CHECK: bb0([[SOURCE:%.*]] : @guaranteed $AsyncLazySequence<Array<Int>>):
// CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var AsyncLazySequence<Array<Int>>.Iterator }, var, name "$x$generator"
// CHECK: [[ITERATOR_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[ITERATOR_BOX]]
// CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_LIFETIME]]
// CHECK: br [[LOOP_DEST:bb[0-9]+]]
// CHECK: [[LOOP_DEST]]:
// CHECK: [[NEXT_RESULT:%.*]] = alloc_stack $Optional<Int>
// CHECK: [[MUTATION:%.*]] = begin_access
// CHECK: [[WITNESS_METHOD:%.*]] = witness_method $AsyncLazySequence<Array<Int>>.Iterator, #AsyncIteratorProtocol.next : <Self where Self : AsyncIteratorProtocol> (inout Self) -> () async throws -> Self.Element? : $@convention(witness_method: AsyncIteratorProtocol) @async <τ_0_0 where τ_0_0 : AsyncIteratorProtocol> (@inout τ_0_0) -> (@out Optional<τ_0_0.Element>, @error Error)
// CHECK: try_apply [[WITNESS_METHOD]]<AsyncLazySequence<[Int]>.Iterator>([[NEXT_RESULT]], [[MUTATION]]) : $@convention(witness_method: AsyncIteratorProtocol) @async <τ_0_0 where τ_0_0 : AsyncIteratorProtocol> (@inout τ_0_0) -> (@out Optional<τ_0_0.Element>, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]([[VAR:%.*]] : $()):
// CHECK: end_access [[MUTATION]]
// CHECK: switch_enum [[IND_VAR:%.*]] : $Optional<Int>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int):
// CHECK: condition
// CHECK: cond_br [[VAR:%.*]], [[COND_TRUE:bb[0-9]+]], [[COND_FALSE:bb[0-9]+]]
// CHECK: [[COND_TRUE]]:
// CHECK: loopContinueEnd
// CHECK: br [[LOOP_DEST]]
// CHECK: [[COND_FALSE]]:
// CHECK: loopBodyEnd
// CHECK: br [[LOOP_DEST]]
// CHECK: [[NONE_BB]]:
// CHECK: funcEnd
// CHECK return
// CHECK: [[ERROR_BB]]([[VAR:%.*]] : @owned $Error):
// CHECK: unreachable
// CHECK: } // end sil function '$s13foreach_async21trivialStructContinueyyAA17AsyncLazySequenceVySaySiGGYaF'
func trivialStructContinue(_ xx: AsyncLazySequence<[Int]>) async {
for await x in xx {
if (condition()) {
loopContinueEnd()
continue
}
loopBodyEnd()
}
funcEnd()
}
// TODO: Write this test
func trivialStructBreak(_ xx: AsyncLazySequence<[Int]>) async {
for await x in xx {
if (condition()) {
loopBreakEnd()
break
}
loopBodyEnd()
}
funcEnd()
}
// CHECK-LABEL: sil hidden [ossa] @$s13foreach_async26trivialStructContinueBreakyyAA17AsyncLazySequenceVySaySiGGYaF : $@convention(thin) @async (@guaranteed AsyncLazySequence<Array<Int>>) -> ()
// CHECK: bb0([[SOURCE:%.*]] : @guaranteed $AsyncLazySequence<Array<Int>>):
// CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var AsyncLazySequence<Array<Int>>.Iterator }, var, name "$x$generator"
// CHECK: [[ITERATOR_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[ITERATOR_BOX]]
// CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_LIFETIME]]
// CHECK: br [[LOOP_DEST:bb[0-9]+]]
// CHECK: [[LOOP_DEST]]:
// CHECK: [[NEXT_RESULT:%.*]] = alloc_stack $Optional<Int>
// CHECK: [[MUTATION:%.*]] = begin_access
// CHECK: [[WITNESS_METHOD:%.*]] = witness_method $AsyncLazySequence<Array<Int>>.Iterator, #AsyncIteratorProtocol.next : <Self where Self : AsyncIteratorProtocol> (inout Self) -> () async throws -> Self.Element? : $@convention(witness_method: AsyncIteratorProtocol) @async <τ_0_0 where τ_0_0 : AsyncIteratorProtocol> (@inout τ_0_0) -> (@out Optional<τ_0_0.Element>, @error Error)
// CHECK: try_apply [[WITNESS_METHOD]]<AsyncLazySequence<[Int]>.Iterator>([[NEXT_RESULT]], [[MUTATION]]) : $@convention(witness_method: AsyncIteratorProtocol) @async <τ_0_0 where τ_0_0 : AsyncIteratorProtocol> (@inout τ_0_0) -> (@out Optional<τ_0_0.Element>, @error Error), normal [[NORMAL_BB:bb[0-9]+]], error [[ERROR_BB:bb[0-9]+]]
// CHECK: [[NORMAL_BB]]([[VAR:%.*]] : $()):
// CHECK: end_access [[MUTATION]]
// CHECK: switch_enum [[IND_VAR:%.*]] : $Optional<Int>, case #Optional.some!enumelt: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int):
// CHECK: condition
// CHECK: cond_br [[VAR:%.*]], [[COND_TRUE:bb[0-9]+]], [[COND_FALSE:bb[0-9]+]]
// CHECK: [[COND_TRUE]]:
// CHECK: loopBreakEnd
// CHECK: br [[LOOP_EXIT:bb[0-9]+]]
// CHECK: [[COND_FALSE]]:
// CHECK: condition
// CHECK: cond_br [[VAR:%.*]], [[COND_TRUE2:bb[0-9]+]], [[COND_FALSE2:bb[0-9]+]]
// CHECK: [[COND_TRUE2]]:
// CHECK: loopContinueEnd
// CHECK: br [[LOOP_DEST]]
// CHECK: [[COND_FALSE2]]:
// CHECK: br [[LOOP_DEST]]
// CHECK: [[LOOP_EXIT]]:
// CHECK: return
// CHECK: } // end sil function '$s13foreach_async26trivialStructContinueBreakyyAA17AsyncLazySequenceVySaySiGGYaF'
func trivialStructContinueBreak(_ xx: AsyncLazySequence<[Int]>) async {
for await x in xx {
if (condition()) {
loopBreakEnd()
break
}
if (condition()) {
loopContinueEnd()
continue
}
loopBodyEnd()
}
funcEnd()
}
| apache-2.0 | 2ae5badf429c0a829231937a31ec58ea | 37.827434 | 381 | 0.627806 | 3.586024 | false | false | false | false |
wangrui460/WRNavigationBar_swift | WRNavigationBar_swift/WRNavigationBar_swift/WRNavigationBar/WRCustomNavigationBar.swift | 3 | 9259 | //
// WRCustomNavigationBar.swift
// WRNavigationBar_swift
//
// Created by itwangrui on 2017/11/25.
// Copyright © 2017年 wangrui. All rights reserved.
//
import UIKit
fileprivate let WRDefaultTitleSize:CGFloat = 18
fileprivate let WRDefaultTitleColor = UIColor.black
fileprivate let WRDefaultBackgroundColor = UIColor.white
fileprivate let WRScreenWidth = UIScreen.main.bounds.size.width
// MARK: - Router
extension UIViewController
{
// A页面 弹出 登录页面B
// presentedViewController: A页面
// presentingViewController: B页面
func wr_toLastViewController(animated:Bool)
{
if self.navigationController != nil
{
if self.navigationController?.viewControllers.count == 1
{
self.dismiss(animated: animated, completion: nil)
} else {
self.navigationController?.popViewController(animated: animated)
}
}
else if self.presentingViewController != nil {
self.dismiss(animated: animated, completion: nil)
}
}
class func wr_currentViewController() -> UIViewController
{
if let rootVC = UIApplication.shared.delegate?.window??.rootViewController {
return self.wr_currentViewController(from: rootVC)
} else {
return UIViewController()
}
}
class func wr_currentViewController(from fromVC:UIViewController) -> UIViewController
{
if fromVC.isKind(of: UINavigationController.self) {
let navigationController = fromVC as! UINavigationController
return wr_currentViewController(from: navigationController.viewControllers.last!)
}
else if fromVC.isKind(of: UITabBarController.self) {
let tabBarController = fromVC as! UITabBarController
return wr_currentViewController(from: tabBarController.selectedViewController!)
}
else if fromVC.presentedViewController != nil {
return wr_currentViewController(from:fromVC.presentingViewController!)
}
else {
return fromVC
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
class WRCustomNavigationBar: UIView
{
var onClickLeftButton:(()->())?
var onClickRightButton:(()->())?
var title:String? {
willSet {
titleLabel.isHidden = false
titleLabel.text = newValue
}
}
var titleLabelColor:UIColor? {
willSet {
titleLabel.textColor = newValue
}
}
var titleLabelFont:UIFont? {
willSet {
titleLabel.font = newValue
}
}
var barBackgroundColor:UIColor? {
willSet {
backgroundImageView.isHidden = true
backgroundView.isHidden = false
backgroundView.backgroundColor = newValue
}
}
var barBackgroundImage:UIImage? {
willSet {
backgroundView.isHidden = true
backgroundImageView.isHidden = false
backgroundImageView.image = newValue
}
}
// fileprivate UI variable
fileprivate lazy var titleLabel:UILabel = {
let label = UILabel()
label.textColor = WRDefaultTitleColor
label.font = UIFont.systemFont(ofSize: WRDefaultTitleSize)
label.textAlignment = .center
label.isHidden = true
return label
}()
fileprivate lazy var leftButton:UIButton = {
let button = UIButton()
button.imageView?.contentMode = .center
button.isHidden = true
button.addTarget(self, action: #selector(clickBack), for: .touchUpInside)
return button
}()
fileprivate lazy var rightButton:UIButton = {
let button = UIButton()
button.imageView?.contentMode = .center
button.isHidden = true
button.addTarget(self, action: #selector(clickRight), for: .touchUpInside)
return button
}()
fileprivate lazy var bottomLine:UIView = {
let view = UIView()
view.backgroundColor = UIColor(red: (218.0/255.0), green: (218.0/255.0), blue: (218.0/255.0), alpha: 1.0)
return view
}()
fileprivate lazy var backgroundView:UIView = {
let view = UIView()
return view
}()
fileprivate lazy var backgroundImageView:UIImageView = {
let imgView = UIImageView()
imgView.isHidden = true
return imgView
}()
// fileprivate other variable
fileprivate static var isIphoneX:Bool {
get {
return UIScreen.main.bounds.equalTo(CGRect(x: 0, y: 0, width: 375, height: 812))
}
}
fileprivate static var navBarBottom:Int {
get {
return isIphoneX ? 88 : 64
}
}
// init
class func CustomNavigationBar() -> WRCustomNavigationBar {
let frame = CGRect(x: 0, y: 0, width: WRScreenWidth, height: CGFloat(navBarBottom))
return WRCustomNavigationBar(frame: frame)
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
func setupView()
{
addSubview(backgroundView)
addSubview(backgroundImageView)
addSubview(leftButton)
addSubview(titleLabel)
addSubview(rightButton)
addSubview(bottomLine)
updateFrame()
backgroundColor = UIColor.clear
backgroundView.backgroundColor = WRDefaultBackgroundColor
}
func updateFrame()
{
let top:CGFloat = WRCustomNavigationBar.isIphoneX ? 44 : 20
let margin:CGFloat = 0
let buttonHeight:CGFloat = 44
let buttonWidth:CGFloat = 44
let titleLabelHeight:CGFloat = 44
let titleLabelWidth:CGFloat = 180
backgroundView.frame = self.bounds
backgroundImageView.frame = self.bounds
leftButton.frame = CGRect(x: margin, y: top, width: buttonWidth, height: buttonHeight)
rightButton.frame = CGRect(x: WRScreenWidth-buttonWidth-margin, y: top, width: buttonWidth, height: buttonHeight)
titleLabel.frame = CGRect(x: (WRScreenWidth-titleLabelWidth)/2.0, y: top, width: titleLabelWidth, height: titleLabelHeight)
bottomLine.frame = CGRect(x: 0, y: bounds.height-0.5, width: WRScreenWidth, height: 0.5)
}
}
extension WRCustomNavigationBar
{
func wr_setBottomLineHidden(hidden:Bool) {
bottomLine.isHidden = hidden
}
func wr_setBackgroundAlpha(alpha:CGFloat) {
backgroundView.alpha = alpha
backgroundImageView.alpha = alpha
bottomLine.alpha = alpha
}
func wr_setTintColor(color:UIColor) {
leftButton.setTitleColor(color, for: .normal)
rightButton.setTitleColor(color, for: .normal)
titleLabel.textColor = color
}
// 左右按钮共有方法
func wr_setLeftButton(normal:UIImage, highlighted:UIImage) {
wr_setLeftButton(normal: normal, highlighted: highlighted, title: nil, titleColor: nil)
}
func wr_setLeftButton(image:UIImage) {
wr_setLeftButton(normal: image, highlighted: image, title: nil, titleColor: nil)
}
func wr_setLeftButton(title:String, titleColor:UIColor) {
wr_setLeftButton(normal: nil, highlighted: nil, title: title, titleColor: titleColor)
}
func wr_setRightButton(normal:UIImage, highlighted:UIImage) {
wr_setRightButton(normal: normal, highlighted: highlighted, title: nil, titleColor: nil)
}
func wr_setRightButton(image:UIImage) {
wr_setRightButton(normal: image, highlighted: image, title: nil, titleColor: nil)
}
func wr_setRightButton(title:String, titleColor:UIColor) {
wr_setRightButton(normal: nil, highlighted: nil, title: title, titleColor: titleColor)
}
// 左右按钮私有方法
private func wr_setLeftButton(normal:UIImage?, highlighted:UIImage?, title:String?, titleColor:UIColor?) {
leftButton.isHidden = false
leftButton.setImage(normal, for: .normal)
leftButton.setImage(highlighted, for: .highlighted)
leftButton.setTitle(title, for: .normal)
leftButton.setTitleColor(titleColor, for: .normal)
}
private func wr_setRightButton(normal:UIImage?, highlighted:UIImage?, title:String?, titleColor:UIColor?) {
rightButton.isHidden = false
rightButton.setImage(normal, for: .normal)
rightButton.setImage(highlighted, for: .highlighted)
rightButton.setTitle(title, for: .normal)
rightButton.setTitleColor(titleColor, for: .normal)
}
}
// MARK: - 导航栏左右按钮事件
extension WRCustomNavigationBar
{
@objc func clickBack() {
if let onClickBack = onClickLeftButton {
onClickBack()
} else {
let currentVC = UIViewController.wr_currentViewController()
currentVC.wr_toLastViewController(animated: true)
}
}
@objc func clickRight() {
if let onClickRight = onClickRightButton {
onClickRight()
}
}
}
| mit | d7cf0c657ab792ad980bf8dfa3c69dab | 29.504983 | 131 | 0.62971 | 4.995647 | false | false | false | false |
arieeel/NMPopUpView | NMPopUpView/DemoViewController.swift | 1 | 2987 | //
// DemoViewController.swift
// NMPopUpView
//
// Created by Nikos Maounis on 13/9/14.
// Copyright (c) 2014 Nikos Maounis. All rights reserved.
//
import UIKit
import QuartzCore
@objc class DemoViewController : UIViewController
{
@IBOutlet weak var showPopupBtn: UIButton!
var popViewController : PopUpViewControllerSwift!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.setRoundedBorder(5, withBorderWidth: 1, withColor: UIColor(red: 0.0, green: 122.0/2550, blue: 1.0, alpha: 1.0), forButton: showPopupBtn)
}
@IBAction func showPopUp(sender: AnyObject) {
if (UIDevice.currentDevice().userInterfaceIdiom == .Pad)
{
self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController_iPad", bundle: nil)
self.popViewController.title = "This is a popup view"
self.popViewController.showInView(self.view, withImage: UIImage(named: "typpzDemo"), withMessage: "You just triggered a great popup window", animated: true)
} else
{
if UIScreen.mainScreen().bounds.size.width > 320 {
if UIScreen.mainScreen().scale == 3 {
self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController_iPhone6Plus", bundle: nil)
self.popViewController.title = "This is a popup view"
self.popViewController.showInView(self.view, withImage: UIImage(named: "typpzDemo"), withMessage: "You just triggered a great popup window", animated: true)
} else {
self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController_iPhone6", bundle: nil)
self.popViewController.title = "This is a popup view"
self.popViewController.showInView(self.view, withImage: UIImage(named: "typpzDemo"), withMessage: "You just triggered a great popup window", animated: true)
}
} else {
self.popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController", bundle: nil)
self.popViewController.title = "This is a popup view"
self.popViewController.showInView(self.view, withImage: UIImage(named: "typpzDemo"), withMessage: "You just triggered a great popup window", animated: true)
}
}
}
func setRoundedBorder(radius : CGFloat, withBorderWidth borderWidth: CGFloat, withColor color : UIColor, forButton button : UIButton)
{
let l : CALayer = button.layer
l.masksToBounds = true
l.cornerRadius = radius
l.borderWidth = borderWidth
l.borderColor = color.CGColor
}
}
| mit | cbd41983c88768fff571d34cf0cca08b | 41.671429 | 176 | 0.651825 | 4.763955 | false | false | false | false |
dreamsxin/swift | test/stmt/foreach.swift | 2 | 4756 | // RUN: %target-parse-verify-swift
// Bad containers and ranges
struct BadContainer1 {
}
func bad_containers_1(bc: BadContainer1) {
for e in bc { } // expected-error{{type 'BadContainer1' does not conform to protocol 'Sequence'}}
}
struct BadContainer2 : Sequence { // expected-error{{type 'BadContainer2' does not conform to protocol 'Sequence'}}
var generate : Int
}
func bad_containers_2(bc: BadContainer2) {
for e in bc { }
}
struct BadContainer3 : Sequence { // expected-error{{type 'BadContainer3' does not conform to protocol 'Sequence'}}
func makeIterator() { } // expected-note{{inferred type '()' (by matching requirement 'makeIterator()') is invalid: does not conform to 'IteratorProtocol'}}
}
func bad_containers_3(bc: BadContainer3) {
for e in bc { }
}
struct BadIterator1 {}
struct BadContainer4 : Sequence { // expected-error{{type 'BadContainer4' does not conform to protocol 'Sequence'}}
typealias Iterator = BadIterator1 // expected-note{{possibly intended match 'Iterator' (aka 'BadIterator1') does not conform to 'IteratorProtocol'}}
func makeIterator() -> BadIterator1 { }
}
func bad_containers_4(bc: BadContainer4) {
for e in bc { }
}
// Pattern type-checking
struct GoodRange<Int> : Sequence, IteratorProtocol {
typealias Element = Int
func next() -> Int? {}
typealias Iterator = GoodRange<Int>
func makeIterator() -> GoodRange<Int> { return self }
}
struct GoodTupleIterator: Sequence, IteratorProtocol {
typealias Element = (Int, Float)
func next() -> (Int, Float)? {}
typealias Iterator = GoodTupleIterator
func makeIterator() -> GoodTupleIterator {}
}
func patterns(gir: GoodRange<Int>, gtr: GoodTupleIterator) {
var sum : Int
var sumf : Float
for i : Int in gir { sum = sum + i }
for i in gir { sum = sum + i }
for f : Float in gir { sum = sum + f } // expected-error{{'Int' is not convertible to 'Float'}}
for (i, f) : (Int, Float) in gtr { sum = sum + i }
for (i, f) in gtr {
sum = sum + i
sumf = sumf + f
sum = sum + f // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Float'}} expected-note {{expected an argument list of type '(Int, Int)'}}
}
for (i, _) : (Int, Float) in gtr { sum = sum + i }
for (i, _) : (Int, Int) in gtr { sum = sum + i } // expected-error{{'Element' (aka '(Int, Float)') is not convertible to '(Int, Int)'}}
for (i, f) in gtr {}
}
func slices(i_s: [Int], ias: [[Int]]) {
var sum = 0
for i in i_s { sum = sum + i }
for ia in ias {
for i in ia {
sum = sum + i
}
}
}
func discard_binding() {
for _ in [0] {}
}
struct X<T> {
var value: T
}
struct Gen<T> : IteratorProtocol {
func next() -> T? { return nil }
}
struct Seq<T> : Sequence {
func makeIterator() -> Gen<T> { return Gen() }
}
func getIntSeq() -> Seq<Int> { return Seq() }
func getOvlSeq() -> Seq<Int> { return Seq() } // expected-note{{found this candidate}}
func getOvlSeq() -> Seq<Double> { return Seq() } // expected-note{{found this candidate}}
func getOvlSeq() -> Seq<X<Int>> { return Seq() } // expected-note{{found this candidate}}
func getGenericSeq<T>() -> Seq<T> { return Seq() }
func getXIntSeq() -> Seq<X<Int>> { return Seq() }
func getXIntSeqIUO() -> Seq<X<Int>>! { return nil }
func testForEachInference() {
for i in getIntSeq() { }
// Overloaded sequence resolved contextually
for i: Int in getOvlSeq() { }
for d: Double in getOvlSeq() { }
// Overloaded sequence not resolved contextually
for v in getOvlSeq() { } // expected-error{{ambiguous use of 'getOvlSeq()'}}
// Generic sequence resolved contextually
for i: Int in getGenericSeq() { }
for d: Double in getGenericSeq() { }
// Inference of generic arguments in the element type from the
// sequence.
for x: X in getXIntSeq() {
let z = x.value + 1
}
for x: X in getOvlSeq() {
let z = x.value + 1
}
// Inference with implicitly unwrapped optional
for x: X in getXIntSeqIUO() {
let z = x.value + 1
}
// Range overloading.
for i: Int8 in 0..<10 { }
for i: UInt in 0...10 { }
}
func testMatchingPatterns() {
// <rdar://problem/21428712> for case parse failure
let myArray : [Int?] = []
for case .some(let x) in myArray {
_ = x
}
// <rdar://problem/21392677> for/case/in patterns aren't parsed properly
class A {}
class B : A {}
class C : A {}
let array : [A] = [A(), B(), C()]
for case (let x as B) in array {
_ = x
}
}
// <rdar://problem/21662365> QoI: diagnostic for for-each over an optional sequence isn't great
func testOptionalSequence() {
let array : [Int]? = nil
for x in array { // expected-error {{value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?}} {{17-17=!}}
}
}
| apache-2.0 | 158e045ae378d7c3037fc5ec7e7b7e3f | 26.333333 | 181 | 0.635828 | 3.448876 | false | false | false | false |
banxi1988/Staff | Pods/PinAuto/Pod/Classes/UIView+PinAuto.swift | 5 | 14791 | //
// UIView+PinAuto.swift
// Pods
//
// Created by Haizhen Lee on 16/1/14.
//
//
import UIKit
// PinAuto Chian Style Method Value Container
public class LayoutConstraintParams{
public var priority:UILayoutPriority = UILayoutPriorityRequired
public var relation: NSLayoutRelation = NSLayoutRelation.Equal
public var firstItemAttribute:NSLayoutAttribute = NSLayoutAttribute.NotAnAttribute
public var secondItemAttribute:NSLayoutAttribute = NSLayoutAttribute.NotAnAttribute
public var multiplier:CGFloat = 1.0
public var constant:CGFloat = 0
public let firstItem:UIView
public var secondItem:AnyObject?
public var identifier:String? = LayoutConstraintParams.constraintIdentifier
public static let constraintIdentifier = "pin_auto"
private let attributesOfOpposite: [NSLayoutAttribute] = [.Right,.RightMargin,.Trailing,.TrailingMargin,.Bottom,.BottomMargin]
private var shouldReverseValue:Bool{
if firstItemAttribute == secondItemAttribute{
return attributesOfOpposite.contains(firstItemAttribute)
}
return false
}
public init(firstItem:UIView){
self.firstItem = firstItem
}
public var required:LayoutConstraintParams{
priority = UILayoutPriorityRequired
return self
}
public func withPriority(value:UILayoutPriority) -> LayoutConstraintParams{
priority = value
return self
}
public var withLowPriority:LayoutConstraintParams{
priority = UILayoutPriorityDefaultLow
return self
}
public var withHighPriority:LayoutConstraintParams{
priority = UILayoutPriorityDefaultHigh
return self
}
@warn_unused_result
public func decrPriorityBy(value:UILayoutPriority) -> LayoutConstraintParams{
priority = priority - value
return self
}
@warn_unused_result
public func incrPriorityBy(value:UILayoutPriority) -> LayoutConstraintParams{
priority = priority - value
return self
}
@warn_unused_result
public func withRelation(relation:NSLayoutRelation){
self.relation = relation
}
public var withGteRelation:LayoutConstraintParams{
self.relation = .GreaterThanOrEqual
return self
}
public var withLteRelation:LayoutConstraintParams{
self.relation = .LessThanOrEqual
return self
}
public var withEqRelation:LayoutConstraintParams{
self.relation = .Equal
return self
}
@warn_unused_result
public func to(value:CGFloat) -> LayoutConstraintParams{
constant = value
relation = .Equal
return self
}
@warn_unused_result
public func equal(value:CGFloat) -> LayoutConstraintParams{
constant = value
relation = .Equal
return self
}
@warn_unused_result
public func equalTo(value:CGFloat) -> LayoutConstraintParams{
constant = value
relation = .Equal
return self
}
@warn_unused_result
public func eq(value:CGFloat) -> LayoutConstraintParams{
constant = value
relation = .Equal
return self
}
@warn_unused_result
public func lte(value:CGFloat) -> LayoutConstraintParams{
constant = value
relation = .LessThanOrEqual
return self
}
@warn_unused_result
public func gte(value:CGFloat) -> LayoutConstraintParams{
constant = value
relation = .GreaterThanOrEqual
return self
}
@warn_unused_result
public func to(item:UIView) -> LayoutConstraintParams{
secondItem = item
return self
}
@warn_unused_result
public func to(item:UILayoutSupport) -> LayoutConstraintParams{
secondItem = item
return self
}
@warn_unused_result
public func equalTo(item:UIView) -> LayoutConstraintParams{
secondItem = item
relation = .Equal
secondItemAttribute = firstItemAttribute
return self
}
@warn_unused_result
public func eqTo(item:UIView) -> LayoutConstraintParams{
secondItem = item
relation = .Equal
secondItemAttribute = firstItemAttribute
return self
}
@warn_unused_result
public func offset(value:CGFloat) -> LayoutConstraintParams{
constant = value
return self
}
@warn_unused_result
public func lteTo(item:UIView) -> LayoutConstraintParams{
secondItem = item
relation = .LessThanOrEqual
secondItemAttribute = firstItemAttribute
return self
}
@warn_unused_result
public func gteTo(item:UIView) -> LayoutConstraintParams{
secondItem = item
relation = .GreaterThanOrEqual
secondItemAttribute = firstItemAttribute
return self
}
@warn_unused_result
public func lessThanOrEqualTo(item:UIView) -> LayoutConstraintParams{
secondItem = item
relation = .LessThanOrEqual
secondItemAttribute = firstItemAttribute
return self
}
@warn_unused_result
public func greaterThanOrEqualTo(item:UIView) -> LayoutConstraintParams{
secondItem = item
relation = .GreaterThanOrEqual
secondItemAttribute = firstItemAttribute
return self
}
@warn_unused_result
public func identifier(id:String?) -> LayoutConstraintParams{
self.identifier = id
return self
}
@warn_unused_result
public func equalTo(itemAttribute:NSLayoutAttribute,ofView view:UIView) -> LayoutConstraintParams{
self.secondItem = view
self.relation = .Equal
self.secondItemAttribute = itemAttribute
return self
}
public var inSuperview: LayoutConstraintParams{
secondItem = firstItem.superview
return self
}
public var toSuperview: LayoutConstraintParams{
secondItem = firstItem.superview
return self
}
public func autoadd() -> NSLayoutConstraint{
return install()
}
public func install() -> NSLayoutConstraint{
let finalConstanValue = shouldReverseValue ? -constant : constant
let constraint = NSLayoutConstraint(item: firstItem,
attribute: firstItemAttribute,
relatedBy: relation,
toItem: secondItem,
attribute: secondItemAttribute,
multiplier: multiplier,
constant: finalConstanValue)
constraint.identifier = identifier
firstItem.translatesAutoresizingMaskIntoConstraints = false
if let secondItem = secondItem{
firstItem.assertHasSuperview()
let containerView:UIView
if let secondItemView = secondItem as? UIView{
if firstItem.superview == secondItemView{
containerView = secondItemView
}else if firstItem.superview == secondItemView.superview{
containerView = firstItem.superview!
}else{
fatalError("Second Item Should be First Item 's superview or sibling view")
}
}else if secondItem is UILayoutSupport{
containerView = firstItem.superview!
}else{
fatalError("Second Item Should be UIView or UILayoutSupport")
}
containerView.addConstraint(constraint)
}else{
firstItem.addConstraint(constraint)
}
return constraint
}
}
// PinAuto Core Method
public extension UIView{
private var pa_makeConstraint:LayoutConstraintParams{
assertHasSuperview()
return LayoutConstraintParams(firstItem: self)
}
public var pa_width:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = .Width
pa.secondItem = nil
pa.secondItemAttribute = .NotAnAttribute
return pa
}
public var pa_height:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = .Height
pa.secondItem = nil
pa.secondItemAttribute = .NotAnAttribute
return pa
}
@warn_unused_result
@available(*,introduced=1.2)
public func pa_aspectRatio(ratio:CGFloat) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = .Height
pa.secondItemAttribute = .Width
pa.secondItem = self
pa.multiplier = ratio // height = width * ratio
// ratio = width:height
return pa
}
public var pa_leading:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = .Leading
pa.secondItem = superview
pa.secondItemAttribute = .Leading
return pa
}
public var pa_trailing:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .Trailing
pa.secondItemAttribute = .Trailing
return pa
}
public var pa_top:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .Top
pa.secondItemAttribute = .Top
return pa
}
public var pa_bottom:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .Bottom
pa.secondItemAttribute = .Bottom
return pa
}
public var pa_centerX:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .CenterX
pa.secondItemAttribute = .CenterX
return pa
}
public var pa_centerY:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .CenterY
pa.secondItemAttribute = .CenterY
return pa
}
public var pa_left:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .Left
pa.secondItemAttribute = .Left
return pa
}
public var pa_right:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .Right
pa.secondItemAttribute = .Right
return pa
}
public var pa_leadingMargin:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .LeadingMargin
pa.secondItemAttribute = .LeadingMargin
return pa
}
public var pa_trailingMargin:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .TrailingMargin
pa.secondItemAttribute = .TrailingMargin
return pa
}
public var pa_topMargin:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .TopMargin
pa.secondItemAttribute = .TopMargin
return pa
}
public var pa_bottomMargin:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .BottomMargin
pa.secondItemAttribute = .BottomMargin
return pa
}
public var pa_leftMargin:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .LeftMargin
pa.secondItemAttribute = .LeadingMargin
return pa
}
public var pa_rightMargin:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .RightMargin
pa.secondItemAttribute = .RightMargin
return pa
}
public var pa_centerXWithinMargins:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .CenterXWithinMargins
pa.secondItemAttribute = .CenterXWithinMargins
return pa
}
public var pa_centerYWithinMargins:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = superview
pa.firstItemAttribute = .CenterYWithinMargins
pa.secondItemAttribute = .CenterYWithinMargins
return pa
}
public var pa_baseline:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = .Baseline
return pa
}
public var pa_firstBaseline:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = .FirstBaseline
return pa
}
public var pa_lastBaseline:LayoutConstraintParams{
let pa = pa_makeConstraint
pa.firstItemAttribute = NSLayoutAttribute.LastBaseline
return pa
}
@warn_unused_result
public func pa_below(item:UILayoutSupport,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .Top
pa.relation = .Equal
pa.secondItemAttribute = .Bottom
pa.constant = offset
return pa
}
@warn_unused_result
public func pa_below(item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .Top
pa.relation = .Equal
pa.secondItemAttribute = .Bottom
pa.constant = offset
return pa
}
@warn_unused_result
public func pa_above(item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .Bottom
pa.relation = .Equal
pa.secondItemAttribute = .Top
pa.constant = -offset
return pa
}
@warn_unused_result
public func pa_above(item:UILayoutSupport,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .Bottom
pa.relation = .Equal
pa.secondItemAttribute = .Top
pa.constant = -offset
return pa
}
@warn_unused_result
public func pa_toLeadingOf(item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .Trailing
pa.relation = .Equal
pa.secondItemAttribute = .Leading
pa.constant = -offset
return pa
}
@warn_unused_result
public func pa_before(item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .Trailing
pa.relation = .Equal
pa.secondItemAttribute = .Leading
pa.constant = -offset
return pa
}
@warn_unused_result
public func pa_toLeftOf(item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .Right
pa.relation = .Equal
pa.secondItemAttribute = .Left
pa.constant = -offset
return pa
}
@warn_unused_result
public func pa_toTrailingOf(item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .Leading
pa.relation = .Equal
pa.secondItemAttribute = .Trailing
pa.constant = offset
return pa
}
@warn_unused_result
public func pa_after(item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .Leading
pa.relation = .Equal
pa.secondItemAttribute = .Trailing
pa.constant = offset
return pa
}
@warn_unused_result
public func pa_toRightOf(item:UIView,offset:CGFloat = 0) -> LayoutConstraintParams{
let pa = pa_makeConstraint
pa.secondItem = item
pa.firstItemAttribute = .Left
pa.relation = .Equal
pa.secondItemAttribute = .Right
pa.constant = offset
return pa
}
} | mit | 3f9697af898d2955349c2409066c6414 | 24.905429 | 127 | 0.709621 | 4.948478 | false | false | false | false |
yanagiba/swift-ast | Sources/AST/Declaration/ProtocolDeclaration.swift | 2 | 10844 | /*
Copyright 2017 Ryuichi Intellectual Property and the Yanagiba project contributors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class ProtocolDeclaration : ASTNode, Declaration {
public struct PropertyMember {
public let attributes: Attributes
public let modifiers: DeclarationModifiers
public let name: Identifier
public let typeAnnotation: TypeAnnotation
public let getterSetterKeywordBlock: GetterSetterKeywordBlock
public init(
attributes: Attributes = [],
modifiers: DeclarationModifiers = [],
name: Identifier,
typeAnnotation: TypeAnnotation,
getterSetterKeywordBlock: GetterSetterKeywordBlock
) {
self.attributes = attributes
self.modifiers = modifiers
self.name = name
self.typeAnnotation = typeAnnotation
self.getterSetterKeywordBlock = getterSetterKeywordBlock
}
}
public struct MethodMember {
public let attributes: Attributes
public let modifiers: DeclarationModifiers
public let name: Identifier
public let genericParameter: GenericParameterClause?
public let signature: FunctionSignature
public let genericWhere: GenericWhereClause?
public init(
attributes: Attributes = [],
modifiers: DeclarationModifiers = [],
name: Identifier,
genericParameter: GenericParameterClause? = nil,
signature: FunctionSignature,
genericWhere: GenericWhereClause? = nil
) {
self.attributes = attributes
self.modifiers = modifiers
self.name = name
self.genericParameter = genericParameter
self.signature = signature
self.genericWhere = genericWhere
}
}
public struct InitializerMember {
public let attributes: Attributes
public let modifiers: DeclarationModifiers
public let kind: InitializerDeclaration.InitKind
public let genericParameter: GenericParameterClause?
public let parameterList: [FunctionSignature.Parameter]
public let throwsKind: ThrowsKind
public let genericWhere: GenericWhereClause?
public init(
attributes: Attributes = [],
modifiers: DeclarationModifiers = [],
kind: InitializerDeclaration.InitKind = .nonfailable,
genericParameter: GenericParameterClause? = nil,
parameterList: [FunctionSignature.Parameter] = [],
throwsKind: ThrowsKind = .nothrowing,
genericWhere: GenericWhereClause? = nil
) {
self.attributes = attributes
self.modifiers = modifiers
self.kind = kind
self.genericParameter = genericParameter
self.parameterList = parameterList
self.throwsKind = throwsKind
self.genericWhere = genericWhere
}
}
public struct SubscriptMember {
public let attributes: Attributes
public let modifiers: DeclarationModifiers
public let genericParameter: GenericParameterClause?
public let parameterList: [FunctionSignature.Parameter]
public let resultAttributes: Attributes
public let resultType: Type
public let genericWhere: GenericWhereClause?
public let getterSetterKeywordBlock: GetterSetterKeywordBlock
public init(
attributes: Attributes = [],
modifiers: DeclarationModifiers = [],
genericParameter: GenericParameterClause? = nil,
parameterList: [FunctionSignature.Parameter] = [],
resultAttributes: Attributes = [],
resultType: Type,
genericWhere: GenericWhereClause? = nil,
getterSetterKeywordBlock: GetterSetterKeywordBlock
) {
self.attributes = attributes
self.modifiers = modifiers
self.genericParameter = genericParameter
self.parameterList = parameterList
self.resultAttributes = resultAttributes
self.resultType = resultType
self.genericWhere = genericWhere
self.getterSetterKeywordBlock = getterSetterKeywordBlock
}
}
public struct AssociativityTypeMember {
public let attributes: Attributes
public let accessLevelModifier: AccessLevelModifier?
public let name: Identifier
public let typeInheritance: TypeInheritanceClause?
public let assignmentType: Type?
public let genericWhere: GenericWhereClause?
public init(
attributes: Attributes = [],
accessLevelModifier: AccessLevelModifier? = nil,
name: Identifier,
typeInheritance: TypeInheritanceClause? = nil,
assignmentType: Type? = nil,
genericWhere: GenericWhereClause? = nil
) {
self.attributes = attributes
self.accessLevelModifier = accessLevelModifier
self.name = name
self.typeInheritance = typeInheritance
self.assignmentType = assignmentType
self.genericWhere = genericWhere
}
}
public enum Member {
case property(PropertyMember)
case method(MethodMember)
case initializer(InitializerMember)
case `subscript`(SubscriptMember)
case associatedType(AssociativityTypeMember)
case compilerControl(CompilerControlStatement)
}
public let attributes: Attributes
public let accessLevelModifier: AccessLevelModifier?
public let name: Identifier
public let typeInheritanceClause: TypeInheritanceClause?
public private(set) var members: [Member]
public init(
attributes: Attributes = [],
accessLevelModifier: AccessLevelModifier? = nil,
name: Identifier,
typeInheritanceClause: TypeInheritanceClause? = nil,
members: [Member] = []
) {
self.attributes = attributes
self.accessLevelModifier = accessLevelModifier
self.name = name
self.typeInheritanceClause = typeInheritanceClause
self.members = members
}
// MARK: - Node Mutations
public func replaceMember(at index: Int, with member: Member) {
guard index >= 0 && index < members.count else { return }
members[index] = member
}
// MARK: - ASTTextRepresentable
override public var textDescription: String {
let attrsText = attributes.isEmpty ? "" : "\(attributes.textDescription) "
let modifierText = accessLevelModifier.map({ "\($0.textDescription) " }) ?? ""
let headText = "\(attrsText)\(modifierText)protocol \(name)"
let typeText = typeInheritanceClause?.textDescription ?? ""
let membersText = members.map({ $0.textDescription }).joined(separator: "\n")
let memberText = members.isEmpty ? "" : "\n\(membersText)\n"
return "\(headText)\(typeText) {\(memberText)}"
}
}
extension ProtocolDeclaration.PropertyMember : ASTTextRepresentable {
public var textDescription: String {
let attrsText = attributes.isEmpty ? "" : "\(attributes.textDescription) "
let modifiersText = modifiers.isEmpty ? "" : "\(modifiers.textDescription) "
let blockText = getterSetterKeywordBlock.textDescription
return "\(attrsText)\(modifiersText)var \(name)\(typeAnnotation) \(blockText)"
}
}
extension ProtocolDeclaration.MethodMember : ASTTextRepresentable {
public var textDescription: String {
let attrsText = attributes.isEmpty ? "" : "\(attributes.textDescription) "
let modifiersText = modifiers.isEmpty ? "" : "\(modifiers.textDescription) "
let headText = "\(attrsText)\(modifiersText)func"
let genericParameterClauseText = genericParameter?.textDescription ?? ""
let signatureText = signature.textDescription
let genericWhereClauseText = genericWhere.map({ " \($0.textDescription)" }) ?? ""
return "\(headText) \(name)\(genericParameterClauseText)\(signatureText)\(genericWhereClauseText)"
}
}
extension ProtocolDeclaration.InitializerMember : ASTTextRepresentable {
public var textDescription: String {
let attrsText = attributes.isEmpty ? "" : "\(attributes.textDescription) "
let modifiersText = modifiers.isEmpty ? "" : "\(modifiers.textDescription) "
let headText = "\(attrsText)\(modifiersText)init\(kind.textDescription)"
let genericParameterClauseText = genericParameter?.textDescription ?? ""
let parameterText = "(\(parameterList.map({ $0.textDescription }).joined(separator: ", ")))"
let throwsKindText = throwsKind.textDescription.isEmpty ? "" : " \(throwsKind.textDescription)"
let genericWhereClauseText = genericWhere.map({ " \($0.textDescription)" }) ?? ""
return "\(headText)\(genericParameterClauseText)\(parameterText)\(throwsKindText)\(genericWhereClauseText)"
}
}
extension ProtocolDeclaration.SubscriptMember : ASTTextRepresentable {
public var textDescription: String {
let attrsText = attributes.isEmpty ? "" : "\(attributes.textDescription) "
let modifiersText = modifiers.isEmpty ? "" : "\(modifiers.textDescription) "
let genericParamClauseText = genericParameter?.textDescription ?? ""
let parameterText = "(\(parameterList.map({ $0.textDescription }).joined(separator: ", ")))"
let headText = "\(attrsText)\(modifiersText)subscript\(genericParamClauseText)\(parameterText)"
let resultAttrsText = resultAttributes.isEmpty ? "" : "\(resultAttributes.textDescription) "
let resultText = "-> \(resultAttrsText)\(resultType.textDescription)"
let genericWhereClauseText = genericWhere.map({ " \($0.textDescription)" }) ?? ""
return "\(headText) \(resultText)\(genericWhereClauseText) \(getterSetterKeywordBlock.textDescription)"
}
}
extension ProtocolDeclaration.AssociativityTypeMember : ASTTextRepresentable {
public var textDescription: String {
let attrsText = attributes.isEmpty ? "" : "\(attributes.textDescription) "
let modifierText = accessLevelModifier.map({ "\($0.textDescription) " }) ?? ""
let typeText = typeInheritance?.textDescription ?? ""
let assignmentText = assignmentType.map({ " = \($0.textDescription)" }) ?? ""
let genericWhereClauseText = genericWhere.map({ " \($0.textDescription)" }) ?? ""
return "\(attrsText)\(modifierText)associatedtype \(name)\(typeText)\(assignmentText)\(genericWhereClauseText)"
}
}
extension ProtocolDeclaration.Member : ASTTextRepresentable {
public var textDescription: String {
switch self {
case .property(let member):
return member.textDescription
case .method(let member):
return member.textDescription
case .initializer(let member):
return member.textDescription
case .subscript(let member):
return member.textDescription
case .associatedType(let member):
return member.textDescription
case .compilerControl(let stmt):
return stmt.textDescription
}
}
}
| apache-2.0 | 4c8df4a42de31b3875146a2a42119e50 | 38.148014 | 115 | 0.722796 | 5.496199 | false | false | false | false |
stuffrabbit/SwiftCoAP | Example_Projects/SwiftCoAPServerExample/SwiftCoAPServerExample/SeparateResourceModel.swift | 1 | 2731 | //
// SeparateResourceModel.swift
// SwiftCoAPServerExample
//
// Created by Wojtek Kordylewski on 23.06.15.
// Copyright (c) 2015 Wojtek Kordylewski. All rights reserved.
//
import UIKit
class SeparateResourceModel: SCResourceModel {
//Individual Properties
var myText: String {
didSet {
self.dataRepresentation = myText.data(using: String.Encoding.utf8) //update observable Data anytime myText is changed
}
}
weak var server: SCServer!
//
init(name: String, allowedRoutes: UInt, text: String, server: SCServer!) {
self.myText = text
self.server = server
super.init(name: name, allowedRoutes: allowedRoutes)
self.dataRepresentation = myText.data(using: String.Encoding.utf8)
}
func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC),
execute: closure
)
}
override func willHandleDataAsynchronouslyForRoute(_ route: SCAllowedRoute, queryDictionary: [String : String], options: [Int : [Data]], originalMessage: SCMessage) -> Bool {
switch route {
case .get:
delay(6.0) {
self.server.didCompleteAsynchronousRequestForOriginalMessage(originalMessage, resource: self, values: (SCCodeValue(classValue: 2, detailValue: 05)!, self.myText.data(using: String.Encoding.utf8), .plain, nil))
}
case .post:
delay(6.0) {
if let data = originalMessage.payload, let string = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) as String? {
self.myText = string
self.server.didCompleteAsynchronousRequestForOriginalMessage(originalMessage, resource: self, values: (SCCodeSample.created.codeValue(), "Data created successfully".data(using: String.Encoding.utf8), .plain, self.name))
}
else {
self.server.didCompleteAsynchronousRequestForOriginalMessage(originalMessage, resource: self, values: (SCCodeSample.forbidden.codeValue(), "Invalid Data sent".data(using: String.Encoding.utf8), .plain, nil))
}
}
case .put, .delete:
return false
}
return true
}
override func dataForDelete(queryDictionary: [String : String], options: [Int : [Data]]) -> (statusCode: SCCodeValue, payloadData: Data?, contentFormat: SCContentFormat?)? {
myText = "<>"
return (SCCodeSample.deleted.codeValue(), "Deleted".data(using: String.Encoding.utf8), .plain)
}
}
| mit | 09ab900be7dbae1c48c98814d2b2c5e1 | 43.048387 | 239 | 0.636397 | 4.455139 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/Swift Note/ObjC.io/Swift4/Advanced/Protocol.swift | 1 | 6669 | //
// Protocol.swift
// Advanced
//
// Created by 朱双泉 on 2018/6/19.
// Copyright © 2018 Castie!. All rights reserved.
//
import Foundation
import UIKit
struct Protocol {
static func run() {
var context: Drawing = SVG()
let rect1 = CGRect(x: 0, y: 0, width: 100, height: 100)
let rect2 = CGRect(x: 0, y: 0, width: 50, height: 50)
context.addRectangle(rect: rect1, fill: .yellow)
context.addEllipse(rect: rect2, fill: .blue)
print(context)
var sample = SVG()
sample.addCircle(center: .zero, radius: 20, fill: .red)
print(sample)
var otherSample: Drawing = SVG()
otherSample.addCircle(center: .zero, radius: 20, fill: .red)
print(otherSample)
// Protocol 'Equatable' can only be used as a generic constraint because it has Self or associated type requirements
// let x: Equatable = MonetaryAmount(currency: "EUR", amountInCents: 100)
let one = IntegerRef(1)
let otherOne = IntegerRef(1)
print(one == otherOne)
let two: NSObject = IntegerRef(2)
let otherTwo: NSObject = IntegerRef(2)
print(two == otherTwo)
print(f(5))
print(g(5))
// typealias Any = protocol<>
print(MemoryLayout<Any>.size)
typealias P = Prot & Prot2 & Prot3 & Prot4
print(MemoryLayout<P>.size)
print(MemoryLayout<ClassOnly>.size)
print(MemoryLayout<NSObjectProtocol>.size)
}
}
//extension Sequence where Element: Comparable {
// func sorted() -> [Self.Element]
//}
//extension MutableCollection where Self: RandomAccessCollection, Self.Element: Comparable {
// mutating func sort()
//}
protocol Drawing {
mutating func addEllipse(rect: CGRect, fill: UIColor)
mutating func addRectangle(rect: CGRect, fill: UIColor)
mutating func addCircle(center: CGPoint, radius: CGFloat, fill: UIColor)
}
extension CGContext: Drawing {
func addEllipse(rect: CGRect, fill: UIColor) {
setFillColor(fill.cgColor)
fillEllipse(in: rect)
}
func addRectangle(rect: CGRect, fill fillColor: UIColor) {
setFillColor(fillColor.cgColor)
fill(rect)
}
}
struct XMLNode {
let tag: String
var children = [XMLNode]()
init(tag: String) {
self.tag = tag
}
init(tag: String, attributes: [String : String]) {
self.tag = tag
}
}
struct SVG {
var rootNode = XMLNode(tag: "tag")
mutating func append(node: XMLNode) {
rootNode.children.append(node)
}
}
extension CGRect {
var svgAttributes: [String : String] {
return ["" : ""]
}
}
extension String {
init(hexColor: UIColor) {
self.init()
}
}
extension SVG: Drawing {
mutating func addEllipse(rect: CGRect, fill: UIColor) {
var attributes: [String : String] = rect.svgAttributes
attributes["fill"] = String(hexColor: fill)
append(node: XMLNode(tag: "ellipse", attributes: attributes))
}
mutating func addRectangle(rect: CGRect, fill: UIColor) {
var attributes: [String : String] = rect.svgAttributes
attributes["fill"] = String(hexColor: fill)
append(node: XMLNode(tag: "rect", attributes: attributes))
}
}
extension Drawing {
mutating func addCircle(center: CGPoint, radius: CGFloat, fill: UIColor) {
let diameter = radius * 2
let origin = CGPoint(x: center.x - radius, y: center.y - radius)
let size = CGSize(width: diameter, height: diameter)
let rect = CGRect(origin: origin, size: size)
addEllipse(rect: rect, fill: fill)
}
}
extension SVG {
mutating func addCircle(center: CGPoint, radius: CGFloat, fill: UIColor) {
var attributes: [String : String] = [
"cx" : "\(center.x)",
"cy" : "\(center.y)",
"r" : "\(radius)"
]
attributes["fill"] = String(hexColor: fill)
append(node: XMLNode(tag: "circle", attributes: attributes))
}
}
class IntIterator {
var nextImpl: () -> Int?
init<I: IteratorProtocol>(_ iterator: I) where I.Element == Int {
var iteratorCopy = iterator
self.nextImpl = {iteratorCopy.next()}
}
}
extension IntIterator: IteratorProtocol {
func next() -> Int? {
return nextImpl()
}
}
//class AnyIterator<A>: IteratorProtocol {
// var nextImpl: () -> A?
//
// init<I: IteratorProtocol>(_ iterator: I) where I.Element == A {
// var iteratorCopy = iterator
// self.nextImpl = {iteratorCopy.next()}
// }
//
// func next() -> A? {
// return nextImpl()
// }
//}
//
class IteratorBox<Element>: IteratorProtocol {
func next() -> Element? {
fatalError("This method is abstract.")
}
}
#if false
class IteratorBoxHelper<I: IteratorProtocol> {
var iterator: I
init(iterator: I) {
self.iterator = iterator
}
func next() -> I.Element? {
return iterator.next()
}
}
#endif
class IteratorBoxHelper<I: IteratorProtocol>: IteratorBox<I.Element> {
var iterator: I
init(_ iterator: I) {
self.iterator = iterator
}
override func next() -> I.Element? {
return iterator.next()
}
}
struct MonetaryAmount: Equatable {
var currency: String
var amountInCents: Int
static func ==(lhs: MonetaryAmount, rhs: MonetaryAmount) -> Bool {
return lhs.currency == rhs.currency && lhs.amountInCents == rhs.amountInCents
}
}
func allEqual<E: Equatable>(x: [E]) -> Bool {
guard let firstElement = x.first else {return true}
for element in x {
guard element == firstElement else {return false}
}
return true
}
extension Collection where Element: Equatable {
func allEqual() -> Bool {
guard let firstElement = first else {return true}
for element in self {
guard element == firstElement else {return false}
}
return true
}
}
class IntegerRef: NSObject {
let int: Int
init(_ int: Int) {
self.int = int
}
}
func ==(lhs: IntegerRef, rhs: IntegerRef) -> Bool {
return lhs.int == rhs.int
}
func f<C: CustomStringConvertible>(_ x: C) -> Int {
return MemoryLayout.size(ofValue: x)
}
func g(_ x: CustomStringConvertible) -> Int {
return MemoryLayout.size(ofValue: x)
}
protocol Prot {}
protocol Prot2 {}
protocol Prot3 {}
protocol Prot4 {}
protocol ClassOnly: AnyObject {}
func printProtocol(array: [CustomStringConvertible]) {
print(array)
}
func printGeneric<A: CustomStringConvertible>(array: [A]) {
print(array)
}
| mit | 8ef6e9d5d15d741dd14bfed491a69a05 | 24.524904 | 119 | 0.609276 | 3.923439 | false | false | false | false |
SwiftKit/Cuckoo | Generator/Source/cuckoo_generator/GenerateMocksCommand.swift | 1 | 10305 | //
// GenerateMocksCommand.swift
// CuckooGenerator
//
// Created by Tadeas Kriz on 12/01/16.
// Copyright © 2016 Brightify. All rights reserved.
//
import Commandant
import Result
import SourceKittenFramework
import FileKit
import CuckooGeneratorFramework
import Foundation
private func curry<P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12, R>
(_ f: @escaping (P1, P2, P3, P4, P5, P6, P7, P8, P9, P10, P11, P12) -> R)
-> (P1) -> (P2) -> (P3) -> (P4) -> (P5) -> (P6) -> (P7) -> (P8) -> (P9) -> (P10) -> (P11) -> (P12) -> R {
return { p1 in { p2 in { p3 in { p4 in { p5 in { p6 in { p7 in { p8 in { p9 in { p10 in { p11 in { p12 in
f(p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12)
} } } } } } } } } } } }
}
public struct GenerateMocksCommand: CommandProtocol {
public let verb = "generate"
public let function = "Generates mock files"
public func run(_ options: Options) -> Result<Void, CuckooGeneratorError> {
let getFullPathSortedArray: ([String]) -> [String] = { stringArray in
Array(Set(stringArray.map { Path($0).standardRawValue })).sorted()
}
let inputPathValues: [String]
if options.globEnabled {
inputPathValues = getFullPathSortedArray(options.files.flatMap { Glob(pattern: $0).paths })
} else {
inputPathValues = getFullPathSortedArray(options.files)
}
let inputFiles = inputPathValues.map { File(path: $0) }.compactMap { $0 }
let tokens = inputFiles.map { Tokenizer(sourceFile: $0, debugMode: options.debugMode).tokenize() }
let tokensWithInheritance = options.noInheritance ? tokens : mergeInheritance(tokens)
// filter classes/protocols based on the settings passed to the generator
var typeFilters = [] as [(Token) -> Bool]
if options.noClassMocking {
typeFilters.append(ignoreClasses)
}
if !options.regex.isEmpty {
typeFilters.append(keepMatching(pattern: options.regex))
}
if !options.exclude.isEmpty {
typeFilters.append(ignoreIfExists(in: options.exclude))
}
let parsedFiles = removeTypes(from: tokensWithInheritance, using: typeFilters)
// generating headers and mocks
let headers = parsedFiles.map { options.noHeader ? "" : FileHeaderHandler.getHeader(of: $0, includeTimestamp: !options.noTimestamp) }
let imports = parsedFiles.map { FileHeaderHandler.getImports(of: $0, testableFrameworks: options.testableFrameworks) }
let mocks = parsedFiles.map { try! Generator(file: $0).generate(debug: options.debugMode) }
let mergedFiles = zip(zip(headers, imports), mocks).map { $0.0 + $0.1 + $1 }
let outputPath = Path(options.output)
do {
if outputPath.isDirectory {
let inputPaths = inputFiles.compactMap { $0.path }.map { Path($0) }
for (inputPath, outputText) in zip(inputPaths, mergedFiles) {
let fileName = options.filePrefix + inputPath.fileName
let outputFile = TextFile(path: outputPath + fileName)
try outputText |> outputFile
}
} else {
let outputFile = TextFile(path: outputPath)
try mergedFiles.joined(separator: "\n") |> outputFile
}
} catch let error as FileKitError {
return .failure(.ioError(error))
} catch let error {
return .failure(.unknownError(error))
}
return stderrUsed ? .failure(.stderrUsed) : .success(())
}
private func mergeInheritance(_ filesRepresentation: [FileRepresentation]) -> [FileRepresentation] {
return filesRepresentation.compactMap { $0.mergeInheritance(with: filesRepresentation) }
}
private func removeTypes(from files: [FileRepresentation], using filters: [(Token) -> Bool]) -> [FileRepresentation] {
// Only keep those that pass all filters
let filter: (Token) -> Bool = { token in
!filters.contains { !$0(token) }
}
return files.compactMap { file in
let filteredDeclarations = file.declarations.filter(filter)
guard !filteredDeclarations.isEmpty else { return nil }
return FileRepresentation(sourceFile: file.sourceFile, declarations: filteredDeclarations)
}
}
// filter that keeps the protocols while removing all classes
private func ignoreClasses(token: Token) -> Bool {
return !(token is ClassDeclaration)
}
// filter that keeps the classes/protocols that match the passed regular expression
private func keepMatching(pattern: String) -> (Token) -> Bool {
do {
let regex = try NSRegularExpression(pattern: pattern, options: [])
return { token in
guard let containerToken = token as? ContainerToken else { return true }
return regex.firstMatch(in: containerToken.name, options: [], range: NSMakeRange(0, containerToken.name.count)) != nil
}
} catch {
fatalError("Invalid regular expression: " + (error as NSError).description)
}
}
// filter that keeps only the classes/protocols that are not supposed to be excluded
private func ignoreIfExists(in excluded: [String]) -> (Token) -> Bool {
let excludedSet = Set(excluded)
return { token in
guard let containerToken = token as? ContainerToken else { return true }
return !excludedSet.contains(containerToken.name)
}
}
public struct Options: OptionsProtocol {
let files: [String]
let output: String
let noHeader: Bool
let noTimestamp: Bool
let noInheritance: Bool
let testableFrameworks: [String]
let exclude: [String]
let filePrefix: String
let noClassMocking: Bool
let debugMode: Bool
let globEnabled: Bool
let regex: String
public init(output: String,
testableFrameworks: String,
exclude: String,
noHeader: Bool,
noTimestamp: Bool,
noInheritance: Bool,
filePrefix: String,
noClassMocking: Bool,
debugMode: Bool,
globEnabled: Bool,
regex: String,
files: [String]
) {
self.output = output
self.testableFrameworks = testableFrameworks.components(separatedBy: ",").filter { !$0.isEmpty }
self.exclude = exclude.components(separatedBy: ",").filter { !$0.isEmpty }.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }
self.noHeader = noHeader
self.noTimestamp = noTimestamp
self.noInheritance = noInheritance
self.filePrefix = filePrefix
self.noClassMocking = noClassMocking
self.debugMode = debugMode
self.globEnabled = globEnabled
self.regex = regex
self.files = files
}
// all options are declared here and then parsed by Commandant
public static func evaluate(_ m: CommandMode) -> Result<Options, CommandantError<CuckooGeneratorError>> {
let output: Result<String, CommandantError<ClientError>> = m <| Option(key: "output", defaultValue: "GeneratedMocks.swift", usage: "Where to put the generated mocks.\nIf a path to a directory is supplied, each input file will have a respective output file with mocks.\nIf a path to a Swift file is supplied, all mocks will be in a single file.\nDefault value is `GeneratedMocks.swift`.")
let testable: Result<String, CommandantError<ClientError>> = m <| Option(key: "testable", defaultValue: "", usage: "A comma separated list of frameworks that should be imported as @testable in the mock files.")
let exclude: Result<String, CommandantError<ClientError>> = m <| Option(key: "exclude", defaultValue: "", usage: "A comma separated list of classes and protocols that should be skipped during mock generation.")
let noHeader: Result<Bool, CommandantError<ClientError>> = m <| Option(key: "no-header", defaultValue: false, usage: "Do not generate file headers.")
let noTimestamp: Result<Bool, CommandantError<ClientError>> = m <| Option(key: "no-timestamp", defaultValue: false, usage: "Do not generate timestamp.")
let noInheritance: Result<Bool, CommandantError<ClientError>> = m <| Option(key: "no-inheritance", defaultValue: false, usage: "Do not generate stubs/mock for super class/protocol even if available.")
let filePrefix: Result<String, CommandantError<ClientError>> = m <| Option(key: "file-prefix", defaultValue: "", usage: "Names of generated files in directory will start with this prefix. Only works when output path is directory.")
let noClassMocking: Result<Bool, CommandantError<ClientError>> = m <| Option(key: "no-class-mocking", defaultValue: false, usage: "Do not generate mocks for classes.")
let debugMode: Result<Bool, CommandantError<ClientError>> = m <| Switch(flag: "d", key: "debug", usage: "Run generator in debug mode.")
let globEnabled: Result<Bool, CommandantError<ClientError>> = m <| Switch(flag: "g", key: "glob", usage: "Use glob for specifying input paths.")
let regex: Result<String, CommandantError<ClientError>> = m <| Option(key: "regex", defaultValue: "", usage: "A regular expression pattern that is used to match Classes and Protocols.\nAll that do not match are excluded.\nCan be used alongside `--exclude`.")
let input: Result<[String], CommandantError<ClientError>> = m <| Argument(usage: "Files to parse and generate mocks for.")
return curry(Options.init)
<*> output
<*> testable
<*> exclude
<*> noHeader
<*> noTimestamp
<*> noInheritance
<*> filePrefix
<*> noClassMocking
<*> debugMode
<*> globEnabled
<*> regex
<*> input
}
}
}
| mit | bbe245c3cc304a9ad480b1cea09288b5 | 47.375587 | 399 | 0.618207 | 4.604111 | false | false | false | false |
auth0/Lock.iOS-OSX | Lock/InfoBarView.swift | 1 | 3954 | // InfoBarView.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class InfoBarView: UIView {
weak var container: UIView?
weak var iconView: UIImageView?
weak var titleView: UILabel?
var title: String? {
get {
return self.titleView?.text
}
set {
self.titleView?.text = newValue
self.setNeedsUpdateConstraints()
}
}
var icon: UIImage? {
get {
return self.iconView?.image
}
set {
self.iconView?.image = newValue
}
}
convenience init() {
self.init(frame: CGRect.zero)
}
required override init(frame: CGRect) {
super.init(frame: frame)
self.layoutHeader()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.layoutHeader()
}
private func layoutHeader() {
let container = UIView()
let titleView = UILabel()
let iconView = UIImageView()
self.addSubview(container)
container.addSubview(titleView)
container.addSubview(iconView)
constraintEqual(anchor: container.leftAnchor, toAnchor: self.leftAnchor)
constraintEqual(anchor: container.bottomAnchor, toAnchor: self.bottomAnchor)
constraintEqual(anchor: container.topAnchor, toAnchor: self.topAnchor)
constraintEqual(anchor: container.rightAnchor, toAnchor: self.rightAnchor)
container.translatesAutoresizingMaskIntoConstraints = false
constraintEqual(anchor: titleView.centerXAnchor, toAnchor: container.centerXAnchor)
constraintEqual(anchor: titleView.centerYAnchor, toAnchor: container.centerYAnchor)
titleView.translatesAutoresizingMaskIntoConstraints = false
constraintEqual(anchor: iconView.rightAnchor, toAnchor: titleView.leftAnchor, constant: -7)
constraintEqual(anchor: iconView.centerYAnchor, toAnchor: titleView.centerYAnchor)
iconView.translatesAutoresizingMaskIntoConstraints = false
container.backgroundColor = UIColor(red: 0.97, green: 0.97, blue: 0.97, alpha: 1.0)
titleView.font = UIFont.systemFont(ofSize: 12.5)
titleView.textColor = UIColor.black.withAlphaComponent(0.56)
iconView.tintColor = UIColor( red: 0.5725, green: 0.5804, blue: 0.5843, alpha: 1.0 )
self.titleView = titleView
self.iconView = iconView
self.clipsToBounds = true
}
override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.viewNoIntrinsicMetric, height: 35)
}
static var ssoInfoBar: InfoBarView {
let ssoBar = InfoBarView()
ssoBar.title = "SINGLE SIGN-ON ENABLED".i18n(key: "com.auth0.lock.enterprise.sso.title", comment: "SSO Header")
ssoBar.icon = image(named: "ic_lock_full")
return ssoBar
}
}
| mit | 93d497ad42e419794b5d2184387e3dd1 | 35.275229 | 120 | 0.687658 | 4.701546 | false | false | false | false |
10533176/TafelTaferelen | Tafel Taferelen/DinnerInfoViewController.swift | 1 | 13916 | //
// DinnerInfoViewController.swift
// Tafel Taferelen
//
// Created by Femke van Son on 17-01-17.
// Copyright © 2017 Femke van Son. All rights reserved.
//
import UIKit
import Firebase
import EventKit
class DinnerInfoViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var groupNameLabel: UILabel!
@IBOutlet weak var dateNextDinnerField: UITextField!
@IBOutlet weak var locationNextDinnerField: UITextField!
@IBOutlet weak var chefNextDinnerField: UITextField!
@IBOutlet weak var newMessageText: UITextField!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var saveDateBtn: UIButton!
@IBOutlet weak var coverUpImage: UIImageView!
var chat = [String]()
var sender = [String]()
var chatID = [String]()
var dinnerDate = NSDate()
let userID = FIRAuth.auth()?.currentUser?.uid
var keyboardSizeRect: CGRect?
var ref: FIRDatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
datePicker.isHidden = true
coverUpImage.isHidden = true
ref = FIRDatabase.database().reference()
loadExistingGroupInfo()
readChat()
refreshTableView()
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: functions for reloading tableview when dragged down
func refreshTableView() {
if #available(iOS 10.0, *) {
let refreshControl = UIRefreshControl()
let title = NSLocalizedString("PullToRefresh", comment: "refresh chat")
refreshControl.attributedTitle = NSAttributedString(string: title)
refreshControl.addTarget(self,
action: #selector(refreshOptions(sender:)),
for: .valueChanged)
tableView.refreshControl = refreshControl
}
}
@objc private func refreshOptions(sender: UIRefreshControl) {
readChat()
sender.endRefreshing()
}
// MARK: functions for properly hide and show keyboard
func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
self.keyboardSizeRect = keyboardSize
}
}
@IBAction func didBeginChatting(_ sender: Any) {
if self.view.frame.origin.y == 0{
if let keyboardSize = keyboardSizeRect {
self.view.frame.origin.y -= keyboardSize.height
}
}
}
@IBAction func didEndChatting(_ sender: Any) {
if let keyboardSize = keyboardSizeRect {
if self.view.frame.origin.y != 0{
self.view.frame.origin.y += keyboardSize.height
}
}
}
// MARK: Saving new info when location or chef textfield changed
@IBAction func locationChanged(_ sender: Any) {
let newLocation = locationNextDinnerField.text
if newLocation != "" {
self.ref?.child("users").child(userID!).child("groupID").observeSingleEvent(of: .value, with: { (snapshot) in
let groupID = snapshot.value as? String
if groupID != nil {
self.ref?.child("groups").child(groupID!).child("location").setValue(newLocation)
}
})
}
}
@IBAction func chefsChanged(_ sender: Any) {
let newDate = chefNextDinnerField.text
if newDate != "" {
self.ref?.child("users").child(userID!).child("groupID").observeSingleEvent(of: .value, with: { (snapshot) in
let groupID = snapshot.value as? String
if groupID != nil {
self.ref?.child("groups").child(groupID!).child("chef").setValue(newDate)
}
})
}
}
// MARK: when datePicker is touched, selecting/ displaying and saving new date
@IBAction func EdditingDateDidBegin(_ sender: Any) {
dateNextDinnerField.isHidden = true
coverUpImage.isHidden = false
datePicker.isHidden = false
}
@IBAction func datpickerChanged(_ sender: Any) {
dinnerDate = datePicker.date as NSDate
let date = dinnerDate
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.short
formatter.timeStyle = .short
let dateDinnerStiring = formatter.string(from: date as Date)
dateNextDinnerField.text = dateDinnerStiring
}
@IBAction func dateChanged(_ sender: Any) {
datePicker.isHidden = true
coverUpImage.isHidden = true
dateNextDinnerField.isHidden = false
let newChef = dateNextDinnerField.text
if newChef != "" {
self.ref?.child("users").child(userID!).child("groupID").observeSingleEvent(of: .value, with: { (snapshot) in
let groupID = snapshot.value as? String
if groupID != nil {
self.ref?.child("groups").child(groupID!).child("date").setValue(newChef)
}
})
}
}
@IBAction func saveDateCalendar(_ sender: Any) {
signupErrorAlert(title: "Save the Date", message: "Date is saved to your calendar!")
let gregorian = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
var components = gregorian.components([.year, .month, .day, .hour], from: dinnerDate as Date)
components.hour = components.hour! + 4
let endDate = gregorian.date(from: components)!
addEventToCalendar(title: "Dinner with \(groupNameLabel.text!)", description: "©Ready, Set, Dinner", startDate: dinnerDate, endDate: endDate as NSDate)
}
// MARK: Loading information from group
func loadExistingGroupInfo() {
self.ref?.child("users").child(userID!).child("groupID").observeSingleEvent(of: .value, with: { (snapshot) in
let groupID = snapshot.value as? String
if groupID != nil {
self.getGroupName(groupID: groupID!)
self.getGroupChef(groupID: groupID!)
self.getGroupLocation(GroupID: groupID!)
self.getGroupNextDate(groupID: groupID!)
}
})
}
func getGroupName(groupID: String) {
self.ref?.child("groups").child(groupID).child("name").observeSingleEvent(of: .value, with: { (snapshot) in
let groupName = snapshot.value as? String
self.groupNameLabel.text = groupName
})
}
func getGroupNextDate(groupID: String) {
self.ref?.child("groups").child(groupID).child("date").observeSingleEvent(of: .value, with: { (snapshot) in
let date = snapshot.value as? String
if date != nil {
self.dateNextDinnerField.text = date
}
})
}
func getGroupChef(groupID: String) {
self.ref?.child("groups").child(groupID).child("chef").observeSingleEvent(of: .value, with: { (snapshot) in
let chef = snapshot.value as? String
if chef != nil {
self.chefNextDinnerField.text = chef
}
})
}
func getGroupLocation(GroupID: String) {
self.ref?.child("groups").child(GroupID).child("location").observeSingleEvent(of: .value, with: { (snapshot) in
let location = snapshot.value as? String
if location != nil {
self.locationNextDinnerField.text = location
}
})
}
@IBAction func messageSendPressed(_ sender: Any) {
if newMessageText.text! != "" {
newChatMes()
}
}
func readChat() {
self.chat = []
self.sender = []
self.ref?.child("users").child(userID!).child("groupID").observeSingleEvent(of: .value, with: { (snapshot) in
let groupID = snapshot.value as? String
if groupID != nil {
self.readingchatInOrder(groupID: groupID!)
} else {
self.signupErrorAlert(title: "Oops", message: "Join or create a dinner group to pick a date for the dinner!")
}
})
}
func readingchatInOrder(groupID: String) {
self.ref?.child("groups").child(groupID).child("chat").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot) in
let dictionary = snapshot.value as? NSDictionary
if dictionary != nil {
self.readingMessages(groupID: groupID, messagesDic: dictionary!)
self.readingSenderIDs(groupID: groupID, messagesDic: dictionary!)
}
})
}
func readingMessages(groupID: String, messagesDic: NSDictionary) {
var dateStemps = messagesDic.allKeys as! [String]
dateStemps = dateStemps.sorted()
for key in dateStemps {
self.ref?.child("groups").child(groupID).child("chat").child(key).child("message").observeSingleEvent(of: .value, with: { (snapshot) in
let singleChat = snapshot.value as? String
if singleChat != nil {
self.chat.insert(singleChat!, at: self.chat.count)
}
})
}
}
func readingSenderIDs(groupID: String, messagesDic: NSDictionary) {
var dateStemps = messagesDic.allKeys as! [String]
dateStemps = dateStemps.sorted()
for key in dateStemps {
self.ref?.child("groups").child(groupID).child("chat").child(key).child("userid").observeSingleEvent(of: .value, with: { (snapshot) in
let singleUser = snapshot.value as? String
self.readingSenderNames(singleUser: singleUser!)
})
}
}
func readingSenderNames(singleUser: String) {
self.ref?.child("users").child(singleUser).child("full name").observeSingleEvent(of: .value, with: { (snapshot) in
let username = snapshot.value as? String
if username != nil {
self.sender.insert(username!, at: self.sender.count)
let numberOfSections = self.tableView.numberOfSections
let numberOfRows = self.tableView.numberOfRows(inSection: numberOfSections-1)
let indexPath = IndexPath(row: numberOfRows-1 , section: numberOfSections-1)
if numberOfRows != 0 {
self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.bottom, animated: true)
}
self.tableView.reloadData()
}
})
}
// MARK: Sending new chat message
func newChatMes() {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let mesID = formatter.string(from: Date())
self.ref?.child("users").child(userID!).child("groupID").observeSingleEvent(of: .value, with: { (snapshot) in
let valueCheck = snapshot.value as? String
if valueCheck != nil {
let groupID = valueCheck!
self.ref?.child("groups").child(groupID).child("chat").child(mesID).child("userid").setValue(self.userID)
self.ref?.child("groups").child(groupID).child("chat").child(mesID).child("message").setValue(self.newMessageText.text)
self.newMessageText.text = ""
self.readChat()
}
})
}
func addEventToCalendar(title: String, description: String?, startDate: NSDate, endDate: NSDate, completion: ((_ success: Bool, _ error: NSError?) -> Void)? = nil) {
let eventStore = EKEventStore()
eventStore.requestAccess(to: .event, completion: { (granted, error) in
if (granted) && (error == nil) {
let event = EKEvent(eventStore: eventStore)
event.title = title
event.startDate = startDate as Date
event.endDate = endDate as Date
event.notes = description
event.calendar = eventStore.defaultCalendarForNewEvents
do {
try eventStore.save(event, span: .thisEvent)
} catch let e as NSError {
completion?(false, e)
return
}
completion?(true, nil)
} else {
completion?(false, error as NSError?)
}
})
}
// MARK: displaying chat in tableView
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return chat.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ChatTableViewCell
if self.sender.isEmpty == false && self.chat.isEmpty == false && self.sender.count == self.chat.count {
cell.message.text = self.chat[indexPath.row]
cell.chatName.text = self.sender[indexPath.row]
}
return cell
}
}
| mit | 3144c829b26b851a7fd3983e35fe20b0 | 36.403226 | 169 | 0.576542 | 5.055959 | false | false | false | false |
dmiedema/MapPointMapper-Swift | MapPointMapper/ViewController.swift | 1 | 8309 | //
// ViewController.swift
// MapPointMapper
//
// Created by Daniel on 11/18/14.
// Copyright (c) 2014 dmiedema. All rights reserved.
//
import Cocoa
import MapKit
class ViewController: NSViewController, MKMapViewDelegate, NSTextFieldDelegate {
// MARK: - Properties
// MARK: Buttons
@IBOutlet weak var loadFileButton: NSButton!
@IBOutlet weak var removeLastLineButton: NSButton!
@IBOutlet weak var removeAllLinesButton: NSButton!
@IBOutlet weak var addLineFromTextButton: NSButton!
@IBOutlet weak var switchLatLngButton: NSButton!
@IBOutlet weak var centerUSButton: NSButton!
@IBOutlet weak var centerAllLinesButton: NSButton!
@IBOutlet weak var colorWell: NSColorWell!
// MARK: Views
@IBOutlet weak var mapview: MKMapView!
@IBOutlet weak var textfield: NSTextField!
@IBOutlet weak var latlngLabel: NSTextField!
@IBOutlet weak var searchfield: NSTextField!
var parseLongitudeFirst = false
// MARK: - Methods
// MARK: View life cycle
override func viewDidLoad() {
super.viewDidLoad()
mapview.delegate = self
textfield.delegate = self
}
// MARK: Actions
@IBAction func loadFileButtonPressed(_ sender: NSButton!) {
let openPanel = NSOpenPanel()
openPanel.canChooseDirectories = false
openPanel.beginSheetModal(for: NSApplication.shared().keyWindow!, completionHandler: { (result) -> Void in
self.readFileAtURL(openPanel.url)
})
}
@IBAction func addLineFromTextPressed(_ sender: NSObject) {
if textfield.stringValue.isEmpty { return }
if renderInput(textfield.stringValue as NSString) {
textfield.stringValue = ""
} else {
// TODO: dont wipe out string field and stop event from propagating!
textfield.stringValue = ""
}
}
@IBAction func removeLastLinePressed(_ sender: NSButton) {
if let overlay: AnyObject = mapview.overlays.last {
mapview.remove(overlay as! MKOverlay)
}
}
@IBAction func removeAllLinesPressed(_ sender: NSButton) {
mapview.removeOverlays(mapview.overlays)
}
@IBAction func switchLatLngPressed(_ sender: NSButton) {
parseLongitudeFirst = !parseLongitudeFirst
if self.parseLongitudeFirst {
self.latlngLabel.stringValue = "Lng/Lat"
} else {
self.latlngLabel.stringValue = "Lat/Lng"
}
}
@IBAction func centerUSPressed(_ sender: NSButton) {
let centerUS = CLLocationCoordinate2D(
latitude: 37.09024,
longitude: -95.712891
)
let northeastUS = CLLocationCoordinate2D(
latitude: 49.38,
longitude: -66.94
)
let southwestUS = CLLocationCoordinate2D(
latitude: 25.82,
longitude: -124.39
)
let latDelta = northeastUS.latitude - southwestUS.latitude
let lngDelta = northeastUS.longitude - southwestUS.longitude
let span = MKCoordinateSpanMake(latDelta, lngDelta)
let usRegion = MKCoordinateRegion(center: centerUS, span: span)
mapview.setRegion(usRegion, animated: true)
}
@IBAction func centerAllLinesPressed(_ sender: NSButton) {
let polylines = mapview.overlays as [MKOverlay]
let boundingMapRect = boundingMapRectForPolylines(polylines)
mapview.setVisibleMapRect(boundingMapRect, edgePadding: EdgeInsets(top: 10, left: 10, bottom: 10, right: 10), animated: true)
}
// MARK: MKMapDelegate
func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
let renderer = MKPolylineRenderer(overlay: overlay)
renderer.alpha = 1.0
renderer.lineWidth = 4.0
renderer.strokeColor = colorWell.color
return renderer
}
@IBAction func searchForLocation(_ sender: NSObject) {
if searchfield.stringValue.isEmpty { return }
renderLocationSearch(searchfield.stringValue)
searchfield.stringValue = ""
}
fileprivate func renderLocationSearch(_ input: String) {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(input) { (placemarks, errors) in
guard let placemark = placemarks?.first,
let center = placemark.location?.coordinate else {
print(errors ?? "")
return
}
let region = MKCoordinateRegion(center: center,
span: MKCoordinateSpan(latitudeDelta: 0.8, longitudeDelta: 0.8))
self.mapview.setRegion(region, animated: true)
}
}
// MARK: - Private
/**
Create an `MKOverlay` for a given array of `CLLocationCoordinate2D` instances
- parameter mapPoints: array of `CLLocationCoordinate2D` instances to convert
- returns: an MKOverlay created from array of `CLLocationCoordinate2D` instances
*/
fileprivate func createPolylineForCoordinates(_ mapPoints: [CLLocationCoordinate2D]) -> MKOverlay {
let coordinates = UnsafeMutablePointer<CLLocationCoordinate2D>.allocate(capacity: mapPoints.count)
var count: Int = 0
for coordinate in mapPoints {
coordinates[count] = coordinate
count += 1
}
let polyline = MKPolyline(coordinates: coordinates, count: count)
free(coordinates)
return polyline
}
/**
Get the bounding `MKMapRect` that contains all given `MKOverlay` objects
- warning: If no `MKOverlay` objects are included the resulting `MKMapRect` will be nonsensical and will results in a warning.
- parameter polylines: array of `MKOverlay` objects.
- returns: an `MKMapRect` that contains all the given `MKOverlay` objects
*/
fileprivate func boundingMapRectForPolylines(_ polylines: [MKOverlay]) -> MKMapRect {
var minX = Double.infinity
var minY = Double.infinity
var maxX = Double(0)
var maxY = Double(0)
for line in polylines {
minX = (line.boundingMapRect.origin.x < minX) ? line.boundingMapRect.origin.x : minX
minY = (line.boundingMapRect.origin.y < minY) ? line.boundingMapRect.origin.y : minY
let width = line.boundingMapRect.origin.x + line.boundingMapRect.size.width
maxX = (width > maxX) ? width : maxX
let height = line.boundingMapRect.origin.y + line.boundingMapRect.size.height
maxY = (height > maxY) ? height : maxY
}
let mapWidth = maxX - minX
let mapHeight = maxY - minY
return MKMapRect(origin: MKMapPoint(x: minX, y: minY), size: MKMapSize(width: mapWidth, height: mapHeight))
}
/**
Read a given file at a url
- parameter passedURL: `NSURL` to attempt to read
*/
fileprivate func readFileAtURL(_ passedURL: URL?) {
guard let url = passedURL else { return }
do {
let contents = try NSString(contentsOf: url, encoding: String.Encoding.utf8.rawValue) as String
renderInput(contents as NSString)
} catch {
NSAlert(error: error as NSError).runModal()
}
} // end readFileAtURL
fileprivate func randomizeColorWell() {
colorWell.color = NSColor.randomColor()
}
fileprivate func renderInput(_ input: NSString) -> Bool {
if parseInput(input) {
randomizeColorWell()
return true
} else {
return false
}
}
/**
Parse the given input.
- parameter input: `NSString` to parse and draw on the map. If no string is given this is essentially a noop
- warning: If invalid WKT input string, will result in `NSAlert()` and false return
- returns: `Bool` on render success
*/
fileprivate func parseInput(_ input: NSString) -> Bool {
var coordinates = [[CLLocationCoordinate2D]()]
do {
coordinates = try Parser.parseString(input, longitudeFirst: parseLongitudeFirst).filter({!$0.isEmpty})
} catch ParseError.invalidWktString {
let error_msg = NSError(domain:String(), code:-1, userInfo:
[NSLocalizedDescriptionKey: "Invalid WKT input string, unable to parse"])
NSAlert(error: error_msg).runModal()
return false
} catch {
NSAlert(error: error as NSError).runModal()
return false
}
var polylines = [MKOverlay]()
for coordinateSet in coordinates {
let polyline = createPolylineForCoordinates(coordinateSet)
mapview.add(polyline, level: .aboveRoads)
polylines.append(polyline)
}
if !polylines.isEmpty {
let boundingMapRect = boundingMapRectForPolylines(polylines)
mapview.setVisibleMapRect(boundingMapRect, edgePadding: EdgeInsets(top: 10, left: 10, bottom: 10, right: 10), animated: true)
}
return true
}
}
| mit | abf5c7b87916b3ed398d0511aead9069 | 31.081081 | 131 | 0.694187 | 4.467204 | false | false | false | false |
AzureADSamples/NativeClient-iOS | QuickStart/ViewController.swift | 1 | 14813 | //------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------
import UIKit
import ADAL
/// 😃 A View Controller that will respond to the events of the Storyboard.
// Note that this is written to be one QuickStart file and meant to demonstrate basic concepts
// with easy to follow flow control and readable syntax. For a sample that demonstrates production
// quality Swift code check out the /Samples folder in the SDK repository.
class ViewController: UIViewController, UITextFieldDelegate, URLSessionDelegate {
// Update the below to your client ID you received in the portal. The below is for running the demo only
let kClientID = "227fe97b-c455-4039-b618-5af215c48d71"
// These settings you don't need to edit unless you wish to attempt deeper scenarios with the app.
let kGraphURI = "https://graph.microsoft.com"
let kAuthority = "https://login.microsoftonline.com/common"
let kRedirectUri = URL(string: "adal-sample-app://com.microsoft.identity.client.sample.quickstart")
let defaultSession = URLSession(configuration: .default)
var applicationContext : ADAuthenticationContext?
var dataTask: URLSessionDataTask?
@IBOutlet weak var loggingText: UITextView!
@IBOutlet weak var signoutButton: UIButton!
override func viewDidLoad() {
/**
Initialize a ADAuthenticationContext with a given authority
- authority: A URL indicating a directory that ADAL can use to obtain tokens. In Azure AD
it is of the form https://<instance/<tenant>, where <instance> is the
directory host (e.g. https://login.microsoftonline.com) and <tenant> is a
identifier within the directory itself (e.g. a domain associated to the
tenant, such as contoso.onmicrosoft.com, or the GUID representing the
TenantID property of the directory)
- error The error that occurred creating the application object, if any, if you're
not interested in the specific error pass in nil.
*/
self.applicationContext = ADAuthenticationContext(authority: kAuthority, error: nil)
self.applicationContext?.credentialsType = AD_CREDENTIALS_AUTO
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let currentAccount = currentAccount(),
currentAccount.accessToken != nil {
signoutButton.isEnabled = true
} else {
signoutButton.isEnabled = false
}
}
/**
This button will invoke the authorization flow.
*/
@IBAction func callGraphButton(_ sender: UIButton) {
self.callAPI()
}
func acquireToken(completion: @escaping (_ success: Bool) -> Void) {
guard let applicationContext = self.applicationContext else { return }
guard let kRedirectUri = kRedirectUri else { return }
/**
Acquire a token for an account
- withResource: The resource you wish to access. This will the Microsoft Graph API for this sample.
- clientId: The clientID of your application, you should get this from the app portal.
- redirectUri: The redirect URI that your application will listen for to get a response of the
Auth code after authentication. Since this a native application where authentication
happens inside the app itself, we can listen on a custom URI that the SDK knows to
look for from within the application process doing authentication.
- completionBlock: The completion block that will be called when the authentication
flow completes, or encounters an error.
*/
applicationContext.acquireToken(withResource: kGraphURI, clientId: kClientID, redirectUri: kRedirectUri){ (result) in
if (result.status != AD_SUCCEEDED) {
if let error = result.error {
if error.domain == ADAuthenticationErrorDomain,
error.code == ADErrorCode.ERROR_UNEXPECTED.rawValue {
self.updateLogging(text: "Unexpected internal error occured: \(error.description))");
} else {
self.updateLogging(text: error.description)
}
}
completion(false)
} else {
self.updateLogging(text: "Access token is \(String(describing: result.accessToken))")
self.updateSignoutButton(enabled: true)
completion(true)
}
}
}
func acquireTokenSilently(completion: @escaping (_ success: Bool) -> Void) {
guard let applicationContext = self.applicationContext else { return }
guard let kRedirectUri = kRedirectUri else { return }
/**
Acquire a token for an existing account silently
- withResource: The resource you wish to access. This will the Microsoft Graph API for this sample.
- clientId: The clientID of your application, you should get this from the app portal.
- redirectUri: The redirect URI that your application will listen for to get a response of the
Auth code after authentication. Since this a native application where authentication
happens inside the app itself, we can listen on a custom URI that the SDK knows to
look for from within the application process doing authentication.
- completionBlock: The completion block that will be called when the authentication
flow completes, or encounters an error.
*/
applicationContext.acquireTokenSilent(withResource: kGraphURI, clientId: kClientID, redirectUri: kRedirectUri) { (result) in
if (result.status != AD_SUCCEEDED) {
// USER_INPUT_NEEDED means we need to ask the user to sign-in. This usually happens
// when the user's Refresh Token is expired or if the user has changed their password
// among other possible reasons.
if let error = result.error {
if error.domain == ADAuthenticationErrorDomain,
error.code == ADErrorCode.ERROR_SERVER_USER_INPUT_NEEDED.rawValue {
DispatchQueue.main.async {
self.acquireToken() { (success) -> Void in
if success {
completion(true)
} else {
self.updateLogging(text: "After determining we needed user input, could not acquire token: \(error.description)")
completion(false)
}
}
}
} else {
self.updateLogging(text: "Could not acquire token silently: \(error.description)")
completion(false)
}
}
} else {
self.updateLogging(text: "Refreshed Access token is \(String(describing: result.accessToken))")
self.updateSignoutButton(enabled: true)
completion(true)
}
}
}
func currentAccount() -> ADTokenCacheItem? {
// We retrieve our current account by getting the last account from cache. This isn't best practice. You should rely
// on AcquireTokenSilent and store the UPN separately in your application. For simplicity of the sample, we just use the cache.
// In multi-account applications, account should be retrieved by home account identifier or username instead
guard let cachedTokens = ADKeychainTokenCache.defaultKeychain().allItems(nil) else {
self.updateLogging(text: "Didn't find a default cache. This is very unusual.")
return nil
}
if !(cachedTokens.isEmpty) {
// In the token cache, refresh tokens and access tokens are separate cache entries.
// Therefore, you need to keep looking until you find an entry with an access token.
for (_, cachedToken) in cachedTokens.enumerated() {
if cachedToken.accessToken != nil {
return cachedToken
}
}
}
return nil
}
func updateLogging(text : String) {
DispatchQueue.main.async {
self.loggingText.text += text + "\n\n"
let bottom = NSMakeRange(self.loggingText.text.count - 1, 1)
self.loggingText.scrollRangeToVisible(bottom)
}
}
func updateSignoutButton(enabled : Bool) {
DispatchQueue.main.async {
self.signoutButton.isEnabled = enabled
}
}
/**
This button will invoke the call to the Microsoft Graph API. It uses the
built in URLSession to create a connection.
*/
func callAPI(retry: Bool = true) {
// Specify the Graph API endpoint
let url = URL(string: kGraphURI + "/v1.0/me/")
var request = URLRequest(url: url!)
guard let accessToken = currentAccount()?.accessToken else {
// We haven't signed in yet, so let's do so now, then retry.
// To ensure we don't prompt the user twice,
// we set retry to false. If acquireToken() has some
// other issue we don't want an infinite loop.
if retry {
self.acquireToken() { (success) -> Void in
if success {
self.callAPI(retry: false)
}
}
} else {
self.updateLogging(text: "Couldn't get access token and we were told to not retry.")
}
return
}
// Set the Authorization header for the request. We use Bearer tokens, so we specify Bearer + the token we got from the result
request.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")
dataTask = defaultSession.dataTask(with: request) { data, response, error in
if let error = error {
self.updateLogging(text: "Couldn't get graph result: \(error)")
}
guard let httpResponse = response as? HTTPURLResponse else {
self.updateLogging(text: "Couldn't get graph result")
return
}
// If we get HTTP 200: Success, go ahead and parse the JSON
if httpResponse.statusCode == 200 {
guard let result = try? JSONSerialization.jsonObject(with: data!, options: []) else {
self.updateLogging(text: "Couldn't deserialize result JSON")
return
}
self.updateLogging(text: "Result from Graph: \(result))")
}
// Sometimes the server API will throw HTTP 401: Unauthorized if it is expired or needs some
// other interaction from the authentication service. You should always refresh the
// token on first failure just to make sure that you cannot recover.
if httpResponse.statusCode == 401 {
if retry {
// We will try to refresh the token silently first. This way if there are any
// issues that can be resolved by getting a new access token from the refresh
// token, we avoid prompting the user. If user interaction is required, the
// acquireTokenSilently() will call acquireToken()
self.acquireTokenSilently() { (success) -> Void in
if success {
self.callAPI(retry: false)
}
}
} else {
self.updateLogging(text: "Couldn't access API with current access token, and we were told to not retry.")
}
}
}
dataTask?.resume()
}
/**
This button will invoke the signout APIs to clear the token cache.
*/
@IBAction func signoutButton(_ sender: UIButton) {
/**
Removes all tokens from the cache for this application for the current account in use
- account: The account user ID to remove from the cache
*/
guard let account = currentAccount()?.userInformation?.userId else {
self.updateLogging(text: "Didn't find a logged in account in the cache.")
return
}
ADKeychainTokenCache.defaultKeychain().removeAll(forUserId: account, clientId: kClientID, error: nil)
self.signoutButton.isEnabled = false
self.updateLogging(text: "Removed account for: \(account)" )
}
}
| apache-2.0 | 32a2f5d649ca8a51a0ea7c32d40e70ce | 42.687316 | 149 | 0.581567 | 5.546816 | false | false | false | false |
AndreaMiotto/BoutTime | BoutTime/ViewController.swift | 1 | 12464 | //
// ViewController.swift
// BoutTime
//
// Created by Andrea Miotto on 12/07/16.
// Copyright © 2016 Andrea Miotto. All rights reserved.
//
import UIKit
import AudioToolbox
class ViewController: UIViewController {
//MARK: IBOUTLETS
@IBOutlet weak var nextRoundButton: UIButton!
@IBOutlet weak var taskLabel: UILabel!
@IBOutlet weak var counterLabel: UILabel!
@IBOutlet weak var firstEvent: UIButton!
@IBOutlet weak var secondEvent: UIButton!
@IBOutlet weak var thirdEvent: UIButton!
@IBOutlet weak var fourthEvent: UIButton!
//MARK: VARIABLES
var game: PlayableGame
var collection: [EventType]
var eventsCollection: EventsCollection
var eventTexts: [UIButton] = []
var timer: Timer = Timer.init()
let timePerRound = 60
let nRounds: Int = 6
var correctSound: SystemSoundID = 0
var incorrectSound: SystemSoundID = 1
//MARK: CONTROLLER INIT
required init?(coder aDecoder: NSCoder) {
do {
print("ciao")
debugPrint("prova")
let dictionary = try PlistConverter.dictionaryFromFile("EventsList", ofType: "plist")
collection = try CollectionUnarchiver.eventsCollectionFromDictionary(dictionary)
eventsCollection = EventsCollection(collection: collection)
game = try PlayableGame(eventsCollection: eventsCollection, nRoundsPerGame: nRounds, timer: timePerRound)
} catch let error {
fatalError("Impossible initialization: \(error)")
}
super.init(coder: aDecoder)
}
//MARK: CONTROLLERS OVERRIDE
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
loadCorrectSound()
loadIncorrectSound()
createUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//method to send answer when phone is shaked
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if motion == .motionShake {
roundOver()
}
}
//MARK: ACTIONS
///action for first event down button
@IBAction func firstEventDown(_ sender: UIButton) {
triggerSelectedImage(sender, imageName: "DownFullSelected")
switchEvent(indexEventToSwitch: 0, indexEventTarget: 1)
}
/// action for second event up button
@IBAction func secondEventUp(_ sender: UIButton) {
triggerSelectedImage(sender, imageName: "UpHalfSelected")
switchEvent(indexEventToSwitch: 1, indexEventTarget: 0)
}
///action for second event down button
@IBAction func secondEventDown(_ sender: UIButton) {
triggerSelectedImage(sender, imageName: "DownHalfSelected")
switchEvent(indexEventToSwitch: 1, indexEventTarget: 2)
}
///action for third event up button
@IBAction func thirdEventUp(_ sender: UIButton) {
triggerSelectedImage(sender, imageName: "UpHalfSelected")
switchEvent(indexEventToSwitch: 2, indexEventTarget: 1)
}
///action for third event down button
@IBAction func thirdEventDown(_ sender: UIButton) {
triggerSelectedImage(sender, imageName: "DownHalfSelected")
switchEvent(indexEventToSwitch: 2, indexEventTarget: 3)
}
///action for fourth event up button
@IBAction func fourthEventUp(_ sender: UIButton) {
triggerSelectedImage(sender, imageName: "UpFullSelected")
switchEvent(indexEventToSwitch: 3, indexEventTarget: 2)
}
///action for nextRound Button
@IBAction func requestingNextRound() {
//if wasn't the last round
if !game.isGameEnd() {
do {
try game.playNextRound(eventsCollection: eventsCollection)
} catch EventError.impossibleEqualization {
showAlert(title: "Impossible Equalization between events")
} catch let error {
showAlert(title: "\(error)")
}
createUI()
} else {
//making a costant for the points in string
let pointsInString: String = "\(game.points)/\(game.nRounds)"
//creating and presenting the Ending View
let vc = self.storyboard?.instantiateViewController(withIdentifier: "EndingController") as! EndingController
vc.pointsInString = pointsInString //passing the points from one view to anohter
self.present(vc, animated: true, completion: nil)
}
}
///action for firstEvent Button
@IBAction func firstEventInfo(_ sender: UIButton) {
showInfo(eventPressed: sender)
print("event pressed")
}
///action for secondEvent Button
@IBAction func secondEventInfo(_ sender: UIButton) {
showInfo(eventPressed: sender)
}
///action for thirdEvent Button
@IBAction func thirdEventInfo(_ sender: UIButton) {
showInfo(eventPressed: sender)
}
///action for forthEvent Button
@IBAction func fourthEventInfo(_ sender: UIButton) {
showInfo(eventPressed: sender)
}
//MARK: METHODS
///method to create the UIElements
func createUI() {
game.roundEnded = false
//resetting the counter
game.timer = timePerRound
//setting the events label
eventTexts.append(contentsOf: [firstEvent, secondEvent, thirdEvent, fourthEvent])
displayEvents()
//display the proper elements
displayProperUIForRound()
//creating and starting the timer
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
}
/// method to display the proper UI elements in the GameView according of the round status
func displayProperUIForRound(){
if !game.roundEnded {
nextRoundButton.isHidden = true
counterLabel.text = "\(game.timer)"
taskLabel.text = "Shake to complete"
counterLabel.isHidden = false
} else {
var isCorrect: Bool = false
do {
isCorrect = try game.checkAnswer() //checking the answer
} catch EventError.impossibleEqualization {
showAlert(title: "Impossible Equalization between events")
} catch let error {
showAlert(title: "\(error)")
}
showNextRoundButton(isCorrect) //showing the proper button
taskLabel.text = "Tap event to learn more" //updating the label
counterLabel.isHidden = true //hiding the timer
}
}
///method called by the counter
func updateCounter() {
//if the timer hasn't reach the zero
if game.timer > 0 {
game.timer -= 1 //decrease the timer
counterLabel.text = "\(game.timer)" //printing the timer in the label
} else {
roundOver() //if the timer is zero, the round is over
}
}
///method to switch events
func switchEvent(indexEventToSwitch indexStart: Int, indexEventTarget indexArrival: Int) {
if !game.roundEnded {
/* Switching events */
var events: [EventType] = game.round.selectedEvents
let helper: EventType = events[indexArrival]
events[indexArrival] = events[indexStart]
events[indexStart] = helper
game.round.selectedEvents = events
/* Redrawing labels */
displayEvents()
}
}
///calling this method when the round is over
func roundOver() {
timer.invalidate() //it stops the timer
game.roundEnded = true //mark the round as ended
game.roundsPlayed += 1 //increase the n rounds played
displayProperUIForRound() //re-draw the UI
playProperSound() //play the proper sound
}
///method that is called when an event is pressed when the round is over
func showInfo(eventPressed: UIButton) {
//if the round is ended, we can go on
if game.roundEnded {
var link: String = ""
//we can force the unwrapping because when the event is pressed it has for 100% an assigned title
let eventName: String = eventPressed.currentTitle!
//retrieving the link of the event
for event in game.round.selectedEvents {
if event.event == eventName {
link = event.link
}
}
guard link != "" else {
showAlert(title: "Invalid Link")
return
}
//creating and presenting the Web View
let vc = self.storyboard?.instantiateViewController(withIdentifier: "WebController") as! WebController
vc.urlString = link //passing the link from one view to anohter
self.present(vc, animated: true, completion: nil)
}
}
func showAlert(title: String, message: String? = nil, style: UIAlertControllerStyle = .alert) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: style)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
//MARK: HELPER METHODS
///method to display events in the labels
func displayEvents() {
let events: [EventType] = game.round.selectedEvents
for index in 0...events.count - 1 {
eventTexts[index].setTitle(events[index].event, for: UIControlState())
}
}
///method to trigger the selected image for arrow buttons
func triggerSelectedImage(_ button: UIButton, imageName name: String) {
if let currentImage: UIImage = button.currentImage, let selectedImage: UIImage = UIImage(named: name) {
button.setImage(selectedImage, for: UIControlState())
//this is a delay to reset the original image
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
button.setImage(currentImage, for: UIControlState())
}
}
}
///method to display the proper next round button
func showNextRoundButton(_ isCorrect: Bool) {
//if the answer is correct
if isCorrect {
let success = #imageLiteral(resourceName: "NextRoundSuccess")
nextRoundButton.setImage(success, for: UIControlState())
//if the answer isn't correct
} else {
let fail = #imageLiteral(resourceName: "NextRoundFail")
nextRoundButton.setImage(fail, for: UIControlState())
}
nextRoundButton.isHidden = false
}
//MARK: AUDIO METHODS
func loadCorrectSound() {
let pathToSoundFile = Bundle.main.path(forResource: "CorrectDing", ofType: "wav")
let soundURL = NSURL(fileURLWithPath: pathToSoundFile!)
AudioServicesCreateSystemSoundID(soundURL, &correctSound)
}
func loadIncorrectSound() {
let pathToSoundFile = Bundle.main.path(forResource: "IncorrectBuzz", ofType: "wav")
let soundURL = NSURL(fileURLWithPath: pathToSoundFile!)
AudioServicesCreateSystemSoundID(soundURL, &incorrectSound)
}
func playIncorrectSound() {
AudioServicesPlaySystemSound(incorrectSound)
}
func playCorrectSound() {
AudioServicesPlaySystemSound(correctSound)
}
func playProperSound() {
do {
if try game.checkAnswer() {
playCorrectSound()
} else {
playIncorrectSound()
}
} catch EventError.impossibleEqualization {
showAlert(title: "Impossible Equalization between events")
} catch let error {
showAlert(title: "\(error)")
}
}
}
| apache-2.0 | 088be2e696285880619dada84b1505b5 | 32.592992 | 135 | 0.606275 | 5.227768 | false | false | false | false |
FoodMob/FoodMob-iOS | FoodMob/Model/User.swift | 1 | 7604 | //
// User.swift
// FoodMob
//
// Created by Jonathan Jemson on 2/5/16.
// Copyright © 2016 Jonathan Jemson. All rights reserved.
//
import Foundation
import Locksmith
/**
Represents a FoodMob user.
*/
public class User: CreateableSecureStorable, ReadableSecureStorable, DeleteableSecureStorable, GenericPasswordSecureStorable, Hashable {
// MARK: - Properties
/**
The user's first name (or given name)
*/
private(set) public var firstName: String
/**
The user's last name (or family name)
*/
private(set) public var lastName: String
/**
The user's email address (used as their unique identifier).
*/
private(set) public var emailAddress: String
/**
The user's authentication token for the current login.
*/
private(set) internal var authToken: String
/**
Stores the user's likes, dislikes, and restrictions.
*/
public var categories = [FoodCategory: Preference]()
/**
Get the user's full name, localized by region.
*/
public var fullName: String {
let nameFormatter = NSPersonNameComponentsFormatter()
let nameComponents = NSPersonNameComponents()
nameComponents.givenName = firstName
nameComponents.familyName = lastName
return nameFormatter.stringFromPersonNameComponents(nameComponents)
}
/// Conformance to Hashable protocol
public var hashValue: Int {
return emailAddress.hashValue
}
// MARK: - Initializers
/**
Initializes a new user, typically when they register.
- Parameters:
- firstName: User's first name/given name.
- lastName: User's last name/family name.
- emailAddress: User's email address
- authToken: Authorization token for use with the API
- saveToKeychain: Whether or not the credentials should be stored in the keychain.
*/
public init(firstName: String, lastName: String, emailAddress: String, authToken: String, saveToKeychain: Bool = true) {
self.firstName = firstName
self.lastName = lastName
self.emailAddress = emailAddress
self.authToken = authToken
if saveToKeychain {
NSUserDefaults.standardUserDefaults().setObject(emailAddress, forKey: UserField.emailAddress)
do {
try Locksmith.saveData([UserField.emailAddress: emailAddress], forUserAccount: "FDMB-FoodMob")
} catch {
print(error)
}
do {
try self.deleteFromSecureStore()
} catch {
print(error)
}
do {
try self.createInSecureStore()
} catch {
print(error)
}
}
}
/**
Convenience initializer, used for initializing friends.
This object is NOT eligible for communicating with the server as an authenticated user.
- parameter firstName: User's given name/first name.
- parameter lastName: User's last name/family name
- parameter emailAddress: User's email address
*/
public convenience init(firstName: String, lastName: String, emailAddress: String) {
self.init(firstName: firstName, lastName: lastName, emailAddress: emailAddress, authToken: "FRIEND\(emailAddress.md5())", saveToKeychain: false)
}
/**
Initialize a user from their email address.
This intializer requires that the user has attempted to log in at least once before,
and that the `eraseUser` method has not been called.
*/
public init?(emailAddress: String?) {
// Blah blah compiler complained.
self.firstName = ""
self.lastName = ""
self.emailAddress = emailAddress ?? Locksmith.loadDataForUserAccount("FDMB-FoodMob")?[UserField.emailAddress] as? String ?? ""
self.authToken = ""
if let storeData = self.readFromSecureStore(), data = storeData.data,
firstName = data[UserField.firstName] as? String, lastName = data[UserField.lastName] as? String,
authToken = data[UserField.authToken] as? String
{
self.firstName = firstName
self.lastName = lastName
self.authToken = authToken
return
}
return nil
}
// MARK: - Instance Methods
/**
Removes the user from the device's keychain.
*/
public func eraseUser() {
do {
try self.deleteFromSecureStore()
try Locksmith.deleteDataForUserAccount("FDMB-FoodMob")
} catch {
print(error)
}
}
/**
Returns a user's preference for a food category.
- parameter category: The category of interest
- returns: Their preference level.
*/
public func preferenceForCategory(category: FoodCategory) -> Preference {
return categories[category] ?? Preference.None
}
public func categoriesForPreference(preference: Preference) -> [FoodCategory] {
return categories.filter({ (tuple) -> Bool in
return tuple.1 == preference
}).map { $0.0 }
}
/**
Returns a human-readable string of a user's food categories for a given preference.
- parameter preference: Preference to stringify.
- returns: Human-readable string of food categories.
*/
@warn_unused_result
func stringForPreference(preference: Preference) -> String {
var str = ""
for (cat, pref) in categories {
if pref == preference {
str += cat.displayName + ", "
}
}
if (str.length < 2) {
return str
}
return str.substringToIndex(str.endIndex.advancedBy(-2))
}
/**
Sets preference for a category.
- parameter preference: A preference to set on a category
- parameter category: The category that is being manipulated
*/
public func setPreference(preference: Preference, forCategory category: FoodCategory) {
if preference == .None {
categories.removeValueForKey(category)
} else {
categories[category] = preference
}
}
// MARK: - Locksmith: Keychain services.
public let service = "FoodMob"
public var account: String {
return self.emailAddress
}
public var data: [String : AnyObject] {
return [
UserField.firstName: firstName,
UserField.lastName: lastName,
UserField.authToken: self.authToken
]
}
}
/**
Conformance to Equatable for the User class
- parameter user1: User on LHS of expression
- parameter user2: User on RHS of expression
- returns: Whether the email addresses are the same for the user.
*/
public func ==(user1: User, user2: User) -> Bool {
return user1.emailAddress == user2.emailAddress
}
// MARK: - JSON Serialization
/**
User Fields used in JSON responses
*/
internal struct UserField {
static let emailAddress = "email"
static let friendEmail = "friend_email"
static let password = "password"
static let firstName = "first_name"
static let lastName = "last_name"
static let profile = "profile"
static let foodProfile = "food_profile"
static let authToken = "auth_token"
static let friends = "friends"
struct FoodProfile {
static let restrictions = "allergies"
static let likes = "likes"
static let dislikes = "dislikes"
}
} | mit | 1e4ac5885e781d0becf1b4262161e7c3 | 29.416 | 152 | 0.619098 | 4.93061 | false | false | false | false |
JuweTakeheshi/ajuda | Ajuda/VC/JUWMapViewController.swift | 1 | 11393 | //
// JUWMapViewController.swift
// Ajuda
//
// Created by Juwe Takeheshi on 9/21/17.
// Copyright © 2017 Juwe Takeheshi. All rights reserved.
//
import UIKit
import RealmSwift
import MapKit
class JUWMapViewController: UIViewController {
// MARK: Properties
fileprivate var currentCenter:JUWMapCollectionCenter!
fileprivate var locationManager: CLLocationManager!
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var needLabel: UILabel!
@IBOutlet weak var contactLabel: UILabel!
@IBOutlet weak var callButton: UIButton!
@IBOutlet weak var filterView: UIView!
@IBOutlet weak var filterLabel: UILabel!
var onSignOut: OnSignOut?
override func viewDidLoad() {
super.viewDidLoad()
setupLocationManager()
customizeUserInterface()
showCollectionCenters()
}
func customizeUserInterface() {
title = "Centros acopio"
showRightBarButton()
self.navigationItem.setHidesBackButton(true, animated:false)
let infoButton = UIButton()
infoButton.setImage(UIImage(named: "infoButtonWhite"), for: .normal)
infoButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
infoButton.addTarget(self, action: #selector(JUWMapViewController.presentInfoViewController), for: .touchUpInside)
let dismissBarButton = UIBarButtonItem(customView: infoButton)
navigationItem.leftBarButtonItem = dismissBarButton
navigationController?.navigationBar.tintColor = .white
}
func showCollectionCenters() {
JUWCollectionCenterManager().updateCollectionCenters { result in
switch result {
case let .success(collectionCenters):
self.createMapAnnotations(with: collectionCenters!)
case .failure(_):
self.showCollectionCentersError()
}
}
}
func showCollectionCentersError() {
self.displayHandlAlert(
title: "Error",
message: "Tuvimos un problema al obtener los centros de acopio. Mostraremos los centros de la última actualización; recuerda que podría ser información desactualizada.\nAnte cualquier duda te recomendamos ponerte en contacto con ellos") { _ in
self.createMapAnnotations(with: JUWCollectionCenterManager().collectionCentersFromCache())
}
}
func createMapAnnotations(with collectionCenters: [JUWCollectionCenter]) {
mapView.removeAnnotations(mapView.annotations)
for center in collectionCenters {
let annotation = JUWMapCollectionCenter(title: center.name,
name: center.name,
address: center.address,
phoneNumber: center.phoneNumber,
identifier: center.centerIdentifier,
twitter: center.twitterHandle,
coordinate: CLLocationCoordinate2D(latitude: center.latitude, longitude: center.longitude))
mapView.addAnnotation(annotation)
}
self.startLocationUpdates()
}
func showRightBarButton() {
navigationItem.rightBarButtonItem = UIBarButtonItem(
title: "Ayudar",
style: .plain,
target: self,
action: #selector(JUWMapViewController.sendHelp(_:))
)
}
@IBAction func call(_ sender: UIButton) {
let phoneNumber = sender.titleLabel?.text
guard let formattedNumber = phoneNumber?.components(separatedBy: NSCharacterSet.decimalDigits.inverted).joined(separator: ""),
let url = URL(string: "tel://\(formattedNumber)") else {
return
}
if (UIApplication.shared.canOpenURL(url)) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
}
}
@IBAction func showDetail(_ sender: Any) {
let sb = UIStoryboard(name: "Products", bundle: nil)
let detailCenterNC = sb.instantiateViewController(withIdentifier: "JUWCollectionNavigationViewController") as! UINavigationController
let collectionCenterViewController = detailCenterNC.viewControllers[0] as! JUWCollectionCenterViewController
collectionCenterViewController.center = currentCenter
present(detailCenterNC, animated: true, completion: nil)
}
@IBAction func sendHelp(_ sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let searchViewController = storyboard.instantiateViewController(withIdentifier: "JUWShelterViewController") as! JUWShelterViewController
searchViewController.onResultsFound = { results, product in
self.navigationItem.rightBarButtonItem = nil
self.filterLabel.text = product
self.filterView.isHidden = false
self.createMapAnnotations(with: results)
}
let navigationController = UINavigationController(rootViewController: searchViewController)
navigationController.view.backgroundColor = UIColor(white: 0, alpha: 0.8)
navigationController.modalPresentationStyle = .overCurrentContext
present(navigationController, animated: true, completion: nil)
}
@IBAction func removeFilter(_ sender: UIButton) {
createMapAnnotations(with: JUWCollectionCenterManager().collectionCentersFromCache())
showRightBarButton()
filterView.isHidden = true
}
@objc func presentInfoViewController() {
let infoViewController = storyboard?.instantiateViewController(withIdentifier: "JUWInfoViewController") as! JUWInfoViewController
infoViewController.onSignOut = {
if self.onSignOut != nil{
self.onSignOut!()
}
self.navigationController?.popViewController(animated: true)
}
let navigationController = UINavigationController(rootViewController: infoViewController)
present(navigationController, animated: true, completion: nil)
}
}
extension JUWMapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
var annotationView = self.mapView.dequeueReusableAnnotationView(withIdentifier: "reuseIdentifier")
if annotationView == nil{
annotationView = AnnotationView(annotation: annotation, reuseIdentifier: "reuseIdentifier")
annotationView?.canShowCallout = false
}else{
annotationView?.annotation = annotation
}
annotationView?.image = UIImage(named:"circle")
return annotationView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
if view.annotation is MKUserLocation {
return
}
let annotation = view.annotation as! JUWMapCollectionCenter
let views = Bundle.main.loadNibNamed("detailCalloutAccessoryView", owner: nil, options: nil)
let detailCalloutAccessoryView = views?[0] as! detailCalloutAccessoryView
detailCalloutAccessoryView.labelTitle.text = annotation.name
detailCalloutAccessoryView.labelSubTitle.text = annotation.address
//Add Button For calling in XIB
let button = UIButton()
button.frame = CGRect(x: 10, y: 170, width: 260, height: 40)
button.backgroundColor = UIColor(red:1.00, green:0.47, blue:0.00, alpha:1.0)
detailCalloutAccessoryView.addSubview(button)
//Add button for detail center in XIB
let btnDetailCenter = UIButton()
btnDetailCenter.setTitle("Cargando...", for: .normal)
btnDetailCenter.frame = CGRect(x: 10, y: 120, width: 260, height: 40)
btnDetailCenter.backgroundColor = UIColor(red:1.00, green:0.47, blue:0.00, alpha:1.0)
detailCalloutAccessoryView.addSubview(btnDetailCenter)
annotation.retrieveContacInfotWith(completion: { (resultPhone) in
if resultPhone.isEmpty {
button.setTitle("Sin teléfono registrado", for: .normal)
}
else {
button.setTitle(resultPhone, for: .normal)
button.addTarget(self, action: #selector(JUWMapViewController.call(_:)), for: .touchUpInside)
}
}, failure: { (error) in
button.setTitle("Sin teléfono", for: .normal)
button.alpha = 0.5
})
annotation.retrieveProductsWith(completion: { (products) in
self.currentCenter = annotation
btnDetailCenter.setTitle("Ver más", for: .normal)
btnDetailCenter.addTarget(self, action: #selector(JUWMapViewController.showDetail(_:)), for: .touchUpInside)
detailCalloutAccessoryView.center = CGPoint(x: view.bounds.size.width / 2, y: -detailCalloutAccessoryView.bounds.size.height*0.52)
view.addSubview(detailCalloutAccessoryView)
mapView.setCenter((view.annotation?.coordinate)!, animated: true)
}) { (error) in
self.displayOKAlert(title: "Error", message: "Tuvimos un problema al obtener los productos que se necesitan en este centro de acopio. Mostraremos los productos de la ultima actualización recuerda que puede ser información desactualizada.\nAnte cualquier duda te recomendamos ponerte en contacto con ellos.")
}
}
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
if view.isKind(of: AnnotationView.self) {
for subview in view.subviews {
subview.removeFromSuperview()
}
}
}
}
extension JUWMapViewController: CLLocationManagerDelegate {
func setupLocationManager() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if CLLocationManager.locationServicesEnabled() {
locationManager.requestWhenInUseAuthorization()
}
}
func startLocationUpdates() {
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let currentLocation = locations.first else {
return
}
zoomMapView(with: currentLocation)
}
private func zoomMapView(with location: CLLocation) {
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
let latDelta: CLLocationDegrees = 0.05
let lonDelta: CLLocationDegrees = 0.05
let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
let location: CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
let region: MKCoordinateRegion = MKCoordinateRegionMake(location, span)
mapView.setRegion(region, animated: true)
mapView.showsUserLocation = true
locationManager.stopUpdatingLocation()
}
}
| mit | 654a55c8c058475a1bb8ee5946e5028f | 42.780769 | 319 | 0.657032 | 5.402468 | false | false | false | false |
kimyoutora/RouterKit | RouterKit/Request.swift | 1 | 6623 | //
// Request.swift
// RouterKit
//
// Created by Kang Chen on 1/2/16.
//
//
import Foundation
/**
* Base protocol of a request. Isolating this enables
* support for potentially multiple URL standards.
*/
public protocol RequestType {
var parameters: [String: String] { get set }
var path: String { get }
var scheme: String? { get }
init(url: NSURL)
}
/**
* A Request represents an inbound or outbound URL request
* with structured metadata, namely conformance to AppLink v1.0 spec.
*/
public struct Request: AppLinkType, RequestType {
/// The original URL representing this request.
public let rawURL: NSURL
/// Protocol conformance is done within this class due to performance
/// penalty of only having computed properties for extensions.
// MARK: AppLink Protocol
static let AppLinkDataParameterKey = "al_applink_data"
static let AppLinkTargetURLKey = "target_url"
static let AppLinkUserAgentKey = "user_agent"
static let AppLinkExtrasKey = "extras"
static let AppLinkVersionKey = "version"
static let AppLinkRefererAppLinkKey = "referer_app_link"
static let AppLinkRefererURLKey = "url"
static let AppLinkRefererAppNameKey = "app_name"
/// Underlying
private var requestProperties: [String: AnyObject]
/// Extras as passed along in the App link request.
public var extras: [String: String] {
get {
return self.requestProperties[Request.AppLinkExtrasKey] as! [String: String]
} set {
self.requestProperties[Request.AppLinkExtrasKey] = newValue
}
}
/// App link request's targetURL
public let targetURL: String
/// Referrer of the App link request
public var refererAppLink: RefererAppLinkType? {
get {
if let refererDict = self.requestProperties[Request.AppLinkRefererAppLinkKey] as? [String: String] {
let appName = refererDict[Request.AppLinkRefererAppNameKey] ?? ""
let url = refererDict[Request.AppLinkRefererURLKey] ?? ""
return RefererAppLink(appName: appName, url: url)
} else {
return nil
}
}
}
/// App link request spec version. Defaults to 1.0.
public var version: String {
get {
return self.requestProperties[Request.AppLinkVersionKey] as? String ?? "1.0"
}
}
/// App link request's user agent.
public var userAgent: String? {
get {
return self.requestProperties[Request.AppLinkUserAgentKey] as? String
}
}
// MARK: Convenience Properties
/// Alias for `extras`.
public var parameters: [String: String] {
get {
return self.extras
} set {
self.requestProperties[Request.AppLinkExtrasKey] = newValue
}
}
/// Path of the request e.g. example://foo/bar -> /foo/bar, /foo/bar -> /foo/bar
public var path: String {
get {
return Request.normalizedPath(self.rawURL)
}
}
/// The scheme of the request. Nil when this is an internal requests within the app i.e. /foo/bar
public let scheme: String?
public init(url: NSURL) {
self.rawURL = url
self.scheme = url.scheme.isEmpty ? nil : Optional(url.scheme)
self.targetURL = Request.targetURLFromNSURL(url)
self.requestProperties = url.query.map(Request.normalizedURLParams) ?? [String: AnyObject]()
}
// url.absoluteString does not behave as you would expect for custom schemes so we need to normalize it
private static func targetURLFromNSURL(url: NSURL) -> String {
let schemeSuffix = url.scheme.isEmpty ? "" : ":/"
let combinedPath = self.normalizedPath(url) // always returns with / prefix
return "\(url.scheme)\(schemeSuffix)\(combinedPath)"
}
/**
Normalized path from the specified URL. This mainly handles different semantics that `NSURL` depending on whether url.scheme is present.
Examples:
scheme://foo/bar -> /foo/bar
/foo -> /foo
/foo/bar -> /foo/bar
- parameter url: URL to normalize.
- returns: Normalized path regardless of whether `url.scheme` is set.
*/
private static func normalizedPath(url: NSURL) -> String {
// URL parsing in NSURL doesn't handle all combinations of scheme and with or without path.
// For our purposes, everything after scheme:// and / for schemeless is considered the path
switch (url.host, url.path) {
case (nil, nil): return "/"
case (.Some(let host), nil): return "/\(host)"
case (nil, .Some(let path)): return path
case let (.Some(host), .Some(path)): return "/\(host)\(path)"
}
}
private static func normalizedURLParams(encodedQuery: String) -> [String: AnyObject] {
typealias GenericKVParamsType = [String: AnyObject]
var params = dictionaryFromURLParams(encodedQuery) ?? GenericKVParamsType()
var appLinkParams = params.removeValueForKey(AppLinkDataParameterKey) as? GenericKVParamsType ?? GenericKVParamsType()
for (k, v) in params {
appLinkParams[k] = v
}
return appLinkParams
}
/// App Link uses url encoded JSON vs. query parameters
/// encodedParams: foo=bar&baz=qux
private static func dictionaryFromURLParams(encodedQuery: String) -> [String: AnyObject] {
let encodedParams = encodedQuery.componentsSeparatedByString("&")
var resultParamsDictionary = [String: AnyObject]()
encodedParams.forEach { kv in
let kvPair = kv.componentsSeparatedByString("=")
let key = kvPair[0]
guard let decodedValue = kvPair[1].stringByRemovingPercentEncoding else {
print("Invalid request parameters.")
return
}
let valueIsJSON = decodedValue.hasPrefix("{") && decodedValue.hasSuffix("}")
if valueIsJSON {
let valueData = decodedValue.dataUsingEncoding(NSUTF8StringEncoding)
do {
let deserializedParams = try NSJSONSerialization.JSONObjectWithData(valueData!, options: .AllowFragments) as! [String: AnyObject]
resultParamsDictionary[key] = deserializedParams
} catch {
return resultParamsDictionary[key] = [String: AnyObject]()
}
} else {
resultParamsDictionary[key] = decodedValue
}
}
return resultParamsDictionary
}
}
| mit | 8ce060859cd5b8f6d36ae1981b988dac | 35.39011 | 149 | 0.631134 | 4.670663 | false | false | false | false |
rowungiles/TodayExtensionCoreDataExample | TodayExtension/TodayViewController.swift | 1 | 4465 | //
// TodayViewController.swift
// TodayExtensionCoreDataExample
//
// Created by Rowun Giles on 27/09/2014.
// Copyright (c) 2014 Rowun Giles. All rights reserved.
//
import UIKit
import NotificationCenter
import TodayExtensionExampleCoreDataFramework
class TodayTableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate, NCWidgetProviding {
// TODO: an FRC?
// TODO: Test viewWillTransitionToSize
// TODO: sometimes random line?
var titles = [String]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 47.0;
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let updates: Array<String>? = CoreDataMediator.sharedInstance.retrieveStubDataSubset()
self.updateTableView(updates: updates)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) {
// Perform any setup necessary in order to update the view.
self.populateTitlesFromDataSource(completionHandler)
}
func populateTitlesFromDataSource(completionHandler: ((NCUpdateResult) -> Void)?) {
let stubData: Array<String>? = CoreDataMediator.sharedInstance.retrieveStubDataSubset()
if (completionHandler != nil) {
self.determineContentUpdateStatusForArray(updates: stubData, completionHandler: completionHandler)
}
}
func determineContentUpdateStatusForArray(#updates: [String]?, completionHandler: ((NCUpdateResult) -> Void)?) {
if (updates == nil) {
completionHandler?(.Failed)
} else if (updates! == self.titles) {
completionHandler?(.NoData)
} else {
self.updateTableView(updates: updates)
completionHandler?(.NewData)
}
}
func updateTableView(#updates: [String]?) {
if let data = updates {
self.titles = data
self.tableView.reloadData()
self.preferredContentSize = self.tableView.contentSize
}
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return self.titles.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TodayExtensionTableCell", forIndexPath: indexPath) as TodayExtensionTableViewCell
let title: String = titles[indexPath.row]
cell.title.text = title
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let url: NSURL = "http://twitter.com/rowungiles"
self.extensionContext?.openURL(url, completionHandler: { (success) -> Void in
println("url opened")
})
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
coordinator.animateAlongsideTransition({ context in
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.tableView.alpha = 0.0
}, completion: { (finished) -> Void in
self.tableView.alpha = 1.0
})
}, completion: nil)
}
}
extension NSURL: StringLiteralConvertible, ExtendedGraphemeClusterLiteralConvertible {
typealias ExtendedGraphemeClusterLiteralType = StringLiteralType
public class func convertFromExtendedGraphemeClusterLiteral(value: StringLiteralType) -> Self {
return self(string: value)
}
public class func convertFromStringLiteral(value: StringLiteralType) -> Self {
return self(string: value)
}
} | mit | 698d8a954590c38bc80ecb9d80fbb429 | 31.838235 | 145 | 0.650616 | 5.798701 | false | false | false | false |
gkaimakas/ReactiveBluetooth | Example/Tests/Tests.swift | 1 | 1167 | // https://github.com/Quick/Quick
import Quick
import Nimble
import ReactiveBluetooth
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | 80a90f1605927a6d9ef9c5c4ad0f5bb1 | 22.22 | 60 | 0.361757 | 5.555024 | false | false | false | false |
watr/PTPPT | PTP/PTPOperationResponse.swift | 1 | 2206 |
import Foundation
public enum PTPResponseCode: PTPCode {
case undefined = 0x2000
case ok = 0x2001
case generalError = 0x2002
case sessionNotOpen = 0x2003
case invalidTransactionID = 0x2004
case operationNotSupported = 0x2005
case parameterNotSupported = 0x2006
case incompleteTransfer = 0x2007
case invalidStorageID = 0x2008
case invalidObjectHandle = 0x2009
case devicePropNotSupported = 0x200A
case invalidObjectFormatCode = 0x200B
case storeFull = 0x200C
case objectWriteProtected = 0x200D
case storeReadOnly = 0x200E
case accessDenied = 0x200F
case noThumbnailPresent = 0x2010
case selfTestFailed = 0x2011
case partialDeletion = 0x2012
case storeNotAvailable = 0x2013
case specificationByFormatUnsupported = 0x2014
case noValidObjectInfo = 0x2015
case invalidCodeFormat = 0x2016
case unknownVendorCode = 0x2017
case captureAlreadyTerminated = 0x2018
case deviceBusy = 0x2019
case invalidParentObject = 0x201A
case invalidDevicePropFormat = 0x201B
case invalidDevicePropValue = 0x201C
case invalidParameter = 0x201D
case sessionAlreadyOpen = 0x201E
case transactionCancelled = 0x201F
case specificationOfDestinationUnsupported = 0x2020
}
public struct PTPOperationResponse {
public let container: PTPContainer
public init?(data: Data) {
guard let container = PTPContainer(type: PTPContainerType.response.rawValue, data: data) else {
return nil
}
self.container = container
}
}
| mit | 14e0e36f5d5aca9e7b8b0f3de3c0389d | 44.020408 | 103 | 0.522665 | 5.446914 | false | false | false | false |
mirai418/leaflet-ios | leaflet/ENSideMenu/ENSideMenu.swift | 2 | 11251 | //
// SideMenu.swift
// SwiftSideMenu
//
// Created by Evgeny on 24.07.14.
// Copyright (c) 2014 Evgeny Nazarov. All rights reserved.
//
import UIKit
@objc public protocol ENSideMenuDelegate {
optional func sideMenuWillOpen()
optional func sideMenuWillClose()
optional func sideMenuShouldOpenSideMenu () -> Bool
}
@objc public protocol ENSideMenuProtocol {
var sideMenu : ENSideMenu? { get }
func setContentViewController(contentViewController: UIViewController)
}
public enum ENSideMenuAnimation : Int {
case None
case Default
}
public enum ENSideMenuPosition : Int {
case Left
case Right
}
public extension UIViewController {
public func toggleSideMenuView () {
sideMenuController()?.sideMenu?.toggleMenu()
}
public func hideSideMenuView () {
sideMenuController()?.sideMenu?.hideSideMenu()
}
public func showSideMenuView () {
sideMenuController()?.sideMenu?.showSideMenu()
}
public func isSideMenuOpen () -> Bool {
let sieMenuOpen = self.sideMenuController()?.sideMenu?.isMenuOpen
return sieMenuOpen!
}
public func sideMenuController () -> ENSideMenuProtocol? {
var iteration : UIViewController? = self.parentViewController
if (iteration == nil) {
return topMostController()
}
do {
if (iteration is ENSideMenuProtocol) {
return iteration as? ENSideMenuProtocol
} else if (iteration?.parentViewController != nil && iteration?.parentViewController != iteration) {
iteration = iteration!.parentViewController
} else {
iteration = nil
}
} while (iteration != nil)
return iteration as? ENSideMenuProtocol
}
internal func topMostController () -> ENSideMenuProtocol? {
var topController : UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController
while (topController?.presentedViewController is ENSideMenuProtocol) {
topController = topController?.presentedViewController
}
return topController as? ENSideMenuProtocol
}
}
public class ENSideMenu : NSObject, UIGestureRecognizerDelegate {
public var menuWidth : CGFloat = 160.0 {
didSet {
needUpdateApperance = true
updateFrame()
}
}
private var menuPosition:ENSideMenuPosition = .Left
public var bouncingEnabled :Bool = true
private let sideMenuContainerView = UIView()
private var menuTableViewController : UITableViewController!
private var animator : UIDynamicAnimator!
private var sourceView : UIView!
private var needUpdateApperance : Bool = false
public weak var delegate : ENSideMenuDelegate?
private(set) var isMenuOpen : Bool = false
public var allowLeftSwipe : Bool = true
public var allowRightSwipe : Bool = true
public init(sourceView: UIView, menuPosition: ENSideMenuPosition) {
super.init()
self.sourceView = sourceView
self.menuPosition = menuPosition
self.setupMenuView()
animator = UIDynamicAnimator(referenceView:sourceView)
// Add right swipe gesture recognizer
let rightSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:")
rightSwipeGestureRecognizer.delegate = self
rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right
// Add left swipe gesture recognizer
let leftSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:")
leftSwipeGestureRecognizer.delegate = self
leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Left
if (menuPosition == .Left) {
sourceView.addGestureRecognizer(rightSwipeGestureRecognizer)
sideMenuContainerView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
else {
sideMenuContainerView.addGestureRecognizer(rightSwipeGestureRecognizer)
sourceView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
}
public convenience init(sourceView: UIView, menuTableViewController: UITableViewController, menuPosition: ENSideMenuPosition) {
self.init(sourceView: sourceView, menuPosition: menuPosition)
self.menuTableViewController = menuTableViewController
self.menuTableViewController.tableView.frame = sideMenuContainerView.bounds
self.menuTableViewController.tableView.autoresizingMask = .FlexibleHeight | .FlexibleWidth
sideMenuContainerView.addSubview(self.menuTableViewController.tableView)
}
private func updateFrame() {
let menuFrame = CGRectMake(
(menuPosition == .Left) ?
isMenuOpen ? 0 : -menuWidth-1.0 :
isMenuOpen ? sourceView.frame.size.width - menuWidth : sourceView.frame.size.width+1.0,
sourceView.frame.origin.y,
menuWidth,
sourceView.frame.size.height
)
sideMenuContainerView.frame = menuFrame
}
private func setupMenuView() {
// Configure side menu container
updateFrame()
sideMenuContainerView.backgroundColor = UIColor.clearColor()
sideMenuContainerView.clipsToBounds = false
sideMenuContainerView.layer.masksToBounds = false
sideMenuContainerView.layer.shadowOffset = (menuPosition == .Left) ? CGSizeMake(1.0, 1.0) : CGSizeMake(-1.0, -1.0)
sideMenuContainerView.layer.shadowRadius = 1.0
sideMenuContainerView.layer.shadowOpacity = 0.125
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath
sourceView.addSubview(sideMenuContainerView)
if (NSClassFromString("UIVisualEffectView") != nil) {
// Add blur view
var visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView
visualEffectView.frame = sideMenuContainerView.bounds
visualEffectView.autoresizingMask = .FlexibleHeight | .FlexibleWidth
sideMenuContainerView.addSubview(visualEffectView)
}
else {
// TODO: add blur for ios 7
}
}
private func toggleMenu (shouldOpen: Bool) {
if (shouldOpen && delegate?.sideMenuShouldOpenSideMenu?() == false) {
return
}
updateSideMenuApperanceIfNeeded()
isMenuOpen = shouldOpen
if (bouncingEnabled) {
animator.removeAllBehaviors()
var gravityDirectionX: CGFloat
var pushMagnitude: CGFloat
var boundaryPointX: CGFloat
var boundaryPointY: CGFloat
if (menuPosition == .Left) {
// Left side menu
gravityDirectionX = (shouldOpen) ? 1 : -1
pushMagnitude = (shouldOpen) ? 20 : -20
boundaryPointX = (shouldOpen) ? menuWidth : -menuWidth-2
boundaryPointY = 20
}
else {
// Right side menu
gravityDirectionX = (shouldOpen) ? -1 : 1
pushMagnitude = (shouldOpen) ? -20 : 20
boundaryPointX = (shouldOpen) ? sourceView.frame.size.width-menuWidth : sourceView.frame.size.width+menuWidth+2
boundaryPointY = -20
}
let gravityBehavior = UIGravityBehavior(items: [sideMenuContainerView])
gravityBehavior.gravityDirection = CGVectorMake(gravityDirectionX, 0)
animator.addBehavior(gravityBehavior)
let collisionBehavior = UICollisionBehavior(items: [sideMenuContainerView])
collisionBehavior.addBoundaryWithIdentifier("menuBoundary", fromPoint: CGPointMake(boundaryPointX, boundaryPointY),
toPoint: CGPointMake(boundaryPointX, sourceView.frame.size.height))
animator.addBehavior(collisionBehavior)
let pushBehavior = UIPushBehavior(items: [sideMenuContainerView], mode: UIPushBehaviorMode.Instantaneous)
pushBehavior.magnitude = pushMagnitude
animator.addBehavior(pushBehavior)
let menuViewBehavior = UIDynamicItemBehavior(items: [sideMenuContainerView])
menuViewBehavior.elasticity = 0.25
animator.addBehavior(menuViewBehavior)
}
else {
var destFrame :CGRect
if (menuPosition == .Left) {
destFrame = CGRectMake((shouldOpen) ? -2.0 : -menuWidth, 0, menuWidth, sideMenuContainerView.frame.size.height)
}
else {
destFrame = CGRectMake((shouldOpen) ? sourceView.frame.size.width-menuWidth : sourceView.frame.size.width+2.0,
0,
menuWidth,
sideMenuContainerView.frame.size.height)
}
UIView.animateWithDuration(0.4, animations: { () -> Void in
self.sideMenuContainerView.frame = destFrame
})
}
if (shouldOpen) {
delegate?.sideMenuWillOpen?()
} else {
delegate?.sideMenuWillClose?()
}
}
public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer is UISwipeGestureRecognizer {
let swipeGestureRecognizer = gestureRecognizer as! UISwipeGestureRecognizer
if !self.allowLeftSwipe {
if swipeGestureRecognizer.direction == .Left {
return false
}
}
if !self.allowRightSwipe {
if swipeGestureRecognizer.direction == .Right {
return false
}
}
}
return true
}
internal func handleGesture(gesture: UISwipeGestureRecognizer) {
toggleMenu((self.menuPosition == .Right && gesture.direction == .Left)
|| (self.menuPosition == .Left && gesture.direction == .Right))
}
private func updateSideMenuApperanceIfNeeded () {
if (needUpdateApperance) {
var frame = sideMenuContainerView.frame
frame.size.width = menuWidth
sideMenuContainerView.frame = frame
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath
needUpdateApperance = false
}
}
public func toggleMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
else {
updateSideMenuApperanceIfNeeded()
toggleMenu(true)
}
}
public func showSideMenu () {
if (!isMenuOpen) {
toggleMenu(true)
}
}
public func hideSideMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
}
}
| mit | d148184bd33dcf46d8fd07d983c3a652 | 35.888525 | 131 | 0.622967 | 6.134678 | false | false | false | false |
SettlePad/client-iOS | SettlePad/IdentifiersViewController.swift | 1 | 16528 | //
// IdentifiersViewController.swift
// SettlePad
//
// Created by Rob Everhardt on 24/03/15.
// Copyright (c) 2015 SettlePad. All rights reserved.
//
// See http://nshipster.com/uialertcontroller/
import UIKit
class IdentifiersViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
//Hide additional gridlines, and set gray background for footer
self.tableView.tableFooterView = UIView(frame:CGRectZero)
//self.tableView.backgroundColor = UIColor.groupTableViewBackgroundColor()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
if activeUser != nil {
return activeUser!.userIdentifiers.count
} else {
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("emailAddressRow", forIndexPath: indexPath) as! IdentifierCell
// Configure the cell...
let identifier = activeUser!.userIdentifiers[indexPath.row]
cell.markup(identifier)
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
/*if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
} */
}
override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? {
let identifier = activeUser!.userIdentifiers[indexPath.row]
let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete" , handler: { (action:UITableViewRowAction, indexPath:NSIndexPath) -> Void in
self.deleteIdentifier(identifier, tableView: tableView, indexPath: indexPath)
})
deleteAction.backgroundColor = Colors.danger.textToUIColor()
return [deleteAction]
}
func deleteIdentifier (identifier: UserIdentifier, tableView: UITableView, indexPath: NSIndexPath) {
var message: String
if activeUser!.userIdentifiers.count == 1 {
message = "If you proceed, you will close your account and log out. You cannot login ever again. Are you sure that is what you want?"
} else {
message = "Do you really want to delete "+identifier.identifier+"?"
}
let alertController = UIAlertController(title: "Are you sure?", message: message, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
tableView.setEditing(false, animated: true)
}
alertController.addAction(cancelAction)
let destroyAction = UIAlertAction(title: "Delete", style: .Destructive) { (action) in
tableView.setEditing(false, animated: true)
activeUser!.deleteIdentifier(identifier,
success: {
if activeUser != nil {
if activeUser!.userIdentifiers.count == 0 {
clearUser() //No need to logout on the server, that is already done with removing the last identifier
dispatch_async(dispatch_get_main_queue()) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("LoginController")
self.presentViewController(vc, animated: false, completion: nil)
}
} else {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
}
},
failure: {error in
displayError(error.errorText,viewController: self)
}
)
//already add with spinner
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
alertController.addAction(destroyAction)
self.presentViewController(alertController, animated: true) {
// ...
}
}
func setPrimary(identifier: UserIdentifier) {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
activeUser!.setAsPrimary(identifier, success: {},
failure: {error in
displayError(error.errorText,viewController: self)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
)
}
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let identifier = activeUser!.userIdentifiers[indexPath.row]
let cell = tableView.cellForRowAtIndexPath(indexPath)
//show Action sheet
let actionSheetController: UIAlertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
//For iPad
actionSheetController.popoverPresentationController?.sourceView = tableView.cellForRowAtIndexPath(indexPath)
actionSheetController.popoverPresentationController?.sourceRect = tableView.cellForRowAtIndexPath(indexPath)!.bounds
let cancelAction: UIAlertAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
//Just dismiss the action sheet
}
actionSheetController.addAction(cancelAction)
let changePasswordAction: UIAlertAction = UIAlertAction(title: "Change password", style: .Default) { action -> Void in
self.changePasswordForm(identifier)
}
actionSheetController.addAction(changePasswordAction)
if identifier.verified == false {
let verifyAction: UIAlertAction = UIAlertAction(title: "Enter verification code", style: .Default) { action -> Void in
let identifier = activeUser!.userIdentifiers[indexPath.row]
self.validationCodeForm(identifier)
}
actionSheetController.addAction(verifyAction)
let resendCodeAction: UIAlertAction = UIAlertAction(title: "Resend verification code", style: .Default) { action -> Void in
activeUser!.resendToken(identifier,
failure: {error in
displayError(error.errorText,viewController: self)
}
)
}
actionSheetController.addAction(resendCodeAction)
}
if identifier.primary == false && identifier.verified {
let setPrimaryAction: UIAlertAction = UIAlertAction(title: "Set as primary", style: .Default) { action -> Void in
let identifier = activeUser!.userIdentifiers[indexPath.row]
self.setPrimary(identifier)
}
actionSheetController.addAction(setPrimaryAction)
}
let deleteAction: UIAlertAction = UIAlertAction(title: "Delete", style: .Destructive) { action -> Void in
let identifier = activeUser!.userIdentifiers[indexPath.row]
self.deleteIdentifier (identifier, tableView: tableView, indexPath: indexPath)
}
actionSheetController.addAction(deleteAction)
//We need to provide a popover sourceView when using it on iPad
actionSheetController.popoverPresentationController?.sourceView = cell?.contentView
actionSheetController.popoverPresentationController?.permittedArrowDirections = [UIPopoverArrowDirection.Up, UIPopoverArrowDirection.Down]
actionSheetController.popoverPresentationController?.sourceRect = CGRectMake(cell!.frame.width / 2, cell!.frame.height,0,0)
//Present the AlertController
self.presentViewController(actionSheetController, animated: true, completion: nil)
}
func changePasswordForm(identifier: UserIdentifier) {
//show change password form
let alertController = UIAlertController(title: "Change password", message: "Enter your new password twice to change it", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in }
let changeAction = UIAlertAction(title: "Change", style: .Default) { (action) in
let firstPasswordTextField = alertController.textFields![0]
activeUser!.changePassword(identifier, password: firstPasswordTextField.text!,
failure: {error in
displayError(error.errorText,viewController: self)
}
)
}
changeAction.enabled = false
alertController.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "Password"
textField.secureTextEntry = true
textField.addTarget(self, action: #selector(IdentifiersViewController.changePasswordFormTextChanged(_:)), forControlEvents: .EditingChanged)
}
alertController.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "Password (again)"
textField.secureTextEntry = true
textField.addTarget(self, action: #selector(IdentifiersViewController.changePasswordFormTextChanged(_:)), forControlEvents: .EditingChanged)
}
alertController.addAction(cancelAction)
alertController.addAction(changeAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func changePasswordFormTextChanged(sender:AnyObject) {
//get a handler to the UIAlertController
let tf = sender as! UITextField
var resp : UIResponder = tf
while !(resp is UIAlertController) { resp = resp.nextResponder()! }
let alertController = resp as! UIAlertController
let firstPasswordTextField = alertController.textFields![0]
let secondPasswordTextField = alertController.textFields![1]
(alertController.actions[1] ).enabled = (
firstPasswordTextField.text != "" &&
firstPasswordTextField.text == secondPasswordTextField.text
)
}
@IBAction func newIdentifierAction(sender: AnyObject) {
//show new identifier form
let alertController = UIAlertController(title: "New identifier", message: nil, preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
}
let addAction = UIAlertAction(title: "Add", style: .Default) { (action) in
let emailTextField = alertController.textFields![0]
let firstPasswordTextField = alertController.textFields![1]
activeUser!.addIdentifier(emailTextField.text!, password: firstPasswordTextField.text!,
success: {
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
},
failure: {error in
displayError(error.errorText,viewController: self)
}
)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
addAction.enabled = false
alertController.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "Email address"
textField.secureTextEntry = false
textField.addTarget(self, action: #selector(IdentifiersViewController.newIdentifierFormTextChanged(_:)), forControlEvents: .EditingChanged)
}
alertController.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "Password"
textField.secureTextEntry = true
textField.addTarget(self, action: #selector(IdentifiersViewController.newIdentifierFormTextChanged(_:)), forControlEvents: .EditingChanged)
}
alertController.addTextFieldWithConfigurationHandler { (textField) in
textField.placeholder = "Password (again)"
textField.secureTextEntry = true
textField.addTarget(self, action: #selector(IdentifiersViewController.newIdentifierFormTextChanged(_:)), forControlEvents: .EditingChanged)
}
alertController.addAction(cancelAction)
alertController.addAction(addAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
func newIdentifierFormTextChanged(sender:AnyObject) {
//get a handler to the UIAlertController
let tf = sender as! UITextField
var resp : UIResponder = tf
while !(resp is UIAlertController) { resp = resp.nextResponder()! }
let alertController = resp as! UIAlertController
let emailTextField = alertController.textFields![0]
let firstPasswordTextField = alertController.textFields![1]
let secondPasswordTextField = alertController.textFields![2]
alertController.actions[1].enabled = (
emailTextField.text!.isEmail() &&
firstPasswordTextField.text != "" &&
firstPasswordTextField.text == secondPasswordTextField.text
)
}
func validationCodeForm(identifier: UserIdentifier) {
//show validation code form
displayValidationFormLoggedIn(identifier, viewController: self,
requestCompleted: {(succeeded, error_msg) -> () in
if !succeeded {
displayError(error_msg!,viewController: self)
}
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData() //To show result
})
}
)
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData() //To show spinner
})
}
}
class IdentifierCell: UITableViewCell {
@IBOutlet var identifierLabel: UILabel!
@IBOutlet var verificationLabel: UILabel!
@IBOutlet var processingSpinner: UIActivityIndicatorView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func markup(identifier: UserIdentifier){
identifierLabel.text = identifier.identifier
if identifier.pending {
processingSpinner.hidden = false
verificationLabel.hidden = true
processingSpinner.startAnimating()
} else {
processingSpinner.hidden = true
verificationLabel.hidden = false
if identifier.verified {
verificationLabel.text = ""
//verificationLabel.textColor = Colors.success.textToUIColor()
} else {
verificationLabel.text = "not verified"
verificationLabel.textColor = Colors.danger.textToUIColor()
}
}
if identifier.primary {
self.accessoryType = .Checkmark
} else {
self.accessoryType = .None
}
}
}
| mit | 540d9364f2e8070a7524c7b95c476a07 | 37.526807 | 182 | 0.691433 | 5.194217 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV | PopcornTime/UI/iOS/Extensions/String+Truncation.swift | 1 | 3619 |
import Foundation
extension String {
func truncateToSize(size: CGSize,
ellipsesString: String,
trailingText: String,
attributes: [NSAttributedString.Key : Any],
trailingTextAttributes: [NSAttributedString.Key : Any]) -> NSAttributedString {
if !willFit(to: size, attributes: attributes) {
let indexOfLastCharacterThatFits = indexThatFits(size: size,
ellipsesString: ellipsesString,
trailingText: trailingText,
attributes: attributes,
minIndex: 0,
maxIndex: count)
let range = startIndex..<index(startIndex, offsetBy: indexOfLastCharacterThatFits)
let substring = self[range]
let attributedString = NSMutableAttributedString(string: substring + ellipsesString, attributes: attributes)
let attributedTrailingString = NSAttributedString(string: trailingText, attributes: trailingTextAttributes)
attributedString.append(attributedTrailingString)
return attributedString
}
else {
return NSAttributedString(string: self, attributes: attributes)
}
}
func willFit(to size: CGSize,
ellipsesString: String = "",
trailingText: String = "",
attributes: [NSAttributedString.Key : Any]) -> Bool {
let text = (self + ellipsesString + trailingText) as NSString
let boundedSize = CGSize(width: size.width, height: .greatestFiniteMagnitude)
let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading]
let boundedRect = text.boundingRect(with: boundedSize, options: options, attributes: attributes, context: nil)
return boundedRect.height <= size.height
}
// MARK: - Private
private func indexThatFits(size: CGSize,
ellipsesString: String,
trailingText: String,
attributes: [NSAttributedString.Key : Any],
minIndex: Int,
maxIndex: Int) -> Int {
guard maxIndex - minIndex != 1 else { return minIndex }
let midIndex = (minIndex + maxIndex) / 2
let range = startIndex..<index(startIndex, offsetBy: midIndex)
let substring = String(self[range])
if !substring.willFit(to: size, ellipsesString: ellipsesString, trailingText: trailingText, attributes: attributes) {
return indexThatFits(size: size,
ellipsesString: ellipsesString,
trailingText: trailingText,
attributes: attributes,
minIndex: minIndex,
maxIndex: midIndex)
}
else {
return indexThatFits(size: size,
ellipsesString: ellipsesString,
trailingText: trailingText,
attributes: attributes,
minIndex: midIndex,
maxIndex: maxIndex)
}
}
}
| gpl-3.0 | 3cd6c51cbe73900667cee78743cb77cb | 44.810127 | 125 | 0.505112 | 7.054581 | false | false | false | false |
Webtrekk/webtrekk-ios-sdk | Source/Internal/Utility/AdClearIdUtil.swift | 1 | 2448 | import Foundation
public struct AdClearId {
private static let bitsOfMilliseconds: UInt64 = 39
private static let bitsOfRandom: UInt64 = 10
private static let bitsOfApplication: UInt64 = 10
private static let bitsOfProcess: UInt64 = 4
private static let bitShiftForApplication: UInt64 = bitsOfProcess
private static let bitShiftForCounter: UInt64 = bitShiftForApplication + bitsOfApplication
private static let bitShiftForTimestamp: UInt64 = bitShiftForCounter + bitsOfRandom
private static let applicationId = 713
public static func getAdClearId() -> UInt64 {
var adClearId = UserDefaults.standardDefaults.child(namespace: "webtrekk").uInt64ForKey(DefaultsKeys.adClearId)
if adClearId != nil {
return adClearId!
}
adClearId = generateAdClearId()
UserDefaults.standardDefaults.child(namespace: "webtrekk").set(key: DefaultsKeys.adClearId, to: adClearId)
return adClearId!
}
public static func generateAdClearId() -> UInt64 {
var dateComponents = DateComponents()
dateComponents.year = 2011
dateComponents.month = 01
dateComponents.day = 01
dateComponents.timeZone = TimeZone.current
dateComponents.hour = 0
dateComponents.minute = 0
let diffInMilliseconds = UInt64(Date().timeIntervalSince(Calendar.current.date(from: dateComponents)!) * 1000)
let randomInt = UInt64(arc4random_uniform(99999999) + 1)
let processId = UInt64(ProcessInfo().processIdentifier)
return combineAdClearId(diffInMilliseconds: diffInMilliseconds, randomInt: randomInt, processId: processId)
}
private static func combineAdClearId(diffInMilliseconds: UInt64, randomInt: UInt64, processId: UInt64) -> UInt64 {
let adClearId = ((AdClearId.limitBitsTo(value: diffInMilliseconds, maxBits: bitsOfMilliseconds) << bitShiftForTimestamp)
+ (AdClearId.limitBitsTo(value: randomInt, maxBits: bitsOfRandom) << bitShiftForCounter)
+ (AdClearId.limitBitsTo(value: UInt64(AdClearId.applicationId), maxBits: bitsOfApplication) << bitShiftForApplication)
+ AdClearId.limitBitsTo(value: processId, maxBits: bitsOfProcess))
return adClearId
}
private static func limitBitsTo(value: UInt64, maxBits: UInt64) -> UInt64 {
let maxLength: UInt64 = (1 << maxBits) - 1
return value & UInt64(maxLength)
}
}
| mit | 6e874cfd1fcef6f7c3829b8acb1e079a | 41.206897 | 131 | 0.712418 | 5.037037 | false | false | false | false |
ubi-naist/SenStick | ios/SenStickViewer/SenStickViewer/DeviceInformationViewController.swift | 1 | 8618 | //
// DeviceInformationViewController.swift
// SenStickViewer
//
// Created by AkihiroUehara on 2016/06/12.
// Copyright © 2016年 AkihiroUehara. All rights reserved.
//
import UIKit
import SenStickSDK
import iOSDFULibrary
import CoreBluetooth
class DeviceInformationViewController : UIViewController, LoggerDelegate, DFUServiceDelegate, DFUProgressDelegate, CBCentralManagerDelegate
{
// Properties
@IBOutlet var serialNumberTextLabel: UILabel!
@IBOutlet var manufacturerNameTextLabel: UILabel!
@IBOutlet var hardwareRevisionTextLabel: UILabel!
@IBOutlet var firmwareRevisionTextLabel: UILabel!
@IBOutlet var updateFirmwareButton: UIButton!
@IBOutlet var doneButton: UIBarButtonItem!
@IBOutlet var progressBar: UIProgressView!
@IBOutlet var progressTextLabel: UILabel!
@IBOutlet var dfuMessageTextLabel: UILabel!
var device: SenStickDevice?
var firmwareRevision: String = ""
var firmwareFilePath: String = ""
var dfuController: DFUServiceController?
var didEnterDFUmode = false
var didStartingFirmwareUpdating = false
var dfuAdvertisingName: String = ""
// View controller life cycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.serialNumberTextLabel.text = self.device?.deviceInformationService?.serialNumber
self.manufacturerNameTextLabel.text = self.device?.deviceInformationService?.manufacturerName
self.hardwareRevisionTextLabel.text = self.device?.deviceInformationService?.hardwareRevision
self.firmwareRevisionTextLabel.text = self.device?.deviceInformationService?.firmwareRevision
self.progressBar.isHidden = true
self.progressTextLabel.text = ""
self.dfuMessageTextLabel.text = ""
// plistを開いて更新ファーム情報を読み取る。
if let path = Bundle.main.path(forResource: "firmwareInfo", ofType: "plist") {
let dict = NSDictionary(contentsOfFile: path)
if (self.device?.deviceInformationService?.hardwareRevision.hasPrefix("rev 1"))! { // nRF51
dfuAdvertisingName = "ActDfu"
firmwareRevision = dict!.value(forKey: "nrf51_revision")! as! String
let resourcePath = Bundle.main.resourcePath! as NSString
firmwareFilePath = resourcePath.appendingPathComponent( dict!.value(forKey: "nrf51_filename") as! String)
} else { // nRF52
dfuAdvertisingName = "ACT-DFU2"
firmwareRevision = dict!.value(forKey: "nrf52_revision")! as! String
let resourcePath = Bundle.main.resourcePath! as NSString
firmwareFilePath = resourcePath.appendingPathComponent( dict!.value(forKey: "nrf52_filename") as! String)
}
}
// ファームの番号確認。最新でなければ、更新ボタンを有効に
if self.device?.deviceInformationService?.firmwareRevision != firmwareRevision {
updateFirmwareButton.isEnabled = true
} else {
updateFirmwareButton.isEnabled = false
}
}
func dismiss()
{
if didEnterDFUmode || didStartingFirmwareUpdating {
// DFU更新でCentralManagerのDelegateが持って行かれているのを、元に戻す
SenStickDeviceManager.sharedInstance.reset()
_ = self.navigationController?.popToRootViewController(animated: true)
} else {
_ = self.navigationController?.popViewController(animated: true)
}
}
func showDialogAndDismiss(_ title: String, message:String)
{
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: { (UIAlertAction) -> Void in
self.dismiss()
})
alert.addAction(okAction)
present(alert, animated: true, completion:nil)
}
func performDfu(_ peripheral:CBPeripheral)
{
didStartingFirmwareUpdating = true
let firmware = DFUFirmware(urlToZipFile: URL(fileURLWithPath: self.firmwareFilePath))
let initiator = DFUServiceInitiator(centralManager: self.device!.manager, target: peripheral).with(firmware: firmware!)
initiator.logger = self
initiator.delegate = self
initiator.progressDelegate = self
self.dfuController = initiator.start()
}
// Event handler
@IBAction func doneButtonTouchUpInside(_ sender: UIBarButtonItem) {
dismiss()
}
@IBAction func updateFirmwareButtonToutchUpInside(_ sender: UIButton) {
// ボタンを操作不可能に, DFU更新のUI初期状態
self.updateFirmwareButton.isEnabled = false
self.progressBar.isHidden = false
self.progressBar.progress = 0
// DFUモードに入る
self.device?.controlService?.writeCommand(.enterDFUMode)
// dfu更新フラグを消しておく
didEnterDFUmode = true
// 切断処理、デリゲートを設定
self.device!.manager.delegate = self
// self.device!.cancelConnection() // 自分から切断せず、デバイス側からの切断(DFUモードに入る)を待つ。
// この後のDFU更新処理は、BLEデバイスの切断イベントの中で継続する
// 5秒間でデバイスが発見できない場合は、アラート表示して、このVCを閉じる
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(5 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {
if !self.didStartingFirmwareUpdating {
self.device!.manager.stopScan()
self.showDialogAndDismiss("タイムアウト", message: "DFU更新を開始できませんでした。")
}
})
}
// CBCentralManager
func centralManagerDidUpdateState(_ central: CBCentralManager)
{
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
debugPrint("\(#function) \(peripheral)")
// デバイスとの接続切断、ペリフェラルを検索。DFU更新に入る
// DFU時はサービスUUIDをアドバタイジングしない。したがって、すべてのデバイスがスキャン対象。
self.device!.manager.scanForPeripherals(withServices: nil, options: nil)
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber)
{
// MAGIC WORD, DFUのアドバタイジング時のローカルネームで判定
if let localName = advertisementData[CBAdvertisementDataLocalNameKey] {
debugPrint("localName \(localName) peripheral:\(peripheral)")
if localName as! String == dfuAdvertisingName {
self.device!.manager.stopScan()
performDfu(peripheral)
}
}
}
// LoggerDelegate
func logWith(_ level:LogLevel, message:String)
{
debugPrint("\(#function) \(message)")
/*
dispatch_async(dispatch_get_main_queue(), {
self.dfuMessageTextLabel.text = message
})*/
}
// DFUServiceDelegate
func dfuStateDidChange(to state: DFUState) {
switch state {
case .connecting: break
case .starting: break
case .enablingDfuMode: break
case .uploading:
self.dfuMessageTextLabel.text = "Uploading"
case .validating:
self.dfuMessageTextLabel.text = "Validating"
case .disconnecting: break
case .completed:
showDialogAndDismiss("完了", message: "ファームウェア更新完了")
case .aborted:
showDialogAndDismiss("エラー", message: "アボート")
}
}
func dfuError(_ error: DFUError, didOccurWithMessage message: String)
{
debugPrint("\(#function) \(message)")
showDialogAndDismiss("エラー", message: message)
}
// DFUProgressDelegate
func dfuProgressDidChange(for part: Int, outOf totalParts: Int, to progress: Int, currentSpeedBytesPerSecond: Double, avgSpeedBytesPerSecond: Double) {
self.progressTextLabel.text = "\(progress)%"
self.progressBar.progress = Float(progress) / Float(100)
}
}
| mit | d48eb807d44b1540db2e38bb6b81c7a8 | 37.206731 | 155 | 0.65358 | 4.696809 | false | false | false | false |
mohamede1945/quran-ios | Quran/MoyaNetworkManager.swift | 1 | 2681 | //
// MoyaNetworkManager.swift
// Quran
//
// Created by Mohamed Afifi on 2/23/17.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import BatchDownloader
import Foundation
import Moya
import PromiseKit
import SwiftyJSON
class MoyaNetworkManager<Target>: NetworkManager {
private let provider: MoyaProvider<BackendServices>
private let parser: AnyParser<JSON, Target>
init(provider: MoyaProvider<BackendServices>, parser: AnyParser<JSON, Target>) {
self.provider = provider
self.parser = parser
}
func execute(_ service: BackendServices) -> Promise<Target> {
return Promise { fulfil, reject in
provider.request(service) { [weak self] result in
guard let `self` = self else { return }
do {
switch result {
case var .success(moyaResponse):
// only accept 2xx statuses
moyaResponse = try moyaResponse.filterSuccessfulStatusCodes()
// convert response to the object
let data = moyaResponse.data
let json = JSON(data: data) // convert network data to json
let object: Target = try self.parser.parse(json) // convert json to object
// notify the response
fulfil(object)
case let .failure(error):
throw error
}
} catch {
let finalError: Swift.Error
if let error = error as? MoyaError {
switch error {
case .underlying(let underlyingError):
finalError = NetworkError(error: underlyingError)
default:
finalError = NetworkError.unknown(error)
}
} else {
finalError = error
}
reject(finalError)
}
}
}
}
}
| gpl-3.0 | 22bf2b9cba12b50f86dfbfc7f05ff906 | 35.22973 | 98 | 0.55166 | 5.427126 | false | false | false | false |
AlbertWu0212/MyDailyTodo | MyDailyTodo/AllListsViewController.swift | 1 | 5062 | //
// AllListsViewController.swift
// MyDailyTodo
//
// Created by WuZhengBin on 16/7/4.
// Copyright © 2016年 WuZhengBin. All rights reserved.
//
import UIKit
class AllListsViewController: UITableViewController, ListDetailViewControllerDelegate, UINavigationControllerDelegate {
var dataModel: DataModel!
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
navigationController?.delegate = self
let index = dataModel.indexOfSelectedChecklist
if index >= 0 && index < dataModel.lists.count {
let checklist = dataModel.lists[index]
performSegueWithIdentifier("ShowChecklist", sender: checklist)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: UITableView Delegate & Datasource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataModel.lists.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = cellForTableView(tableView)
let checklist = dataModel.lists[indexPath.row]
cell.textLabel!.text = checklist.name
cell.accessoryType = .DetailDisclosureButton
let count = checklist.countUncheckedItems()
if checklist.items.count == 0 {
cell.detailTextLabel!.text = "No Items"
} else if count == 0 {
cell.detailTextLabel!.text = "All done!"
} else {
cell.detailTextLabel!.text = "\(checklist.countUncheckedItems()) Remaining"
}
cell.imageView!.image = UIImage(named: checklist.iconName)
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
dataModel.indexOfSelectedChecklist = indexPath.row
let checklist = dataModel.lists[indexPath.row]
performSegueWithIdentifier("ShowChecklist", sender: checklist)
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
dataModel.lists.removeAtIndex(indexPath.row)
let indexPaths = [indexPath]
tableView.deleteRowsAtIndexPaths(indexPaths, withRowAnimation: .Automatic)
}
override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
let navigationController = storyboard!.instantiateViewControllerWithIdentifier("ListDetailNavigationController") as! UINavigationController
let controller = navigationController.topViewController as! ListDetailViewController
controller.delegate = self
let checklist = dataModel.lists[indexPath.row]
controller.checklistToEdit = checklist
presentViewController(navigationController, animated: true, completion: nil)
}
// MARK: Segue
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ShowChecklist" {
let controller = segue.destinationViewController as! ChecklistViewController
controller.checklist = sender as! Checklist
} else if segue.identifier == "AddChecklist" {
let navigationController = segue.destinationViewController as! UINavigationController
let controller = navigationController.topViewController as! ListDetailViewController
controller.delegate = self
controller.checklistToEdit = nil
}
}
// MARK: Some private methods
func cellForTableView(tableView: UITableView) -> UITableViewCell {
let cellIdentifier = "cell"
if let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) {
return cell
} else {
return UITableViewCell(style: .Subtitle, reuseIdentifier: cellIdentifier)
}
}
// MARK: ListDetailViewControllerDelegate
func listDetailViewControllerDidCancel(controller: ListDetailViewController) {
dismissViewControllerAnimated(true, completion: nil)
}
func listDetailViewController(controller: ListDetailViewController, didFinishAddingChecklist checklist: Checklist) {
dataModel.lists.append(checklist)
dataModel.sortChecklist()
tableView.reloadData()
dismissViewControllerAnimated(true, completion: nil)
}
func listDetailViewController(controller: ListDetailViewController, didFinishEditingChecklist checklist: Checklist) {
dataModel.sortChecklist()
tableView.reloadData()
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: NavigationControllerDelegate
func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) {
if viewController == self {
dataModel.indexOfSelectedChecklist = -1
}
}
}
| mit | 09ca6869d1a25e7fa7bf6c5d7532b7bd | 32.726667 | 155 | 0.743625 | 5.742338 | false | false | false | false |
arvedviehweger/swift | stdlib/public/core/Mirror.swift | 1 | 34992 | //===--- 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
}
@_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.Iterator.Element == Child,
// FIXME(ABI)#47 (Associated Types with where clauses): these constraints should be applied to
// associated types of Collection.
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
) where
// FIXME(ABI)#48 (Associated Types with where clauses): these constraints should be applied to
// associated types of Collection.
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({ IntMax($0) }) ?? (e as? IntMax) {
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)"
///
/// - SeeAlso: `String.init<Subject>(reflecting: Subject)`
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)"
///
/// - SeeAlso: `String.init<Subject>(Subject)`
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 | ff58f7e449ac33f3dfcb6cef3e48c3fb | 36.384615 | 106 | 0.662723 | 4.711458 | false | false | false | false |
dnevera/ImageMetalling | ImageMetalling-16/ImageMetalling-16/Classes/Filters/IMPPlaneFilter.swift | 1 | 8674 | //
// IMPColorPlaneFilter.swift
// ImageMetalling-16
//
// Created by denis svinarchuk on 12.06.2018.
// Copyright © 2018 ImageMetalling. All rights reserved.
//
import Foundation
import IMProcessing
public class IMPCommonPlaneFilter: IMPFilter {
public var rgb:float3 {
set{
reference = space.from(.rgb, value: newValue)
}
get {
return space.to(.rgb, value: reference)
}
}
public var reference:float3 = float3(0) {
didSet{
dirty = true
}
}
public var space:IMPColorSpace = .rgb {
didSet{
reference = space.from(oldValue, value: reference)
dirty = true
}
}
public var spaceChannels:(Int,Int) = (0,1) { didSet{ dirty = true } }
public override func configure(complete: IMPFilter.CompleteHandler?) {
super.extendName(suffix: "Common Plane")
super.configure(complete: complete)
}
}
public class IMPMSLPlaneFilter: IMPCommonPlaneFilter {
public typealias Controls=MLSControls
public var controls:Controls = Controls(p: [], q: []) {
didSet{
let length = MemoryLayout<float2>.size * self.controls.p.count
if self.pBuffer.length == length {
memcpy(self.pBuffer.contents(), self.controls.p, length)
memcpy(self.qBuffer.contents(), self.controls.q, length)
}
else {
self.pBuffer = self.context.device.makeBuffer(
bytes: self.controls.p,
length: length,
options: [])!
self.qBuffer = self.context.device.makeBuffer(
bytes: self.controls.q,
length: length,
options: [])!
}
dirty = true
}
}
public var kernelName:String {
return "kernel_mlsPlaneTransform"
}
override public func configure(complete: IMPFilter.CompleteHandler?) {
super.extendName(suffix: "MLS Plane Filter")
super.configure(complete: nil)
let ci = NSImage(color:NSColor.darkGray, size:NSSize(width: 16, height: 16))
source = IMPImage(context: context, image: ci)
let kernel = IMPFunction(context: self.context, kernelName: kernelName)
kernel.optionsHandler = {(shader, commandEncoder, input, output) in
commandEncoder.setBytes(&self.reference,
length: MemoryLayout.size(ofValue: self.reference),
index: 0)
var index = self.space.index
commandEncoder.setBytes(&index,
length: MemoryLayout.size(ofValue: index),
index: 1)
var pIndices = uint2(UInt32(self.spaceChannels.0),UInt32(self.spaceChannels.1))
commandEncoder.setBytes(&pIndices,
length: MemoryLayout.size(ofValue: pIndices),
index: 2)
commandEncoder.setBuffer(self.pBuffer,
offset: 0,
index: 3)
commandEncoder.setBuffer(self.qBuffer,
offset: 0,
index: 4)
var count = self.controls.p.count
commandEncoder.setBytes(&count,
length: MemoryLayout.stride(ofValue: count),
index: 5)
var kind = self.controls.kind
commandEncoder.setBytes(&kind,
length: MemoryLayout.stride(ofValue: kind),
index: 6)
var alpha = self.controls.alpha
commandEncoder.setBytes(&alpha,
length: MemoryLayout.stride(ofValue: alpha),
index: 7)
}
add(function: kernel) { (image) in
complete?(image)
}
}
private lazy var pBuffer:MTLBuffer = self.context.device.makeBuffer(length: MemoryLayout.size(ofValue: [float2]()), options:[])!
private lazy var qBuffer:MTLBuffer = self.context.device.makeBuffer(length: MemoryLayout.size(ofValue: [float2]()), options:[])!
}
public class IMPMSLLutFilter: IMPMSLPlaneFilter {
public override var kernelName:String {
return "kernel_mlsLutTransform"
}
public var cLut:IMPCLut!
override public func configure(complete: IMPFilter.CompleteHandler?) {
super.extendName(suffix: "MLS Lut Filter")
super.configure(complete: nil)
source = identityLut
cLut = try! IMPCLut(context: context, lutType: .lut_2d, lutSize: 64, format: .float)
addObserver(destinationUpdated: { image in
do {
try self.cLut.update(from: image)
}
catch let error {
Swift.print("IMPMSLLutFilter error: \(error)")
}
})
}
private lazy var identityLut:IMPCLut =
try! IMPCLut(context: context, lutType: .lut_2d, lutSize: 64, format: .float)
}
extension IMPCommonPlaneFilter {
public func planeCoord(for color: float3) -> float2 {
let xyz01 = IMPColorSpace.rgb.toNormalized(space, value: color)
return float2(xyz01[self.spaceChannels.0],xyz01[self.spaceChannels.1])
}
}
public extension NSImage {
public func resize(factor level: CGFloat) -> NSImage {
let _image = self
let newRect: NSRect = NSMakeRect(0, 0, _image.size.width, _image.size.height)
let imageSizeH: CGFloat = _image.size.height * level
let imageSizeW: CGFloat = _image.size.width * level
let newImage = NSImage(size: NSMakeSize(imageSizeW, imageSizeH))
newImage.lockFocus()
NSGraphicsContext.current?.imageInterpolation = NSImageInterpolation.medium
_image.draw(in: NSMakeRect(0, 0, imageSizeW, imageSizeH), from: newRect, operation: .sourceOver, fraction: 1)
newImage.unlockFocus()
return newImage
}
convenience init(color: NSColor, size: NSSize) {
self.init(size: size)
lockFocus()
color.drawSwatch(in: NSMakeRect(0, 0, size.width, size.height))
unlockFocus()
}
public static var typeExtensions:[String] {
return NSImage.imageTypes.map { (name) -> String in
return name.components(separatedBy: ".").last!
}
}
public class func getMeta(contentsOf url: URL) -> [String: AnyObject]? {
guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }
guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [String: AnyObject] else { return nil }
return properties
}
public class func getSize(contentsOf url: URL) -> NSSize? {
guard let properties = NSImage.getMeta(contentsOf: url) else { return nil }
if let w = properties[kCGImagePropertyPixelWidth as String]?.floatValue,
let h = properties[kCGImagePropertyPixelHeight as String]?.floatValue {
return NSSize(width: w.cgfloat, height: h.cgfloat)
}
return nil
}
public class func thumbNail(contentsOf url: URL, size max: Int) -> NSImage? {
guard let imageSource = CGImageSourceCreateWithURL(url as CFURL, nil) else { return nil }
let options = [
kCGImageSourceShouldAllowFloat as String: true as NSNumber,
kCGImageSourceCreateThumbnailWithTransform as String: false as NSNumber,
kCGImageSourceCreateThumbnailFromImageAlways as String: true as NSNumber,
kCGImageSourceThumbnailMaxPixelSize as String: max as NSNumber
] as CFDictionary
guard let thumbnail = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options) else { return nil }
return NSImage(cgImage: thumbnail, size: NSSize(width: max, height: max))
}
}
| mit | 98601a0e88d3ab9c49885ef97bedd003 | 35.75 | 135 | 0.546754 | 4.995968 | false | false | false | false |
jemartti/OnTheMap | OnTheMap/BorderedButton.swift | 1 | 2627 | //
// BorderedButton.swift
// OnTheMap
//
// Created by Jarrod Parkes on 1/23/15.
// Copyright (c) 2015 Udacity. All rights reserved.
//
import UIKit
// MARK: - BorderedButton: Button
class BorderedButton: UIButton {
// MARK: Properties
// constants for styling and configuration
let darkerBlue = UIColor(red: 0.0, green: 0.298, blue: 0.686, alpha:1.0)
let lighterBlue = UIColor(red: 0.0, green:0.502, blue:0.839, alpha: 1.0)
let titleLabelFontSize: CGFloat = 17.0
let borderedButtonHeight: CGFloat = 44.0
let borderedButtonCornerRadius: CGFloat = 4.0
let phoneBorderedButtonExtraPadding: CGFloat = 14.0
var backingColor: UIColor? = nil
var highlightedBackingColor: UIColor? = nil
// MARK: Initialization
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
themeBorderedButton()
}
override init(frame: CGRect) {
super.init(frame: frame)
themeBorderedButton()
}
private func themeBorderedButton() {
layer.masksToBounds = true
layer.cornerRadius = borderedButtonCornerRadius
highlightedBackingColor = darkerBlue
backingColor = lighterBlue
backgroundColor = lighterBlue
setTitleColor(.white, for: UIControlState())
titleLabel?.font = UIFont.systemFont(ofSize: titleLabelFontSize)
}
// MARK: Setters
private func setBackingColor(_ newBackingColor: UIColor) {
if let _ = backingColor {
backingColor = newBackingColor
backgroundColor = newBackingColor
}
}
private func setHighlightedBackingColor(_ newHighlightedBackingColor: UIColor) {
highlightedBackingColor = newHighlightedBackingColor
backingColor = highlightedBackingColor
}
// MARK: Tracking
override func beginTracking(_ touch: UITouch, with withEvent: UIEvent?) -> Bool {
backgroundColor = highlightedBackingColor
return true
}
override func endTracking(_ touch: UITouch?, with event: UIEvent?) {
backgroundColor = backingColor
}
override func cancelTracking(with event: UIEvent?) {
backgroundColor = backingColor
}
// MARK: Layout
override func sizeThatFits(_ size: CGSize) -> CGSize {
let extraButtonPadding : CGFloat = phoneBorderedButtonExtraPadding
var sizeThatFits = CGSize.zero
sizeThatFits.width = super.sizeThatFits(size).width + extraButtonPadding
sizeThatFits.height = borderedButtonHeight
return sizeThatFits
}
}
| mit | f8d813d8647409bfacc680918eca942c | 28.852273 | 85 | 0.660069 | 5.254 | false | false | false | false |
Johennes/firefox-ios | Account/FxADeviceRegistration.swift | 1 | 7991 | /* 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 Deferred
import Shared
private let log = Logger.syncLogger
/// The current version of the device registration. We use this to re-register
/// devices after we update what we send on device registration.
private let DeviceRegistrationVersion = 1
public enum FxADeviceRegistrationResult {
case Registered
case Updated
case AlreadyRegistered
}
public enum FxADeviceRegistratorError: MaybeErrorType {
case AccountDeleted
case CurrentDeviceNotFound
case InvalidSession
case UnknownDevice
public var description: String {
switch self {
case AccountDeleted: return "Account no longer exists."
case CurrentDeviceNotFound: return "Current device not found."
case InvalidSession: return "Session token was invalid."
case UnknownDevice: return "Unknown device."
}
}
}
public class FxADeviceRegistration: NSObject, NSCoding {
/// The device identifier identifying this device. A device is uniquely identified
/// across the lifetime of a Firefox Account.
let id: String
/// The version of the device registration. We use this to re-register
/// devices after we update what we send on device registration.
let version: Int
/// The last time we successfully (re-)registered with the server.
let lastRegistered: Timestamp
init(id: String, version: Int, lastRegistered: Timestamp) {
self.id = id
self.version = version
self.lastRegistered = lastRegistered
}
public convenience required init(coder: NSCoder) {
let id = coder.decodeObjectForKey("id") as! String
let version = coder.decodeObjectForKey("version") as! Int
let lastRegistered = (coder.decodeObjectForKey("lastRegistered") as! NSNumber).unsignedLongLongValue
self.init(id: id, version: version, lastRegistered: lastRegistered)
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(id, forKey: "id")
aCoder.encodeObject(version, forKey: "version")
aCoder.encodeObject(NSNumber(unsignedLongLong: lastRegistered), forKey: "lastRegistered")
}
}
public class FxADeviceRegistrator {
public static func registerOrUpdateDevice(account: FirefoxAccount, sessionToken: NSData, client: FxAClient10? = nil) -> Deferred<Maybe<FxADeviceRegistrationResult>> {
// If we've already registered, the registration version is up-to-date, *and* we've (re-)registered
// within the last week, do nothing. We re-register weekly as a sanity check.
if let registration = account.deviceRegistration
where registration.version == DeviceRegistrationVersion &&
NSDate.now() < registration.lastRegistered + OneWeekInMilliseconds {
return deferMaybe(FxADeviceRegistrationResult.AlreadyRegistered)
}
let client = client ?? FxAClient10(endpoint: account.configuration.authEndpointURL)
let name = DeviceInfo.defaultClientName()
let device: FxADevice
let registrationResult: FxADeviceRegistrationResult
if let registration = account.deviceRegistration {
device = FxADevice.forUpdate(name, id: registration.id)
registrationResult = FxADeviceRegistrationResult.Updated
} else {
device = FxADevice.forRegister(name, type: "mobile")
registrationResult = FxADeviceRegistrationResult.Registered
}
let registeredDevice = client.registerOrUpdateDevice(sessionToken, device: device)
let registration: Deferred<Maybe<FxADeviceRegistration>> = registeredDevice.bind { result in
if let device = result.successValue {
return deferMaybe(FxADeviceRegistration(id: device.id!, version: DeviceRegistrationVersion, lastRegistered: NSDate.now()))
}
// Recover from the error -- if we can.
if let error = result.failureValue as? FxAClientError,
case .Remote(let remoteError) = error {
switch (remoteError.code) {
case FxAccountRemoteError.DeviceSessionConflict:
return recoverFromDeviceSessionConflict(account, client: client, sessionToken: sessionToken)
case FxAccountRemoteError.InvalidAuthenticationToken:
return recoverFromTokenError(account, client: client)
case FxAccountRemoteError.UnknownDevice:
return recoverFromUnknownDevice(account)
default: break
}
}
// Not an error we can recover from. Rethrow it and fall back to the failure handler.
return deferMaybe(result.failureValue!)
}
// Post-recovery. We either registered or we didn't, but update the account either way.
return registration.bind { result in
switch result {
case .Success(let registration):
account.deviceRegistration = registration.value
return deferMaybe(registrationResult)
case .Failure(let error):
log.error("Device registration failed: \(error.description)")
if let registration = account.deviceRegistration {
account.deviceRegistration = FxADeviceRegistration(id: registration.id, version: 0, lastRegistered: registration.lastRegistered)
}
return deferMaybe(error)
}
}
}
private static func recoverFromDeviceSessionConflict(account: FirefoxAccount, client: FxAClient10, sessionToken: NSData) -> Deferred<Maybe<FxADeviceRegistration>> {
// FxA has already associated this session with a different device id.
// Perhaps we were beaten in a race to register. Handle the conflict:
// 1. Fetch the list of devices for the current user from FxA.
// 2. Look for ourselves in the list.
// 3. If we find a match, set the correct device id and device registration
// version on the account data and return the correct device id. At next
// sync or next sign-in, registration is retried and should succeed.
log.warning("Device session conflict. Attempting to find the current device ID…")
return client.devices(sessionToken) >>== { response in
guard let currentDevice = response.devices.find({ $0.isCurrentDevice }) else {
return deferMaybe(FxADeviceRegistratorError.CurrentDeviceNotFound)
}
return deferMaybe(FxADeviceRegistration(id: currentDevice.id!, version: 0, lastRegistered: NSDate.now()))
}
}
private static func recoverFromTokenError(account: FirefoxAccount, client: FxAClient10) -> Deferred<Maybe<FxADeviceRegistration>> {
return client.status(account.uid) >>== { status in
if !status.exists {
// TODO: Should be in an "I have an iOS account, but the FxA is gone." state.
// This will do for now...
account.makeDoghouse()
return deferMaybe(FxADeviceRegistratorError.AccountDeleted)
}
account.makeDoghouse()
return deferMaybe(FxADeviceRegistratorError.InvalidSession)
}
}
private static func recoverFromUnknownDevice(account: FirefoxAccount) -> Deferred<Maybe<FxADeviceRegistration>> {
// FxA did not recognize the device ID. Handle it by clearing the registration on the account data.
// At next sync or next sign-in, registration is retried and should succeed.
log.warning("Unknown device ID. Clearing the local device data.")
account.deviceRegistration = nil
return deferMaybe(FxADeviceRegistratorError.UnknownDevice)
}
} | mpl-2.0 | ee4cf27d09bd5d158dc643cf49bc103f | 46 | 170 | 0.675804 | 5.376178 | false | false | false | false |
yangyueguang/MyCocoaPods | tools/PreViewController.swift | 1 | 7037 | //
// PreViewTool.swift
import UIKit
import QuickLook
import SnapKit
@objcMembers
open class PreviewItem: NSObject,QLPreviewItem {
public var previewItemURL: URL?
public var previewItemTitle:String?
init(url:URL,title itemTitle:String?){
previewItemURL = url
previewItemTitle = itemTitle!;
super.init()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
@objcMembers
open class PreviewController: QLPreviewController,UIDocumentInteractionControllerDelegate ,QLPreviewControllerDataSource,QLPreviewControllerDelegate,UIWebViewDelegate{
let documentController = UIDocumentInteractionController()
let webView = UIWebView()
var containerVC :UIViewController!
var previewRecorces = [CRResource]()
public static let service = PreviewController()
override open func viewDidLoad() {
super.viewDidLoad()
}
deinit {
print("销毁预览")
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let res = previewRecorces.first{
self.title = res.name
}
}
override open func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
clearAllNotice()
}
@objc private func tapGesture(){
self.navigationController?.isNavigationBarHidden = !(self.navigationController?.isNavigationBarHidden)!
}
///除了quickView,其它的都只能打开一个文件
func preView(_ sources:[CRResource],_ vc:UIViewController,quickView isQuick:Bool,inMenu isInMenu:Bool){
self.previewRecorces = sources
self.containerVC = vc
webView.isHidden = true
let res = sources.first!
if !FileManager.default.fileExists(atPath: res.path){//本地没有则选用网络webview加载方式
if res.type == .pdf || res.type == .unknown{
noticeInfo("该文件不支持预览\n请先下载")
return
}
guard let _ = webView.superview else{
webView.delegate = self
webView.scrollView.bounces = false
webView.scalesPageToFit = true
webView.scrollView.isScrollEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(tapGesture))
tap.numberOfTapsRequired = 1
tap.numberOfTouchesRequired = 2
webView.isUserInteractionEnabled = true
webView.addGestureRecognizer(tap);
view.addSubview(webView)
webView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
return
}
self.previewRecorces.removeAll()
self.reloadData()
webView.loadRequest(URLRequest(url:URL(string: res.url)!))
if let nav = vc.navigationController{
nav.pushViewController(self, animated: true)
}else{
vc.present(self, animated: true) {
}
}
}else if isQuick && res.type != .unknown{//快速预览模式
self.dataSource = self
self.delegate = self
self.reloadData()
if let nav = vc.navigationController{
nav.pushViewController(self, animated: true)
}else{
vc.present(self, animated: true) {}
}
}else{
documentController.url = URL(fileURLWithPath:res.path)
documentController.delegate = self
documentController.name = res.name
documentController.uti = res.type.UTI().1
if isInMenu || res.type == .unknown{//用文档打开的按钮选择模式
documentController.presentOptionsMenu(from: CGRect(x: 0, y: 0, width: APPW, height: 100), in: containerVC.view, animated: true)
}else{//用文档直接打开模式
documentController.presentPreview(animated: true)
}
}
}
///FIXME: QuickViewDelegate
public func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
return previewRecorces.count
}
public func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
let res = previewRecorces[index]
return PreviewItem(url:URL(fileURLWithPath: res.path), title: res.name)
}
public func previewController(_ controller: QLPreviewController, frameFor item: QLPreviewItem, inSourceView view: AutoreleasingUnsafeMutablePointer<UIView?>) -> CGRect {
return CGRect(x: 0, y: 0, width: APPW, height: 200)
}
///FIXME: UIDocumentDelegate
public func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return containerVC
}
public func documentInteractionControllerViewForPreview(_ controller: UIDocumentInteractionController) -> UIView? {
return containerVC.view
}
public func documentInteractionControllerRectForPreview(_ controller: UIDocumentInteractionController) -> CGRect {
return containerVC.view.frame
}
public func documentInteractionControllerWillBeginPreview(_ controller: UIDocumentInteractionController) {
}
public func documentInteractionControllerDidEndPreview(_ controller: UIDocumentInteractionController) {
}
public func documentInteractionControllerWillPresentOpenInMenu(_ controller: UIDocumentInteractionController) {
}
public func documentInteractionControllerDidDismissOpenInMenu(_ controller: UIDocumentInteractionController) {
}
public func documentInteractionControllerWillPresentOptionsMenu(_ controller: UIDocumentInteractionController) {
}
public func documentInteractionControllerDidDismissOptionsMenu(_ controller: UIDocumentInteractionController) {
}
public func documentInteractionController(_ controller: UIDocumentInteractionController, willBeginSendingToApplication application: String?) {
noticeInfo("正在加载...")
}
public func documentInteractionController(_ controller: UIDocumentInteractionController, didEndSendingToApplication application: String?) {
clearAllNotice()
}
///FIXME: webViewDelegate
public func webViewDidStartLoad(_ webView: UIWebView) {
noticeInfo("正在加载...")
}
public func webViewDidFinishLoad(_ webView: UIWebView) {
self.webView.isHidden = false
clearAllNotice()
}
public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
noticeInfo("加载失败,请稍后重试")
}
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard self.containerVC.navigationController != nil else {
self.dismiss(animated: true) {}
return;
}
}
}
| mit | 7128a9b0c1aa8a212cde5c8d45d6ccd1 | 36.895028 | 173 | 0.663362 | 5.590057 | false | false | false | false |
giangbvnbgit128/AnViet | AnViet/Class/ViewControllers/TutorialViewController/AVTutorialViewController.swift | 1 | 4010 | //
// AVTutorialViewController.swift
// AnViet
//
// Created by Bui Giang on 5/25/17.
// Copyright © 2017 Bui Giang. All rights reserved.
//
import UIKit
class AVTutorialViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var btnRegis: UIButton!
@IBOutlet weak var btnLogin: UIButton!
@IBOutlet weak var pageControl: UIPageControl!
let arrayImage:[String] = ["tutorial1","tutorial1","tutorial2","tutorial3",
"tutorial4","tutorial1","tutorial1","tutorial0"]
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView.dataSource = self
self.collectionView.delegate = self
self.collectionView.registerNib(AVTutorialCollectionViewCell.self)
self.automaticallyAdjustsScrollViewInsets = false
self.pageControl.currentPage = 0
self.btnLogin.layer.cornerRadius = 4
self.btnRegis.layer.cornerRadius = 4
self.pageControl.numberOfPages = arrayImage.count
navigationController?.navigationBar.isTranslucent = false
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func movePageControlWithScroll () {
let pageWidth = collectionView.frame.width
let page = Int(floor((collectionView.contentOffset.x - pageWidth / 2) / pageWidth) + 1)
if pageControl.currentPage != page {
self.pageControl.currentPage = page
}
}
@IBAction func actionLogin(_ sender: AnyObject) {
let logicVC = AVLoginViewController()
navigationController?.pushViewController(logicVC, animated: true)
}
@IBAction func actionRegis(_ sender: AnyObject) {
let regisVC = AVRegisterAccountAccountViewController()
navigationController?.pushViewController(regisVC, animated: true)
}
}
extension AVTutorialViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.arrayImage.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeue(AVTutorialCollectionViewCell.self, forIndexPath: indexPath) as AVTutorialCollectionViewCell
cell.ConfigCell(nameImage: self.arrayImage[indexPath.row])
return cell
}
}
extension AVTutorialViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return UIScreen.main.bounds.size
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0.1
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0.1
}
}
extension AVTutorialViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
movePageControlWithScroll()
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
movePageControlWithScroll()
}
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
print("====Scroll \(scrollView.contentOffset.x) prin y = \(scrollView.contentOffset.y)")
}
}
| apache-2.0 | 3cdb13ccf63d110959d7830975c82551 | 37.548077 | 133 | 0.700923 | 5.662429 | false | false | false | false |
apple/swift-format | Sources/SwiftFormat/Exports.swift | 1 | 874 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftFormatCore
// The `SwiftFormatCore` module isn't meant for public use, but these types need to be since they
// are also part of the public `SwiftFormat` API. Use public typealiases to "re-export" them for
// now.
public typealias Finding = SwiftFormatCore.Finding
public typealias FindingCategorizing = SwiftFormatCore.FindingCategorizing
| apache-2.0 | 7cae5071b5a6ec723ed83bbc97e51e92 | 42.7 | 97 | 0.629291 | 4.965909 | false | false | false | false |
ahmad-raza/QDStepsController | Pod/Classes/UIColorExtensions.swift | 1 | 1363 | //
// UIColorExtensions.swift
// AttendanceSystem
//
// Created by Ahmad Raza on 11/23/15.
// Copyright © 2015 Qadib. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
convenience init(hexString: String) {
let hex = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet)
var int = UInt32()
NSScanner(string: hex).scanHexInt(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
default:
(a, r, g, b) = (1, 1, 1, 0)
}
self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
}
extension UIView {
func roundCorners(corners:UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.CGPath
self.layer.mask = mask
}
} | mit | 9d0ccf27d5f00ce9ebbb8a6b3a768e0d | 33.948718 | 137 | 0.574156 | 3.379653 | false | false | false | false |
practicalswift/swift | validation-test/Evolution/test_backward_deploy_top_level.swift | 4 | 422 | // RUN: %target-resilience-test --backward-deployment
// REQUIRES: executable_test
import StdlibUnittest
import backward_deploy_top_level
var BackwardDeployTopLevelTest = TestSuite("BackwardDeployTopLevel")
BackwardDeployTopLevelTest.test("TopLevel") {
if getVersion() == 1 {
topLevelFunction(storedGlobal)
topLevelFunction(computedGlobal)
storedGlobal += 1
computedGlobal += 1
}
}
runAllTests()
| apache-2.0 | 40fbb4070d9e0587836bdd99a67e2d2c | 20.1 | 68 | 0.755924 | 4.350515 | false | true | false | false |
cikelengfeng/HTTPIDL | Sources/Runtime/RequestContent.swift | 1 | 6454 | //
// RequestContent.swift
// everfilter
//
// Created by 徐 东 on 2017/1/2//
import Foundation
public protocol RequestContentKeyType {
func asHTTPParamterKey() -> String
}
public protocol RequestContentConvertible {
func asRequestContent() -> RequestContent
}
public enum RequestContent {
case number(value: NSNumber)
case string(value: String)
case file(value: URL, fileName: String?, mimeType: String?)
case data(value: Data, fileName: String?, mimeType: String?)
case array(value: [RequestContent])
case dictionary(value: [String: RequestContent])
}
extension Int64: RequestContentKeyType {
public func asHTTPParamterKey() -> String {
return String(self)
}
}
extension Int64: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
return .number(value: NSNumber(value: self))
}
}
extension UInt64: RequestContentKeyType {
public func asHTTPParamterKey() -> String {
return String(self)
}
}
extension UInt64: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
return .number(value: NSNumber(value: self))
}
}
extension Int: RequestContentKeyType {
public func asHTTPParamterKey() -> String {
return String(self)
}
}
extension Int: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
return .number(value: NSNumber(value: self))
}
}
extension UInt: RequestContentKeyType {
public func asHTTPParamterKey() -> String {
return String(self)
}
}
extension UInt: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
return .number(value: NSNumber(value: self))
}
}
extension Int32: RequestContentKeyType {
public func asHTTPParamterKey() -> String {
return String(self)
}
}
extension Int32: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
return .number(value: NSNumber(value: self))
}
}
extension UInt32: RequestContentKeyType {
public func asHTTPParamterKey() -> String {
return String(self)
}
}
extension UInt32: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
return .number(value: NSNumber(value: self))
}
}
extension Bool: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
return .number(value: NSNumber(value: self))
}
}
extension Double: RequestContentKeyType {
public func asHTTPParamterKey() -> String {
return String(self)
}
}
extension Double: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
return .number(value: NSNumber(value: self))
}
}
extension String: RequestContentKeyType {
public func asHTTPParamterKey() -> String {
return self
}
}
extension String: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
return .string(value: self)
}
}
extension NSString: RequestContentKeyType {
public func asHTTPParamterKey() -> String {
return self as String
}
}
extension NSString: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
return .string(value: self as String)
}
}
extension NSNumber: RequestContentKeyType {
public func asHTTPParamterKey() -> String {
return self.stringValue
}
}
extension NSNumber: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
return .number(value: self)
}
}
extension Array where Element: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
let value = self.map ({ (convertible) in
return convertible.asRequestContent()
})
return .array(value: value)
}
}
extension Array where Element == RequestContentConvertible {
public func asRequestContent() -> RequestContent {
let value = self.map ({ (convertible) in
return convertible.asRequestContent()
})
return .array(value: value)
}
}
extension Array: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
let value = self.compactMap { (element) -> RequestContent? in
guard let convertible = element as? RequestContentConvertible else {
assertionFailure("request content value: \(element) in Array must adopt RequestContentConvertible protocol!")
return nil
}
return convertible.asRequestContent()
}
return .array(value: value)
}
}
extension Dictionary where Key: RequestContentKeyType, Value: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
let value = self.reduce([String: RequestContent]()) { (soFar, soGood) -> [String: RequestContent] in
var result = soFar
result[soGood.key.asHTTPParamterKey()] = soGood.value.asRequestContent()
return result
}
return .dictionary(value: value)
}
}
extension Dictionary where Key: RequestContentKeyType, Value == RequestContentConvertible {
public func asRequestContent() -> RequestContent {
let value = self.reduce([String: RequestContent]()) { (soFar, soGood) -> [String: RequestContent] in
var result = soFar
result[soGood.key.asHTTPParamterKey()] = soGood.value.asRequestContent()
return result
}
return .dictionary(value: value)
}
}
extension Dictionary: RequestContentConvertible {
public func asRequestContent() -> RequestContent {
let value = self.reduce([String: RequestContent]()) { (soFar, soGood) -> [String: RequestContent] in
guard let key = soGood.key as? RequestContentKeyType else {
assert(false, "request content key:\(soGood.key) must adopt RequestContentKeyType protocol!")
return soFar
}
guard let value = soGood.value as? RequestContentConvertible else {
assert(false, "request content value:\(soGood.value) must adopt RequestContentConvertible protocol!")
return soFar
}
var result = soFar
result[key.asHTTPParamterKey()] = value.asRequestContent()
return result
}
return .dictionary(value: value)
}
}
| mit | 5f94f1bc6a0eb31755065acc1be8075d | 27.794643 | 125 | 0.667597 | 5.176565 | false | false | false | false |
toshiapp/toshi-ios-client | Toshi/APIClients/HeaderGenerator.swift | 1 | 7902 | // Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import Foundation
import EtherealCereal
enum HeaderGenerationError: Error {
case
/// The data provided could not be transformed into a string for hashing and signing.
couldNotCreatePayloadString,
/// The dictionary provided could not be serialized
couldNotSerializePayloadDictionary
}
struct HeaderGenerator {
private static var testingCereal: Cereal?
static func defaultCereal() -> Cereal {
guard testingCereal == nil else {
return testingCereal!
}
return Cereal.shared
}
static func setTestingCereal(_ cereal: Cereal) {
testingCereal = cereal
}
static func clearTestingCereal() {
testingCereal = nil
}
enum HTTPMethod: String {
case
GET,
PUT,
POST
}
enum HeaderField: String {
case
address = "Toshi-ID-Address",
contentLength = "Content-Length",
contentType = "Content-Type",
signature = "Toshi-Signature",
timestamp = "Toshi-Timestamp"
static func headers(address: String, signature: String, timestamp: String) -> [String: String] {
return [
self.address.rawValue: address,
self.signature.rawValue: signature,
self.timestamp.rawValue: timestamp
]
}
}
/// Creates signed headers from a Dictionary.
///
/// - Parameters:
/// - timestamp: The timestamp to use when creating a header
/// - path: The path you're sending this data to
/// - method: The `HTTPMethod` you're using to send this data. Defaults to `POST`.
/// - cereal: The cereal to use for signing. Defaults to the shared Cereal.
/// - payloadDictionary: The dictionary of data being sent to the server.
/// - Returns: A dictionary of string keys and string values which can be passed through as headers.
/// - Throws: see `HeaderGenerationError`
static func createHeaders(timestamp: String,
path: String,
method: HTTPMethod = .POST,
cereal: Cereal = defaultCereal(),
payloadDictionary: [String: Any]) throws -> [String: String] {
guard let data = try? JSONSerialization.data(withJSONObject: payloadDictionary, options: []) else {
throw HeaderGenerationError.couldNotSerializePayloadDictionary
}
return try createHeaders(timestamp: timestamp,
path: path,
method: method,
cereal: cereal,
payloadData: data)
}
/// Creates signed headers from serialized JSON Data.
///
/// - Parameters:
/// - timestamp: The timestamp to use when creating a header
/// - path: The path you're sending this data to
/// - method: The `HTTPMethod` you're using to send this data. Defaults to `POST`
/// - cereal: The cereal to use for signing. Defaults to the shared Cereal.
/// - payloadData: The JSON data being sent to the server.
/// - Returns: A dictionary of string keys and string values which can be passed through as headers.
/// - Throws: see `HeaderGenerationError`
static func createHeaders(timestamp: String,
path: String,
method: HTTPMethod = .POST,
cereal: Cereal = defaultCereal(),
payloadData: Data) throws -> [String: String] {
guard let payloadString = String(data: payloadData, encoding: .utf8) else {
throw HeaderGenerationError.couldNotCreatePayloadString
}
return createHeaders(payloadString: payloadString,
path: path,
method: method,
timestamp: timestamp,
cereal: cereal)
}
private static func createHeaders(payloadString: String,
path: String,
method: HTTPMethod,
timestamp: String,
cereal: Cereal) -> [String: String] {
let hashedPayload = cereal.sha3WithID(string: payloadString)
let message = "\(method.rawValue)\n\(path)\n\(timestamp)\n\(hashedPayload)"
let signature = "0x\(cereal.signWithID(message: message))"
return HeaderField.headers(address: cereal.address,
signature: signature,
timestamp: timestamp)
}
/// Creates headers for requests uploading multipart data.
///
/// - Parameters:
/// - boundary: The boundary string between the parts of the data.
/// - path: The path the data is being uploaded to
/// - timestamp: The timestamp to use when creating a header
/// - payload: The data being sent as multipart data (with boundaries already included)
/// - method: The HTTPMethod being used to send the data. Defaults to `.POST`
/// - cereal: The cereal to use for signing. Defaults to the shared Cereal.
/// - Returns: The headers for your multipart request.
static func createMultipartHeaders(boundary: String,
path: String,
timestamp: String,
payload: Data,
method: HTTPMethod = .POST,
cereal: Cereal = defaultCereal()) -> [String: String] {
let hashedPayload = cereal.sha3WithID(data: payload)
let signature = "0x\(cereal.signWithID(message: "\(method.rawValue)\n\(path)\n\(timestamp)\n\(hashedPayload)"))"
var headers = HeaderField.headers(address: cereal.address,
signature: signature,
timestamp: timestamp)
headers[HeaderField.contentLength.rawValue] = String(describing: payload.count)
headers[HeaderField.contentType.rawValue] = "multipart/form-data; boundary=\(boundary)"
return headers
}
/// Creates a simple signature header for a GET request
///
/// - Parameters:
/// - path: The path you're requesting the GET from
/// - cereal: The cereal to use for signing. Defaults to the shared cereal.
/// - timestamp: The timestamp to use when creating a header
/// - Returns: A dictionary of string keys and string values which can be passed through as headers.
static func createGetSignatureHeaders(path: String,
cereal: Cereal = defaultCereal(),
timestamp: String) -> [String: String] {
let signature = "0x\(cereal.signWithID(message: "\(HTTPMethod.GET.rawValue)\n\(path)\n\(timestamp)\n"))"
return HeaderField.headers(address: cereal.address,
signature: signature,
timestamp: timestamp)
}
}
| gpl-3.0 | 88fd1b3be8371725053cbeaeeba17e22 | 42.180328 | 120 | 0.579727 | 5.289157 | false | false | false | false |
finder39/resumod | Resumod/SkillsModel.swift | 1 | 779 | //
// SkillsModel.swift
// Resumod
//
// Created by Joseph Neuman on 7/18/14.
// Copyright (c) 2014 Joseph Neuman. All rights reserved.
//
import Foundation
class SkillModel {
var name:String = "" // e.g. We Developement
var level:String = "" // e.g. Master
var keywords:[String] = [] // List some keywords pertaining to this skill e.g. HTML
init() {
}
init(fromJSONData json:Dictionary<String, AnyObject>) {
if let name = (json["name"] as AnyObject?) as? String {
self.name = name
}
if let level = (json["level"] as AnyObject?) as? String {
self.level = level
}
if let keywords = (json["keywords"] as AnyObject?) as? [String] {
for keyword in keywords {
self.keywords.append(keyword)
}
}
}
} | mit | 9c21f1e272f6aaa94425fcff248a1acd | 22.636364 | 85 | 0.608472 | 3.573394 | false | false | false | false |
iOSWizards/AwesomeMedia | Example/Pods/Mixpanel-swift/Mixpanel/TweakPersistency.swift | 1 | 6928 | //
// TweakPersistency.swift
// SwiftTweaks
//
// Created by Bryan Clark on 11/16/15.
// Copyright © 2015 Khan Academy. All rights reserved.
//
import UIKit
/// Identifies tweaks in TweakPersistency
internal protocol TweakIdentifiable {
var persistenceIdentifier: String { get }
}
/// Caches Tweak values
internal typealias TweakCache = [String: TweakableType]
/// Persists state for tweaks in a TweakCache
internal final class TweakPersistency {
private let diskPersistency: TweakDiskPersistency
private var tweakCache: TweakCache = [:]
init(identifier: String) {
self.diskPersistency = TweakDiskPersistency(identifier: identifier)
self.tweakCache = self.diskPersistency.loadFromDisk()
}
internal func currentValueForTweak<T>(_ tweak: Tweak<T>) -> T? {
return persistedValueForTweakIdentifiable(AnyTweak(tweak: tweak)) as? T
}
internal func currentValueForTweak<T>(_ tweak: Tweak<T>) -> T? where T: SignedNumeric & Comparable {
if let currentValue = persistedValueForTweakIdentifiable(AnyTweak(tweak: tweak)) as? T {
// If the tweak can be clipped, then we'll need to clip it - because
// the tweak might've been persisted without a min / max, but then you changed the tweak definition.
// example: you tweaked it to 11, then set a max of 10 - the persisted value is still 11!
return clip(currentValue, tweak.minimumValue, tweak.maximumValue)
}
return nil
}
internal func persistedValueForTweakIdentifiable(_ tweakID: TweakIdentifiable) -> TweakableType? {
return tweakCache[tweakID.persistenceIdentifier]
}
internal func setValue(_ value: TweakableType?, forTweakIdentifiable tweakID: TweakIdentifiable) {
tweakCache[tweakID.persistenceIdentifier] = value
self.diskPersistency.saveToDisk(tweakCache)
}
internal func clearAllData() {
tweakCache = [:]
self.diskPersistency.saveToDisk(tweakCache)
}
}
/// Persists a TweakCache on disk using NSCoding
private final class TweakDiskPersistency {
private let fileURL: URL
private static func fileURLForIdentifier(_ identifier: String) -> URL {
return try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
.appendingPathComponent("MPSwiftTweaks")
.appendingPathComponent("\(identifier)")
.appendingPathExtension("db")
}
private let queue = DispatchQueue(label: "org.khanacademy.swift_tweaks.disk_persistency", attributes: [])
init(identifier: String) {
self.fileURL = TweakDiskPersistency.fileURLForIdentifier(identifier)
self.ensureDirectoryExists()
}
/// Creates a directory (if needed) for our persisted TweakCache on disk
private func ensureDirectoryExists() {
(self.queue).async {
try! FileManager.default.createDirectory(at: self.fileURL.deletingLastPathComponent(),
withIntermediateDirectories: true,
attributes: nil)
}
}
func loadFromDisk() -> TweakCache {
var result: TweakCache!
self.queue.sync {
NSKeyedUnarchiver.setClass(Data.self, forClassName: "Data")
result = (try? Foundation.Data(contentsOf: self.fileURL))
.flatMap(NSKeyedUnarchiver.unarchiveObject(with:))
.flatMap { $0 as? Data }
.map { $0.cache }
?? [:]
}
return result
}
func saveToDisk(_ data: TweakCache) {
self.queue.async {
let data = Data(cache: data)
NSKeyedArchiver.setClassName("Data", for: type(of: data))
let nsData = NSKeyedArchiver.archivedData(withRootObject: data)
try? nsData.write(to: self.fileURL, options: [.atomic])
}
}
/// Implements NSCoding for TweakCache.
/// TweakCache a flat dictionary: [String: TweakableType].
/// However, because re-hydrating TweakableType from its underlying NSNumber gets Bool & Int mixed up,
/// we have to persist a different structure on disk: [TweakViewDataType: [String: AnyObject]]
/// This ensures that if something was saved as a Bool, it's read back as a Bool.
@objc(TweakDiskPersistencyData) private final class Data: NSObject, NSCoding {
let cache: TweakCache
init(cache: TweakCache) {
self.cache = cache
}
@objc convenience init?(coder aDecoder: NSCoder) {
var cache: TweakCache = [:]
// Read through each TweakViewDataType...
for dataType in TweakViewDataType.allTypes {
// If a sub-dictionary exists for that type,
if let dataTypeDictionary = aDecoder.decodeObject(forKey: dataType.nsCodingKey) as? Dictionary<String, AnyObject> {
// Read through each entry and populate the cache
for (key, value) in dataTypeDictionary {
if let value = Data.tweakableTypeWithAnyObject(value, withType: dataType) {
cache[key] = value
}
}
}
}
self.init(cache: cache)
}
@objc fileprivate func encode(with aCoder: NSCoder) {
// Our "dictionary of dictionaries" that is persisted on disk
var diskPersistedDictionary: [TweakViewDataType : [String: AnyObject]] = [:]
// For each thing in our TweakCache,
for (key, value) in cache {
let dataType = type(of: value).tweakViewDataType
// ... create the "sub-dictionary" if it doesn't already exist for a particular TweakViewDataType
if diskPersistedDictionary[dataType] == nil {
diskPersistedDictionary[dataType] = [:]
}
// ... and set the cached value inside the sub-dictionary.
diskPersistedDictionary[dataType]![key] = value.nsCoding
}
// Now we persist the "dictionary of dictionaries" on disk!
for (key, value) in diskPersistedDictionary {
aCoder.encode(value, forKey: key.nsCodingKey)
}
}
// Reads from the cache, casting to the appropriate TweakViewDataType
private static func tweakableTypeWithAnyObject(_ anyObject: AnyObject, withType type: TweakViewDataType) -> TweakableType? {
switch type {
case .integer: return anyObject as? Int
case .boolean: return anyObject as? Bool
case .cgFloat: return anyObject as? CGFloat
case .double: return anyObject as? Double
case .string: return anyObject as? String
}
}
}
}
private extension TweakViewDataType {
/// Identifies our TweakViewDataType when in NSCoding. See implementation of TweakDiskPersistency.Data
var nsCodingKey: String {
switch self {
case .boolean: return "boolean"
case .integer: return "integer"
case .cgFloat: return "cgfloat"
case .double: return "double"
case .string: return "string"
}
}
}
private extension TweakableType {
/// Gets the underlying value from a Tweakable Type
var nsCoding: AnyObject {
switch type(of: self).tweakViewDataType {
case .boolean: return self as AnyObject
case .integer: return self as AnyObject
case .cgFloat: return self as AnyObject
case .double: return self as AnyObject
case .string: return self as AnyObject
}
}
}
| mit | 981065270c1d8ee6fc9f41314d55fe4a | 32.955882 | 126 | 0.701602 | 4.210942 | false | false | false | false |
hmx101607/mhweibo | weibo/weibo/App/module/AFNetworking/APIClient.swift | 1 | 3053 | //
// APIClient.swift
// weibo
//
// Created by mason on 2017/8/12.
// Copyright © 2017年 mason. All rights reserved.
//
import AFNetworking
// 定义枚举类型
enum RequestType : String {
case GET = "GET"
case POST = "POST"
}
class APIClient: AFHTTPSessionManager {
static let shareInstance : APIClient = {
let instance = APIClient()
instance.responseSerializer.acceptableContentTypes?.insert("text/html")
return instance
}()
}
extension APIClient {
func request(_ methodType : RequestType, urlString : String, parameters : [String : AnyObject], finished : @escaping (_ result : AnyObject?, _ error : NSError?) -> ()) {
// 1.定义成功的回调闭包
let successCallBack = { (task : URLSessionDataTask, result : AnyObject?) -> Void in
finished(result, nil)
}
// 2.定义失败的回调闭包
let failureCallBack = { (task : URLSessionDataTask?, error : NSError) -> Void in
finished(nil, error)
}
// 3.发送网络请求
if methodType == .GET {
get(urlString, parameters: parameters, progress: nil, success: successCallBack as? (URLSessionDataTask, Any?) -> Void, failure: failureCallBack as? (URLSessionDataTask?, Error) -> Void)
} else {
post(urlString, parameters: parameters, progress: nil, success: successCallBack as? (URLSessionDataTask, Any?) -> Void, failure: failureCallBack as? (URLSessionDataTask?, Error) -> Void)
}
}
}
// MARK:- 请求AccessToken
extension APIClient {
func loadAccessToken(code : String, finished : @escaping ((_ result : [String : AnyObject]?, _ error : NSError?)->())) {
// 1.获取请求的URLString
let urlString = "https://api.weibo.com/oauth2/access_token"
// 2.获取请求的参数
let parameters = ["client_id" : weibo_appkey, "client_secret" : weibo_appsecret, "grant_type" : "authorization_code", "redirect_uri" : weibo_redirect_uri, "code" : code]
// 3.发送网络请求
request(.POST, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
MLog(message: result)
MLog(message: error?.localizedDescription)
finished(result as? [String : AnyObject], error)
}
}
}
// MARK:- 请求用户的信息
extension APIClient {
func loadUserInfo(_ access_token : String, uid : String, finished : @escaping (_ result : [String : AnyObject]?, _ error : NSError?) -> ()) {
// 1.获取请求的URLString
let urlString = "https://api.weibo.com/2/users/show.json"
// 2.获取请求的参数
let parameters = ["access_token" : access_token, "uid" : uid]
// 3.发送网络请求
request(.GET, urlString: urlString, parameters: parameters as [String : AnyObject]) { (result, error) -> () in
finished(result as? [String : AnyObject] , error)
}
}
}
| mit | f63a4fcdbb4fbbae525be10ab769c9ad | 31.222222 | 198 | 0.602069 | 4.334828 | false | false | false | false |
sagpatil/TipSter | Tipster/ViewController.swift | 1 | 2693 | //
// ViewController.swift
// Tipster
//
// Created by Patil, Sagar on 8/13/14.
// Copyright (c) 2014 Patil, Sagar. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipSegControl: UISegmentedControl!
@IBOutlet weak var totalByTwo: UILabel!
@IBOutlet weak var totalByThree: UILabel!
@IBOutlet weak var totalByFour: UILabel!
@IBOutlet weak var tipView: UIView!
var billCentre: CGPoint = CGPointMake(0.0,0.0)
var tipCentre: CGPoint = CGPointMake(0.0,0.0)
override func viewDidLoad() {
super.viewDidLoad()
tipLabel.text = "$0.00"
totalLabel.text = "$0.00"
tipCentre = tipView.center
tipView.center = CGPointMake(tipView.center.x, tipView.center.y + 400)
billField.becomeFirstResponder()
billCentre = billField.center
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onEditingChanged(sender: AnyObject) {
var billAmount = (billField.text as NSString).doubleValue
if(billAmount > 0)
{
UIView .animateWithDuration(0.1, animations: { () -> Void in
self.billField.center = CGPointMake(self.billCentre.x, self.billCentre.y-50)
self.tipView.center = self.tipCentre
})
}
else{
UIView .animateWithDuration(0.1, animations: { () -> Void in
self.billField.center = self.billCentre;
self.tipView.center = CGPointMake(self.tipCentre.x, self.tipCentre.y + 400)
})
}
var tipPercentages = [0.18,0.2,0.22]
var tipPercent:Double
tipPercent = tipPercentages[tipSegControl.selectedSegmentIndex]
var tip = billAmount * tipPercent
var total = tip + billAmount
println("\(billAmount) \(tip) \(tipPercent) \(total)")
tipLabel.text = "$\(tip)"
totalLabel.text = "$\(total)"
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
totalByTwo.text = String(format: "$%.2f", total/2)
totalByThree.text = String(format: "$%.2f", total/3)
totalByFour.text = String(format: "$%.2f", total/4)
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
}
| gpl-2.0 | 8edd114cb74b87384564400e719e80e3 | 29.602273 | 92 | 0.591534 | 4.422003 | false | false | false | false |
neekon/ios | Neekon/Neekon/MainNavigationController.swift | 1 | 998 | //
// MainNavigationController.swift
// Neekon
//
// Created by Eiman Zolfaghari on 2/9/15.
// Copyright (c) 2015 Iranican Inc. All rights reserved.
//
import UIKit
class MainNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
let bgImage = UIImage(named:"home-BG.jpg")
let bgImageView = UIImageView(image: bgImage)
bgImageView.frame = self.view.frame
self.view.addSubview(bgImageView)
self.view.sendSubviewToBack(bgImageView)
self.view.backgroundColor = UIColor.clearColor()
self.navigationBar.translucent = true
self.navigationBar.barTintColor = UIColor.purpleColor()
UITabBar.appearance().barTintColor = UIColor.purpleColor()
UITabBar.appearance().tintColor = UIColor.whiteColor()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
| mit | fb30954939d6c83b1fd78e9161393910 | 28.352941 | 66 | 0.667335 | 5.015075 | false | false | false | false |
tevelee/LTFramer | Example/LTFramer.playground/Pages/Basic.xcplaygroundpage/Contents.swift | 1 | 636 | import UIKit
import PlaygroundSupport
import LTFramer
let container = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let view = UIView(frame: .zero)
container.addSubview(view)
let page = PlaygroundPage.current
page.needsIndefiniteExecution = true
page.liveView = container
view.skyFramer.resetRules()
view.skyFramer.top(5).right(10).width(50).and.height(25).computedFrame()
view.skyFramer.resetRules()
view.skyFramer.paddings(UIEdgeInsets(top: 8,left: 8,bottom: 8,right: 8)).computedFrame()
view.skyFramer.resetRules()
view.skyFramer.alignCenter.with.size(CGSize(width: 50, height: 50)).computedFrame()
//: [Next](@next) | mit | 03553b54fe83a69743aae4d0de9a9879 | 30.85 | 88 | 0.77044 | 3.494505 | false | false | false | false |
marksands/SwiftLensLuncheon | Pods/ReactiveCocoa/ReactiveCocoa/Swift/Flatten.swift | 4 | 18536 | //
// Flatten.swift
// ReactiveCocoa
//
// Created by Neil Pankey on 11/30/15.
// Copyright © 2015 GitHub. All rights reserved.
//
/// Describes how multiple producers should be joined together.
public enum FlattenStrategy: Equatable {
/// The producers should be merged, so that any value received on any of the
/// input producers will be forwarded immediately to the output producer.
///
/// The resulting producer will complete only when all inputs have completed.
case Merge
/// The producers should be concatenated, so that their values are sent in the
/// order of the producers themselves.
///
/// The resulting producer will complete only when all inputs have completed.
case Concat
/// Only the events from the latest input producer should be considered for
/// the output. Any producers received before that point will be disposed of.
///
/// The resulting producer will complete only when the producer-of-producers and
/// the latest producer has completed.
case Latest
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Flattens the inner producers sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` or an active inner producer fails, the returned signal will
/// forward that failure immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
switch strategy {
case .Merge:
return self.merge()
case .Concat:
return self.concat()
case .Latest:
return self.switchToLatest()
}
}
}
extension SignalProducerType where Value: SignalProducerType, Error == Value.Error {
/// Flattens the inner producers sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If `producer` or an active inner producer fails, the returned producer will
/// forward that failure immediately.
///
/// `Interrupted` events on inner producers will be treated like `Completed`
/// events on inner producers.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
switch strategy {
case .Merge:
return self.merge()
case .Concat:
return self.concat()
case .Latest:
return self.switchToLatest()
}
}
}
extension SignalType where Value: SignalType, Error == Value.Error {
/// Flattens the inner signals sent upon `signal` (into a single signal of
/// values), according to the semantics of the given strategy.
///
/// If `signal` or an active inner signal emits an error, the returned
/// signal will forward that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatten(strategy: FlattenStrategy) -> Signal<Value.Value, Error> {
return self.map(SignalProducer.init).flatten(strategy)
}
}
extension SignalProducerType where Value: SignalType, Error == Value.Error {
/// Flattens the inner signals sent upon `producer` (into a single producer of
/// values), according to the semantics of the given strategy.
///
/// If `producer` or an active inner signal emits an error, the returned
/// producer will forward that error immediately.
///
/// `Interrupted` events on inner signals will be treated like `Completed`
/// events on inner signals.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatten(strategy: FlattenStrategy) -> SignalProducer<Value.Value, Error> {
return self.map(SignalProducer.init).flatten(strategy)
}
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Returns a signal which sends all the values from producer signal emitted from
/// `signal`, waiting until each inner producer completes before beginning to
/// send the values from the next inner producer.
///
/// If any of the inner producers fail, the returned signal will forward
/// that failure immediately
///
/// The returned signal completes only when `signal` and all producers
/// emitted from `signal` complete.
private func concat() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { observer in
self.observeConcat(observer)
}
}
private func observeConcat(observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable? = nil) -> Disposable? {
let state = ConcatState(observer: observer, disposable: disposable)
return self.observe { event in
switch event {
case let .Next(value):
state.enqueueSignalProducer(value.producer)
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
// Add one last producer to the queue, whose sole job is to
// "turn out the lights" by completing `observer`.
state.enqueueSignalProducer(SignalProducer.empty.on(completed: {
observer.sendCompleted()
}))
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerType where Value: SignalProducerType, Error == Value.Error {
/// Returns a producer which sends all the values from each producer emitted from
/// `producer`, waiting until each inner producer completes before beginning to
/// send the values from the next inner producer.
///
/// If any of the inner producers emit an error, the returned producer will emit
/// that error.
///
/// The returned producer completes only when `producer` and all producers
/// emitted from `producer` complete.
private func concat() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
self.startWithSignal { signal, signalDisposable in
disposable += signalDisposable
signal.observeConcat(observer, disposable)
}
}
}
}
extension SignalProducerType {
/// `concat`s `next` onto `self`.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func concat(next: SignalProducer<Value, Error>) -> SignalProducer<Value, Error> {
return SignalProducer<SignalProducer<Value, Error>, Error>(values: [self.producer, next]).flatten(.Concat)
}
}
private final class ConcatState<Value, Error: ErrorType> {
/// The observer of a started `concat` producer.
let observer: Observer<Value, Error>
/// The top level disposable of a started `concat` producer.
let disposable: CompositeDisposable?
/// The active producer, if any, and the producers waiting to be started.
let queuedSignalProducers: Atomic<[SignalProducer<Value, Error>]> = Atomic([])
init(observer: Signal<Value, Error>.Observer, disposable: CompositeDisposable?) {
self.observer = observer
self.disposable = disposable
}
func enqueueSignalProducer(producer: SignalProducer<Value, Error>) {
if let d = disposable where d.disposed {
return
}
var shouldStart = true
queuedSignalProducers.modify {
// An empty queue means the concat is idle, ready & waiting to start
// the next producer.
var queue = $0
shouldStart = queue.isEmpty
queue.append(producer)
return queue
}
if shouldStart {
startNextSignalProducer(producer)
}
}
func dequeueSignalProducer() -> SignalProducer<Value, Error>? {
if let d = disposable where d.disposed {
return nil
}
var nextSignalProducer: SignalProducer<Value, Error>?
queuedSignalProducers.modify {
// Active producers remain in the queue until completed. Since
// dequeueing happens at completion of the active producer, the
// first producer in the queue can be removed.
var queue = $0
if !queue.isEmpty { queue.removeAtIndex(0) }
nextSignalProducer = queue.first
return queue
}
return nextSignalProducer
}
/// Subscribes to the given signal producer.
func startNextSignalProducer(signalProducer: SignalProducer<Value, Error>) {
signalProducer.startWithSignal { signal, disposable in
let handle = self.disposable?.addDisposable(disposable) ?? nil
signal.observe { event in
switch event {
case .Completed, .Interrupted:
handle?.remove()
if let nextSignalProducer = self.dequeueSignalProducer() {
self.startNextSignalProducer(nextSignalProducer)
}
default:
self.observer.action(event)
}
}
}
}
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased toward the producer
/// added earlier. Returns a Signal that will forward events from the inner producers as they arrive.
private func merge() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { relayObserver in
self.observeMerge(relayObserver)
}
}
private func observeMerge(observer: Observer<Value.Value, Error>, _ disposable: CompositeDisposable? = nil) -> Disposable? {
let inFlight = Atomic(1)
let decrementInFlight: () -> () = {
let orig = inFlight.modify { $0 - 1 }
if orig == 1 {
observer.sendCompleted()
}
}
return self.observe { event in
switch event {
case let .Next(producer):
producer.startWithSignal { innerSignal, innerDisposable in
inFlight.modify { $0 + 1 }
let handle = disposable?.addDisposable(innerDisposable) ?? nil
innerSignal.observe { event in
switch event {
case .Completed, .Interrupted:
handle?.remove()
decrementInFlight()
default:
observer.action(event)
}
}
}
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
decrementInFlight()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerType where Value: SignalProducerType, Error == Value.Error {
/// Merges a `signal` of SignalProducers down into a single signal, biased toward the producer
/// added earlier. Returns a Signal that will forward events from the inner producers as they arrive.
private func merge() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { relayObserver, disposable in
self.startWithSignal { signal, signalDisposable in
disposable.addDisposable(signalDisposable)
signal.observeMerge(relayObserver, disposable)
}
}
}
}
extension SignalType {
/// Merges the given signals into a single `Signal` that will emit all values
/// from each of them, and complete when all of them have completed.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public static func merge<S: SequenceType where S.Generator.Element == Signal<Value, Error>>(signals: S) -> Signal<Value, Error> {
let producer = SignalProducer<Signal<Value, Error>, Error>(values: signals)
var result: Signal<Value, Error>!
producer.startWithSignal { (signal, _) in
result = signal.flatten(.Merge)
}
return result
}
}
extension SignalType where Value: SignalProducerType, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
private func switchToLatest() -> Signal<Value.Value, Error> {
return Signal<Value.Value, Error> { observer in
self.observeSwitchToLatest(observer, SerialDisposable())
}
}
private func observeSwitchToLatest(observer: Observer<Value.Value, Error>, _ latestInnerDisposable: SerialDisposable) -> Disposable? {
let state = Atomic(LatestState<Value, Error>())
return self.observe { event in
switch event {
case let .Next(innerProducer):
innerProducer.startWithSignal { innerSignal, innerDisposable in
state.modify {
// When we replace the disposable below, this prevents the
// generated Interrupted event from doing any work.
var state = $0
state.replacingInnerSignal = true
return state
}
latestInnerDisposable.innerDisposable = innerDisposable
state.modify {
var state = $0
state.replacingInnerSignal = false
state.innerSignalComplete = false
return state
}
innerSignal.observe { event in
switch event {
case .Interrupted:
// If interruption occurred as a result of a new producer
// arriving, we don't want to notify our observer.
let original = state.modify {
var state = $0
if !state.replacingInnerSignal {
state.innerSignalComplete = true
}
return state
}
if !original.replacingInnerSignal && original.outerSignalComplete {
observer.sendCompleted()
}
case .Completed:
let original = state.modify {
var state = $0
state.innerSignalComplete = true
return state
}
if original.outerSignalComplete {
observer.sendCompleted()
}
default:
observer.action(event)
}
}
}
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
let original = state.modify {
var state = $0
state.outerSignalComplete = true
return state
}
if original.innerSignalComplete {
observer.sendCompleted()
}
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerType where Value: SignalProducerType, Error == Value.Error {
/// Returns a signal that forwards values from the latest signal sent on
/// `signal`, ignoring values sent on previous inner signal.
///
/// An error sent on `signal` or the latest inner signal will be sent on the
/// returned signal.
///
/// The returned signal completes when `signal` and the latest inner
/// signal have both completed.
private func switchToLatest() -> SignalProducer<Value.Value, Error> {
return SignalProducer<Value.Value, Error> { observer, disposable in
let latestInnerDisposable = SerialDisposable()
disposable.addDisposable(latestInnerDisposable)
self.startWithSignal { signal, signalDisposable in
signal.observeSwitchToLatest(observer, latestInnerDisposable)
}
}
}
}
private struct LatestState<Value, Error: ErrorType> {
var outerSignalComplete: Bool = false
var innerSignalComplete: Bool = true
var replacingInnerSignal: Bool = false
}
extension SignalType {
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting producers (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created producers fail, the returned signal
/// will forward that failure immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `signal` to a new signal, then flattens the
/// resulting signals (into a signal of values), according to the
/// semantics of the given strategy.
///
/// If `signal` or any of the created signals emit an error, the returned
/// signal will forward that error immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> Signal<U, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalProducerType {
/// Maps each event from `self` to a new producer, then flattens the
/// resulting producers (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created producers fail, the returned producer
/// will forward that failure immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> SignalProducer<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
/// Maps each event from `self` to a new producer, then flattens the
/// resulting signals (into a producer of values), according to the
/// semantics of the given strategy.
///
/// If `self` or any of the created signals emit an error, the returned
/// producer will forward that error immediately.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMap<U>(strategy: FlattenStrategy, transform: Value -> Signal<U, Error>) -> SignalProducer<U, Error> {
return map(transform).flatten(strategy)
}
}
extension SignalType {
/// Catches any failure that may occur on the input signal, mapping to a new producer
/// that starts in its place.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> Signal<Value, F> {
return Signal { observer in
self.observeFlatMapError(handler, observer, SerialDisposable())
}
}
private func observeFlatMapError<F>(handler: Error -> SignalProducer<Value, F>, _ observer: Observer<Value, F>, _ serialDisposable: SerialDisposable) -> Disposable? {
return self.observe { event in
switch event {
case let .Next(value):
observer.sendNext(value)
case let .Failed(error):
handler(error).startWithSignal { signal, disposable in
serialDisposable.innerDisposable = disposable
signal.observe(observer)
}
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
extension SignalProducerType {
/// Catches any failure that may occur on the input producer, mapping to a new producer
/// that starts in its place.
@warn_unused_result(message="Did you forget to call `start` on the producer?")
public func flatMapError<F>(handler: Error -> SignalProducer<Value, F>) -> SignalProducer<Value, F> {
return SignalProducer { observer, disposable in
let serialDisposable = SerialDisposable()
disposable.addDisposable(serialDisposable)
self.startWithSignal { signal, signalDisposable in
serialDisposable.innerDisposable = signalDisposable
signal.observeFlatMapError(handler, observer, serialDisposable)
}
}
}
}
| mit | 0aecfb074bee462f448237d3024caf10 | 32.454874 | 167 | 0.715712 | 4.115009 | false | false | false | false |
silence0201/Swift-Study | AdvancedSwift/结构体/Memory - Weak References.playgroundpage/Contents.swift | 1 | 1754 | /*:
### Weak References
To break the reference cycle, we need to make sure that one of the references is
either `weak` or `unowned`. When you mark a variable as `weak`, assigning a
value to it doesn't change the reference count. A weak reference also means that
the reference will be `nil` once the referred object gets deallocated. For
example, we could make the `rootView` property `weak`, which means it won't be
strongly referenced by the window and automatically becomes `nil` once the view
is deallocated. When you're dealing with a weak variable, you have to make it
optional. To debug the memory behavior, we can add a deinitializer, which gets
called just before the class deallocates:
*/
//#-editable-code
class View {
var window: Window
init(window: Window) {
self.window = window
}
deinit {
print("Deinit View")
}
}
class Window {
weak var rootView: View?
deinit {
print("Deinit Window")
}
}
//#-end-editable-code
/*:
In the code below, we create a window and a view. The view strongly references
the window, but because the window's `rootView` is declared as `weak`, the
window doesn't strongly reference the view. This way, we have no reference
cycle, and after setting both variables to `nil`, both views get deallocated:
*/
//#-editable-code
var window: Window? = Window()
var view: View? = View(window: window!)
window?.rootView = view!
window = nil
view = nil
//#-end-editable-code
/*:
A weak reference is very useful when working with delegates. The object that
calls the delegate methods shouldn't own the delegate. Therefore, a delegate is
usually marked as `weak`, and another object is responsible for making sure the
delegate stays around for as long as needed.
*/
| mit | 02d13ccdc6a569896f29c0c0199b82ba | 29.77193 | 80 | 0.72691 | 4.127059 | false | false | false | false |
Vadimkomis/Myclok | Pods/Auth0/Auth0/OAuth2Grant.swift | 2 | 6551 | // OAuth2Grant.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
protocol OAuth2Grant {
var defaults: [String: String] { get }
func credentials(from values: [String: String], callback: @escaping (Result<Credentials>) -> Void)
func values(fromComponents components: URLComponents) -> [String: String]
}
struct ImplicitGrant: OAuth2Grant {
let defaults: [String : String]
let responseType: [ResponseType]
init(responseType: [ResponseType] = [.token], nonce: String? = nil) {
self.responseType = responseType
if let nonce = nonce {
self.defaults = ["nonce": nonce]
} else {
self.defaults = [:]
}
}
func credentials(from values: [String : String], callback: @escaping (Result<Credentials>) -> Void) {
guard validate(responseType: self.responseType, token: values["id_token"], nonce: self.defaults["nonce"]) else {
return callback(.failure(error: WebAuthError.invalidIdTokenNonce))
}
guard !responseType.contains(.token) || values["access_token"] != nil else {
return callback(.failure(error: WebAuthError.missingAccessToken))
}
callback(.success(result: Credentials(json: values as [String : Any])))
}
func values(fromComponents components: URLComponents) -> [String : String] {
return components.a0_fragmentValues
}
}
struct PKCE: OAuth2Grant {
let authentication: Authentication
let redirectURL: URL
let defaults: [String : String]
let verifier: String
let responseType: [ResponseType]
init(authentication: Authentication, redirectURL: URL, generator: A0SHA256ChallengeGenerator = A0SHA256ChallengeGenerator(), reponseType: [ResponseType] = [.code], nonce: String? = nil) {
self.init(authentication: authentication, redirectURL: redirectURL, verifier: generator.verifier, challenge: generator.challenge, method: generator.method, responseType: reponseType, nonce: nonce)
}
// swiftlint:disable:next function_parameter_count
init(authentication: Authentication, redirectURL: URL, verifier: String, challenge: String, method: String, responseType: [ResponseType], nonce: String? = nil) {
self.authentication = authentication
self.redirectURL = redirectURL
self.verifier = verifier
self.responseType = responseType
var newDefaults: [String: String] = [
"code_challenge": challenge,
"code_challenge_method": method
]
if let nonce = nonce {
newDefaults["nonce"] = nonce
}
self.defaults = newDefaults
}
func credentials(from values: [String: String], callback: @escaping (Result<Credentials>) -> Void) {
guard
let code = values["code"]
else {
let string = "No code found in parameters \(values)"
return callback(.failure(error: AuthenticationError(string: string)))
}
guard validate(responseType: self.responseType, token: values["id_token"], nonce: self.defaults["nonce"]) else {
return callback(.failure(error: WebAuthError.invalidIdTokenNonce))
}
let clientId = self.authentication.clientId
self.authentication
.tokenExchange(withCode: code, codeVerifier: verifier, redirectURI: redirectURL.absoluteString)
.start { result in
// Special case for PKCE when the correct method for token endpoint authentication is not set (it should be None)
if case .failure(let cause as AuthenticationError) = result, cause.description == "Unauthorized" {
let error = WebAuthError.pkceNotAllowed("Please go to 'https://manage.auth0.com/#/applications/\(clientId)/settings' and make sure 'Client Type' is 'Native' to enable PKCE.")
callback(Result.failure(error: error))
} else {
callback(result)
}
}
}
func values(fromComponents components: URLComponents) -> [String : String] {
var items = components.a0_fragmentValues
components.a0_queryValues.forEach { items[$0] = $1 }
return items
}
}
private func validate(responseType: [ResponseType], token: String?, nonce: String?) -> Bool {
guard responseType.contains(.idToken) else { return true }
guard
let expectedNonce = nonce,
let token = token
else { return false }
let claims = decode(jwt: token)
let actualNonce = claims?["nonce"] as? String
return actualNonce == expectedNonce
}
private func decode(jwt: String) -> [String: Any]? {
let parts = jwt.components(separatedBy: ".")
guard parts.count == 3 else { return nil }
var base64 = parts[1]
.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
let length = Double(base64.lengthOfBytes(using: String.Encoding.utf8))
let requiredLength = 4 * ceil(length / 4.0)
let paddingLength = requiredLength - length
if paddingLength > 0 {
let padding = "".padding(toLength: Int(paddingLength), withPad: "=", startingAt: 0)
base64 += padding
}
guard
let bodyData = Data(base64Encoded: base64, options: .ignoreUnknownCharacters)
else { return nil }
let json = try? JSONSerialization.jsonObject(with: bodyData, options: [])
return json as? [String: Any]
}
| mit | e7eedd7b9dd9110450d6c36c6b5092bd | 40.99359 | 204 | 0.665547 | 4.600421 | false | false | false | false |
anicolaspp/rate-my-meetings-ios | Pods/Cosmos/Cosmos/CosmosAccessibility.swift | 2 | 2807 | import UIKit
/**
Functions for making cosmos view accessible.
*/
struct CosmosAccessibility {
/**
Makes the view accesible by settings its label and using rating as value.
*/
static func update(view: UIView, rating: Double, text: String?, settings: CosmosSettings) {
view.isAccessibilityElement = true
view.accessibilityTraits = settings.updateOnTouch ?
UIAccessibilityTraitAdjustable :UIAccessibilityTraitNone
var accessibilityLabel = CosmosLocalizedRating.ratingTranslation
if let text = text where text != "" {
accessibilityLabel += " \(text)"
}
view.accessibilityLabel = accessibilityLabel
view.accessibilityValue = accessibilityValue(view, rating: rating, settings: settings)
}
/**
Returns the rating that is used as accessibility value.
The accessibility value depends on the star fill mode.
For example, if rating is 4.6 and fill mode is .Half the value will be 4.5. And if the fill mode
if .Full the value will be 5.
*/
static func accessibilityValue(view: UIView, rating: Double, settings: CosmosSettings) -> String {
let accessibilityRating = CosmosRating.displayedRatingFromPreciseRating(rating,
fillMode: settings.fillMode, totalStars: settings.totalStars)
// Omit decimals if the value is an integer
let isInteger = (accessibilityRating * 10) % 10 == 0
if isInteger {
return "\(Int(accessibilityRating))"
} else {
// Only show a single decimal place
let roundedToFirstDecimalPlace = Double( round(10 * accessibilityRating) / 10 )
return "\(roundedToFirstDecimalPlace)"
}
}
/**
Returns the amount of increment for the rating. When .Half and .Precise fill modes are used the
rating is incremented by 0.5.
*/
static func accessibilityIncrement(rating: Double, settings: CosmosSettings) -> Double {
var increment: Double = 0
switch settings.fillMode {
case .Full:
increment = ceil(rating) - rating
if increment == 0 { increment = 1 }
case .Half, .Precise:
increment = (ceil(rating * 2) - rating * 2) / 2
if increment == 0 { increment = 0.5 }
}
if rating >= Double(settings.totalStars) { increment = 0 }
return increment
}
static func accessibilityDecrement(rating: Double, settings: CosmosSettings) -> Double {
var increment: Double = 0
switch settings.fillMode {
case .Full:
increment = rating - floor(rating)
if increment == 0 { increment = 1 }
case .Half, .Precise:
increment = (rating * 2 - floor(rating * 2)) / 2
if increment == 0 { increment = 0.5 }
}
if rating <= settings.minTouchRating { increment = 0 }
return increment
}
}
| mit | 2aa5e8ec04fc2a2cf262cc1d168e078e | 27.353535 | 100 | 0.657998 | 4.701843 | false | false | false | false |
open-telemetry/opentelemetry-swift | Sources/OpenTelemetryApi/Internal/SwiftExtensions.swift | 1 | 1346 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
public extension TimeInterval {
/// `TimeInterval` represented in milliseconds (capped to `UInt64.max`).
var toMilliseconds: UInt64 {
let milliseconds = self * 1_000
return UInt64(withReportingOverflow: milliseconds) ?? .max
}
var toMicroseconds: UInt64 {
let microseconds = self * 1_000_000
return UInt64(withReportingOverflow: microseconds) ?? .max
}
/// `TimeInterval` represented in nanoseconds (capped to `UInt64.max`).
var toNanoseconds: UInt64 {
let nanoseconds = self * 1_000_000_000
return UInt64(withReportingOverflow: nanoseconds) ?? .max
}
static func fromMilliseconds(_ millis: Int64) -> TimeInterval {
return Double(millis) / 1_000
}
static func fromMicroseconds(_ micros: Int64) -> TimeInterval {
return Double(micros) / 1_000_000
}
static func fromNanoseconds(_ nanos: Int64) -> TimeInterval {
return Double(nanos) / 1_000_000_000
}
}
private extension FixedWidthInteger {
init?<T: BinaryFloatingPoint>(withReportingOverflow floatingPoint: T) {
guard let converted = Self(exactly: floatingPoint.rounded()) else {
return nil
}
self = converted
}
}
| apache-2.0 | e750d5e0cfbcfd8d31a851940d0470e8 | 28.26087 | 76 | 0.656761 | 4.413115 | false | false | false | false |
DanielSmith1239/KosherSwift | KosherSwift/Core/Calendar/Sefira/KSSefiraFormatter.swift | 1 | 2434 | //
// Created by Daniel Smith on 3/9/16.
// Copyright (c) 2016 Dani Smith. All rights reserved.
//
import Foundation
/** This class formats an integer into a sefira day */
public class SefiraFormatter
{
public var ashkenazTransliteratedStrings : [String]?
public var sefardTransliteratedStrings : [String]?
public var ashkenazHebrewStrings : [String]?
public var sephardicTransliteratedStrings : [String]?
public var sefardHebrewStrings : [String]?
public var sephardicHebrewStrings : [String]?
public var englishStrings : [String]?
/**
* The custom for the formatter to use.
*/
public var custom = SefiraCustom.Sefard
/**
* The language for the formatter to use.
*/
public var language = SefiraLanguage.Hebrew
public init()
{
language = SefiraLanguage.Hebrew;
custom = SefiraCustom.Ashkenaz;
}
// public func stringFromInteger(num: Int) -> String?
// {
// if num < 0 || num > 49
// {
// return nil
// }
// if let composite: [[String]] = [ashkenazHebrewStrings?, sefardHebrewStrings?, sephardicHebrewStrings?]
// {
// if language == .English
// {
// custom = .Ashkenaz // There's only one version of English.
// }
//
// return composite[language][custom][integer]
// }
// }
}
/**
* This flag determines which custom to use when returning a formatted string.
*/
public enum SefiraCustom: Int
{
case Ashkenaz // Uses the bet prefix
case Sefard // Uses the lamed prefix
case ephardic // Uses the lamed prefix and sephardic formula
case Ari // Chabad - not sure what's different here yet.
}
/**
* This flag determines which language to use to display the text.
*/
public enum SefiraLanguage: Int
{
case Hebrew // The count, in Hebrew
case English // The count, in English
case TransliteratedHebrew // The count, in Hebrew, spelled in English
}
/**
* The options for the formatter.
*
* If the SefiraLanguage is not set to SefiraLanguageHebrew
* or SefiraCustom is not SefiraCustomAshkenaz, these flags are ignored.
*/
public enum SefiraPrayerAddition: Int
{
case LeshaimYichud //= 1 << 0
case Beracha //= 1 << 1
case Harachaman //= 1 << 2
case Lamenatzaiach //= 1 << 3
case Ana //= 1 << 4
case Ribono //= 1 << 5
case Aleinu //= 1 << 6
}
| lgpl-3.0 | 36126bcfe3dd9f44f61857f76567ea8e | 26.659091 | 109 | 0.630238 | 3.803125 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/Swiftz/Sources/Swiftz/Reader.swift | 3 | 5997 | //
// Reader.swift
// Swiftz
//
// Created by Matthew Purland on 11/25/15.
// Copyright © 2015-2016 TypeLift. All rights reserved.
//
#if SWIFT_PACKAGE
import Operadics
import Swiftx
#endif
/// A `Reader` monad with `R` for environment and `A` to represent the modified
/// environment.
public struct Reader<R, A> {
/// The function that modifies the environment
public let reader : (R) -> A
init(_ reader : @escaping (R) -> A) {
self.reader = reader
}
/// Runs the reader and extracts the final value from it
public func runReader(_ environment : R) -> A {
return reader(environment)
}
/// Executes a computation in a modified environment
public func local(_ f : @escaping (R) -> R) -> Reader<R, A> {
return Reader(reader • f)
}
}
public func runReader<R, A>(_ reader : Reader<R, A>) -> (R) -> A {
return reader.runReader
}
/// Runs the reader and extracts the final value from it. This provides a global
/// function for running a reader.
public func reader<R, A>(_ f : @escaping (R) -> A) -> Reader<R, A> {
return Reader(f)
}
/// Retrieves the monad environment
public func ask<R>() -> Reader<R, R> {
return Reader(identity)
}
/// Retrieves a function of the current environment
public func asks<R, A>(_ f : @escaping (R) -> A) -> Reader<R, A> {
return Reader(f)
}
extension Reader /*: Functor*/ {
public typealias B = Any
public typealias FB = Reader<R, B>
public func fmap<B>(_ f : @escaping (A) -> B) -> Reader<R, B> {
return Reader<R, B>(f • runReader)
}
}
public func <^> <R, A, B>(_ f : @escaping (A) -> B, r : Reader<R, A>) -> Reader<R, B> {
return r.fmap(f)
}
extension Reader /*: Pointed*/ {
public static func pure(_ a : A) -> Reader<R, A> {
return Reader<R, A> { _ in a }
}
}
extension Reader /*: Applicative*/ {
public typealias FAB = Reader<R, (A) -> B>
public func ap(_ r : Reader<R, (A) -> B>) -> Reader<R, B> {
return Reader<R, B>(runReader)
}
}
public func <*> <R, A, B>(rfs : Reader<R, (A) -> B>, xs : Reader<R, A>) -> Reader<R, B> {
return Reader<R, B> { (environment : R) -> B in
let a = xs.runReader(environment)
let ab = rfs.runReader(environment)
let b = ab(a)
return b
}
}
extension Reader /*: Cartesian*/ {
public typealias FTOP = Reader<R, ()>
public typealias FTAB = Reader<R, (A, B)>
public typealias FTABC = Reader<R, (A, B, C)>
public typealias FTABCD = Reader<R, (A, B, C, D)>
public static var unit : Reader<R, ()> { return Reader<R, ()> { _ in () } }
public func product<B>(r : Reader<R, B>) -> Reader<R, (A, B)> {
return Reader<R, (A, B)> { c in
return (self.runReader(c), r.runReader(c))
}
}
public func product<B, C>(r : Reader<R, B>, _ s : Reader<R, C>) -> Reader<R, (A, B, C)> {
return Reader<R, (A, B, C)> { c in
return (self.runReader(c), r.runReader(c), s.runReader(c))
}
}
public func product<B, C, D>(r : Reader<R, B>, _ s : Reader<R, C>, _ t : Reader<R, D>) -> Reader<R, (A, B, C, D)> {
return Reader<R, (A, B, C, D)> { c in
return (self.runReader(c), r.runReader(c), s.runReader(c), t.runReader(c))
}
}
}
extension Reader /*: ApplicativeOps*/ {
public typealias C = Any
public typealias FC = Reader<R, C>
public typealias D = Any
public typealias FD = Reader<R, D>
public static func liftA(_ f : @escaping (A) -> B) -> (Reader<R, A>) -> Reader<R, B> {
return { (a : Reader<R, A>) -> Reader<R, B> in Reader<R, (A) -> B>.pure(f) <*> a }
}
public static func liftA2(_ f : @escaping (A) -> (B) -> C) -> (Reader<R, A>) -> (Reader<R, B>) -> Reader<R, C> {
return { (a : Reader<R, A>) -> (Reader<R, B>) -> Reader<R, C> in { (b : Reader<R, B>) -> Reader<R, C> in f <^> a <*> b } }
}
public static func liftA3(_ f : @escaping (A) -> (B) -> (C) -> D) -> (Reader<R, A>) -> (Reader<R, B>) -> (Reader<R, C>) -> Reader<R, D> {
return { (a : Reader<R, A>) -> (Reader<R, B>) -> (Reader<R, C>) -> Reader<R, D> in { (b : Reader<R, B>) -> (Reader<R, C>) -> Reader<R, D> in { (c : Reader<R, C>) -> Reader<R, D> in f <^> a <*> b <*> c } } }
}
}
extension Reader /*: Monad*/ {
public func bind(_ f : @escaping (A) -> Reader<R, B>) -> Reader<R, B> {
return self >>- f
}
}
public func >>- <R, A, B>(r : Reader<R, A>, f : @escaping (A) -> Reader<R, B>) -> Reader<R, B> {
return Reader<R, B> { (environment : R) -> B in
let a = r.runReader(environment)
let readerB = f(a)
return readerB.runReader(environment)
}
}
extension Reader /*: MonadOps*/ {
public static func liftM(_ f : @escaping (A) -> B) -> (Reader<R, A>) -> Reader<R, B> {
return { (m1 : Reader<R, A>) -> Reader<R, B> in m1 >>- { (x1 : A) in Reader<R, B>.pure(f(x1)) } }
}
public static func liftM2(_ f : @escaping (A) -> (B) -> C) -> (Reader<R, A>) -> (Reader<R, B>) -> Reader<R, C> {
return { (m1 : Reader<R, A>) -> (Reader<R, B>) -> Reader<R, C> in { (m2 : Reader<R, B>) -> Reader<R, C> in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in Reader<R, C>.pure(f(x1)(x2)) } } } }
}
public static func liftM3(_ f : @escaping (A) -> (B) -> (C) -> D) -> (Reader<R, A>) -> (Reader<R, B>) -> (Reader<R, C>) -> Reader<R, D> {
return { (m1 : Reader<R, A>) -> (Reader<R, B>) -> (Reader<R, C>) -> Reader<R, D> in { (m2 : Reader<R, B>) -> (Reader<R, C>) -> Reader<R, D> in { (m3 : Reader<R, C>) -> Reader<R, D> in m1 >>- { (x1 : A) in m2 >>- { (x2 : B) in m3 >>- { (x3 : C) in Reader<R, D>.pure(f(x1)(x2)(x3)) } } } } } }
}
}
public func >>->> <R, A, B, C>(_ f : @escaping (A) -> Reader<R, B>, g : @escaping (B) -> Reader<R, C>) -> ((A) -> Reader<R, C>) {
return { x in f(x) >>- g }
}
public func <<-<< <R, A, B, C>(g : @escaping (B) -> Reader<R, C>, f : @escaping (A) -> Reader<R, B>) -> ((A) -> Reader<R, C>) {
return f >>->> g
}
// Can't get this to type check.
//public func sequence<R, A>(_ ms : [Reader<R, A>]) -> Reader<R, [A]> {
// return ms.reduce(Reader.pure([]), combine: { n, m in
// return n.bind { xs in
// return m.bind { x in
// return Reader.pure(xs + [x])
// }
// }
// })
//}
| apache-2.0 | 0d27ae7860762b4420a178ac4f94c69a | 32.104972 | 293 | 0.549399 | 2.615452 | false | false | false | false |
artsy/Emergence | Emergence/Extensions/Apple/UIImageView+Artsy.swift | 1 | 1171 | import UIKit
import Artsy_UIColors
import SDWebImage
extension UIImageView {
func ar_setImageURL(url: NSURL, takeThisURLFromCacheFirst: NSURL?, size: CGSize) {
let manager = SDWebImageManager.sharedManager()
if let cacheuRL = takeThisURLFromCacheFirst where manager.cachedImageExistsForURL(takeThisURLFromCacheFirst) {
let key = manager.cacheKeyForURL(cacheuRL)
let smallerInitialThumbnail = manager.imageCache.imageFromMemoryCacheForKey(key)
sd_setImageWithURL(url, placeholderImage:smallerInitialThumbnail)
} else {
ar_setImageWithURL(url, size: size)
}
}
func ar_setImage(image: Image, height:CGFloat) {
guard let thumbnail = image.bestThumbnailWithHeight(height) else { return }
ar_setImageWithURL(thumbnail, color: .artsyGrayLight(), size: image.imageSize)
}
func ar_setImageWithURL(url:NSURL, color: UIColor = .artsyGrayLight(), size:CGSize = CGSize(width: 600, height: 400)) {
async {
let image = UIImage.imageFromColor(color, size: size)
self.sd_setImageWithURL(url, placeholderImage: image)
}
}
} | mit | fa30287d726d2d75b513fe8fed158871 | 36.806452 | 123 | 0.690009 | 4.521236 | false | false | false | false |
acastano/tabs-scrolling-controller | Tabs/Tabs/Controllers/TabsComponentViewController.swift | 1 | 4220 | import UIKit
class TabsComponentViewController: UIViewController {
private let navBarHeight: CGFloat = 64.0
private let topContainerView = UIView()
private let tabContainerView = UIView()
private let contentContainerView = UIView()
private let topComponent: TabsTopComponent
private let tabsComponents: [TabsChildComponent]
private var selectorComponent: TabsSelectorComponent
private var selectedTabComponent: TabsChildComponent!
private var topTopContainerViewConstraint: NSLayoutConstraint!
private var heightTopContainerViewConstraint: NSLayoutConstraint!
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(tabsTopComponent: TabsTopComponent, tabsSelectorComponent: TabsSelectorComponent, tabsChildComponents: [TabsChildComponent]) {
guard tabsChildComponents.count != 0 else {
preconditionFailure("No tabs added")
}
topComponent = tabsTopComponent
tabsComponents = tabsChildComponents
selectorComponent = tabsSelectorComponent
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
setupHierarchy()
setupConstraints()
}
private func setupViews() {
selectorComponent.delegate = self
let childComponent = tabsComponents[0]
selectedTabComponent = childComponent
selectedTabComponent.tabsDelegate = self
selectedTabComponent.tabsDataSource = self
automaticallyAdjustsScrollViewInsets = false
}
private func setupHierarchy() {
view.addSubview(contentContainerView)
view.addSubview(topContainerView)
view.addSubview(tabContainerView)
}
private func setupConstraints() {
add(topComponent.viewController, to: topContainerView)
add(selectedTabComponent.viewController, to: contentContainerView)
topContainerView.pinToSuperview([.left, .right])
topTopContainerViewConstraint = topContainerView.pinToSuperviewTop()
heightTopContainerViewConstraint = topContainerView.addHeightConstraint(withConstant: topComponent.height)
contentContainerView.pinToSuperviewEdges()
tabContainerView.pinToSuperview([.left, .right])
tabContainerView.alignBottomToView(topContainerView)
tabContainerView.addHeightConstraint(withConstant: selectorComponent.height)
add(selectorComponent.viewController, to: tabContainerView)
}
}
extension TabsComponentViewController: TabsSelectorDelegate {
func tabsSelectorDelegateDidSelect(index: Int) {
if index < tabsComponents.count,
selectedTabComponent.viewController != tabsComponents[index].viewController {
selectTabComponent(tabsComponents[index])
}
}
private func selectTabComponent(_ tabComponent: TabsChildComponent) {
selectedTabComponent.reset()
remove(selectedTabComponent.viewController)
topTopContainerViewConstraint.constant = 0
heightTopContainerViewConstraint.constant = topComponent.height
selectedTabComponent = tabComponent
selectedTabComponent.tabsDelegate = self
selectedTabComponent.tabsDataSource = self
add(selectedTabComponent.viewController, to: contentContainerView)
}
}
extension TabsComponentViewController: TabsComponentDelegate {
func scrollDidScroll(offset: CGFloat) {
if offset <= 0 {
topTopContainerViewConstraint.constant = 0
heightTopContainerViewConstraint?.constant = topComponent.height + -offset
} else {
let constant = min(offset, topComponent.height - navBarHeight - selectorComponent.height)
topTopContainerViewConstraint.constant = -constant
heightTopContainerViewConstraint.constant = topComponent.height
}
}
}
extension TabsComponentViewController: TabsComponentDataSource {
func heightForTopComponent() -> CGFloat {
return topComponent.height
}
func collapsedTopOffset() -> CGFloat {
return navBarHeight + selectorComponent.height
}
}
| apache-2.0 | e337e67bc45920a39220bbad28ab882e | 29.80292 | 135 | 0.722275 | 6.345865 | false | false | false | false |
IFTTT/RazzleDazzle | Source/ConstraintMultiplierAnimation.swift | 1 | 2245 | //
// ConstraintMultiplierAnimation.swift
// RazzleDazzle
//
// Created by Laura Skelton on 6/15/15.
// Copyright (c) 2015 IFTTT. All rights reserved.
//
import UIKit
public enum LayoutAttribute {
case originX
case originY
case centerX
case centerY
case width
case height
}
/**
Animates the `constant` of an `NSLayoutConstraint` to a multiple of an attribute of another view, and lays out the given `superview`.
*/
public class ConstraintMultiplierAnimation : Animation<CGFloat>, Animatable {
private let superview : UIView
private let constraint : NSLayoutConstraint
private let referenceView : UIView
private let attribute : LayoutAttribute
private let constant : CGFloat
public convenience init(superview: UIView, constraint: NSLayoutConstraint, attribute: LayoutAttribute, referenceView: UIView) {
self.init(superview: superview, constraint: constraint, attribute: attribute, referenceView: referenceView, constant: 0)
}
public init(superview: UIView, constraint: NSLayoutConstraint, attribute: LayoutAttribute, referenceView: UIView, constant: CGFloat) {
self.superview = superview
self.constraint = constraint
self.referenceView = referenceView
self.attribute = attribute
self.constant = constant
}
public func animate(_ time: CGFloat) {
if !hasKeyframes() {return}
let multiplier = self[time]
var referenceAttributeValue : CGFloat
switch attribute {
case .originX:
referenceAttributeValue = referenceView.frame.minX
case .originY:
referenceAttributeValue = referenceView.frame.minY
case .centerX:
referenceAttributeValue = referenceView.frame.minX + (referenceView.frame.width / 2.0)
case .centerY:
referenceAttributeValue = referenceView.frame.minY + (referenceView.frame.height / 2.0)
case .width:
referenceAttributeValue = referenceView.frame.width
case .height:
referenceAttributeValue = referenceView.frame.height
}
constraint.constant = (multiplier * referenceAttributeValue) + constant
superview.layoutIfNeeded()
}
}
| mit | 894d07bec2ed2d172f215354fc9f2ab4 | 34.634921 | 138 | 0.691314 | 5.2331 | false | false | false | false |
SuPair/firefox-ios | XCUITests/ThirdPartySearchTest.swift | 3 | 6792 | /* 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 XCTest
class ThirdPartySearchTest: BaseTestCase {
fileprivate func dismissKeyboardAssistant(forApp app: XCUIApplication) {
if iPad() {
let searchTheDocsSearchField = app.webViews.searchFields["Search the docs"]
searchTheDocsSearchField.typeText("\r")
} else {
app.buttons["Done"].tap()
}
}
func testCustomSearchEngines() {
// Visit MDN to add a custom search engine
loadWebPage("https://developer.mozilla.org/en-US/search", waitForLoadToFinish: true)
if iPad() {
let searchTheDocsSearchField = app.webViews.searchFields["Search the docs"]
searchTheDocsSearchField.tap()
app.keyboards.buttons["Search"].tap()
searchTheDocsSearchField.tap()
} else {
app.webViews.searchFields.element(boundBy: 0).tap()
}
app.buttons["AddSearch"].tap()
app.alerts["Add Search Provider?"].buttons["OK"].tap()
XCTAssertFalse(app.buttons["AddSearch"].isEnabled)
dismissKeyboardAssistant(forApp: app)
// Perform a search using a custom search engine
tabTrayButton(forApp: app).tap()
app.buttons["TabTrayController.addTabButton"].tap()
app.textFields["url"].tap()
app.typeText("window")
app.scrollViews.otherElements.buttons["developer.mozilla.org search"].tap()
var url = app.textFields["url"].value as! String
if url.hasPrefix("https://") == false {
url = "https://\(url)"
}
XCTAssert(url.hasPrefix("https://developer.mozilla.org/en-US/search"), "The URL should indicate that the search was performed on MDN and not the default")
}
func testCustomSearchEngineAsDefault() {
// Visit MDN to add a custom search engine
loadWebPage("https://developer.mozilla.org/en-US/search", waitForLoadToFinish: true)
if iPad() {
let searchTheDocsSearchField = app.webViews.searchFields["Search the docs"]
searchTheDocsSearchField.tap()
app.keyboards.buttons["Search"].tap()
searchTheDocsSearchField.tap()
} else {
app.webViews.searchFields.element(boundBy: 0).tap()
}
app.buttons["AddSearch"].tap()
app.alerts["Add Search Provider?"].buttons["OK"].tap()
XCTAssertFalse(app.buttons["AddSearch"].isEnabled)
dismissKeyboardAssistant(forApp: app)
// Go to settings and set MDN as the default
navigator.goto(SearchSettings)
app.tables.cells.element(boundBy: 0).tap()
app.tables.staticTexts["developer.mozilla.org"].tap()
navigator.goto(BrowserTab)
// Perform a search to check
navigator.openNewURL(urlString:"window")
// Ensure that the default search is MDN
var url = app.textFields["url"].value as! String
if url.hasPrefix("https://") == false {
url = "https://\(url)"
}
XCTAssert(url.hasPrefix("https://developer.mozilla.org/en-US/search"), "The URL should indicate that the search was performed on MDN and not the default")
}
func testCustomSearchEngineDeletion() {
// Visit MDN to add a custom search engine
loadWebPage("https://developer.mozilla.org/en-US/search", waitForLoadToFinish: true)
if iPad() {
let searchTheDocsSearchField = app.webViews.searchFields["Search the docs"]
searchTheDocsSearchField.tap()
app.keyboards.buttons["Search"].tap()
searchTheDocsSearchField.tap()
} else {
app.webViews.searchFields.element(boundBy: 0).tap()
}
app.buttons["AddSearch"].tap()
app.alerts["Add Search Provider?"].buttons["OK"].tap()
XCTAssertFalse(app.buttons["AddSearch"].isEnabled)
dismissKeyboardAssistant(forApp: app)
let tabTrayButton = self.tabTrayButton(forApp: app)
tabTrayButton.tap()
app.buttons["TabTrayController.addTabButton"].tap()
app.textFields["url"].tap()
app.typeText("window")
// For timing issue, we need a wait statement
waitforExistence(app.scrollViews.otherElements.buttons["developer.mozilla.org search"])
XCTAssert(app.scrollViews.otherElements.buttons["developer.mozilla.org search"].exists)
app.typeText("\r")
// Go to settings and set MDN as the default
waitUntilPageLoad()
navigator.goto(SearchSettings)
app.navigationBars["Search"].buttons["Edit"].tap()
app.tables.buttons["Delete developer.mozilla.org"].tap()
app.tables.buttons["Delete"].tap()
navigator.goto(BrowserTab)
// Perform a search to check
tabTrayButton.tap(force: true)
app.buttons["TabTrayController.addTabButton"].tap()
app.textFields["url"].tap()
app.typeText("window")
waitforNoExistence(app.scrollViews.otherElements.buttons["developer.mozilla.org search"])
XCTAssertFalse(app.scrollViews.otherElements.buttons["developer.mozilla.org search"].exists)
}
func testCustomEngineFromCorrectTemplate() {
navigator.goto(SearchSettings)
app.tables.cells["customEngineViewButton"].tap()
app.textViews["customEngineTitle"].tap()
app.typeText("Ask")
app.textViews["customEngineUrl"].tap()
app.typeText("http://www.ask.com/web?q=%s")
app.navigationBars.buttons["customEngineSaveButton"].tap()
// Perform a search using a custom search engine
waitforExistence(app.tables.staticTexts["Ask"])
navigator.goto(HomePanelsScreen)
app.textFields["url"].tap()
app.typeText("strange charm")
app.scrollViews.otherElements.buttons["Ask search"].tap()
// Ensure that correct search is done
let url = app.textFields["url"].value as! String
XCTAssert(url.hasPrefix("www.ask.com"), "The URL should indicate that the search was performed using ask")
}
func testCustomEngineFromIncorrectTemplate() {
navigator.goto(SearchSettings)
app.tables.cells["customEngineViewButton"].tap()
app.textViews["customEngineTitle"].tap()
app.typeText("Feeling Lucky")
app.textViews["customEngineUrl"].tap()
app.typeText("http://www.google.com/search?q=&btnI") //Occurunces of %s != 1
app.navigationBars.buttons["customEngineSaveButton"].tap()
waitforExistence(app.alerts.element(boundBy: 0))
XCTAssert(app.alerts.element(boundBy: 0).label == "Failed")
}
}
| mpl-2.0 | 2119fdf4e796fc50d9d471e3fb5cece1 | 40.414634 | 162 | 0.646496 | 4.766316 | false | false | false | false |
catloafsoft/AudioKit | AudioKit/Common/Nodes/Effects/Filters/Low Pass Filter/AKLowPassFilter.swift | 1 | 4434 | //
// AKLowPassFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// AudioKit version of Apple's LowPassFilter Audio Unit
///
/// - parameter input: Input node to process
/// - parameter cutoffFrequency: Cutoff Frequency (Hz) ranges from 10 to 22050 (Default: 6900)
/// - parameter resonance: Resonance (dB) ranges from -20 to 40 (Default: 0)
///
public class AKLowPassFilter: AKNode, AKToggleable {
private let cd = AudioComponentDescription(
componentType: kAudioUnitType_Effect,
componentSubType: kAudioUnitSubType_LowPassFilter,
componentManufacturer: kAudioUnitManufacturer_Apple,
componentFlags: 0,
componentFlagsMask: 0)
internal var internalEffect = AVAudioUnitEffect()
internal var internalAU = AudioUnit()
private var mixer: AKMixer
/// Cutoff Frequency (Hz) ranges from 10 to 22050 (Default: 6900)
public var cutoffFrequency: Double = 6900 {
didSet {
if cutoffFrequency < 10 {
cutoffFrequency = 10
}
if cutoffFrequency > 22050 {
cutoffFrequency = 22050
}
AudioUnitSetParameter(
internalAU,
kLowPassParam_CutoffFrequency,
kAudioUnitScope_Global, 0,
Float(cutoffFrequency), 0)
}
}
/// Resonance (dB) ranges from -20 to 40 (Default: 0)
public var resonance: Double = 0 {
didSet {
if resonance < -20 {
resonance = -20
}
if resonance > 40 {
resonance = 40
}
AudioUnitSetParameter(
internalAU,
kLowPassParam_Resonance,
kAudioUnitScope_Global, 0,
Float(resonance), 0)
}
}
/// Dry/Wet Mix (Default 100)
public var dryWetMix: Double = 100 {
didSet {
if dryWetMix < 0 {
dryWetMix = 0
}
if dryWetMix > 100 {
dryWetMix = 100
}
inputGain?.volume = 1 - dryWetMix / 100
effectGain?.volume = dryWetMix / 100
}
}
private var lastKnownMix: Double = 100
private var inputGain: AKMixer?
private var effectGain: AKMixer?
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted = true
/// Initialize the low pass filter node
///
/// - parameter input: Input node to process
/// - parameter cutoffFrequency: Cutoff Frequency (Hz) ranges from 10 to 22050 (Default: 6900)
/// - parameter resonance: Resonance (dB) ranges from -20 to 40 (Default: 0)
///
public init(
_ input: AKNode,
cutoffFrequency: Double = 6900,
resonance: Double = 0) {
self.cutoffFrequency = cutoffFrequency
self.resonance = resonance
inputGain = AKMixer(input)
inputGain!.volume = 0
mixer = AKMixer(inputGain!)
effectGain = AKMixer(input)
effectGain!.volume = 1
internalEffect = AVAudioUnitEffect(audioComponentDescription: cd)
super.init()
AudioKit.engine.attachNode(internalEffect)
internalAU = internalEffect.audioUnit
AudioKit.engine.connect((effectGain?.avAudioNode)!, to: internalEffect, format: AudioKit.format)
AudioKit.engine.connect(internalEffect, to: mixer.avAudioNode, format: AudioKit.format)
avAudioNode = mixer.avAudioNode
AudioUnitSetParameter(internalAU, kLowPassParam_CutoffFrequency, kAudioUnitScope_Global, 0, Float(cutoffFrequency), 0)
AudioUnitSetParameter(internalAU, kLowPassParam_Resonance, kAudioUnitScope_Global, 0, Float(resonance), 0)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
if isStopped {
dryWetMix = lastKnownMix
isStarted = true
}
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
if isPlaying {
lastKnownMix = dryWetMix
dryWetMix = 0
isStarted = false
}
}
}
| mit | 5ff235a30600fa18c17e89b6ddead3bd | 31.130435 | 130 | 0.590212 | 5.355072 | false | false | false | false |
yulingtianxia/HardChoice | HardChoice/HardChoice/MasterViewController.swift | 3 | 13137 | //
// MasterViewController.swift
// HardChoice
//
// Created by 杨萧玉 on 14-7-1.
// Copyright (c) 2014年 杨萧玉. All rights reserved.
//
import UIKit
import DataKit
import CoreData
private let rollup = CATransform3DMakeRotation( CGFloat(M_PI_2), CGFloat(0.0), CGFloat(0.7), CGFloat(0.4))
private let rolldown = CATransform3DMakeRotation( CGFloat(-M_PI_2), CGFloat(0.0), CGFloat(0.7), CGFloat(0.4))
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate, UITextFieldDelegate{
var managedObjectContext: NSManagedObjectContext? = nil
var selectedIndexPath:NSIndexPath!
var lastVisualRow = 0
var wormhole:Wormhole!
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
navigationItem.rightBarButtonItem = addButton
tableView.estimatedRowHeight = 44
tableView.tableFooterView = UIView()
navigationController?.hidesBarsOnSwipe = true
//初始化虫洞
wormhole = Wormhole(applicationGroupIdentifier: appGroupIdentifier, optionalDirectory: "wormhole")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
showEditAlertWithInsert(true)
}
func modifyObject(){
showEditAlertWithInsert(false)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
let indexPath = self.tableView.indexPathForSelectedRow()
let object = self.fetchedResultsController.objectAtIndexPath(indexPath!) as! Question
(segue.destinationViewController as! DetailViewController).managedObjectContext = self.managedObjectContext
(segue.destinationViewController as! DetailViewController).detailItem = object
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections!.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section] as! NSFetchedResultsSectionInfo
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("QuestionCell", forIndexPath: indexPath) as! DynamicCell
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
tableView.deselectRowAtIndexPath(indexPath, animated: true)
selectedIndexPath = indexPath
}
override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath){
selectedIndexPath = indexPath
modifyObject()
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
//1. Setup the CATransform3D structure
var rotation:CATransform3D
if lastVisualRow <= indexPath.row {//roll up
cell.layer.transform = rollup
}
else{//roll down
cell.layer.transform = rolldown
}
lastVisualRow = indexPath.row
//2. Define the initial state (Before the animation)
cell.layer.shadowColor = UIColor.blackColor().CGColor
cell.layer.shadowOffset = CGSizeMake(10, 10)
cell.alpha = 0
cell.layer.anchorPoint = CGPointMake(0, 0.5)
cell.layer.position.x = 0
//3. Define the final state (After the animation) and commit the animation
UIView.animateWithDuration(0.8, animations: { () -> Void in
cell.layer.transform = CATransform3DIdentity
cell.alpha = 1
cell.layer.shadowOffset = CGSizeMake(0, 0)
})
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
let context = fetchedResultsController.managedObjectContext
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject)
var error: NSError? = nil
if !context.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
func configureCell(cell: DynamicCell, atIndexPath indexPath: NSIndexPath) {
let object = fetchedResultsController.objectAtIndexPath(indexPath) as! Question
cell.textLabel?.text = object.content
}
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
// Edit the entity name as appropriate.
let entity = NSEntityDescription.entityForName("Question", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
// Set the batch size to a suitable number.
fetchRequest.fetchBatchSize = 20
// Edit the sort key as appropriate.
let sortDescriptor = NSSortDescriptor(key: "content", ascending: true)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = sortDescriptors
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
var error: NSError? = nil
if !_fetchedResultsController!.performFetch(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath!) as! DynamicCell, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
default:
return
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
wormhole.passMessageObject(true, identifier: "questionData")
}
// MARK: - UITextFieldDelegate
func textFieldDidBeginEditing(textField: UITextField){
}
func textFieldShouldEndEditing(textField: UITextField) -> Bool{
textField.resignFirstResponder();
return true
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
func controllerDidChangeContent(controller: NSFetchedResultsController) {
// In the simplest, most efficient, case, reload the table view.
self.tableView.reloadData()
}
*/
func showEditAlertWithInsert(isNew:Bool){
let title = NSLocalizedString("Please Enter Your Trouble",comment:"")
let message = NSLocalizedString("Don't write too long😊",comment:"")
let okbtn = NSLocalizedString("OK",comment:"")
let cancelbtn = NSLocalizedString("Cancel",comment:"")
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: okbtn, style: UIAlertActionStyle.Destructive) { [unowned self](action) -> Void in
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity
var newManagedObject:Question!
if isNew{
newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity!.name!, inManagedObjectContext: context) as! Question
}
else{
newManagedObject = self.fetchedResultsController.objectAtIndexPath(self.selectedIndexPath) as! Question
}
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
newManagedObject.content = (alert.textFields?.first as! UITextField).text
// Save the context.
var error: NSError? = nil
if !context.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
let cancelAction = UIAlertAction(title: cancelbtn, style: .Cancel) { (action) -> Void in
}
alert.addAction(okAction)
alert.addAction(cancelAction)
alert.addTextFieldWithConfigurationHandler { (questionNameTF) -> Void in
if !isNew {
let question = self.fetchedResultsController.objectAtIndexPath(self.selectedIndexPath) as! Question
questionNameTF.text = question.content
}
questionNameTF.placeholder = NSLocalizedString("Write your trouble here",comment:"")
questionNameTF.delegate = self
questionNameTF.becomeFirstResponder()
}
self.presentViewController(alert, animated: true, completion: nil)
}
}
| mit | 4e9a1c96ba1b396efde7edf42a142252 | 43.89726 | 359 | 0.66804 | 6.030359 | false | false | false | false |
lukesutton/uut | Sources/Properties-Font.swift | 1 | 1157 | extension PropertyNames {
public static let font = "font"
public static let fontFamily = "font-family"
public static let fontSize = "font-size"
public static let fontStyle = "font-style"
public static let fontVariant = "font-variant"
public static let fontWeight = "font-weight"
}
public func font(value: PropertyValues.Font) -> Property {
return Property(PropertyNames.font, value)
}
public func fontFamily(value: PropertyValues.FontFamily) -> Property {
return Property(PropertyNames.fontFamily, value)
}
public func fontSize(value: PropertyValues.FontSize) -> Property {
return Property(PropertyNames.fontSize, value)
}
public func fontSize(value: Measurement) -> Property {
return Property(PropertyNames.fontSize, PropertyValues.FontSize.Value(value))
}
public func fontStyle(value: PropertyValues.FontStyle) -> Property {
return Property(PropertyNames.fontStyle, value)
}
public func fontVariant(value: PropertyValues.FontVariant) -> Property {
return Property(PropertyNames.fontVariant, value)
}
public func fontWeight(value: PropertyValues.FontWeight) -> Property {
return Property(PropertyNames.fontWeight, value)
}
| mit | d75f9b50c8b8ef9a86091b73a236d219 | 31.138889 | 79 | 0.773552 | 4.317164 | false | false | false | false |
alvesjtiago/hnr | HNR/Controllers/NewsTableViewController.swift | 1 | 4287 | //
// NewsTableViewController.swift
// HNR
//
// Created by Tiago Alves on 14/03/2017.
// Copyright © 2017 Tiago Alves. All rights reserved.
//
import UIKit
let maxNumberOfNews = 30
class NewsTableViewController: UITableViewController {
var allNews : Array<News> = []
override func viewDidLoad() {
super.viewDidLoad()
// Set automatic height calculation for cells
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 85.0
// Trigger refresh news when pull to refres is triggered
refreshControl?.addTarget(self, action: #selector(refreshNews), for: UIControlEvents.valueChanged)
// Start refresh when view is loaded
tableView.setContentOffset(CGPoint(x: 0, y: tableView.contentOffset.y - 30), animated: false)
tableView.refreshControl?.beginRefreshing()
refreshNews()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return allNews.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "newsCell", for: indexPath) as! NewsCell
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressed(sender:)))
cell.addGestureRecognizer(longPressRecognizer)
let news = allNews[indexPath.row]
cell.set(news: news)
cell.commentsButton?.indexPath = indexPath
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let news = allNews[indexPath.row]
if let url = news.url {
let safari: CustomWebViewController = CustomWebViewController(url: url)
present(safari, animated: true, completion: nil)
}
}
func refreshNews() {
API.sharedInstance.fetchNews(size: maxNumberOfNews) { (success, news) in
// Update array of news and interface
self.allNews = news
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
if (!success) {
// Display error
let alertView: UIAlertController = UIAlertController.init(title: "Error fetching news",
message: "There was an error fetching the new Hacker News articles. Please make sure you're connected to the internet and try again.",
preferredStyle: .alert)
let dismissButton: UIAlertAction = UIAlertAction.init(title: "OK",
style: .default,
handler: nil)
alertView.addAction(dismissButton)
self.present(alertView, animated: true, completion: nil)
}
}
}
@IBAction func longPressed(sender: UILongPressGestureRecognizer)
{
let newsCell:NewsCell = (sender.view as? NewsCell)!
if let myWebsite = newsCell.news?.url {
let objectsToShare = [myWebsite]
let activityVC = UIActivityViewController(activityItems: objectsToShare,
applicationActivities: nil)
self.present(activityVC, animated: true, completion: nil)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "comments" {
let commentsViewController = segue.destination as! CommentsTableViewController
let button = sender as! CommentsButton
let indexPath = button.indexPath!
let news = allNews[indexPath.row]
let commentsIds = news.commentsIds
commentsViewController.commentsIds = commentsIds
}
}
}
| mit | 82882c8151ba85c79226ebff4e31720f | 37.267857 | 208 | 0.591227 | 5.75302 | false | false | false | false |
drewag/Swiftlier | Sources/Swiftlier/Formatting/TimeInterval+Formatting.swift | 1 | 5417 | //
// NSTimeInterval+Formatting.swift
// Meditate
//
// Created by Andrew J Wagner on 4/3/16.
// Copyright © 2016 Learn Brigade. All rights reserved.
//
import Foundation
extension TimeInterval {
public var seconds: Int {
return Int(self.truncatingRemainder(dividingBy: 60))
}
public var minutes: Int {
return Int((self / 60).truncatingRemainder(dividingBy: 60))
}
public var hours: Int {
return Int((self / 60 / 60).truncatingRemainder(dividingBy: 60))
}
public var days: Int {
return Int((self / 60 / 60 / 24).truncatingRemainder(dividingBy: 24))
}
/// Largest unit
public var roughly: String {
if self.days > 1 {
return "\(self.days) days"
}
else if self.days == 1 {
return "\(self.days) day"
}
else if self.hours > 1 {
return "\(self.hours) hours"
}
else if self.hours == 1 {
return "\(self.hours) hour"
}
else if self.minutes > 1 {
return "\(self.minutes) minutes"
}
else if self.minutes == 1 {
return "\(self.minutes) minute"
}
else {
return "seconds"
}
}
/// H:M with rounded minutes
public var shortestDisplay: String {
let minutes = self.minutes + Int((Float(self.seconds) / 60).rounded())
let hours = self.hours
var output = ""
if minutes < 10 {
output = "0\(minutes)"
}
else {
output = "\(minutes)"
}
if hours > 0 {
if hours < 10 {
output = "0\(hours):" + output
}
else {
output = "\(hours):" + output
}
}
else {
output = "0:" + output
}
return output
}
/// M:S with hours as minutes
public var shortestWithSeconds: String {
let seconds = self.seconds
let minutes = self.minutes + self.hours * 60
var output = ""
if seconds < 10 {
output = "0\(seconds)"
}
else {
output = "\(seconds)"
}
if minutes > 0 {
if minutes < 10 {
output = "0\(minutes):" + output
}
else {
output = "\(minutes):" + output
}
}
else {
output = "0:" + output
}
return output
}
/// Hh Mm Ss hiding smallest units of 0 length
public var shortDisplay: String {
let seconds = self.seconds
let minutes = self.minutes
let hours = self.hours
switch self {
case 0:
return "0"
case let x where x < 60:
return "\(seconds)s"
case let x where x < 60 * 60:
if seconds > 0 {
return "\(minutes)m \(seconds)s"
}
return "\(minutes)m"
default:
if seconds > 0 {
return "\(hours)h \(minutes)m \(seconds)s"
}
else if minutes > 0 {
return "\(hours)h \(minutes)m"
}
else {
return "\(hours)h"
}
}
}
/// Hh Mm
public var shortDisplayRoundedMinutes: String {
let minutes = self.minutes + Int((Double(self.seconds)/60).rounded())
let hours = self.hours
switch self {
case 0:
return "0"
case let x where x < 60 * 60:
return "\(minutes)m"
default:
if minutes > 0 {
return "\(hours)h \(minutes)m"
}
else {
return "\(hours)h"
}
}
}
/// H hours M minutes S seconds
public var longDisplay: String {
let seconds = Int(self.truncatingRemainder(dividingBy: 60))
let minutes = Int((self / 60).truncatingRemainder(dividingBy: 60))
let hours = Int((self / 60 / 60).truncatingRemainder(dividingBy: 60))
switch Int(self) {
case 0:
return "0 seconds"
case 1:
return "\(seconds) second"
case let x where x < 60:
return "\(seconds) seconds"
case let x where x < 60 * 60:
var output = ""
switch minutes {
case 1:
output += "1 minute"
default:
output += "\(minutes) minutes"
}
switch seconds {
case 0:
break
case 1:
output += ", 1 second"
default:
output += ", \(seconds) seconds"
}
return output
default:
var output = ""
switch hours {
case 1:
output += "1 hour"
default:
output += "\(hours) hours"
}
switch minutes {
case 0:
break
case 1:
output += "1 minute"
default:
output += "\(minutes) minutes"
}
switch seconds {
case 0:
break
case 1:
output += ", 1 second"
default:
output += ", \(seconds) seconds"
}
return output
}
}
}
| mit | 5c3d2594189a71856ea7c1cbac9049c2 | 24.913876 | 78 | 0.440916 | 4.734266 | false | false | false | false |
cocoaheadsru/server | Tests/AppTests/Common/Extensions/Models/Event+Random.swift | 1 | 784 | import Vapor
@testable import App
extension App.Event {
convenience init(_ randomlyInitialized: Bool = true, endDate: Date? = nil, placeId: Identifier) {
var date = Date()
if randomlyInitialized {
if endDate != nil {
date = endDate!
}
self.init(
title: String.randomValue,
description: String.randomValue,
photo: String.randomValue,
placeId: placeId,
isRegistrationOpen: Bool.randomValue,
startDate: date.fiveHoursAgo,
endDate: date,
hide: Bool.randomValue
)
} else {
self.init(
title: "",
description: "",
photo: "",
placeId: placeId,
startDate: date.fiveHoursAgo,
endDate: date
)
}
}
}
| mit | c900625b26d5db3d26e190d48601df1a | 20.189189 | 99 | 0.558673 | 4.55814 | false | false | false | false |
cdmx/MiniMancera | miniMancera/Controller/Abstract/Controller.swift | 1 | 850 | import UIKit
class Controller<T:View>:UIViewController
{
init()
{
super.init(nibName:nil, bundle:nil)
}
required init?(coder:NSCoder)
{
return nil
}
override var shouldAutorotate:Bool
{
get
{
return true
}
}
override func loadView()
{
let view:View = T(controller:self)
self.view = view
}
override func viewDidLoad()
{
super.viewDidLoad()
edgesForExtendedLayout = UIRectEdge()
extendedLayoutIncludesOpaqueBars = false
automaticallyAdjustsScrollViewInsets = false
}
override var preferredStatusBarStyle:UIStatusBarStyle
{
return UIStatusBarStyle.lightContent
}
override var prefersStatusBarHidden:Bool
{
return true
}
}
| mit | af0f3d2b21aca2b7f09cfb48d75a6930 | 17.478261 | 57 | 0.581176 | 5.555556 | false | false | false | false |
mrdepth/EVEUniverse | Neocom/Neocom/Character/Skills/SkillQueueSection.swift | 2 | 1478 | //
// SkillQueueSection.swift
// Neocom
//
// Created by Artem Shimanski on 1/29/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import Expressible
struct SkillQueueSection: View {
var pilot: Pilot
@Environment(\.managedObjectContext) private var managedObjectContext
var body: some View {
let date = Date()
let skillQueue = pilot.skillQueue.filter{($0.queuedSkill.finishDate ?? .distantPast) > date}
let endDate = skillQueue.compactMap{$0.queuedSkill.finishDate}.max()
let skillsCount = skillQueue.count
let title: Text
if let timeLeft = endDate?.timeIntervalSinceNow, timeLeft > 0, skillsCount > 0 {
let s = TimeIntervalFormatter.localizedString(from: timeLeft, precision: .minutes)
title = Text("SKILL QUEUE: \(s) (\(skillsCount) skills)")
}
else {
title = Text("NO SKILLS IN TRAINING")
}
return Section(header: title) {
ForEach(skillQueue, id: \.self) { i in
(try? self.managedObjectContext.from(SDEInvType.self).filter(/\SDEInvType.typeID == Int32(i.skill.typeID)).first()).map { type in
SkillCell(type: type, pilot: self.pilot, skillQueueItem: i)
}
}
}
}
}
struct SkillQueueSection_Previews: PreviewProvider {
static var previews: some View {
SkillQueueSection(pilot: .empty)
}
}
| lgpl-2.1 | e3b2602565288993283355c5a44c40bd | 31.108696 | 145 | 0.619499 | 4.395833 | false | false | false | false |
phbraga/OpenWeatherMap | OpenWeatherMap/OpenWeatherMap/MapViewController.swift | 1 | 1261 | //
// MapViewController.swift
// OpenWeatherMap
//
// Created by Pedro Magalhaes on 14/11/16.
// Copyright © 2016 PHMB. All rights reserved.
//
import UIKit
import GoogleMaps
class MapViewController: UIViewController, GMSMapViewDelegate {
@IBOutlet weak var mapView: GMSMapView!
@IBOutlet weak var searchButton: UIButton!
private var currentMarker : GMSMarker?
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Map"
self.mapView?.delegate = self
}
@IBAction func searchButtonTapped(_ sender: UIButton) {
self.navigationController?.pushViewController(CityViewController.init(position: self.currentMarker?.position), animated: true)
}
//MARK: GMSMapViewDelegate
func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
if currentMarker == nil {
self.currentMarker = GMSMarker.init()
}
self.searchButton.isEnabled = true
self.currentMarker!.position = coordinate
self.currentMarker!.title = "Click on Search Button"
self.currentMarker!.snippet = "\tto find the nearest 15 cities"
self.currentMarker!.map = self.mapView
}
}
| apache-2.0 | ed818ba60624c5823fa475d9f3aea6d4 | 27 | 134 | 0.661111 | 4.96063 | false | false | false | false |
hanquochan/Charts | Source/Charts/Renderers/XAxisRenderer.swift | 1 | 17327 | //
// XAxisRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
@objc(ChartXAxisRenderer)
open class XAxisRenderer: AxisRendererBase
{
public init(viewPortHandler: ViewPortHandler?, xAxis: XAxis?, transformer: Transformer?)
{
super.init(viewPortHandler: viewPortHandler, transformer: transformer, axis: xAxis)
}
open override func computeAxis(min: Double, max: Double, inverted: Bool)
{
guard let
viewPortHandler = self.viewPortHandler
else { return }
var min = min, max = max
if let transformer = self.transformer
{
// calculate the starting and entry point of the y-labels (depending on
// zoom / contentrect bounds)
if viewPortHandler.contentWidth > 10 && !viewPortHandler.isFullyZoomedOutX
{
let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop))
let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop))
if inverted
{
min = Double(p2.x)
max = Double(p1.x)
}
else
{
min = Double(p1.x)
max = Double(p2.x)
}
}
}
computeAxisValues(min: min, max: max)
}
open override func computeAxisValues(min: Double, max: Double)
{
super.computeAxisValues(min: min, max: max)
computeSize()
}
open func computeSize()
{
guard let
xAxis = self.axis as? XAxis
else { return }
let longest = xAxis.getLongestLabel()
let labelSize = longest.size(attributes: [NSFontAttributeName: xAxis.labelFont])
let labelWidth = labelSize.width
let labelHeight = labelSize.height
let labelRotatedSize = ChartUtils.sizeOfRotatedRectangle(labelSize, degrees: xAxis.labelRotationAngle)
xAxis.labelWidth = labelWidth
xAxis.labelHeight = labelHeight
xAxis.labelRotatedWidth = min(labelRotatedSize.width, 60)
xAxis.labelRotatedHeight = min(labelRotatedSize.height, 60)
}
open override func renderAxisLabels(context: CGContext)
{
guard let
xAxis = self.axis as? XAxis,
let viewPortHandler = self.viewPortHandler
else { return }
if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled
{
return
}
let yOffset = xAxis.yOffset
if xAxis.labelPosition == .top
{
drawLabels(context: context, pos: viewPortHandler.contentTop - yOffset, anchor: CGPoint(x: 0.5, y: 1.0))
}
else if xAxis.labelPosition == .topInside
{
drawLabels(context: context, pos: viewPortHandler.contentTop + yOffset + xAxis.labelRotatedHeight, anchor: CGPoint(x: 0.5, y: 1.0))
}
else if xAxis.labelPosition == .bottom
{
drawLabels(context: context, pos: viewPortHandler.contentBottom + yOffset, anchor: CGPoint(x: 0.5, y: 0.0))
}
else if xAxis.labelPosition == .bottomInside
{
drawLabels(context: context, pos: viewPortHandler.contentBottom - yOffset - xAxis.labelRotatedHeight, anchor: CGPoint(x: 0.5, y: 0.0))
}
else
{ // BOTH SIDED
drawLabels(context: context, pos: viewPortHandler.contentTop - yOffset, anchor: CGPoint(x: 0.5, y: 1.0))
drawLabels(context: context, pos: viewPortHandler.contentBottom + yOffset, anchor: CGPoint(x: 0.5, y: 0.0))
}
}
fileprivate var _axisLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
open override func renderAxisLine(context: CGContext)
{
guard
let xAxis = self.axis as? XAxis,
let viewPortHandler = self.viewPortHandler
else { return }
if !xAxis.isEnabled || !xAxis.isDrawAxisLineEnabled
{
return
}
context.saveGState()
context.setStrokeColor(xAxis.axisLineColor.cgColor)
context.setLineWidth(xAxis.axisLineWidth)
if xAxis.axisLineDashLengths != nil
{
context.setLineDash(phase: xAxis.axisLineDashPhase, lengths: xAxis.axisLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
if xAxis.labelPosition == .top
|| xAxis.labelPosition == .topInside
|| xAxis.labelPosition == .bothSided
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop
context.strokeLineSegments(between: _axisLineSegmentsBuffer)
}
if xAxis.labelPosition == .bottom
|| xAxis.labelPosition == .bottomInside
|| xAxis.labelPosition == .bothSided
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
context.strokeLineSegments(between: _axisLineSegmentsBuffer)
}
context.restoreGState()
}
/// draws the x-labels on the specified y-position
open func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint)
{
guard
let xAxis = self.axis as? XAxis,
let viewPortHandler = self.viewPortHandler,
let transformer = self.transformer
else { return }
#if os(OSX)
let paraStyle = NSParagraphStyle.default().mutableCopy() as! NSMutableParagraphStyle
#else
let paraStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
#endif
paraStyle.alignment = .center
//paraStyle.lineBreakMode = .byWordWrapping
let labelAttrs = [NSFontAttributeName: xAxis.labelFont,
NSForegroundColorAttributeName: xAxis.labelTextColor,
NSParagraphStyleAttributeName: paraStyle] as [String : NSObject]
let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD
let centeringEnabled = xAxis.isCenterAxisLabelsEnabled
let valueToPixelMatrix = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
var labelMaxSize = CGSize()
if xAxis.isWordWrapEnabled
{
labelMaxSize.width = xAxis.wordWrapWidthPercent * valueToPixelMatrix.a
labelMaxSize.height = 80
if xAxis.labelRotationAngle == -90 {
labelMaxSize.width = 60
labelMaxSize.height = valueToPixelMatrix.a
}
}
let entries = xAxis.entries
for i in stride(from: 0, to: entries.count, by: 1)
{
if centeringEnabled
{
position.x = CGFloat(xAxis.centeredEntries[i])
}
else
{
position.x = CGFloat(entries[i])
}
position.y = 0.0
position = position.applying(valueToPixelMatrix)
if viewPortHandler.isInBoundsX(position.x)
{
let label = xAxis.valueFormatter?.stringForValue(xAxis.entries[i], axis: xAxis) ?? ""
let labelns = label as NSString
if xAxis.isAvoidFirstLastClippingEnabled
{
// avoid clipping of the last
if i == xAxis.entryCount - 1 && xAxis.entryCount > 1
{
// let width = labelns.boundingRect(with: labelMaxSize, options: .usesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width
//
// if position.x + width > viewPortHandler.chartWidth
// {
// position.x -= width / 2.0
// }
}
else if i == 0
{ // avoid clipping of the first
let width = labelns.boundingRect(with: labelMaxSize, options: .usesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width
if position.x - width > viewPortHandler.chartWidth
{
position.x += width / 2.0
}
}
}
drawLabel(context: context,
formattedLabel: label,
x: position.x,
y: pos,
attributes: labelAttrs,
constrainedToSize: labelMaxSize,
anchor: anchor,
angleRadians: labelRotationAngleRadians)
}
}
}
open func drawLabel(
context: CGContext,
formattedLabel: String,
x: CGFloat,
y: CGFloat,
attributes: [String: NSObject],
constrainedToSize: CGSize,
anchor: CGPoint,
angleRadians: CGFloat)
{
ChartUtils.drawMultilineText(
context: context,
text: formattedLabel,
point: CGPoint(x: x, y: y),
attributes: attributes,
constrainedToSize: constrainedToSize,
anchor: anchor,
angleRadians: angleRadians)
}
open override func renderGridLines(context: CGContext)
{
guard
let xAxis = self.axis as? XAxis,
let transformer = self.transformer
else { return }
if !xAxis.isDrawGridLinesEnabled || !xAxis.isEnabled
{
return
}
context.saveGState()
defer { context.restoreGState() }
context.clip(to: self.gridClippingRect)
context.setShouldAntialias(xAxis.gridAntialiasEnabled)
context.setStrokeColor(xAxis.gridColor.cgColor)
context.setLineWidth(xAxis.gridLineWidth)
context.setLineCap(xAxis.gridLineCap)
if xAxis.gridLineDashLengths != nil
{
context.setLineDash(phase: xAxis.gridLineDashPhase, lengths: xAxis.gridLineDashLengths)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
let valueToPixelMatrix = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
let entries = xAxis.entries
for i in stride(from: 0, to: entries.count, by: 1)
{
position.x = CGFloat(entries[i])
position.y = position.x
position = position.applying(valueToPixelMatrix)
drawGridLine(context: context, x: position.x, y: position.y)
}
}
open var gridClippingRect: CGRect
{
var contentRect = viewPortHandler?.contentRect ?? CGRect.zero
let dx = self.axis?.gridLineWidth ?? 0.0
contentRect.origin.x -= dx / 2.0
contentRect.size.width += dx
return contentRect
}
open func drawGridLine(context: CGContext, x: CGFloat, y: CGFloat)
{
guard
let viewPortHandler = self.viewPortHandler
else { return }
if x >= viewPortHandler.offsetLeft
&& x <= viewPortHandler.chartWidth
{
context.beginPath()
context.move(to: CGPoint(x: x, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: x, y: viewPortHandler.contentBottom))
context.strokePath()
}
}
open override func renderLimitLines(context: CGContext)
{
guard
let xAxis = self.axis as? XAxis,
let viewPortHandler = self.viewPortHandler,
let transformer = self.transformer
else { return }
var limitLines = xAxis.limitLines
if limitLines.count == 0
{
return
}
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in 0 ..< limitLines.count
{
let l = limitLines[i]
if !l.isEnabled
{
continue
}
context.saveGState()
defer { context.restoreGState() }
var clippingRect = viewPortHandler.contentRect
clippingRect.origin.x -= l.lineWidth / 2.0
clippingRect.size.width += l.lineWidth
context.clip(to: clippingRect)
position.x = CGFloat(l.limit)
position.y = 0.0
position = position.applying(trans)
renderLimitLineLine(context: context, limitLine: l, position: position)
renderLimitLineLabel(context: context, limitLine: l, position: position, yOffset: 2.0 + l.yOffset)
}
}
open func renderLimitLineLine(context: CGContext, limitLine: ChartLimitLine, position: CGPoint)
{
guard
let viewPortHandler = self.viewPortHandler
else { return }
context.beginPath()
context.move(to: CGPoint(x: position.x, y: viewPortHandler.contentTop))
context.addLine(to: CGPoint(x: position.x, y: viewPortHandler.contentBottom))
context.setStrokeColor(limitLine.lineColor.cgColor)
context.setLineWidth(limitLine.lineWidth)
if limitLine.lineDashLengths != nil
{
context.setLineDash(phase: limitLine.lineDashPhase, lengths: limitLine.lineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.strokePath()
}
open func renderLimitLineLabel(context: CGContext, limitLine: ChartLimitLine, position: CGPoint, yOffset: CGFloat)
{
guard
let viewPortHandler = self.viewPortHandler
else { return }
let label = limitLine.label
// if drawing the limit-value label is enabled
if limitLine.drawLabelEnabled && label.characters.count > 0
{
let labelLineHeight = limitLine.valueFont.lineHeight
let xOffset: CGFloat = limitLine.lineWidth + limitLine.xOffset
if limitLine.labelPosition == .rightTop
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x + xOffset,
y: viewPortHandler.contentTop + yOffset),
align: .left,
attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor])
}
else if limitLine.labelPosition == .rightBottom
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x + xOffset,
y: viewPortHandler.contentBottom - labelLineHeight - yOffset),
align: .left,
attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor])
}
else if limitLine.labelPosition == .leftTop
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x - xOffset,
y: viewPortHandler.contentTop + yOffset),
align: .right,
attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x - xOffset,
y: viewPortHandler.contentBottom - labelLineHeight - yOffset),
align: .right,
attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor])
}
}
}
}
| apache-2.0 | 699041b2fc2e924bcc1b397feafca3b4 | 34.289206 | 161 | 0.552375 | 5.666122 | false | false | false | false |
aeameen/PDFFormFiller | ILPDFKitExample/ILPDFKitExample/NSData+ImageToPDFConverter.swift | 1 | 3176 | //
// NSData+ImageToPDFConverter.swift
// PDF
//
// Created by Sebastian Andersen on 15/12/14.
// Copyright (c) 2014 SebastianAndersen. All rights reserved.
//
import Foundation
import UIKit
let defaultResolution: Int = 72
extension NSData {
class func convertImageToPDF(image: UIImage) -> NSData? {
return convertImageToPDF(image: image, resolution: 96)
}
class func convertImageToPDF(image: UIImage, resolution: Double) -> NSData? {
return convertImageToPDF(image: image, horizontalResolution: resolution, verticalResolution: resolution)
}
class func convertImageToPDF(image: UIImage, horizontalResolution: Double, verticalResolution: Double) -> NSData? {
if horizontalResolution <= 0 || verticalResolution <= 0 {
return nil;
}
let pageWidth: Double = Double(image.size.width) * Double(image.scale) * Double(defaultResolution) / horizontalResolution
let pageHeight: Double = Double(image.size.height) * Double(image.scale) * Double(defaultResolution) / verticalResolution
let pdfFile: NSMutableData = NSMutableData()
let pdfConsumer: CGDataConsumer = CGDataConsumer(data: pdfFile as CFMutableData)!
var mediaBox: CGRect = CGRect(x: 0, y: 0, width: CGFloat(pageWidth), height: CGFloat(pageHeight))
let pdfContext: CGContext = CGContext(consumer: pdfConsumer, mediaBox: &mediaBox, nil)!
pdfContext.beginPage(mediaBox: &mediaBox)
pdfContext.draw(image.cgImage!, in: mediaBox)
pdfContext.endPage()
return pdfFile
}
class func convertImageToPDF(image: UIImage, resolution: Double, maxBoundRect: CGRect, pageSize: CGSize) -> NSData? {
if resolution <= 0 {
return nil
}
var imageWidth: Double = Double(image.size.width) * Double(image.scale) * Double(defaultResolution) / resolution
var imageHeight: Double = Double(image.size.height) * Double(image.scale) * Double(defaultResolution) / resolution
let sx: Double = imageWidth / Double(maxBoundRect.size.width)
let sy: Double = imageHeight / Double(maxBoundRect.size.height)
if sx > 1 || sy > 1 {
let maxScale: Double = sx > sy ? sx : sy
imageWidth = imageWidth / maxScale
imageHeight = imageHeight / maxScale
}
let imageBox: CGRect = CGRect(x: maxBoundRect.origin.x, y: maxBoundRect.origin.y + maxBoundRect.size.height - CGFloat(imageHeight), width: CGFloat(imageWidth), height: CGFloat(imageHeight));
let pdfFile: NSMutableData = NSMutableData()
let pdfConsumer: CGDataConsumer = CGDataConsumer(data: pdfFile as CFMutableData)!
var mediaBox: CGRect = CGRect(x: 0, y: 0, width: pageSize.width, height: pageSize.height);
let pdfContext: CGContext = CGContext(consumer: pdfConsumer, mediaBox: &mediaBox, nil)!
pdfContext.beginPage(mediaBox: &mediaBox)
pdfContext.draw(image.cgImage!, in: imageBox)
pdfContext.endPage()
return pdfFile
}
}
| mit | 9d173bdfc7883a1fc990d4333af12545 | 36.364706 | 198 | 0.653338 | 4.754491 | false | false | false | false |
benlangmuir/swift | test/StringProcessing/Sema/regex_literal_type_inference.swift | 5 | 1895 | // RUN: %target-typecheck-verify-swift -enable-bare-slash-regex -disable-availability-checking
// REQUIRES: swift_in_compiler
let r0 = #/./#
let _: Regex<Substring> = r0
func takesRegex<Output>(_: Regex<Output>) {}
takesRegex(#//#) // okay
let r1 = #/.(.)/#
// Note: We test its type with a separate statement so that we know the type
// checker inferred the regex's type independently without contextual types.
let _: Regex<(Substring, Substring)>.Type = type(of: r1)
struct S {}
// expected-error @+2 {{cannot assign value of type 'Regex<(Substring, Substring)>' to type 'Regex<S>'}}
// expected-note @+1 {{arguments to generic parameter 'Output' ('(Substring, Substring)' and 'S') are expected to be equal}}
let r2: Regex<S> = #/.(.)/#
let r3 = #/(.)(.)/#
let _: Regex<(Substring, Substring, Substring)>.Type = type(of: r3)
let r4 = #/(?<label>.)(.)/#
let _: Regex<(Substring, label: Substring, Substring)>.Type = type(of: r4)
let r5 = #/(.(.(.)))/#
let _: Regex<(Substring, Substring, Substring, Substring)>.Type = type(of: r5)
let r6 = #/(?'we'.(?'are'.(?'regex'.)+)?)/#
let _: Regex<(Substring, we: Substring, are: Substring?, regex: Substring?)>.Type = type(of: r6)
let r7 = #/(?:(?:(.(.(.)*)?))*?)?/#
// ^ 1
// ^ 2
// ^ 3
let _: Regex<(Substring, Substring?, Substring?, Substring?)>.Type = type(of: r7)
let r8 = #/well(?<theres_no_single_element_tuple_what_can_we>do)/#
let _: Regex<(Substring, theres_no_single_element_tuple_what_can_we: Substring)>.Type = type(of: r8)
let r9 = #/(a)|(b)|(c)|d/#
let _: Regex<(Substring, Substring?, Substring?, Substring?)>.Type = type(of: r9)
let r10 = #/(a)|b/#
let _: Regex<(Substring, Substring?)>.Type = type(of: r10)
let r11 = #/()()()()()()()()/#
let _: Regex<(Substring, Substring, Substring, Substring, Substring, Substring, Substring, Substring, Substring)>.Type = type(of: r11)
| apache-2.0 | 8a754d07f041d59184a498223e109a76 | 38.479167 | 134 | 0.616887 | 3.250429 | false | false | false | false |
hrunar/functional-view-controllers | FunctionalViewControllers/Network.swift | 1 | 5863 | //
// Network.swift
// UIShared
//
// Created by Florian on 14/10/14.
// Copyright (c) 2014 unsignedinteger.com. All rights reserved.
//
import Foundation
public typealias NetworkTaskCompletionHandler = NSData -> ()
public typealias NetworkTaskProgressHandler = Double -> ()
public typealias NetworkTaskFailureHandler = (statusCode: Int, error: NSError?, data: NSData?) -> ()
public class NetworkSession: NSObject, NSURLSessionDataDelegate {
var session: NSURLSession!
var tasks: [NetworkTask] = []
var credential: NSURLCredential?
public override init() {
super.init()
session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(), delegate: self, delegateQueue: nil)
}
deinit {
session.invalidateAndCancel()
}
public func getURL(url: NSURL, failure: NetworkTaskFailureHandler, progress: NetworkTaskProgressHandler, validStatusCode: (Int -> Bool), completion: NetworkTaskCompletionHandler) {
let request = NSURLRequest(URL: url)
makeRequest(request, failure: failure, progress: progress, validStatusCode: validStatusCode, completion: completion)
}
public func makeRequest(request: NSURLRequest, failure: NetworkTaskFailureHandler, progress: NetworkTaskProgressHandler, validStatusCode: (Int -> Bool), completion: NetworkTaskCompletionHandler) {
mainThread {
var t = self.networkTaskForRequest(request)
if (t == nil) {
let newTask = NetworkTask(session: self.session, request: request, failure: failure, progress: progress, completion: completion, validStatusCode: validStatusCode)
self.tasks += [newTask]
} else {
t?.addHandlers(failure: failure, progress: progress, completion: completion)
}
}
}
public func cancelAllTasks() {
session.getTasksWithCompletionHandler { dataTasks, _, _ in
// we purposefully cast to an nsarray and then loop over it to avoid a weird swift 1.2 bad access crash
let dataTasks1: NSArray = dataTasks
for task in dataTasks1 {
(task as! NSURLSessionTask).cancel()
}
}
}
func networkTaskForRequest(request: NSURLRequest) -> NetworkTask? {
return tasks.filter { $0.request == request }.first
}
func removeNetworkTask(task: NetworkTask) {
tasks = tasks.filter { $0 != task }
}
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
// TODO: if countOfBytesExpectedToReceive is less than zero, make sure we call progress with nil (e.g. unknown)
let progress = Double(dataTask.countOfBytesReceived) / Double(dataTask.countOfBytesExpectedToReceive)
let task = networkTaskForRequest(dataTask.originalRequest!)
task?.callProgressHandlers(progress)
task?.data.appendData(data)
}
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let t = networkTaskForRequest(task.originalRequest!) {
removeNetworkTask(t)
var statusCode = 0
if let response = task.response as? NSHTTPURLResponse {
statusCode = response.statusCode
}
if (!t.validStatusCode(statusCode) || error != nil) {
t.callFailureHandlers(statusCode, error: error)
} else {
t.callCompletionHandlers()
}
}
}
// public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
// if challenge.previousFailureCount == 0, let c = self.credential {
// completionHandler(.UseCredential, c)
// } else {
// completionHandler(.CancelAuthenticationChallenge, nil)
// }
// }
}
public func mainThread(f: () -> ()) -> () {
dispatch_async(dispatch_get_main_queue(), f)
}
struct NetworkTask : Equatable {
var validStatusCode : Int -> Bool = { $0 >= 200 && $0 < 300 }
let request: NSURLRequest
var url: NSURL { return request.URL! }
var completionHandlers: [NetworkTaskCompletionHandler] = []
var progressHandlers: [NetworkTaskProgressHandler] = []
var failureHandlers: [NetworkTaskFailureHandler] = []
let data = NSMutableData()
init(session: NSURLSession, request: NSURLRequest, failure: NetworkTaskFailureHandler, progress: NetworkTaskProgressHandler, completion: NetworkTaskCompletionHandler, validStatusCode: Int -> Bool) {
self.request = request
addHandlers(failure: failure, progress: progress, completion: completion)
let task = session.dataTaskWithRequest(request)
task.resume()
self.validStatusCode = validStatusCode
}
func callCompletionHandlers() {
mainThread {
for c in self.completionHandlers {
c(self.data)
}
}
}
func callProgressHandlers(progress: Double) {
mainThread { for p in self.progressHandlers { p(progress) } }
}
func callFailureHandlers(statusCode: Int, error: NSError?) {
mainThread { for f in self.failureHandlers { f(statusCode: statusCode, error: error, data: self.data) } }
}
mutating func addHandlers(failure failure: NetworkTaskFailureHandler, progress: NetworkTaskProgressHandler, completion: NetworkTaskCompletionHandler) {
failureHandlers += [failure]
progressHandlers += [progress]
completionHandlers += [completion]
}
}
func ==(lhs: NetworkTask, rhs: NetworkTask) -> Bool {
return lhs.url == rhs.url
}
| mit | 151af9448468b044de7fc5871068d849 | 38.348993 | 202 | 0.660924 | 5.174757 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/iOS Collection/Business/Business/iPad/All/Controller/iPadAllViewController.swift | 1 | 668 | //
// iPadAllViewController.swift
// Business
//
// Created by 朱双泉 on 2018/11/12.
// Copyright © 2018 Castie!. All rights reserved.
//
import UIKit
class iPadAllViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let items = ["item0", "item1", "item2", "item3"]
let segment = UISegmentedControl(items: items)
segment.tintColor = .darkGray
let attributes = [NSAttributedString.Key.foregroundColor: UIColor.black]
segment.setTitleTextAttributes(attributes, for: .selected)
segment.selectedSegmentIndex = 0
navigationItem.titleView = segment
}
}
| mit | d80ae31a370a1613a56d062d40f372ad | 25.44 | 80 | 0.670197 | 4.527397 | false | false | false | false |
nheagy/WordPress-iOS | WordPress/WordPressTest/NotificationsServiceTests.swift | 1 | 6929 | import Foundation
import XCTest
import WordPress
import OHHTTPStubs
class NotificationsServiceTests : XCTestCase
{
typealias StreamKind = NotificationSettings.Stream.Kind
// MARK: - Properties
var contextManager : TestContextManager!
var remoteApi : WordPressComApi!
var service : NotificationsService!
// MARK: - Constants
let timeout = 2.0
let contentTypeJson = "application/json"
let settingsEndpoint = "notifications/settings/"
let settingsFilename = "notifications-settings.json"
let dummyDeviceId = "1234"
// MARK: - Overriden Methods
override func setUp() {
super.setUp()
contextManager = TestContextManager()
remoteApi = WordPressComApi.anonymousApi()
service = NotificationsService(managedObjectContext: contextManager.mainContext, wordPressComApi: remoteApi)
stub({ request in
return request.URL?.absoluteString.rangeOfString(self.settingsEndpoint) != nil
&& request.HTTPMethod == "GET"
}) { _ in
let stubPath = OHPathForFile(self.settingsFilename, self.dynamicType)
return fixture(stubPath!, headers: ["Content-Type": self.contentTypeJson])
}
}
override func tearDown() {
super.tearDown()
OHHTTPStubs.removeAllStubs()
}
// MARK: - Unit Tests!
func testNotificationSettingsCorrectlyParsesThreeSiteEntities() {
let targetChannel = NotificationSettings.Channel.Blog(blogId: 1)
let targetSettings = loadNotificationSettings().filter { $0.channel == targetChannel }
XCTAssert(targetSettings.count == 1, "Error while parsing Site Settings")
let targetSite = targetSettings.first!
XCTAssert(targetSite.streams.count == 3, "Error while parsing Site Stream Settings")
let parsedDeviceSettings = targetSite.streams.filter { $0.kind == StreamKind.Device }.first
let parsedEmailSettings = targetSite.streams.filter { $0.kind == StreamKind.Email }.first
let parsedTimelineSettings = targetSite.streams.filter { $0.kind == StreamKind.Timeline }.first
let expectedTimelineSettings = [
"new_comment" : false,
"comment_like" : true,
"post_like" : false,
"follow" : true,
"achievement" : false,
"mentions" : true
]
let expectedEmailSettings = [
"new_comment" : true,
"comment_like" : false,
"post_like" : true,
"follow" : false,
"achievement" : true,
"mentions" : false
]
let expectedDeviceSettings = [
"new_comment" : false,
"comment_like" : true,
"post_like" : false,
"follow" : true,
"achievement" : false,
"mentions" : true
]
for (key, value) in parsedDeviceSettings!.preferences! {
XCTAssert(expectedDeviceSettings[key]! == value, "Error while parsing Site Device Settings")
}
for (key, value) in parsedEmailSettings!.preferences! {
XCTAssert(expectedEmailSettings[key]! == value, "Error while parsing Site Email Settings")
}
for (key, value) in parsedTimelineSettings!.preferences! {
XCTAssert(expectedTimelineSettings[key]! == value, "Error while parsing Site Timeline Settings")
}
}
func testNotificationSettingsCorrectlyParsesThreeOtherEntities() {
let filteredSettings = loadNotificationSettings().filter { $0.channel == .Other }
XCTAssert(filteredSettings.count == 1, "Error while parsing Other Settings")
let otherSettings = filteredSettings.first!
XCTAssert(otherSettings.streams.count == 3, "Error while parsing Other Streams")
let parsedDeviceSettings = otherSettings.streams.filter { $0.kind == StreamKind.Device }.first
let parsedEmailSettings = otherSettings.streams.filter { $0.kind == StreamKind.Email }.first
let parsedTimelineSettings = otherSettings.streams.filter { $0.kind == StreamKind.Timeline }.first
let expectedDeviceSettings = [
"comment_like" : true,
"comment_reply" : true
]
let expectedEmailSettings = [
"comment_like" : false,
"comment_reply" : false
]
let expectedTimelineSettings = [
"comment_like" : false,
"comment_reply" : true
]
for (key, value) in parsedDeviceSettings!.preferences! {
XCTAssert(expectedDeviceSettings[key]! == value, "Error while parsing Other Device Settings")
}
for (key, value) in parsedEmailSettings!.preferences! {
XCTAssert(expectedEmailSettings[key]! == value, "Error while parsing Other Email Settings")
}
for (key, value) in parsedTimelineSettings!.preferences! {
XCTAssert(expectedTimelineSettings[key]! == value, "Error while parsing Other Timeline Settings")
}
}
func testNotificationSettingsCorrectlyParsesDotcomSettings() {
let filteredSettings = loadNotificationSettings().filter { $0.channel == .WordPressCom }
XCTAssert(filteredSettings.count == 1, "Error while parsing WordPress.com Settings")
let wordPressComSettings = filteredSettings.first!
XCTAssert(wordPressComSettings.streams.count == 1, "Error while parsing WordPress.com Settings")
let expectedSettings = [
"news" : false,
"recommendation": false,
"promotion" : true,
"digest" : true
]
for (key, value) in wordPressComSettings.streams.first!.preferences! {
XCTAssert(expectedSettings[key]! == value, "Error while parsing WordPress.com Settings")
}
}
// MARK: - Private Helpers
private func loadNotificationSettings() -> [NotificationSettings] {
var settings : [NotificationSettings]?
let expectation = expectationWithDescription("Notification settings reading expecation")
service?.getAllSettings({ (theSettings: [NotificationSettings]) in
settings = theSettings
expectation.fulfill()
},
failure: { (error: NSError!) in
expectation.fulfill()
})
waitForExpectationsWithTimeout(timeout, handler: nil)
XCTAssert(settings != nil, "Error while parsing settings")
return settings!
}
}
| gpl-2.0 | c756ba85e6add655515ae95e930cbfc4 | 37.709497 | 128 | 0.59518 | 5.253222 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.