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
justwatt/JWFloatLabelField
UIFloatLabelTextField/UIFloatLabelTextField.swift
1
7188
// // UIFloatLabelTextField.swift // Created by Justin Watt on 02.02.15 // Copyright (c) 2015 Justin Watt. All rights reserved. // import UIKit class UIFloatLabelTextField: UITextField { // The floating label that is displayed above the text field when there is other // text in the text field. var floatingLabel = UILabel(frame: CGRectMake(0, 0, 0, 0)) // The color of the floating label displayed above the text field when it is in // an active state (i.e. the associated text view is first responder). @IBInspectable var activeTextColorfloatingLabel : UIColor = UIColor.blueColor() { didSet { floatingLabel.textColor = activeTextColorfloatingLabel } } // The color of the floating label displayed above the text field when it is in // an inactive state @IBInspectable var inactiveTextColorfloatingLabel : UIColor = UIColor(white: 0.8, alpha: 1.0) { didSet { floatingLabel.textColor = inactiveTextColorfloatingLabel } } // Used to cache the placeholder string. var cachedPlaceholder = NSString() // Used to draw the placeholder string if necessary. Starting value is true. var shouldDrawPlaceholder = true //Default padding for floatingLabel var verticalPadding : CGFloat = 0 var horizontalPadding : CGFloat = 0 // Initializer // Programmatic Initializer override convenience init(frame: CGRect) { self.init(frame: frame) setup() } //Nib Initializer required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } // Unsupported Initializers init () { fatalError("Using the init() initializer directly is not supported. use init(frame:) instead") } // Deinit deinit { // remove observer NSNotificationCenter.defaultCenter().removeObserver(self) } // Setter & Getter override var placeholder : String? { get { return super.placeholder } set (newValue) { super.placeholder = newValue if (cachedPlaceholder != newValue) { cachedPlaceholder = newValue! floatingLabel.text = self.cachedPlaceholder as String floatingLabel.sizeToFit() } } } override func hasText() ->Bool { return !text.isEmpty } // Setup func setup() { setupObservers() setupFloatingLabel() applyFonts() setupViewDefaults() } func setupObservers() { NSNotificationCenter.defaultCenter().addObserver(self, selector:"textFieldTextDidChange:", name: UITextFieldTextDidChangeNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "fontSizeDidChange:", name: UIContentSizeCategoryDidChangeNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"textFieldTextDidBeginEditing:", name: UITextFieldTextDidBeginEditingNotification, object: self) NSNotificationCenter.defaultCenter().addObserver(self, selector:"textFieldTextDidEndEditing:", name: UITextFieldTextDidEndEditingNotification, object: self) } func setupFloatingLabel() { // Create the floating label instance and add it to the view floatingLabel.alpha = 1 floatingLabel.center = CGPointMake(horizontalPadding, verticalPadding) addSubview(floatingLabel) // Setup default colors for the floating label states floatingLabel.textColor = inactiveTextColorfloatingLabel floatingLabel.alpha = 0 } func applyFonts() { floatingLabel.font = UIFont.preferredFontForTextStyle(UIFontTextStyleCaption2) let textStyle = self.font.fontDescriptor().fontAttributes()["NSCTFontUIUsageAttribute"] as! String font = UIFont.preferredFontForTextStyle(textStyle) } func setupViewDefaults() { // Set vertical padding verticalPadding = 0.5 * CGRectGetHeight(self.frame) // Make sure placeholder setter methods are called if let ph = placeholder { placeholder = ph } else { placeholder = "" } } // Drawing & Animations override func layoutSubviews() { super.layoutSubviews() if (isFirstResponder() && !hasText()) { hideFloatingLabel() } else if(hasText()) { showFloatingLabelWithAnimation(true) } } func showFloatingLabelWithAnimation(isAnimated : Bool) { let fl_frame = CGRectMake( horizontalPadding, 0, CGRectGetWidth(self.floatingLabel.frame), CGRectGetHeight(self.floatingLabel.frame) ) if (isAnimated) { let options = UIViewAnimationOptions.BeginFromCurrentState | UIViewAnimationOptions.CurveEaseOut UIView.animateWithDuration(0.2, delay: 0, options: options, animations: { self.floatingLabel.alpha = 1 self.floatingLabel.frame = fl_frame }, completion: nil) } else { self.floatingLabel.alpha = 1 self.floatingLabel.frame = fl_frame } } func hideFloatingLabel () { let fl_frame = CGRectMake( horizontalPadding, verticalPadding, CGRectGetWidth(self.floatingLabel.frame), CGRectGetHeight(self.floatingLabel.frame) ) let options = UIViewAnimationOptions.BeginFromCurrentState | UIViewAnimationOptions.CurveEaseIn UIView.animateWithDuration(0.1, delay: 0, options: options, animations: { self.floatingLabel.alpha = 0 self.floatingLabel.frame = fl_frame }, completion: nil ) } // Auto Layout override func intrinsicContentSize() -> CGSize { return sizeThatFits(frame.size) } // Adds padding so these text fields align with B68FloatingPlaceholderTextView's override func textRectForBounds (bounds :CGRect) -> CGRect { return UIEdgeInsetsInsetRect(super.textRectForBounds(bounds), floatingLabelInsets()) } // Adds padding so these text fields align with B68FloatingPlaceholderTextView's override func editingRectForBounds (bounds : CGRect) ->CGRect { return UIEdgeInsetsInsetRect(super.editingRectForBounds(bounds), floatingLabelInsets()) } // Helpers func floatingLabelInsets() -> UIEdgeInsets { floatingLabel.sizeToFit() return UIEdgeInsetsMake( floatingLabel.font.lineHeight, horizontalPadding, 0, horizontalPadding) } // Observers func textFieldTextDidChange(notification : NSNotification) { let previousShouldDrawPlaceholderValue = shouldDrawPlaceholder shouldDrawPlaceholder = !hasText() // Only redraw if self.shouldDrawPlaceholder value was changed if (previousShouldDrawPlaceholderValue != shouldDrawPlaceholder) { if (self.shouldDrawPlaceholder) { hideFloatingLabel() } else { showFloatingLabelWithAnimation(true) } } } // TextField Editing Observer func textFieldTextDidEndEditing(notification : NSNotification) { if (hasText()) { floatingLabel.textColor = inactiveTextColorfloatingLabel } } func textFieldTextDidBeginEditing(notification : NSNotification) { floatingLabel.textColor = activeTextColorfloatingLabel } // Font Size Change Oberver func fontSizeDidChange (notification : NSNotification) { applyFonts() invalidateIntrinsicContentSize() setNeedsLayout() } }
mit
f6b0e4e43e28901e393ce9e4d78cf972
28.825726
164
0.707707
5.160086
false
false
false
false
cybertk/CKPickerView
UnitTests/UnitTests.swift
1
3297
// // UnitTests.swift // UnitTests // // Created by generator-swift-framework on 8/26/15. // Copyright © 2015 cybertk. All rights reserved. // import XCTest import Nimble @testable import CKPickerView class UnitTests: XCTestCase { class TestDataSource: NSObject, UIPickerViewDataSource { func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return 100 } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } } var window = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 600)) var dataSource = TestDataSource() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testInit() { // When init a new CKPickerView let p = CKPickerView() expect(p.titles).to(beEmpty()) expect(p.titleHeight).to(equal(kTitleHeight)) } func testTitles() { // When update titles let p = CKPickerView() let expectedTitles = ["T1", "T2"] let expectedAttributedTitles = [NSAttributedString(string: "T1"), NSAttributedString(string: "T2")] p.titles = expectedTitles expect(p.titles).to(equal(expectedTitles)) expect(p.attributedTitles).to(equal(expectedAttributedTitles)) expect(p.titleHeight).to(equal(kTitleHeight)) } func testAttributedTitles() { // When update attributedTitles let p = CKPickerView() let expectedTitles = ["T1", "T2"] let expectedAttributedTitles = [ NSAttributedString(string: "T1", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()]), NSAttributedString(string: "T2", attributes: [NSForegroundColorAttributeName: UIColor.whiteColor()]), ] p.attributedTitles = expectedAttributedTitles expect(p.titles).to(equal(expectedTitles)) expect(p.attributedTitles).to(equal(expectedAttributedTitles)) expect(p.titleHeight).to(equal(kTitleHeight)) } func testSelectionIndicatorColor() { let expectedColor = UIColor.grayColor() var p: CKPickerView! // Given set selectionBackgroundColor p = CKPickerView(frame: CGRect(x: 0, y: 0, width: 600, height: 600)) p.selectionIndicatorColor = expectedColor p.dataSource = dataSource // When layout in window window.addSubview(p) p.layoutSubviews() // It should detect selection indicators expect(p.selectionIndicators.count).to(equal(2)) // It should display with expected color expect(p.selectionIndicators.first?.backgroundColor).to(equal(expectedColor)) } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock { // Put the code you want to measure the time of here. } } }
mit
15101427bd23757469bd479b8236cb49
31.633663
113
0.62682
4.811679
false
true
false
false
zimcherDev/ios
Zimcher/Constants/Validation.swift
2
484
import Foundation struct Validation { //email static let EMAIL_USE_STRICT_FILTER = false private static let EMAIL_STRICTER_FILTER_STRING = "^[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}$" private static let EMAIL_LAX_STRING = "^.+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2}[A-Za-z]*$" static let EMAIL_FILTER = EMAIL_USE_STRICT_FILTER ? EMAIL_STRICTER_FILTER_STRING : EMAIL_LAX_STRING //user name static let USER_NAME_ALLOWED_CHARS = "^[A-Za-z0-9_ ]*$" }
apache-2.0
b9ed178bf74a1d70f364277373c21260
39.416667
110
0.613636
2.813953
false
false
false
false
austinzheng/swift-compiler-crashes
crashes-duplicates/00196-swift-constraints-constraint-create.swift
12
9675
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol a { } protocol b : a { } protocol c : a { } protocol d { typealias f = a } struct e : d { typealias f = b } func i<j : b, k : d where k.f == j> (n: k) { } func i<l : d where l.f == c> (n: l) { } i(e()) func prefi(with: String-> <T>() -> T)t func d() -> String { return 1 k f { typealias c } class g<i{ } d(j i) class h { typealias i = i } struct l<e : SequenceType> { l g: e } func h<e>() -> [l<e>] { f [] } func i(e: g) -> <j>(() -> j) -> k a) func a<b:a func b<e>(e : e) -> c { e class j { func y((Any, j))(v: (Any, AnyObject)) { y(v) } } func w(j: () -> ()) { } class v { l _ = w() { } } ({}) func v<x>() -> (x, x -> x) -> x { l y j s<q : l, y: l m y.n == q.n> { } o l { u n } y q<x> { s w(x, () -> ()) } o n { func j() p } class r { func s() -> p { t "" } } class w: r, n { k v: ))] = [] } class n<x : n> class A: A { } class B : C { } typealias C = B protocol f { k g d { k d k k } j j<l : d> : d { k , d> } class f: f { } class B : l { } k l = B class f<i : f class i<h>: c { var g: h init(g: h) { self.g = g e{ j d> } class f { typealias e = e protocol A { typealias B } class C<D> { init <A: A where A.B == D>(e: A.B) { } } func p<p>() -> (p, p -> p) -> p { l c l.l = { } { p) { (e: o, h:o) -> e }) } j(k(m, k(2, 3))) func l(p: j) -> <n>(() -> n func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c k) func c<i>() -> (i, i -> i) -> i { k b k.i = { } { i) { k } } protocol c { class func i() } class k: c{ class func i { a=1 as a=1 func d<b: SequenceType, e where Optional<e> == b.Generator.Element>(c : b) -> e? { for (mx : e?) in c { func a<T>() -> (T, T -> T) -> T { var b: ({ (x: Int, f: Int -> Int) -> Int in return f(x) }(x1, f1) let crashes: Int = { x, f in return f(x) }(x1ny) -> Any) -> Anyh>, d> } class A<T : A> { } func i(c: () -> ()) { } class a { var _ = i() { } } f e) func f<g>() -> (g, g -> g) -> g { d j d.i = { } { g) { h } } pss d: f{ class func i {} } class f<p : k, p : k n p.d> : o { } class f<p, p> { } protocol k { e o } protocol o { class func k(dynamicType.k() f j = i f l: k -> k = { m }(j, l) f protocol k : f { func f struct c<d: SequenceType, b where Optional<b> == d.Generator.Element> protocol A { typealias E } struct B<T : A> { let h: T let i: T.E } protocol C { typealias F func g<T where T.E == F>(f: B<T>) } struct D : C { typealias F = Int func g<T where T.E == F>(f: B<T>) { } } class k { func l((Any, k))(m } } func j<f: l: e -> e = { { l) { m } } protocol k { class func j() } class e: k{ class func j func b(c) -> <d>(() -> d) protocol A { func c() -> String } class B { func e<T where T: A, T: B>(t: T) { t.c() } func prefix(with: String) -> <T>(() -> T) -> String { return { g in "\(with): \(g())" } } protocol A { typealias B ret } struct C<D, E: A where D.C == E> { } struct A<T> { let a, () -> ())] = [] } enum S<T> { case C(T, () -> ()) } struct A<T> { let a: [(T, () -> ())d : SequenceTy return [] } func prefix(with: String) -> <T>(() -> T) - t.c() } struct c<d : SequenceType> { var b: d } func a<d>() -> [c<d>] { return [] } func e<k>() -> (k, k -> k) -> k { f j f.i = { } { k) { n } } m e { class func i() } class f: e{ class func i {} func n<i>() { k k { f j } } func n(k: Int = l) { } let j = n func ^(a: BooleanType, Bool) -> Bool { return !(a) } protocol a { class func c() class b: a { class func c() { } } (b() as a).dynamicType.c() b protocol c : b { func b func some<S: SequenceType, T where Optional<T> == S.Generator.Element>(xs : S) -> T? { for (mx : if let x = mx { d: f{ ceanTy b { clasi() { } } protocol a { class func c() } class b: a { class func c() { } } (b() as a).dynamicType.c() struct A<T> { let a: [(T, () -> ())] = [] } f> { c(d ()) } func b(e)-> <d>(() -> d) b protocol c : b { func b protocol a { } protocol h : a { } protocol k : a { } protocol g { j n = a } struct n : g { j n = h } func i<h : h, f : g m f.n == h> (g: f) { } func i<n : g m n.n = o) { } let k = a k() h protocol k : h { func h k func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) { return { (m: (Any, Any) -> Any) -> Any in return m(x, y) } } func b(z: (((Any, Any) -> Any) -> Any)) -> Any { return z({ (p: Any, q:Any) -> Any in return p }) } b(a(1, a(2, 3))) d = i } class d<j : i, f : i where j.i == f> : e { } class d<j, f> { } protocol i { typealias i } protocol e { class func i() } i (d() as e).j.i() d protocol i : d { func d f b<g f: func f<g { enum f { func f var _ = f } func a<g>() -> (g, g -> g) -> g { var b: ((g, g -> g) -> g)! return b } func f<g : d { return !(a) enum g { func g var _ = g func b<d { enum b { func c var _ = c func f() { ({}) } func f<T : BooleanType>(b: T) { } f(true as BooleanType) func a<T>() -> (T, T -> T) -> T { var4, nil] println(some(xs)) protocol A { t class func i() } class d: f{ class func i {} var x1 = 1 var f1: Int -> Int tInt -> Int) -> Int in return f>] { return [] } func i(c: () -> ()) { } class a { var _ = i() { } } struct A<T> { let a: [(T, () -> ())] = [namicType.c() func a(b: Int = 0) { } let c = a c() class a { typealias b = b } ({}) import Foundation class m<j>k i<g : g, e : f k(f: l) { } i(()) class h { typealias g = g func b<d-> d { class d:b class b func f<e>() -> (e, e -> e) -> e { e b e.c = { } { e) { f } } protocol f { class func c() } class e: f{ class func c protocol a { class func c() } class b: a { c T) { } f(true as BooleanType) func f() { ({}) } import Foundation class Foo<T>: 1) func c<d { enum c { func e var _ = e } } struct c<d : SequenceType> { var b: d } func a<d>() -> [c<d>] { return [] } a=1 as a=1 func some<S: SequenceType, T where Optional<T> return !(a) } ({}) func prefix(with: String) -> <T>(() -> T) -> String { func b clanType, Bool) -> Bool { ) } strs d typealias b> : b { typealias d = h typealias e = a<c<h>, d> } protocol A { typealias B } class C<D> { init <A: A where A.B == D>(e: A.B) { } } func a() as a).dynamicType.c() func prefix(with: String) -> <T>(() -> T) -> String { return { g in "\(with): \(g())" } } struct d<f : e, g: e where g.h == f.h> { } protocol e { typealias h } protocol a : a { } func a<T>() -> (T, T -> T) -> T)!c : b { func b var f = 1 var e: Int -> Int = { return $0 } let d: Int = { c, b in }(f, e) func f<T : BooleanType>(b: T) { } f(true as BooleanType) i) import Foundation class q<k>: NSObject { var j: k e ^(l: m, h) -> h { f !(l) } protocol l { d g n() } class h: l { class g n() { } } (h() o l).p.n() class l<n : h, d> Bool { e !(f) } b protocol f : b { func b protocol A { typealias B func b(B) } struct X<Y> : A { func b(b: X.Type) { } } protocol b { class func e() } struct c { var d: b.Type func e() { d.e() } } d "" e} class d { func b((Any, d)typealias b = b [] } protocol p { } protocol g : p { } n j } } protocol k { class func q() } class n: k{ class func q {} func r<e: t, s where j<s> == e.m { func g k q<n : t> { q g: n } func p<n>() -> [q<n>] { o : g.l) { } } class p { typealias g = g protocol A { func c() -> String } class B { func d() -> String { return "" } } class C: B, A { override func d() -> String { return "" } func c() -> String { return "" } } func e<T where T: A, T: B>(t: T) { t.c() } protocol l : p { } protocol m { j f = p } f m : m { j f = o } func i<o : o, m : m n m.f == o> (l: m) { } k: m } func p<m>() -> [l<m>] { return [] } f m) func f<o>() -> (o, o -> o) -> o { m o m.i = { } { o) { p } } protocol f { class func i() } class mo : m, o : p o o.m == o> (m: o) { } func s<v : p o v.m == m> (u: String) -> <t>(() -> t) - >) } struct n : C { class p { typealias n = n } l l) func l<u>() -> (u, u -> u) -> u { n j n.q = { } { u) { h } } protocol l { class { func n() -> q { return "" } } class C: s, l { t) { return { (s: (t, t) -> t) -> t o return s(c, u) } } func n(r: (((t, t) -> t) -> t)) -> t { return r({ return k }) class a<f : b, g : b where f.d == g> { } protocol b { typealias d typealias e } struct c<h : b> : b { typealias d = h typealias e = a<c<h>, d> } w class x<u>: d { l i: u init(i: u) { o.i = j { r { w s "\(f): \(w())" } } protocol h { q k { t w } w protocol k : w { func v <h: h m h.p == k>(l: h.p) { } } protocol h { n func w(w: } class h<u : h> { o } class f<p : k, p : k where p.n == p> : n { } class f<p, p> { } protocol k { typealias n } o: i where k.j == f> {l func k() { } } (f() as n).m.k() func k<o { enum k { func o var _ = o () { g g h g } } func e(i: d) -> <f>(() -> f)> q var m: Int -> Int = { n $0 o: Int = { d, l f n l(d) }(k, m) protocol j { typealias d typealias n = d typealias l = d} class g<q : l, m : l p q.g == m> : j { } class g<q, m> { } protocol l { typealias g
mit
4bdacc31ec188867646bb9d3c29717eb
12.981214
87
0.436796
2.350012
false
false
false
false
chriscox/material-components-ios
components/Tabs/examples/supplemental/TabBarIconExampleSupplemental.swift
1
9442
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialComponents.MaterialButtons extension TabBarIconSwiftExample { // MARK: Methods func setupAlignmentButton() -> MDCRaisedButton { let alignmentButton = MDCRaisedButton() alignmentButton.setTitle("Change Alignment", for: .normal) alignmentButton.setTitleColor(.white, for: .normal) self.view.addSubview(alignmentButton) alignmentButton.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint(item: alignmentButton, attribute: .centerX, relatedBy: .equal, toItem: self.view, attribute: .centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: alignmentButton, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: -40).isActive = true return alignmentButton } func setupAppBar() -> MDCAppBar { let appBar = MDCAppBar() self.addChildViewController(appBar.headerViewController) appBar.headerViewController.headerView.backgroundColor = UIColor.white appBar.headerViewController.headerView.minimumHeight = 76 + 72 appBar.headerViewController.headerView.tintColor = MDCPalette.blue().tint500 appBar.headerStackView.bottomBar = self.tabBar appBar.headerStackView.setNeedsLayout() return appBar } func setupExampleViews() { view.backgroundColor = UIColor.white appBar.addSubviewsToParent() let badgeIncrementItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action:#selector(incrementDidTouch(sender: ))) self.navigationItem.rightBarButtonItem = badgeIncrementItem self.title = "Tabs With Icons" setupScrollingContent() } func setupScrollView() -> UIScrollView { let scrollView = UIScrollView(frame: CGRect()) scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.isPagingEnabled = false scrollView.isScrollEnabled = false self.view.addSubview(scrollView) scrollView.backgroundColor = UIColor.red let views = ["scrollView": scrollView, "header": self.appBar.headerStackView] NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:[header][scrollView]|", options: [], metrics: nil, views: views)) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: views)) return scrollView } func setupScrollingContent() { // The scrollView will have two UIViews (pages.) One has a label with text (infoLabel); we call // this infoPage. Another has 1+ star images; we call this self.starPage. Tapping on the 'INFO' // tab will show the infoPage and tapping on the 'STARS' tab will show the self.starPage. // Create the first view and its content. Then add to scrollView. let infoPage = UIView(frame: CGRect()) infoPage.translatesAutoresizingMaskIntoConstraints = false infoPage.backgroundColor = MDCPalette.lightBlue().tint300 scrollView.addSubview(infoPage) let infoLabel = UILabel(frame: CGRect()) infoLabel.translatesAutoresizingMaskIntoConstraints = false infoLabel.textColor = UIColor.white infoLabel.numberOfLines = 0 infoLabel.text = "Tabs enable content organization at a high level," + " such as switching between views" infoPage.addSubview(infoLabel) // Layout the views to be equal height and width to each other and self.view, // hug the edges of the scrollView and meet in the middle. NSLayoutConstraint(item: infoLabel, attribute: .centerX, relatedBy: .equal, toItem: infoPage, attribute: .centerX, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: infoLabel, attribute: .centerY, relatedBy: .equal, toItem: infoPage, attribute: .centerY, multiplier: 1, constant: -50).isActive = true NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|-50-[infoLabel]-50-|", options: [], metrics: nil, views: ["infoLabel": infoLabel])) NSLayoutConstraint(item: infoPage, attribute: .width, relatedBy: .equal, toItem: self.view, attribute: .width, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: infoPage, attribute: .height, relatedBy: .equal, toItem: self.scrollView, attribute: .height, multiplier: 1, constant: 0).isActive = true NSLayoutConstraint(item: self.starPage, attribute: .width, relatedBy: .equal, toItem: infoPage, attribute: .width, multiplier: 1, constant: 0).isActive = true let views = ["infoPage": infoPage, "starPage": self.starPage] NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[infoPage][starPage]|", options: [.alignAllTop, .alignAllBottom], metrics: nil, views: views)) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "V:|[infoPage]|", options: [], metrics: nil, views: views)) addStar(centered: true) } func setupStarPage() -> UIView { let starPage = UIView(frame: CGRect()) starPage.translatesAutoresizingMaskIntoConstraints = false starPage.backgroundColor = MDCPalette.lightBlue().tint200 self.scrollView.addSubview(starPage) return starPage } func addStar(centered: Bool) { let starImage = UIImage(named:"TabBarDemo_ic_star", in:Bundle(for: type(of: self)), compatibleWith:nil) let starView = UIImageView(image: starImage) starView.translatesAutoresizingMaskIntoConstraints = false starPage.addSubview(starView) starView.sizeToFit() let x = centered ? 1.0 : (CGFloat(arc4random_uniform(199) + 1) / 100.0) // 0 < x <=2 let y = centered ? 1.0 : (CGFloat(arc4random_uniform(199) + 1) / 100.0) // 0 < y <=2 NSLayoutConstraint(item: starView, attribute: .centerX, relatedBy: .equal, toItem: starPage, attribute: .centerX, multiplier: x, constant: 0).isActive = true NSLayoutConstraint(item: starView, attribute: .centerY, relatedBy: .equal, toItem: self.starPage, attribute: .centerY, multiplier: y, constant: 0).isActive = true } } extension TabBarIconSwiftExample { override var childViewControllerForStatusBarStyle: UIViewController? { return appBar.headerViewController } } // MARK: Catalog by convention extension TabBarIconSwiftExample { class func catalogBreadcrumbs() -> [String] { return ["Tab Bar", "Icons and Text (Swift)"] } func catalogShouldHideNavigation() -> Bool { return true } }
apache-2.0
e2a2766d1e4b698fea1551682967f876
39.008475
108
0.551049
6.037084
false
false
false
false
rawshooter/newfoto
newfoto/DisclaimerViewController.swift
1
6937
// // DisclaimerViewController.swift // newfoto // // Created by Thomas Alexnat on 11.02.17. // Copyright © 2017 Thomas Alexnat. All rights reserved. // import UIKit import Photos class DisclaimerViewController: UIViewController { @IBOutlet weak var disclaimerLabel: UITextView! @IBOutlet weak var actionButton: UIButton! @IBOutlet weak var imageView: UIImageView! // The cells zoom when focused. var focusedTransform: CGAffineTransform { return CGAffineTransform(scaleX: 1.2, y: 1.2) } // The cells zoom when focused. var unFocusedTransform: CGAffineTransform { return CGAffineTransform(scaleX: 1.0, y: 1.0) } @IBAction func actionUHD(_ sender: UIButton) { if let controller = storyboard?.instantiateViewController(withIdentifier: "UHDViewController") as? UHDViewController{ self.show(controller, sender: self) } } @IBAction func actionHD(_ sender: UIButton) { if let controller = storyboard?.instantiateViewController(withIdentifier: "HDViewController") as? HDViewController{ self.show(controller, sender: self) } } @IBAction func actionAbout(_ sender: UIButton) { if let controller = storyboard?.instantiateViewController(withIdentifier: "AboutController") as? AboutViewController{ print("Controller found") // controller.presentingSmartController = self self.show(controller, sender: self) //self.present(controller, animated: true, completion: nil) } } @IBAction func actionLicense(_ sender: UIButton) { if let controller = storyboard?.instantiateViewController(withIdentifier: "LicenseController") as? LicenseViewController{ print("Controller found") // controller.presentingSmartController = self self.show(controller, sender: self) //self.present(controller, animated: true, completion: nil) } } func zoomIn(){ UIView.animate(withDuration: 40, delay: 1, options: [.beginFromCurrentState, .curveLinear], animations: { () -> Void in self.imageView.transform = self.focusedTransform} , completion: { (completed: Bool) -> Void in self.zoomOut() } ) } func zoomOut(){ UIView.animate(withDuration: 40, delay: 1, options: [.beginFromCurrentState, .curveLinear], animations: { () -> Void in self.imageView.transform = self.unFocusedTransform} , completion: { (completed: Bool) -> Void in self.zoomIn() } ) } // check when the controller is shown if we have access to the photo library override func viewDidAppear(_ animated: Bool) { // start animations zoomIn() } override func viewDidLoad() { super.viewDidLoad() // if access to the library is not // determined yet and not accessed or denied // show the get access button let status = PHPhotoLibrary.authorizationStatus() if (status == PHAuthorizationStatus.notDetermined) { actionButton.isHidden = false disclaimerLabel.isHidden = true } else { actionButton.isHidden = true disclaimerLabel.isHidden = false } // Do any additional setup after loading the view.// print("Disclaimer View Controller was loaded") } func showMainTabController(){ if let controller = self.storyboard?.instantiateViewController(withIdentifier: "TabBarController") as? UITabBarController{ // show it on the highest level as a modal view // present(controller, animated: false, completion: nil) // show it on the highest level as a modal view //show(controller, sender: self) DispatchQueue.main.async { print("Showing off MainTabController") self.view.window?.rootViewController = controller } } } @IBAction func requestLibraryAction(_ sender: Any) { print("requesting photo library action") let status = PHPhotoLibrary.authorizationStatus() // ask again print("Status: \(status) " ) if (status == PHAuthorizationStatus.authorized) { print("Access has been granted.") } else if (status == PHAuthorizationStatus.denied) { // Access has been denied. print("Access has been denied.") } else if (status == PHAuthorizationStatus.restricted) { // Access has been denied. print("restricted.") } PHPhotoLibrary.requestAuthorization({ (newStatus) in if (newStatus == PHAuthorizationStatus.authorized) { print("Authorized") //self.dismiss(animated: false, completion: nil) self.showMainTabController() } else { print("Nothing Authorized") // self.dismiss(animated: false, completion: nil) self.showMainTabController() } }) if (status == PHAuthorizationStatus.notDetermined) { // Access has not been determined. // ask again the user PHPhotoLibrary.requestAuthorization({ (newStatus) in if (newStatus == PHAuthorizationStatus.authorized) { print("Authorized") self.showMainTabController() } else { print("Nothing Authorized") self.showMainTabController() } }) } } 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
e9563636ba8f02ac0fff8869e185f5bb
28.641026
130
0.548731
5.872989
false
false
false
false
yaobanglin/viossvc
viossvc/Scenes/Chat/ChatLocation/SearchHeaderView.swift
1
2550
// // SearchHeaderView.swift // TestAdress // // Created by J-bb on 16/12/30. // Copyright © 2016年 J-bb. All rights reserved. // import UIKit class SearchHeaderView: UITableViewHeaderFooterView { lazy var backView:UIView = { let view = UIView() view.layer.cornerRadius = 6 view.backgroundColor = UIColor(red: 242 / 255.0, green: 242 / 255.0, blue: 242 / 255.0, alpha: 1.0) return view }() lazy var searchImageView:UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named: "chat_search") return imageView }() lazy var textField:UITextField = { let textField = UITextField() textField.font = UIFont.systemFontOfSize(16) textField.placeholder = "搜索" textField.returnKeyType = .Search textField.becomeFirstResponder() return textField }() lazy var cancelButton:UIButton = { let button = UIButton(type: .Custom) button.backgroundColor = UIColor.clearColor() button.setTitleColor(UIColor(red: 102 / 255.0, green: 102 / 255.0, blue: 102 / 255.0, alpha: 1.0), forState: .Normal) button.setTitle("取消", forState: .Normal) return button }() override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) backgroundColor = UIColor(white: 1.0, alpha: 0.5) addSubview(backView) addSubview(cancelButton) backView.addSubview(textField) backView.addSubview(searchImageView) cancelButton.snp_makeConstraints { (make) in make.right.equalTo(-10) make.bottom.equalTo(-10) make.width.equalTo(44) } backView.snp_makeConstraints { (make) in make.left.equalTo(10) make.right.equalTo(cancelButton.snp_left).offset(-10) make.centerY.equalTo(cancelButton.snp_centerY) make.height.equalTo(40) } searchImageView.snp_makeConstraints { (make) in make.left.equalTo(10) make.centerY.equalTo(backView) make.height.equalTo(16) make.width.equalTo(16) } textField.snp_makeConstraints { (make) in make.left.equalTo(searchImageView.snp_right).offset(5) make.right.equalTo(10) make.height.equalTo(30) make.centerY.equalTo(backView) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
c2adcf0e689b952df1130168e7fc62ef
25.175258
125
0.614415
4.274411
false
false
false
false
gu704823/DYTV
dytv/Pods/LeanCloud/Sources/Storage/DataType/User.swift
4
19454
// // LCUser.swift // LeanCloud // // Created by Tang Tianyong on 5/7/16. // Copyright © 2016 LeanCloud. All rights reserved. // import Foundation /** LeanCloud user type. A base type of LeanCloud built-in user system. You can extend this class with custom properties. However, LCUser can be extended only once. */ open class LCUser: LCObject { /// Username of user. open dynamic var username: LCString? /** Password of user. - note: this property will not be filled in when fetched or logged in for security. */ open dynamic var password: LCString? /** Email of user. If the "Enable Email Verification" application option is enabled, a verification email will be sent to user when user registered with an email address. */ open dynamic var email: LCString? /// A flag indicates whether email is verified or not. open fileprivate(set) dynamic var emailVerified: LCBool? /** Mobile phone number. If the "Enable Mobile Phone Number Verification" application option is enabled, an sms message will be sent to user's phone when user registered with a phone number. */ open dynamic var mobilePhoneNumber: LCString? /// A flag indicates whether mobile phone is verified or not. open fileprivate(set) dynamic var mobilePhoneVerified: LCBool? /// Session token of user authenticated by server. open fileprivate(set) dynamic var sessionToken: LCString? /// Current authenticated user. open static var current: LCUser? = nil public final override class func objectClassName() -> String { return "_User" } /** Sign up an user. - returns: The result of signing up request. */ open func signUp() -> LCBooleanResult { return self.save() } /** Sign up an user asynchronously. - parameter completion: The completion callback closure. */ open func signUp(_ completion: @escaping (LCBooleanResult) -> Void) { RESTClient.asynchronize({ self.signUp() }) { result in completion(result) } } /** Log in with username and password. - parameter username: The username. - parameter password: The password. - returns: The result of login request. */ open static func logIn<User: LCUser>(username: String, password: String) -> LCObjectResult<User> { return logIn(parameters: [ "username": username as AnyObject, "password": password as AnyObject ]) } /** Log in with username and password asynchronously. - parameter username: The username. - parameter password: The password. - parameter completion: The completion callback closure. */ open static func logIn<User: LCUser>(username: String, password: String, completion: @escaping (LCObjectResult<User>) -> Void) { RESTClient.asynchronize({ self.logIn(username: username, password: password) }) { result in completion(result) } } /** Log in with mobile phone number and password. - parameter username: The mobile phone number. - parameter password: The password. - returns: The result of login request. */ open static func logIn<User: LCUser>(mobilePhoneNumber: String, password: String) -> LCObjectResult<User> { return logIn(parameters: [ "mobilePhoneNumber": mobilePhoneNumber as AnyObject, "password": password as AnyObject ]) } /** Log in with mobile phone number and password asynchronously. - parameter mobilePhoneNumber: The mobile phone number. - parameter password: The password. - parameter completion: The completion callback closure. */ open static func logIn<User: LCUser>(mobilePhoneNumber: String, password: String, completion: @escaping (LCObjectResult<User>) -> Void) { RESTClient.asynchronize({ self.logIn(mobilePhoneNumber: mobilePhoneNumber, password: password) }) { result in completion(result) } } /** Log in with mobile phone number and verification code. - parameter mobilePhoneNumber: The mobile phone number. - parameter verificationCode: The verification code. - returns: The result of login request. */ open static func logIn<User: LCUser>(mobilePhoneNumber: String, verificationCode: String) -> LCObjectResult<User> { return logIn(parameters: [ "mobilePhoneNumber": mobilePhoneNumber as AnyObject, "smsCode": verificationCode as AnyObject ]) } /** Log in with mobile phone number and verification code asynchronously. - parameter mobilePhoneNumber: The mobile phone number. - parameter verificationCode: The verification code. - parameter completion: The completion callback closure. */ open static func logIn<User: LCUser>(mobilePhoneNumber: String, verificationCode: String, completion: @escaping (LCObjectResult<User>) -> Void) { RESTClient.asynchronize({ self.logIn(mobilePhoneNumber: mobilePhoneNumber, verificationCode: verificationCode) }) { result in completion(result) } } /** Log in with session token. - parameter sessionToken: The session token. - returns: The result of login request. */ open static func logIn<User: LCUser>(sessionToken: String) -> LCObjectResult<User> { let parameters = ["session_token": sessionToken] let endpoint = RESTClient.endpoint(objectClassName()) let response = RESTClient.request(.get, "\(endpoint)/me", parameters: parameters as [String: AnyObject]) let result = objectResult(response) as LCObjectResult<User> if case let .success(user) = result { LCUser.current = user } return result } /** Log in with session token asynchronously. - parameter sessionToken: The session token. - parameter completion: The completion callback closure. */ open static func logIn<User: LCUser>(sessionToken: String, completion: @escaping (LCObjectResult<User>) -> Void) { RESTClient.asynchronize({ self.logIn(sessionToken: sessionToken) }) { result in completion(result) } } /** Log in with parameters. - parameter parameters: The parameters. - returns: The result of login request. */ static func logIn<User: LCUser>(parameters: [String: AnyObject]) -> LCObjectResult<User> { let response = RESTClient.request(.post, "login", parameters: parameters) let result = objectResult(response) as LCObjectResult<User> if case let .success(user) = result { LCUser.current = user } return result } /** Sign up or log in with mobile phone number and verification code. This method will sign up a user automatically if user for mobile phone number not found. - parameter mobilePhoneNumber: The mobile phone number. - parameter verificationCode: The verification code. */ open static func signUpOrLogIn<User: LCUser>(mobilePhoneNumber: String, verificationCode: String) -> LCObjectResult<User> { let parameters = [ "mobilePhoneNumber": mobilePhoneNumber, "smsCode": verificationCode ] let response = RESTClient.request(.post, "usersByMobilePhone", parameters: parameters as [String: AnyObject]) let result = objectResult(response) as LCObjectResult<User> if case let .success(user) = result { LCUser.current = user } return result } /** Sign up or log in with mobile phone number and verification code asynchronously. - parameter mobilePhoneNumber: The mobile phone number. - parameter verificationCode: The verification code. - parameter completion: The completion callback closure. */ open static func signUpOrLogIn<User: LCUser>(mobilePhoneNumber: String, verificationCode: String, completion: @escaping (LCObjectResult<User>) -> Void) { RESTClient.asynchronize({ self.signUpOrLogIn(mobilePhoneNumber: mobilePhoneNumber, verificationCode: verificationCode) }) { result in completion(result) } } /** Convert response to user object result. - parameter response: The response of login request. - returns: The user object result of reponse. */ static func objectResult<User: LCUser>(_ response: LCResponse) -> LCObjectResult<User> { if let error = response.error { return .failure(error: error) } guard var dictionary = response.value as? [String: AnyObject] else { return .failure(error: LCError(code: .malformedData, reason: "Malformed user response data.")) } /* Patch response data to fulfill object format. */ dictionary["__type"] = RESTClient.DataType.object.rawValue as AnyObject? dictionary["className"] = LCUser.objectClassName() as AnyObject? let user = try! ObjectProfiler.object(jsonValue: dictionary as AnyObject) as! User return .success(object: user) } /** Log out current user. */ open static func logOut() { current = nil } /** Request to send a verification mail to specified email address. - parameter email: The email address to where the mail will be sent. - returns: The result of verification request. */ open static func requestVerificationMail(email: String) -> LCBooleanResult { let parameters = ["email": email] let response = RESTClient.request(.post, "requestEmailVerify", parameters: parameters as [String: AnyObject]) return LCBooleanResult(response: response) } /** Request to send a verification mail to specified email address asynchronously. - parameter email: The email address to where the mail will be sent. - parameter completion: The completion callback closure. */ open static func requestVerificationMail(email: String, completion: @escaping (LCBooleanResult) -> Void) { RESTClient.asynchronize({ self.requestVerificationMail(email: email) }) { result in completion(result) } } /** Request to send a verification code to specified mobile phone number. - parameter mobilePhoneNumber: The mobile phone number where the verification code will be sent to. - returns: The result of request. */ open static func requestVerificationCode(mobilePhoneNumber: String) -> LCBooleanResult { let parameters = ["mobilePhoneNumber": mobilePhoneNumber] let response = RESTClient.request(.post, "requestMobilePhoneVerify", parameters: parameters as [String: AnyObject]) return LCBooleanResult(response: response) } /** Request to send a verification code to specified mobile phone number asynchronously. - parameter mobilePhoneNumber: The mobile phone number where the verification code will be sent to. - parameter completion: The completion callback closure. */ open static func requestVerificationCode(mobilePhoneNumber: String, completion: @escaping (LCBooleanResult) -> Void) { RESTClient.asynchronize({ self.requestVerificationCode(mobilePhoneNumber: mobilePhoneNumber) }) { result in completion(result) } } /** Verify a mobile phone number. - parameter mobilePhoneNumber: The mobile phone number. - parameter verificationCode: The verification code. - returns: The result of verification request. */ open static func verifyMobilePhoneNumber(_ mobilePhoneNumber: String, verificationCode: String) -> LCBooleanResult { let parameters = ["mobilePhoneNumber": mobilePhoneNumber] let response = RESTClient.request(.get, "verifyMobilePhone/\(verificationCode)", parameters: parameters as [String: AnyObject]) return LCBooleanResult(response: response) } /** Verify mobile phone number with code asynchronously. - parameter mobilePhoneNumber: The mobile phone number. - parameter verificationCode: The verification code. - parameter completion: The completion callback closure. */ open static func verifyMobilePhoneNumber(_ mobilePhoneNumber: String, verificationCode: String, completion: @escaping (LCBooleanResult) -> Void) { RESTClient.asynchronize({ self.verifyMobilePhoneNumber(mobilePhoneNumber, verificationCode: verificationCode) }) { result in completion(result) } } /** Request a verification code for login with mobile phone number. - parameter mobilePhoneNumber: The mobile phone number where the verification code will be sent to. - returns: The result of request. */ open static func requestLoginVerificationCode(mobilePhoneNumber: String) -> LCBooleanResult { let parameters = ["mobilePhoneNumber": mobilePhoneNumber] let response = RESTClient.request(.post, "requestLoginSmsCode", parameters: parameters as [String: AnyObject]) return LCBooleanResult(response: response) } /** Request a verification code for login with mobile phone number asynchronously. - parameter mobilePhoneNumber: The mobile phone number where the verification code message will be sent to. - parameter completion: The completion callback closure. */ open static func requestLoginVerificationCode(mobilePhoneNumber: String, completion: @escaping (LCBooleanResult) -> Void) { RESTClient.asynchronize({ self.requestLoginVerificationCode(mobilePhoneNumber: mobilePhoneNumber) }) { result in completion(result) } } /** Request password reset mail. - parameter email: The email address where the password reset mail will be sent to. - returns: The result of request. */ open static func requestPasswordReset(email: String) -> LCBooleanResult { let parameters = ["email": email] let response = RESTClient.request(.post, "requestPasswordReset", parameters: parameters as [String: AnyObject]) return LCBooleanResult(response: response) } /** Request password reset email asynchronously. - parameter email: The email address where the password reset email will be sent to. - parameter completion: The completion callback closure. */ open static func requestPasswordReset(email: String, completion: @escaping (LCBooleanResult) -> Void) { RESTClient.asynchronize({ self.requestPasswordReset(email: email) }) { result in completion(result) } } /** Request password reset verification code. - parameter mobilePhoneNumber: The mobile phone number where the password reset verification code will be sent to. - returns: The result of request. */ open static func requestPasswordReset(mobilePhoneNumber: String) -> LCBooleanResult { let parameters = ["mobilePhoneNumber": mobilePhoneNumber] let response = RESTClient.request(.post, "requestPasswordResetBySmsCode", parameters: parameters as [String: AnyObject]) return LCBooleanResult(response: response) } /** Request password reset verification code asynchronously. - parameter mobilePhoneNumber: The mobile phone number where the password reset verification code will be sent to. - parameter completion: The completion callback closure. */ open static func requestPasswordReset(mobilePhoneNumber: String, completion: @escaping (LCBooleanResult) -> Void) { RESTClient.asynchronize({ self.requestPasswordReset(mobilePhoneNumber: mobilePhoneNumber) }) { result in completion(result) } } /** Reset password with verification code and new password. - note: This method will reset password of `LCUser.current`. If `LCUser.current` is nil, in other words, no user logged in, password reset will be failed because of permission. - parameter mobilePhoneNumber: The mobile phone number of user. - parameter verificationCode: The verification code in password reset message. - parameter newPassword: The new password. - returns: The result of reset request. */ open static func resetPassword(mobilePhoneNumber: String, verificationCode: String, newPassword: String) -> LCBooleanResult { let parameters = [ "mobilePhoneNumber": mobilePhoneNumber, "password": newPassword ] let response = RESTClient.request(.put, "resetPasswordBySmsCode/\(verificationCode)", parameters: parameters as [String: AnyObject]) return LCBooleanResult(response: response) } /** Reset password with verification code and new password asynchronously. - parameter mobilePhoneNumber: The mobile phone number of user. - parameter verificationCode: The verification code in password reset message. - parameter newPassword: The new password. - parameter completion: The completion callback closure. */ open static func resetPassword(mobilePhoneNumber: String, verificationCode: String, newPassword: String, completion: @escaping (LCBooleanResult) -> Void) { RESTClient.asynchronize({ self.resetPassword(mobilePhoneNumber: mobilePhoneNumber, verificationCode: verificationCode, newPassword: newPassword) }) { result in completion(result) } } /** Update password for user. - parameter oldPassword: The old password. - parameter newPassword: The new password. - returns: The result of update request. */ open func updatePassword(oldPassword: String, newPassword: String) -> LCBooleanResult { guard let endpoint = RESTClient.eigenEndpoint(self) else { return .failure(error: LCError(code: .notFound, reason: "User not found.")) } guard let sessionToken = sessionToken else { return .failure(error: LCError(code: .notFound, reason: "Session token not found.")) } let parameters = [ "old_password": oldPassword, "new_password": newPassword ] let headers = [RESTClient.HeaderFieldName.session: sessionToken.value] let response = RESTClient.request(.put, endpoint + "/updatePassword", parameters: parameters as [String: AnyObject], headers: headers) if let error = response.error { return .failure(error: error) } else { if let dictionary = response.value as? [String: AnyObject] { ObjectProfiler.updateObject(self, dictionary) } return .success } } /** Update password for user asynchronously. - parameter oldPassword: The old password. - parameter newPassword: The new password. - parameter completion: The completion callback closure. */ open func updatePassword(oldPassword: String, newPassword: String, completion: @escaping (LCBooleanResult) -> Void) { RESTClient.asynchronize({ self.updatePassword(oldPassword: oldPassword, newPassword: newPassword) }) { result in completion(result) } } }
mit
d13844066ca7385a0717e98483375a30
36.554054
167
0.674395
5.014952
false
false
false
false
son11592/STKeyboard
STKeyboard/Classes/STKeyboard.swift
2
4186
// // STKeyboard.swift // Bubu // // Created by Sơn Thái on 9/27/16. // Copyright © 2016 LOZI. All rights reserved. // import UIKit public enum STKeyboardType { case `default` case number case photo } open class STKeyboard: UIView { static let STKeyboardDefaultHeight: CGFloat = 216 open var textInput: UITextInput? fileprivate let backSpace = UIButton() required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init() { super.init(frame: CGRect.zero) self.commonInit() } open func commonInit() { self.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: STKeyboard.STKeyboardDefaultHeight) self.backgroundColor = UIColor.white } open func hideKeyboardTUI() { if let textField = self.textInput as? UITextField, textField.canResignFirstResponder { textField.resignFirstResponder() } if let textView = self.textInput as? UITextView, textView.canResignFirstResponder { textView.resignFirstResponder() } } open func backSpaceTD() { UIDevice.current.playInputClick() NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(autoDelete), object: nil) self.canPerformAction(#selector(autoDelete), withSender: nil) if let textInput = self.textInput, let selectedTextRange = textInput.selectedTextRange { if selectedTextRange.isEmpty { textInput.deleteBackward() } else { self.replaceText(inRange: textInput.selectedTextRange, withText: "") } } self.perform(#selector(autoDelete), with: nil, afterDelay: 0.5, inModes: [RunLoopMode.commonModes]) } open func returnSpaceTUI() { UIDevice.current.playInputClick() if let textField = self.textInput as? UITextField { _ = textField.delegate?.textFieldShouldReturn?(textField) } else if let _ = self.textInput as? UITextView { self.inputText(text: "\n") } } open func autoDelete() { if self.backSpace.isHighlighted, let textInput = self.textInput { textInput.deleteBackward() self.perform(#selector(autoDelete), with: nil, afterDelay: 0.2, inModes: [RunLoopMode.commonModes]) } } /* * Input */ open func setInputViewToView(_ view: UIView?) { (self.textInput as? UITextField)?.inputView = view (self.textInput as? UITextView)?.inputView = view (self.textInput as? UIResponder)?.reloadInputViews() } open func attachToTextInput(textInput: UITextInput) { self.textInput = textInput self.setInputViewToView(self) } open func switchToDefaultKeyboard() { self.setInputViewToView(nil) self.textInput = nil NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SwitchToDefaultKeyboard"), object: nil) } open func inputText(text: String) { if let textInput = self.textInput { self.replaceText(inRange: textInput.selectedTextRange, withText: text) } } open func replaceText(inRange range: UITextRange?, withText text: String) { if let range = range, self.textInputShouldReplaceText(inRange: range, replacementText: text) { self.textInput?.replace(range, withText: text) } } open func textInputShouldReplaceText(inRange range: UITextRange, replacementText text: String) -> Bool { if let textInput = self.textInput { let startOffset = textInput.offset(from: textInput.beginningOfDocument, to: range.start) let endOffset = textInput.offset(from: textInput.beginningOfDocument, to: range.end) let replacementRange = NSRange(location: startOffset, length: endOffset - startOffset) if let textView = textInput as? UITextView, let shouldChange = textView.delegate?.textView?(textView, shouldChangeTextIn: replacementRange, replacementText: text) { return shouldChange } if let textField = textInput as? UITextField, let shouldChange = textField.delegate?.textField?(textField, shouldChangeCharactersIn: replacementRange, replacementString: text) { return shouldChange } } return true } }
mit
7d6c53b1e6696e97333a87a9ae0d7af2
30.451128
139
0.689696
4.556645
false
false
false
false
SlimGinz/HomeworkHelper
Homework Helper/KaedeTextField.swift
1
4101
// // KaedeTextField.swift // Swish // // Created by Raúl Riera on 20/01/2015. // Copyright (c) 2015 com.raulriera.swishapp. All rights reserved. // @IBDesignable public class KaedeTextField: TextFieldEffects { @IBInspectable public var placeholderColor: UIColor? { didSet { updatePlaceholder() } } @IBInspectable public var foregroundColor: UIColor? { didSet { updateForegroundColor() } } override public var placeholder: String? { didSet { updatePlaceholder() } } override public var bounds: CGRect { didSet { drawViewsForRect(bounds) } } private let foregroundView = UIView() private let placeholderInsets = CGPoint(x: 10, y: 5) private let textFieldInsets = CGPoint(x: 10, y: 0) // MARK: - TextFieldsEffectsDelegate override func drawViewsForRect(rect: CGRect) { let frame = CGRect(origin: CGPointZero, size: CGSize(width: rect.size.width, height: rect.size.height)) foregroundView.frame = frame foregroundView.userInteractionEnabled = false placeholderLabel.frame = CGRectInset(frame, placeholderInsets.x, placeholderInsets.y) placeholderLabel.font = placeholderFontFromFont(font) updateForegroundColor() updatePlaceholder() if !text.isEmpty || isFirstResponder() { animateViewsForTextEntry() } addSubview(foregroundView) addSubview(placeholderLabel) delegate = self } // MARK: - private func updateForegroundColor() { foregroundView.backgroundColor = foregroundColor } private func updatePlaceholder() { placeholderLabel.text = placeholder placeholderLabel.textColor = placeholderColor } private func placeholderFontFromFont(font: UIFont) -> UIFont! { let smallerFont = UIFont(name: font.fontName, size: font.pointSize * 0.8) return smallerFont } override func animateViewsForTextEntry() { UIView.animateWithDuration(0.35, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: ({ self.placeholderLabel.frame.origin = CGPoint(x: self.frame.size.width * 0.65, y: self.placeholderInsets.y) }), completion: nil) UIView.animateWithDuration(0.45, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 1.5, options: UIViewAnimationOptions.BeginFromCurrentState, animations: ({ self.foregroundView.frame.origin = CGPoint(x: self.frame.size.width * 0.6, y: 0) }), completion: nil) } override func animateViewsForTextDisplay() { if text.isEmpty { UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: ({ self.placeholderLabel.frame.origin = self.placeholderInsets }), completion: nil) UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 2.0, options: UIViewAnimationOptions.BeginFromCurrentState, animations: ({ self.foregroundView.frame.origin = CGPointZero }), completion: nil) } } // MARK: - Overrides override public func editingRectForBounds(bounds: CGRect) -> CGRect { let frame = CGRect(origin: bounds.origin, size: CGSize(width: bounds.size.width * 0.6, height: bounds.size.height)) return CGRectInset(frame, textFieldInsets.x, textFieldInsets.y) } override public func textRectForBounds(bounds: CGRect) -> CGRect { let frame = CGRect(origin: bounds.origin, size: CGSize(width: bounds.size.width * 0.6, height: bounds.size.height)) return CGRectInset(frame, textFieldInsets.x, textFieldInsets.y) } }
gpl-2.0
38215b6f2a405de9ceaf568aac0a684d
34.973684
182
0.64439
5.099502
false
false
false
false
treejames/firefox-ios
Utils/Extensions/StringExtensions.swift
3
3153
/* 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 public extension String { public func contains(other: String) -> Bool { // rangeOfString returns nil if other is empty, destroying the analogy with (ordered) sets. if other.isEmpty { return true } return self.rangeOfString(other) != nil } public func startsWith(other: String) -> Bool { // rangeOfString returns nil if other is empty, destroying the analogy with (ordered) sets. if other.isEmpty { return true } if let range = self.rangeOfString(other, options: NSStringCompareOptions.AnchoredSearch) { return range.startIndex == self.startIndex } return false } public func endsWith(other: String) -> Bool { // rangeOfString returns nil if other is empty, destroying the analogy with (ordered) sets. if other.isEmpty { return true } if let range = self.rangeOfString(other, options: NSStringCompareOptions.AnchoredSearch | NSStringCompareOptions.BackwardsSearch) { return range.endIndex == self.endIndex } return false } func escape() -> String { var raw: NSString = self var str = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, raw, "[].",":/?&=;+!@#$()',*", CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)) return str as! String } func unescape() -> String { var raw: NSString = self var str = CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, raw, "[].") return str as! String } /** Ellipsizes a String only if it's longer than `maxLength` "ABCDEF".ellipsize(4) // "AB…EF" :param: maxLength The maximum length of the String. :returns: A String with `maxLength` characters or less */ func ellipsize(var #maxLength: Int) -> String { if (maxLength >= 2) && (count(self) > maxLength) { let index1 = advance(self.startIndex, (maxLength + 1) / 2) // `+ 1` has the same effect as an int ceil let index2 = advance(self.endIndex, maxLength / -2) return self.substringToIndex(index1) + "…\u{2060}" + self.substringFromIndex(index2) } return self } private var stringWithAdditionalEscaping: String { return self.stringByReplacingOccurrencesOfString("|", withString: "%7C", options: NSStringCompareOptions.allZeros, range: nil) } public var asURL: NSURL? { // Firefox and NSURL disagree about the valid contents of a URL. // Let's escape | for them. // We'd love to use one of the more sophisticated CFURL* or NSString.* functions, but // none seem to be quite suitable. return NSURL(string: self) ?? NSURL(string: self.stringWithAdditionalEscaping) } }
mpl-2.0
c2ab51c68d7a9a718adf4c5518afcd69
35.195402
134
0.62242
4.728228
false
false
false
false
piv199/EZSwiftExtensions
Sources/StringExtensions.swift
1
21170
// // StringExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // // swiftlint:disable line_length // swiftlint:disable trailing_whitespace #if os(OSX) import AppKit #else import UIKit #endif extension String { /// EZSE: Init string with a base64 encoded string init ? (base64: String) { let pad = String(repeating: "=", count: base64.length % 4) let base64Padded = base64 + pad if let decodedData = Data(base64Encoded: base64Padded, options: NSData.Base64DecodingOptions(rawValue: 0)), let decodedString = NSString(data: decodedData, encoding: String.Encoding.utf8.rawValue) { self.init(decodedString) return } return nil } /// EZSE: base64 encoded of string var base64: String { let plainData = (self as NSString).data(using: String.Encoding.utf8.rawValue) let base64String = plainData!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) return base64String } /// EZSE: Cut string from integerIndex to the end public subscript(integerIndex: Int) -> Character { let index = characters.index(startIndex, offsetBy: integerIndex) return self[index] } /// EZSE: Cut string from range public subscript(integerRange: Range<Int>) -> String { let start = characters.index(startIndex, offsetBy: integerRange.lowerBound) let end = characters.index(startIndex, offsetBy: integerRange.upperBound) return self[start..<end] } /// EZSE: Cut string from closedrange public subscript(integerClosedRange: ClosedRange<Int>) -> String { return self[integerClosedRange.lowerBound..<(integerClosedRange.upperBound + 1)] } /// EZSE: Character count public var length: Int { return self.characters.count } /// EZSE: Counts number of instances of the input inside String public func count(_ substring: String) -> Int { return components(separatedBy: substring).count - 1 } /// EZSE: Capitalizes first character of String public mutating func capitalizeFirst() { guard characters.count > 0 else { return } self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).capitalized) } /// EZSE: Capitalizes first character of String, returns a new string public func capitalizedFirst() -> String { guard characters.count > 0 else { return self } var result = self result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).capitalized) return result } /// EZSE: Uppercases first 'count' characters of String public mutating func uppercasePrefix(_ count: Int) { guard characters.count > 0 && count > 0 else { return } self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)), with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased()) } /// EZSE: Uppercases first 'count' characters of String, returns a new string public func uppercasedPrefix(_ count: Int) -> String { guard characters.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)), with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).uppercased()) return result } /// EZSE: Uppercases last 'count' characters of String public mutating func uppercaseSuffix(_ count: Int) { guard characters.count > 0 && count > 0 else { return } self.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex, with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased()) } /// EZSE: Uppercases last 'count' characters of String, returns a new string public func uppercasedSuffix(_ count: Int) -> String { guard characters.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(characters.index(endIndex, offsetBy: -min(count, length))..<endIndex, with: String(self[characters.index(endIndex, offsetBy: -min(count, length))..<endIndex]).uppercased()) return result } /// EZSE: Uppercases string in range 'range' (from range.startIndex to range.endIndex) public mutating func uppercase(range: CountableRange<Int>) { let from = max(range.lowerBound, 0), to = min(range.upperBound, length) guard characters.count > 0 && (0..<length).contains(from) else { return } self.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to), with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).uppercased()) } /// EZSE: Uppercases string in range 'range' (from range.startIndex to range.endIndex), returns new string public func uppercased(range: CountableRange<Int>) -> String { let from = max(range.lowerBound, 0), to = min(range.upperBound, length) guard characters.count > 0 && (0..<length).contains(from) else { return self } var result = self result.replaceSubrange(characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to), with: String(self[characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to)]).uppercased()) return result } /// EZSE: Lowercases first character of String public mutating func lowercaseFirst() { guard characters.count > 0 else { return } self.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased()) } /// EZSE: Lowercases first character of String, returns a new string public func lowercasedFirst() -> String { guard characters.count > 0 else { return self } var result = self result.replaceSubrange(startIndex...startIndex, with: String(self[startIndex]).lowercased()) return result } /// EZSE: Lowercases first 'count' characters of String public mutating func lowercasePrefix(_ count: Int) { guard characters.count > 0 && count > 0 else { return } self.replaceSubrange(startIndex..<self.index(startIndex, offsetBy: min(count, length)), with: String(self[startIndex..<self.index(startIndex, offsetBy: min(count, length))]).lowercased()) } /// EZSE: Lowercases first 'count' characters of String, returns a new string public func lowercasedPrefix(_ count: Int) -> String { guard characters.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(startIndex..<characters.index(startIndex, offsetBy: min(count, length)), with: String(self[startIndex..<characters.index(startIndex, offsetBy: min(count, length))]).lowercased()) return result } /// EZSE: Lowercases last 'count' characters of String public mutating func lowercaseSuffix(_ count: Int) { guard characters.count > 0 && count > 0 else { return } self.replaceSubrange(self.index(endIndex, offsetBy: -min(count, length))..<endIndex, with: String(self[self.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased()) } /// EZSE: Lowercases last 'count' characters of String, returns a new string public func lowercasedSuffix(_ count: Int) -> String { guard characters.count > 0 && count > 0 else { return self } var result = self result.replaceSubrange(characters.index(endIndex, offsetBy: -min(count, length))..<endIndex, with: String(self[characters.index(endIndex, offsetBy: -min(count, length))..<endIndex]).lowercased()) return result } /// EZSE: Lowercases string in range 'range' (from range.startIndex to range.endIndex) public mutating func lowercase(range: CountableRange<Int>) { let from = max(range.lowerBound, 0), to = min(range.upperBound, length) guard characters.count > 0 && (0..<length).contains(from) else { return } self.replaceSubrange(self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to), with: String(self[self.index(startIndex, offsetBy: from)..<self.index(startIndex, offsetBy: to)]).lowercased()) } /// EZSE: Lowercases string in range 'range' (from range.startIndex to range.endIndex), returns new string public func lowercased(range: CountableRange<Int>) -> String { let from = max(range.lowerBound, 0), to = min(range.upperBound, length) guard characters.count > 0 && (0..<length).contains(from) else { return self } var result = self result.replaceSubrange(characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to), with: String(self[characters.index(startIndex, offsetBy: from)..<characters.index(startIndex, offsetBy: to)]).lowercased()) return result } /// EZSE: Counts whitespace & new lines @available(*, deprecated: 1.6, renamed: "isBlank") public func isOnlyEmptySpacesAndNewLineCharacters() -> Bool { let characterSet = CharacterSet.whitespacesAndNewlines let newText = self.trimmingCharacters(in: characterSet) return newText.isEmpty } /// EZSE: Checks if string is empty or consists only of whitespace and newline characters public var isBlank: Bool { get { let trimmed = trimmingCharacters(in: .whitespacesAndNewlines) return trimmed.isEmpty } } /// EZSE: Trims white space and new line characters public mutating func trim() { self = self.trimmed() } /// EZSE: Trims white space and new line characters, returns a new string public func trimmed() -> String { return self.trimmingCharacters(in: .whitespacesAndNewlines) } /// EZSE: Position of begining character of substing public func positionOfSubstring(_ subString: String, caseInsensitive: Bool = false, fromEnd: Bool = false) -> Int { if subString.isEmpty { return -1 } var searchOption = fromEnd ? NSString.CompareOptions.anchored : NSString.CompareOptions.backwards if caseInsensitive { searchOption.insert(NSString.CompareOptions.caseInsensitive) } if let range = self.range(of: subString, options: searchOption), !range.isEmpty { return self.characters.distance(from: self.startIndex, to: range.lowerBound) } return -1 } /// EZSE: split string using a spearator string, returns an array of string public func split(_ separator: String) -> [String] { return self.components(separatedBy: separator).filter { !$0.trimmed().isEmpty } } /// EZSE: split string with delimiters, returns an array of string public func split(_ characters: CharacterSet) -> [String] { return self.components(separatedBy: characters).filter { !$0.trimmed().isEmpty } } /// EZSE : Returns count of words in string public var countofWords: Int { let regex = try? NSRegularExpression(pattern: "\\w+", options: NSRegularExpression.Options()) return regex?.numberOfMatches(in: self, options: NSRegularExpression.MatchingOptions(), range: NSRange(location: 0, length: self.length)) ?? 0 } /// EZSE : Returns count of paragraphs in string public var countofParagraphs: Int { let regex = try? NSRegularExpression(pattern: "\\n", options: NSRegularExpression.Options()) let str = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) return (regex?.numberOfMatches(in: str, options: NSRegularExpression.MatchingOptions(), range: NSRange(location:0, length: str.length)) ?? -1) + 1 } internal func rangeFromNSRange(_ nsRange: NSRange) -> Range<String.Index>? { let from16 = utf16.startIndex.advanced(by: nsRange.location) let to16 = from16.advanced(by: nsRange.length) if let from = String.Index(from16, within: self), let to = String.Index(to16, within: self) { return from ..< to } return nil } /// EZSE: Find matches of regular expression in string public func matchesForRegexInText(_ regex: String!) -> [String] { let regex = try? NSRegularExpression(pattern: regex, options: []) let results = regex?.matches(in: self, options: [], range: NSRange(location: 0, length: self.length)) ?? [] return results.map { self.substring(with: self.rangeFromNSRange($0.range)!) } } /// EZSE: Checks if String contains Email public var isEmail: Bool { let dataDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) let firstMatch = dataDetector?.firstMatch(in: self, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSRange(location: 0, length: length)) return (firstMatch?.range.location != NSNotFound && firstMatch?.url?.scheme == "mailto") } /// EZSE: Returns if String is a number public func isNumber() -> Bool { if let _ = NumberFormatter().number(from: self) { return true } return false } /// EZSE: Extracts URLS from String public var extractURLs: [URL] { var urls: [URL] = [] let detector: NSDataDetector? do { detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) } catch _ as NSError { detector = nil } let text = self if let detector = detector { detector.enumerateMatches(in: text, options: [], range: NSRange(location: 0, length: text.characters.count), using: { (result: NSTextCheckingResult?, flags: NSRegularExpression.MatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in if let result = result, let url = result.url { urls.append(url) } }) } return urls } /// EZSE: Checking if String contains input with comparing options public func contains(_ find: String, compareOption: NSString.CompareOptions) -> Bool { return self.range(of: find, options: compareOption) != nil } /// EZSE: Converts String to Int public func toInt() -> Int? { if let num = NumberFormatter().number(from: self) { return num.intValue } else { return nil } } /// EZSE: Converts String to Double public func toDouble() -> Double? { if let num = NumberFormatter().number(from: self) { return num.doubleValue } else { return nil } } /// EZSE: Converts String to Float public func toFloat() -> Float? { if let num = NumberFormatter().number(from: self) { return num.floatValue } else { return nil } } /// EZSE: Converts String to Bool public func toBool() -> Bool? { let trimmedString = trimmed().lowercased() if trimmedString == "true" || trimmedString == "false" { return (trimmedString as NSString).boolValue } return nil } ///EZSE: Returns the first index of the occurency of the character in String public func getIndexOf(_ char: Character) -> Int? { for (index, c) in characters.enumerated() { if c == char { return index } } return nil } /// EZSE: Converts String to NSString public var toNSString: NSString { get { return self as NSString } } #if os(iOS) ///EZSE: Returns bold NSAttributedString public func bold() -> NSAttributedString { let boldString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)]) return boldString } #endif ///EZSE: Returns underlined NSAttributedString public func underline() -> NSAttributedString { let underlineString = NSAttributedString(string: self, attributes: [NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue]) return underlineString } #if os(iOS) ///EZSE: Returns italic NSAttributedString public func italic() -> NSAttributedString { let italicString = NSMutableAttributedString(string: self, attributes: [NSFontAttributeName: UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)]) return italicString } #endif #if os(iOS) ///EZSE: Returns hight of rendered string func height(_ width: CGFloat, font: UIFont, lineBreakMode: NSLineBreakMode?) -> CGFloat { var attrib: [String: AnyObject] = [NSFontAttributeName: font] if lineBreakMode != nil { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineBreakMode = lineBreakMode! attrib.updateValue(paragraphStyle, forKey: NSParagraphStyleAttributeName) } let size = CGSize(width: width, height: CGFloat(DBL_MAX)) return ceil((self as NSString).boundingRect(with: size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes:attrib, context: nil).height) } #endif ///EZSE: Returns NSAttributedString public func color(_ color: UIColor) -> NSAttributedString { let colorString = NSMutableAttributedString(string: self, attributes: [NSForegroundColorAttributeName: color]) return colorString } ///EZSE: Returns NSAttributedString public func colorSubString(_ subString: String, color: UIColor) -> NSMutableAttributedString { var start = 0 var ranges: [NSRange] = [] while true { let range = (self as NSString).range(of: subString, options: NSString.CompareOptions.literal, range: NSRange(location: start, length: (self as NSString).length - start)) if range.location == NSNotFound { break } else { ranges.append(range) start = range.location + range.length } } let attrText = NSMutableAttributedString(string: self) for range in ranges { attrText.addAttribute(NSForegroundColorAttributeName, value: color, range: range) } return attrText } /// EZSE: Checks if String contains Emoji public func includesEmoji() -> Bool { for i in 0...length { let c: unichar = (self as NSString).character(at: i) if (0xD800 <= c && c <= 0xDBFF) || (0xDC00 <= c && c <= 0xDFFF) { return true } } return false } #if os(iOS) /// EZSE: copy string to pasteboard public func addToPasteboard() { let pasteboard = UIPasteboard.general pasteboard.string = self } #endif // EZSE: URL encode a string (percent encoding special chars) public func urlEncoded() -> String { return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! } // EZSE: URL encode a string (percent encoding special chars) mutating version mutating func urlEncode() { self = urlEncoded() } // EZSE: Removes percent encoding from string public func urlDecoded() -> String { return removingPercentEncoding ?? self } // EZSE : Mutating versin of urlDecoded mutating func urlDecode() { self = urlDecoded() } } extension String { init(_ value: Float, precision: Int) { let nFormatter = NumberFormatter() nFormatter.numberStyle = .decimal nFormatter.maximumFractionDigits = precision self = nFormatter.string(from: NSNumber(value: value))! } init(_ value: Double, precision: Int) { let nFormatter = NumberFormatter() nFormatter.numberStyle = .decimal nFormatter.maximumFractionDigits = precision self = nFormatter.string(from: NSNumber(value: value))! } } /// EZSE: Pattern matching of strings via defined functions public func ~=<T> (pattern: ((T) -> Bool), value: T) -> Bool { return pattern(value) } /// EZSE: Can be used in switch-case public func hasPrefix(_ prefix: String) -> (_ value: String) -> Bool { return { (value: String) -> Bool in value.hasPrefix(prefix) } } /// EZSE: Can be used in switch-case public func hasSuffix(_ suffix: String) -> (_ value: String) -> Bool { return { (value: String) -> Bool in value.hasSuffix(suffix) } }
mit
481d3a8196242d43e2af5f8b6c3e4f0e
40.18677
206
0.639773
4.825621
false
false
false
false
bluepi0j/BPPopCardTransition
Example/Example/ViewController.swift
1
3145
// // ViewController.swift // Example // // Created by Vic on 2017-08-12. // Copyright © 2017 bluepi0j. All rights reserved. // import UIKit import BPPopCardTransition class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, BPPopCardAnimtionDelegate { @IBOutlet var collectionView: UICollectionView! var selectedCellFrame: CGRect? var selectedCellImageView: UIImageView? let transitionDelegate:BPPopCardTransitionsDelegate = BPPopCardTransitionsDelegate() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 5 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) // rounded corner cell.contentView.layer.cornerRadius = 8.0 cell.contentView.layer.masksToBounds = true // add rounded corner shadow cell.layer.cornerRadius = 8.0 cell.layer.masksToBounds = false cell.layer.shadowColor = UIColor.gray.cgColor cell.layer.shadowRadius = 5.0 cell.layer.shadowOpacity = 0.3 cell.layer.shadowOffset = CGSize(width: 0.4, height: 1.0) cell.layer.shadowPath = UIBezierPath(roundedRect: cell.bounds, cornerRadius: cell.contentView.layer.cornerRadius).cgPath return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let cell: ImageCollectionViewCell = collectionView.cellForItem(at: indexPath)! as! ImageCollectionViewCell selectedCellFrame = collectionView.convert(cell.frame, to: self.view) selectedCellImageView = cell.cellImageView let popCardViewController: PopCardViewController = self.storyboard?.instantiateViewController(withIdentifier: "PopCardViewController") as! PopCardViewController transitionDelegate.delegate = self popCardViewController.transitioningDelegate = transitionDelegate popCardViewController.bannerImage = self.selectedCellImageView!.image popCardViewController.modalPresentationStyle = .custom self.present(popCardViewController, animated: true, completion: nil) } // MARK: - BPPopCardAnimtionDelegate func rectZoomPosition() -> CGRect { return selectedCellFrame! } func cellImageView() -> UIImageView { return selectedCellImageView! } func popCardViewBannerHeight() -> CGFloat { return CGFloat(267) } }
mit
4606221c30bf02bbfa016587d532a460
31.081633
168
0.693066
5.584369
false
false
false
false
carabina/Butterfly
Example/Pods/Butterfly/Butterfly/ButterflyFileUploader.swift
1
9094
// // ButterflyFileUploader.swift // Butterfly // // Created by Zhijie Huang on 15/7/30. // // Copyright (c) 2015 Zhijie Huang <[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. // Largely based on this stackoverflow question: // http://stackoverflow.com/questions/26121827/uploading-file-with-parameters-using-alamofire/28467829// import Foundation import Alamofire private struct ButterflyFileUploadInfo { var name: String? var mimeType: String? var fileName: String? var url: NSURL? var data: NSData? init( name: String, withFileURL url: NSURL, withMimeType mimeType: String? = nil ) { self.name = name self.url = url self.fileName = name self.mimeType = "application/octet-stream" if let mimeType = mimeType { self.mimeType = mimeType } if let _name = url.lastPathComponent { fileName = _name } if let mimeType = mimeType, let _extension = url.pathExtension { switch _extension.lowercaseString { case "jpeg", "jpg": self.mimeType = "image/jpeg" case "png": self.mimeType = "image/png" default: self.mimeType = "application/octet-stream" } } } init( name: String, withData data: NSData, withMimeType mimeType: String ) { self.name = name self.data = data self.fileName = name self.mimeType = mimeType } } private let sharedInstance = ButterflyFileUploader() public class ButterflyFileUploader { // MARK: - Private instance private var parameters = [String: String]() private var files = [ButterflyFileUploadInfo]() private var headers = [String: String]() // @discussion Make sure your serverURLString is valid before a further application. // Call `setServerURLString` to replace the default "http://myserver.com/uploadFile" with your own's. public var serverURLString: String? = "http://myserver.com/uploadFile" /// /// Set uploader 's server URL /// /// @param URL The server URL. /// public func setServerURLString( URL: String ) { serverURLString = URL } public class var sharedUploader: ButterflyFileUploader { return sharedInstance; } /// /// @abstract Set the parameters of file content in the `Content-Disposition` HTTP header. /// /// @param value The value to associate with the file content in the `Content-Disposition` HTTP header. /// @param parameter The parameter to associate with the file content in the `Content-Disposition` HTTP header. /// public func setValue( value: String!, forParameter parameter: String ) { parameters[parameter] = value } /// /// @abstract Set the parameters of file content in the `Content-Disposition` HTTP header. /// /// @param map The key and value of map to associate with the file content in the `Content-Disposition` HTTP header. /// public func addParametersFrom( #map: [String: String!] ) { for (key,value) in map { parameters[key] = value } } /// /// @abstract Sets the value of the given HTTP header field. /// @discussion If a value was previously set for the given header field, that value is replaced with the given value. /// Note that, in keeping with the HTTP RFC, HTTP header field names are case-insensitive. /// /// @param value The header field value. /// @param header The header field name (case-insensitive). /// public func setValue( value: String!, forHeader header: String ) { headers[header] = value } /// /// Set the parameters of file content in the `Content-Disposition` HTTP header. /// /// @param value The value to associate with the file content in the `Content-Disposition` HTTP header. /// /// @param parameter The parameter to associate with the file content in the `Content-Disposition` HTTP header. /// public func addHeadersFrom( #map: [String: String!] ) { for (key,value) in map { headers[key] = value } } /// /// Add one file or multiple files with file URL to uploader. /// /// @param url The URL of the file whose content will be encoded into the multipart form data. /// /// @param name The name to associate with the file content in the `Content-Disposition` HTTP header. /// /// @param mimeType The MIME type to associate with the data in the `Content-Type` HTTP header. /// public func addFileURL( url: NSURL, withName name: String, withMimeType mimeType: String? = nil ) { files.append( ButterflyFileUploadInfo( name: name, withFileURL: url, withMimeType: mimeType ) ) } /// /// Add one file or multiple files with NSData to uploader. /// /// @param data The data to encode into the multipart form data. /// /// @param name The name to associate with the file content in the `Content-Disposition` HTTP header. /// /// @param mimeType The MIME type to associate with the data in the `Content-Type` HTTP header. /// public func addFileData( data: NSData, withName name: String, withMimeType mimeType: String = "application/octet-stream" ) { files.append( ButterflyFileUploadInfo( name: name, withData: data, withMimeType: mimeType ) ) } lazy var request: NSMutableURLRequest = { var urlRequest = NSMutableURLRequest() urlRequest.HTTPMethod = "POST" urlRequest.URL = NSURL(string: ButterflyFileUploader.sharedUploader.serverURLString!) return urlRequest }() // MARK: - Private Method internal func startUploading( request sourceRequest: NSURLRequest? ) -> Request? { var request = sourceRequest!.mutableCopy() as! NSMutableURLRequest let boundary = "FileUploader-boundary-\(arc4random())-\(arc4random())" request.setValue( "multipart/form-data;boundary=\(boundary)", forHTTPHeaderField: "Content-Type") let data = NSMutableData() for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) } // Amazon S3 (probably others) wont take parameters after files, so we put them first for (key, value) in parameters { data.appendData("\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) data.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!) } for fileUploadInfo in files { data.appendData( "\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)! ) data.appendData( "Content-Disposition: form-data; name=\"\(fileUploadInfo.name)\"; filename=\"\(fileUploadInfo.fileName)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) data.appendData( "Content-Type: \(fileUploadInfo.mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) if let fileData = fileUploadInfo.data { data.appendData( fileData ) } else if let url = fileUploadInfo.url, let fileData = NSData(contentsOfURL: url) { data.appendData( fileData ) } else { // ToDo: report error return nil } } data.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) /// Start uploading return Alamofire.upload( request, data: data ) } internal func upload() { ButterflyFileUploader.sharedUploader.startUploading(request: self.request) } // MARK: - Deinit deinit { } }
mit
1e559587226250a0135eedc4776e1c46
39.598214
181
0.633385
4.599899
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Login Management/LoginOnboardingViewController.swift
2
4488
// 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 UIKit import Shared class LoginOnboardingViewController: SettingsViewController { private var shownFromAppMenu: Bool = false private var onboardingMessageLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = .Settings.Passwords.OnboardingMessage label.font = DynamicFontHelper().DeviceFontExtraLarge label.textAlignment = .center label.numberOfLines = 0 return label }() private lazy var learnMoreButton: UIButton = { let button = UIButton(type: .system) button.translatesAutoresizingMaskIntoConstraints = false button.setTitle(.LoginsOnboardingLearnMoreButtonTitle, for: .normal) button.addTarget(self, action: #selector(learnMoreButtonTapped), for: .touchUpInside) button.titleLabel?.font = DynamicFontHelper().DeviceFontExtraLarge return button }() private lazy var continueButton: UIButton = { let button = UIButton(type: .custom) button.translatesAutoresizingMaskIntoConstraints = false button.layer.cornerRadius = 8 button.setTitle(.LoginsOnboardingContinueButtonTitle, for: .normal) button.titleLabel?.font = DynamicFontHelper().MediumSizeBoldFontAS button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0) button.addTarget(self, action: #selector(proceedButtonTapped), for: .touchUpInside) return button }() var doneHandler: () -> Void = {} var proceedHandler: () -> Void = {} init(profile: Profile? = nil, tabManager: TabManager? = nil, shownFromAppMenu: Bool = false) { super.init(profile: profile, tabManager: tabManager) self.shownFromAppMenu = shownFromAppMenu } required init?(coder aDecoder: NSCoder) { fatalError("not implemented") } override func viewDidLoad() { super.viewDidLoad() if shownFromAppMenu { navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(doneButtonTapped)) } self.title = .Settings.Passwords.Title self.view.addSubviews(onboardingMessageLabel, learnMoreButton, continueButton) NSLayoutConstraint.activate([ onboardingMessageLabel.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 20), onboardingMessageLabel.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -20), onboardingMessageLabel.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), onboardingMessageLabel.centerYAnchor.constraint(equalTo: self.view.centerYAnchor), learnMoreButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), learnMoreButton.topAnchor.constraint(equalTo: onboardingMessageLabel.safeAreaLayoutGuide.bottomAnchor, constant: 20), continueButton.bottomAnchor.constraint(equalTo: self.view.layoutMarginsGuide.bottomAnchor, constant: -20), continueButton.heightAnchor.constraint(equalToConstant: 44), continueButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), continueButton.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor, constant: 35, priority: .defaultHigh), continueButton.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -35, priority: .defaultHigh), continueButton.widthAnchor.constraint(lessThanOrEqualToConstant: 360) ]) } @objc func doneButtonTapped(_ sender: UIButton) { self.doneHandler() } @objc func learnMoreButtonTapped(_ sender: UIButton) { let viewController = SettingsContentViewController() viewController.url = SupportUtils.URLForTopic("set-passcode-and-touch-id-firefox") navigationController?.pushViewController(viewController, animated: true) } @objc func proceedButtonTapped(_ sender: UIButton) { self.proceedHandler() } override func applyTheme() { super.applyTheme() continueButton.backgroundColor = themeManager.currentTheme.colors.actionPrimary } }
mpl-2.0
76ef19cb6b940fa68aab1f5caf1d4d4b
43.88
147
0.715909
5.362007
false
false
false
false
Pyroh/Fluor
Fluor/Misc/UserNotificationHelper.swift
1
10717
// // UserNotificationHelper.swift // // Fluor // // MIT License // // Copyright (c) 2020 Pierre Tacchi // // 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 Cocoa import UserNotifications enum UserNotificationHelper { static var holdNextModeChangedNotification: Bool = false static func askUserAtLaunch() { guard !AppManager.default.hideNotificationAuthorizationPopup else { return } if #available(OSX 10.14, *) { askOnStartupIfNeeded() } else { legacyAskOnStartupIfNeededStartup() } } static func askUser(then action: @escaping (Bool) -> ()) { if #available(OSX 10.14, *) { askIfNeeded(then: action) } else { legacyAskIfNeeded(then: action) } } static func sendModeChangedTo(_ mode: FKeyMode) { guard !holdNextModeChangedNotification else { holdNextModeChangedNotification.toggle() return } guard AppManager.default.userNotificationEnablement.contains(.appSwitch) else { return } let title = NSLocalizedString("F-Keys mode changed", comment: "") let message = mode.label send(title: title, message: message) } static func sendFKeyChangedAppBehaviorTo(_ behavior: AppBehavior, appName: String) { guard AppManager.default.userNotificationEnablement.contains(.appKey) else { return } let title = String(format: NSLocalizedString("F-Keys mode changed for %@", comment: ""), appName) let message = behavior.label send(title: title, message: message) } static func sendGlobalModeChangedTo(_ mode: FKeyMode) { guard AppManager.default.userNotificationEnablement.contains(.globalKey) else { return } let title = NSLocalizedString("Default mode changed", comment: "") let message = mode.label send(title: title, message: message) } private static func send(title: String, message: String) { if #available(OSX 10.14, *) { sendNotification(withTitle: title, andMessage: message) } else { legacySendNotification(withMessage: title, andMessage: message) } } @available(OSX 10.14, *) private static func sendNotification(withTitle title: String, andMessage msg: String) { let content = UNMutableNotificationContent() content.title = title content.subtitle = msg let req = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil) UNUserNotificationCenter.current().add(req) } private static func legacySendNotification(withMessage title: String, andMessage msg: String) { let notification = NSUserNotification() notification.title = title notification.subtitle = msg NSUserNotificationCenter.default.deliver(notification) } static func ifAuthorized(perform action: @escaping () -> (), else unauthorizedAction: @escaping () -> ()) { if #available(OSX 10.14, *) { UNUserNotificationCenter.current().getNotificationSettings { (settings) in DispatchQueue.main.async { guard settings.authorizationStatus == .authorized else { return unauthorizedAction() } action() } } } else { guard AppManager.default.sendLegacyUserNotifications else { return unauthorizedAction() } action() } } @available(OSX 10.14, *) private static func askOnStartupIfNeeded() { UNUserNotificationCenter.current().getNotificationSettings { (settings) in DispatchQueue.main.async { guard settings.authorizationStatus != .denied, settings.authorizationStatus != .authorized else { return } guard settings.authorizationStatus != .authorized else { return } let alert = makeAlert(suppressible: true) let avc = makeAccessoryView() alert.buttons.first?.bind(.enabled, to: avc, withKeyPath: "canEnableNotifications", options: nil) alert.accessoryView = avc.view NSApp.activate(ignoringOtherApps: true) let result = alert.runModal() if result == .alertFirstButtonReturn { UNUserNotificationCenter.current().requestAuthorization(options: .alert) { (isAuthorized, err) in DispatchQueue.main.async { if let error = err, isAuthorized { AppErrorManager.showError(withReason: error.localizedDescription) } if isAuthorized { AppManager.default.userNotificationEnablement = .from(avc) } else { AppManager.default.userNotificationEnablement = .none } } } } else { AppManager.default.userNotificationEnablement = .none } AppManager.default.hideNotificationAuthorizationPopup = alert.suppressionButton?.state == .on } } } private static func legacyAskOnStartupIfNeededStartup() { guard !AppManager.default.sendLegacyUserNotifications else { return } let alert = makeAlert(suppressible: true) let avc = makeAccessoryView() alert.buttons.first?.bind(.enabled, to: avc, withKeyPath: "canEnableNotifications", options: nil) alert.accessoryView = avc.view NSApp.activate(ignoringOtherApps: true) let result = alert.runModal() if result == .alertFirstButtonReturn { AppManager.default.sendLegacyUserNotifications = true AppManager.default.userNotificationEnablement = .from(avc) } } @available(OSX 10.14, *) private static func askIfNeeded(then action: @escaping (Bool) -> ()) { UNUserNotificationCenter.current().getNotificationSettings { (settings) in DispatchQueue.main.async { guard settings.authorizationStatus != .authorized else { return action(true) } if settings.authorizationStatus == .denied { if retryOnDenied() { askIfNeeded(then: action) } else { action(false) } } else { let alert = makeAlert() NSApp.activate(ignoringOtherApps: true) let result = alert.runModal() guard result == .alertFirstButtonReturn else { return action(false) } UNUserNotificationCenter.current().requestAuthorization(options: .alert) { (isAuthorized, err) in DispatchQueue.main.async { if let error = err, isAuthorized { AppErrorManager.showError(withReason: error.localizedDescription) } action(isAuthorized) } } } } } } private static func legacyAskIfNeeded(then action: (Bool) -> ()) { guard AppManager.default.sendLegacyUserNotifications else { return } let alert = makeAlert() NSApp.activate(ignoringOtherApps: true) let result = alert.runModal() action(result == .alertFirstButtonReturn) } private static func retryOnDenied() -> Bool { let alert = NSAlert() alert.alertStyle = .critical alert.messageText = NSLocalizedString("Notifications are not allowed from Fluor", comment: "") alert.informativeText = "To allow notifications from Fluor follow these steps:" alert.addButton(withTitle: NSLocalizedString("I allowed it", comment: "")) alert.addButton(withTitle: NSLocalizedString("I won't allow it", comment: "")) let vc = NSStoryboard(name: .preferences, bundle: nil).instantiateController(withIdentifier: "DebugAuthorization") as? NSViewController alert.accessoryView = vc?.view NSApp.activate(ignoringOtherApps: true) let result = alert.runModal() return result == .alertFirstButtonReturn } private static func makeAlert(suppressible: Bool = false) -> NSAlert { let alert = NSAlert() alert.icon = NSImage(imageLiteralResourceName: "QuestionMark") alert.messageText = NSLocalizedString("Enable notifications ?", comment: "") alert.informativeText = NSLocalizedString("Fluor can send notifications when the F-Keys mode changes.", comment: "") if suppressible { alert.showsSuppressionButton = true alert.suppressionButton?.title = NSLocalizedString("Don't ask me on startup again", comment: "") alert.suppressionButton?.state = .off } alert.addButton(withTitle: NSLocalizedString("Enable notfications", comment: "")) alert.addButton(withTitle: NSLocalizedString("Don't enable notifications", comment: "")) return alert } private static func makeAccessoryView() -> UserNotificationEnablementViewController { let avc = UserNotificationEnablementViewController.instantiate() avc.isShownInAlert = true return avc } }
mit
78e276baa905bfa61bd5d3bc6cd60e92
42.388664
143
0.613231
5.440102
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/NSManagedObjectContext+NC.swift
2
1204
// // NSManagedObjectContext+NC.swift // Neocom // // Created by Artem Shimanski on 11.01.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import Foundation import CoreData extension NSManagedObjectContext { public func fetch<Type:NSFetchRequestResult>(_ entityName:String, limit: Int = 0, sortedBy:[NSSortDescriptor] = [], `where`: String? = nil, _ args: CVarArg...) -> Type? { let request = NSFetchRequest<Type>(entityName: entityName) request.sortDescriptors = sortedBy request.fetchLimit = limit if let pred = `where` { request.predicate = withVaList(args) { return NSPredicate(format: pred, arguments: $0) } } request.fetchLimit = 1 return (try? self.fetch(request))?.first } public func fetch<Type:NSFetchRequestResult>(_ entityName:String, limit: Int = 0, sortedBy:[NSSortDescriptor] = [], `where`: String? = nil, _ args: CVarArg...) -> [Type]? { let request = NSFetchRequest<Type>(entityName: entityName) request.sortDescriptors = sortedBy request.fetchLimit = limit if let pred = `where` { request.predicate = withVaList(args) { return NSPredicate(format: pred, arguments: $0) } } return (try? self.fetch(request)) } }
lgpl-2.1
5d01c453a311134a9c71bf3ee87f36db
30.657895
173
0.698254
3.701538
false
false
false
false
khizkhiz/swift
stdlib/public/core/ShadowProtocols.swift
2
5649
//===--- ShadowProtocols.swift - Protocols for decoupled ObjC bridging ----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // To implement bridging, the core standard library needs to interact // a little bit with Cocoa. Because we want to keep the core // decoupled from the Foundation module, we can't use foundation // classes such as NSArray directly. We _can_, however, use an @objc // protocols whose API is "layout-compatible" with that of NSArray, // and use unsafe casts to treat NSArray instances as instances of // that protocol. // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims @objc public protocol _ShadowProtocol {} /// A shadow for the `NSFastEnumeration` protocol. @objc public protocol _NSFastEnumeration : _ShadowProtocol { @objc(countByEnumeratingWithState:objects:count:) func countByEnumeratingWith( state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>, count: Int ) -> Int } /// A shadow for the `NSEnumerator` class. @objc public protocol _NSEnumerator : _ShadowProtocol { init() func nextObject() -> AnyObject? } /// A token that can be used for `NSZone*`. public typealias _SwiftNSZone = OpaquePointer /// A shadow for the `NSCopying` protocol. @objc public protocol _NSCopying : _ShadowProtocol { @objc(copyWithZone:) func copy(with zone: _SwiftNSZone) -> AnyObject } /// A shadow for the "core operations" of NSArray. /// /// Covers a set of operations everyone needs to implement in order to /// be a useful `NSArray` subclass. @unsafe_no_objc_tagged_pointer @objc public protocol _NSArrayCore : _NSCopying, _NSFastEnumeration { @objc(objectAtIndex:) func objectAt(index: Int) -> AnyObject func getObjects(_: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange) @objc(countByEnumeratingWithState:objects:count:) func countByEnumeratingWith( state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>, count: Int ) -> Int var count: Int { get } } /// A shadow for the "core operations" of NSDictionary. /// /// Covers a set of operations everyone needs to implement in order to /// be a useful `NSDictionary` subclass. @objc public protocol _NSDictionaryCore : _NSCopying, _NSFastEnumeration { // The following methods should be overridden when implementing an // NSDictionary subclass. // The designated initializer of `NSDictionary`. init( objects: UnsafePointer<AnyObject?>, forKeys: UnsafePointer<Void>, count: Int) var count: Int { get } @objc(objectForKey:) func objectFor(aKey: AnyObject) -> AnyObject? func keyEnumerator() -> _NSEnumerator // We also override the following methods for efficiency. @objc(copyWithZone:) func copy(with zone: _SwiftNSZone) -> AnyObject func getObjects(objects: UnsafeMutablePointer<AnyObject>, andKeys keys: UnsafeMutablePointer<AnyObject>) @objc(countByEnumeratingWithState:objects:count:) func countByEnumeratingWith( state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>, count: Int ) -> Int } /// A shadow for the API of `NSDictionary` we will use in the core /// stdlib. /// /// `NSDictionary` operations, in addition to those on /// `_NSDictionaryCore`, that we need to use from the core stdlib. /// Distinct from `_NSDictionaryCore` because we don't want to be /// forced to implement operations that `NSDictionary` already /// supplies. @unsafe_no_objc_tagged_pointer @objc public protocol _NSDictionary : _NSDictionaryCore { // Note! This API's type is different from what is imported by the clang // importer. func getObjects(objects: UnsafeMutablePointer<AnyObject>, andKeys keys: UnsafeMutablePointer<AnyObject>) } /// A shadow for the "core operations" of NSSet. /// /// Covers a set of operations everyone needs to implement in order to /// be a useful `NSSet` subclass. @objc public protocol _NSSetCore : _NSCopying, _NSFastEnumeration { // The following methods should be overridden when implementing an // NSSet subclass. // The designated initializer of `NSSet`. init(objects: UnsafePointer<AnyObject?>, count: Int) var count: Int { get } func member(object: AnyObject) -> AnyObject? func objectEnumerator() -> _NSEnumerator // We also override the following methods for efficiency. @objc(copyWithZone:) func copy(with zone: _SwiftNSZone) -> AnyObject @objc(countByEnumeratingWithState:objects:count:) func countByEnumeratingWith( state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>, count: Int ) -> Int } /// A shadow for the API of NSSet we will use in the core /// stdlib. /// /// `NSSet` operations, in addition to those on /// `_NSSetCore`, that we need to use from the core stdlib. /// Distinct from `_NSSetCore` because we don't want to be /// forced to implement operations that `NSSet` already /// supplies. @unsafe_no_objc_tagged_pointer @objc public protocol _NSSet : _NSSetCore { } #else public protocol _NSArrayCore {} public protocol _NSDictionaryCore {} public protocol _NSSetCore {} #endif
apache-2.0
c77fd62ac3dcc4975e226997ac1d785d
30.383333
80
0.711807
4.540997
false
false
false
false
Sephiroth87/C-swifty4
C64/Files/Disk.swift
1
5090
// // Disk.swift // C-swifty4 // // Created by Fabio Ritrovato on 18/11/2015. // Copyright © 2015 orange in a day. All rights reserved. // internal final class Track { private let data: [UInt8] let length: UInt init(data: [UInt8]) { self.data = data self.length = UInt(data.count) * 8 } func readBit(_ offset: UInt) -> UInt8 { return data[Int(offset / 8)] & UInt8(0x80 >> (offset % 8)) != 0x00 ? 0x01 : 0x00 } } let gcr: [UInt64] = [0x0A, 0x0B, 0x12, 0x13, 0x0E, 0x0F, 0x16, 0x17, 0x09, 0x19, 0x1A, 0x1B, 0x0D, 0x1D, 0x1E, 0x15] private func encodeGCR(_ bytes: [UInt8]) -> [UInt8] { var encoded: UInt64 = 0 encoded |= gcr[Int(bytes[0] >> 4)] << 35 encoded |= gcr[Int(bytes[0] & 0x0F)] << 30 encoded |= gcr[Int(bytes[1] >> 4)] << 25 encoded |= gcr[Int(bytes[1] & 0x0F)] << 20 encoded |= gcr[Int(bytes[2] >> 4)] << 15 encoded |= gcr[Int(bytes[2] & 0x0F)] << 10 encoded |= gcr[Int(bytes[3] >> 4)] << 5 encoded |= gcr[Int(bytes[3] & 0x0F)] return [UInt8(truncatingIfNeeded: encoded >> 32), UInt8(truncatingIfNeeded: encoded >> 24), UInt8(truncatingIfNeeded: encoded >> 16), UInt8(truncatingIfNeeded: encoded >> 8), UInt8(truncatingIfNeeded: encoded)] } internal final class Disk { static let sectorsPerTrack: [UInt8] = [0, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 19, 19, 19, 19, 19, 19, 19, 18, 18, 18, 18, 18, 18, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17] let tracksCount: Int let tracks: [Track] init(d64Data: UnsafeBufferPointer<UInt8>) { switch d64Data.count { case 174848: tracksCount = 35 default: print("Unsupported d64 file") tracksCount = 0 } var tracks = [Track]() tracks.append(Track(data: [])) //Track 0 let diskIDLow = d64Data[0x16500 + 0xA2] let diskIDHigh = d64Data[0x16500 + 0xA3] var dataOffset = 0 for trackNumber in 1...UInt8(tracksCount) { var trackData = [UInt8]() trackData.reserveCapacity(7928) // Max track size for sectorNumber in 0..<Disk.sectorsPerTrack[Int(trackNumber)] { // Header SYNC trackData.append(0xFF); trackData.append(0xFF); trackData.append(0xFF); trackData.append(0xFF); trackData.append(0xFF); // Header info let headerChecksum = UInt8(sectorNumber) ^ trackNumber ^ diskIDLow ^ diskIDHigh trackData.append(contentsOf: encodeGCR([0x08, headerChecksum, sectorNumber, trackNumber])) trackData.append(contentsOf: encodeGCR([diskIDLow, diskIDHigh, 0x0F, 0x0F])) // Header gap trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); // Data SYNC trackData.append(0xFF); trackData.append(0xFF); trackData.append(0xFF); trackData.append(0xFF); trackData.append(0xFF); // Data block var dataChecksum: UInt8 = d64Data[dataOffset] ^ d64Data[dataOffset + 1] ^ d64Data[dataOffset + 2] trackData.append(contentsOf: encodeGCR([0x07, d64Data[dataOffset + 0], d64Data[dataOffset + 1], d64Data[dataOffset + 2]])) for i in stride(from: (dataOffset + 3), to: dataOffset + 255, by: 4) { dataChecksum ^= d64Data[i] ^ d64Data[i+1] ^ d64Data[i+2] ^ d64Data[i+3] trackData.append(contentsOf: encodeGCR([d64Data[i], d64Data[i+1], d64Data[i+2], d64Data[i+3]])) } dataChecksum ^= d64Data[dataOffset + 255] trackData.append(contentsOf: encodeGCR([d64Data[dataOffset + 255], dataChecksum, 0x00, 0x0])) // Inter-sector gap trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); if sectorNumber % 2 == 1 { if trackNumber >= 18 && trackNumber <= 24 { trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); } else if trackNumber >= 25 && trackNumber <= 30 { trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); trackData.append(0x55); } else if trackNumber >= 31 { trackData.append(0x55); } } dataOffset += 256 } tracks.append(Track(data: trackData)) } self.tracks = tracks } }
mit
b68c7c17b6085aa1edb28a052280a37a
47.932692
214
0.579682
3.313151
false
false
false
false
Yoseob/Trevi
Lime/Lime/Middleware/Logger.swift
1
5102
// // Logger.swift // Trevi // // Created by SeungHyun Lee on 2016. 1. 5.. // Copyright © 2016년 LeeYoseob. All rights reserved. // import Foundation import Trevi public typealias LoggerProccessor = (IncomingMessage, ServerResponse) -> String public var funcTbl: [String : LoggerProccessor] = [ "http-version" : log_http_version, "response-time" : log_response_time, "remote-addr" : log_remote_addr, "date" : log_date, "method" : log_method, "url" : log_url, "referrer" : log_referrer, "user-agent" : log_user_agent, "status" : log_status ] /** * * A Middleware for logging client connection. * */ public class Logger: Middleware { public var name: MiddlewareName public let format: String private let logFile: FileSystem.WriteStream? public init (format: String) { name = .Logger switch (format) { case "default": self.format = ":remote-addr - - [ :date ] \":method :url HTTP/:http-version\" :status :res[content-length] \":referrer\" \":user-agent\"" case "short": self.format = ":remote-addr - :method :url HTTP/:http-version :status :res[content-length] - :response-time ms" case "tiny": self.format = ":method :url :status :res[content-length] - :response-time ms" default: self.format = format } let filename = "\(__dirname)/log_\(getCurrentDatetime("yyyyMMdd_hhmmss")).log" logFile = FileSystem.WriteStream(path: filename) } deinit { logFile?.close() } public func handle(req: IncomingMessage, res: ServerResponse, next: NextCallback?) -> () { res.onFinished = requestLog next!() } /** * * Make log with the format. * * - Parameter response: Can be a source to make a log and also be a * destination. * */ private func requestLog(response res: ServerResponse) { let log = compileLog(self, req: res.req, res: res) logFile?.writeData(("\(log)\n".dataUsingEncoding(NSUTF8StringEncoding)!)) print(log) } } private func compileLog(logger: Logger, req: IncomingMessage, res: ServerResponse) -> String { var isCompiled = false var compiled = String(logger.format) for tokens in searchWithRegularExpression(logger.format, pattern: ":res\\[(.*?)\\]", options: [ .CaseInsensitive ]) { for type in HttpHeaderType.allValues where type.rawValue.lowercaseString == tokens["$1"]!.text.lowercaseString { guard let logPiece : String = res.header[ type.rawValue ] else { compiled = compiled.stringByReplacingOccurrencesOfString( ":res[\(tokens["$1"]!.text)]", withString: "" ) continue } compiled = compiled.stringByReplacingOccurrencesOfString( ":res[\(tokens["$1"]!.text)]", withString: logPiece ) isCompiled = true } } for tokens in searchWithRegularExpression(logger.format, pattern: ":([A-z0-9\\-]*)", options: [ .CaseInsensitive ]) { // get function by token guard let tokenFunc = funcTbl[tokens["$1"]!.text.lowercaseString] else { compiled = compiled.stringByReplacingOccurrencesOfString( ":\(tokens["$1"]!.text)", withString: "" ) continue } compiled = compiled.stringByReplacingOccurrencesOfString( ":\(tokens["$1"]!.text)", withString: tokenFunc(req, res) ) isCompiled = true } return isCompiled ? compiled : "" } private func log_http_version ( req: IncomingMessage, res: ServerResponse ) -> String { return req.version } private func log_response_time ( req: IncomingMessage, res: ServerResponse ) -> String { let elapsedTime = Double( res.startTime.timeIntervalSinceDate( req.startTime ) ) return "\(elapsedTime * 1000)" } private func log_remote_addr ( req: IncomingMessage, res: ServerResponse ) -> String { guard let addr = getEndpointFromSocketAddress(Tcp.getPeerName(uv_tcp_ptr(req.socket.handle))) else { return "" } return addr.host } private func log_date ( req: IncomingMessage, res: ServerResponse ) -> String { return getCurrentDatetime() } private func log_method ( req: IncomingMessage, res: ServerResponse ) -> String { return req.method.rawValue } private func log_url ( req: IncomingMessage, res: ServerResponse ) -> String { return req.url } private func log_referrer ( req: IncomingMessage, res: ServerResponse ) -> String { if let referer = req.header["referer"] { return referer } else if let referrer = req.header["referrer"] { return referrer } else { return "" } } private func log_user_agent ( req: IncomingMessage, res: ServerResponse ) -> String { if let agent = req.header["user-agent"] { return agent } else { return "" } } private func log_status ( req: IncomingMessage, res: ServerResponse ) -> String { return "\(res.statusCode)" }
apache-2.0
c41f713e267660d1f11be103f30905f4
31.692308
149
0.619533
4.207096
false
false
false
false
lincolnge/sparsec
sparsec/sparsecTests/combTests.swift
1
8880
// // combTests.swift // sparsec // // Created by lincoln on 03/04/2015. // Copyright (c) 2015 Dwarf Artisan. All rights reserved. // // The testing name of last number is the serial number // import Cocoa import XCTest class combTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testTry() { let data = "t1" let state = BasicState(data.unicodeScalars) let c: UnicodeScalar = "t" var (re, status) = try(one(c))(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(true, "pass") case let .Failed(msg): XCTAssert(false, "c is equal to data[0] but got error: \(msg)") } } func testEither1a() { let data = "t" let state = BasicState(data.unicodeScalars) let c: UnicodeScalar = "u" let d: UnicodeScalar = "t" var (re, status) = either(try(one(c)), one(d))(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(true, "pass") case let .Failed(msg): XCTAssert(false, "data[0] is equal to c or to d but got error: \(msg)") } } func testEither2a() { let data = "t" let state = BasicState(data.unicodeScalars) let c: UnicodeScalar = "u" let d: UnicodeScalar = "t" var (re, status) = either(one(c), one(d))(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(false, "data[0] is equal to c but got error") case let .Failed(msg): XCTAssert(true) } } func testEither3a() { let data = "t" let state = BasicState(data.unicodeScalars) let c: UnicodeScalar = "u" let d: UnicodeScalar = "v" var (re, status) = either(try(one(c)), one(d))(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(false, "data is neither equal to c nor to d") case let .Failed(msg): XCTAssert(true) } } func testEither1b() { let data = "t" let state = BasicState(data.unicodeScalars) let c: UnicodeScalar = "u" let d: UnicodeScalar = "t" var (re, status) = (try(one(c)) <|> one(d))(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(true, "pass") case let .Failed(msg): XCTAssert(false, "data[0] is either equal to c or to d but got error: \(msg)") } } func testEither2b() { let data = "t" let state = BasicState(data.unicodeScalars) let c: UnicodeScalar = "u" let d: UnicodeScalar = "t" var (re, status) = (one(c) <|> one(d))(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(false, "data[0] is equal to c but error") case let .Failed(msg): XCTAssert(true) } } func testEither3b() { let data = "t" let state = BasicState(data.unicodeScalars) let c: UnicodeScalar = "u" let d: UnicodeScalar = "v" var (re, status) = (try(one(c)) <|> one(d))(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(false, "data is neither equal to c nor to d") case let .Failed(msg): XCTAssert(true) } } func testOtherwise1a() { let data = "t" let state = BasicState(data.unicodeScalars) let c: UnicodeScalar = "t" var (re, status) = otherwise(one(c), "data is not equal to c")(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(true) case let .Failed(msg): XCTAssert(false, msg) } } func testOtherwise2a() { let data = "t" let state = BasicState(data.unicodeScalars) let c: UnicodeScalar = "b" var (re, status) = otherwise(one(c), "data is not equal to c")(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(false) case let .Failed(msg): XCTAssert(true, msg) } } func testOtherwise1b() { let data = "t" let state = BasicState(data.unicodeScalars) let c: UnicodeScalar = "t" var (re, status) = (one(c) <?> "data is not equal to c")(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(true) case let .Failed(msg): XCTAssert(false, msg) } } func testOtherwise2b() { let data = "t" let state = BasicState(data.unicodeScalars) let c: UnicodeScalar = "b" var (re, status) = (one(c) <?> "data is not equal to c")(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(false) case let .Failed(msg): XCTAssert(true, msg) } } func testOption() { let data = "t" let state = BasicState(data.unicodeScalars) let c: UnicodeScalar = "1" let d: UnicodeScalar = "d" var (re, status) = option(try(one(c)), d)(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(re==d, "re is \(re) and equal to \(d)") case let .Failed(msg): XCTAssert(false, msg) } } func testOneOf1() { let data = "2" let state = BasicState(data.unicodeScalars) let c = "3fs2ad1" var (re, status) = oneOf(c.unicodeScalars)(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(true) case let .Failed(msg): XCTAssert(false, msg) } } func testOneOf2() { let data = "b" let state = BasicState(data.unicodeScalars) let c = "3fs2ad1" var (re, status) = oneOf(c.unicodeScalars)(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(false, "data is not in c") case let .Failed(msg): XCTAssert(true, msg) } } func testOneOf3() { let data = " " let state = BasicState(data.unicodeScalars) let c = "3fs 2ad1" var (re, status) = oneOf(c.unicodeScalars)(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(true, "data \(data) is not in c \(c)") case let .Failed(msg): XCTAssert(false, msg) } } func testNoneOf1() { let data = "b" let state = BasicState(data.unicodeScalars) let c = "3fs2ad1" var (re, status) = noneOf(c.unicodeScalars)(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(true) case let .Failed(msg): XCTAssert(false, msg) } } func testNoneOf2() { let data = "2" let state = BasicState(data.unicodeScalars) let c = "3fs2ad1" var (re, status) = noneOf(c.unicodeScalars)(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(false, "data is not in c") case let .Failed(msg): XCTAssert(true, msg) } } func testNoneOf3() { let data = " " let state = BasicState(data.unicodeScalars) let c = "3fs 2a d1" var (re, status) = noneOf(c.unicodeScalars)(state) println("(re, status): \((re, status))") switch status { case .Success: XCTAssert(false, "data \(data) is not in c \(c)") case let .Failed(msg): XCTAssert(true, msg) } } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
mit
944760e2ebc161289be7d4fc1293c460
28.114754
111
0.511261
4.032698
false
true
false
false
goktugyil/EZSwiftExtensions
Sources/UIViewExtensions.swift
1
22601
// // UIViewExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // #if os(iOS) || os(tvOS) import UIKit // MARK: Custom UIView Initilizers extension UIView { /// EZSE: convenience contructor to define a view based on width, height and base coordinates. @objc public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) { self.init(frame: CGRect(x: x, y: y, width: w, height: h)) } /// EZSE: puts padding around the view public convenience init(superView: UIView, padding: CGFloat) { self.init(frame: CGRect(x: superView.x + padding, y: superView.y + padding, width: superView.w - padding*2, height: superView.h - padding*2)) } /// EZSwiftExtensions - Copies size of superview public convenience init(superView: UIView) { self.init(frame: CGRect(origin: CGPoint.zero, size: superView.size)) } } // MARK: Frame Extensions extension UIView { /// EZSE: add multiple subviews public func addSubviews(_ views: [UIView]) { views.forEach { [weak self] eachView in self?.addSubview(eachView) } } //TODO: Add pics to readme /// EZSE: resizes this view so it fits the largest subview public func resizeToFitSubviews() { var width: CGFloat = 0 var height: CGFloat = 0 for someView in self.subviews { let aView = someView let newWidth = aView.x + aView.w let newHeight = aView.y + aView.h width = max(width, newWidth) height = max(height, newHeight) } frame = CGRect(x: x, y: y, width: width, height: height) } /// EZSE: resizes this view so it fits the largest subview public func resizeToFitSubviews(_ tagsToIgnore: [Int]) { var width: CGFloat = 0 var height: CGFloat = 0 for someView in self.subviews { let aView = someView if !tagsToIgnore.contains(someView.tag) { let newWidth = aView.x + aView.w let newHeight = aView.y + aView.h width = max(width, newWidth) height = max(height, newHeight) } } frame = CGRect(x: x, y: y, width: width, height: height) } /// EZSE: resizes this view so as to fit its width. public func resizeToFitWidth() { let currentHeight = self.h self.sizeToFit() self.h = currentHeight } /// EZSE: resizes this view so as to fit its height. public func resizeToFitHeight() { let currentWidth = self.w self.sizeToFit() self.w = currentWidth } /// EZSE: getter and setter for the x coordinate of the frame's origin for the view. public var x: CGFloat { get { return self.frame.origin.x } set(value) { self.frame = CGRect(x: value, y: self.y, width: self.w, height: self.h) } } /// EZSE: getter and setter for the y coordinate of the frame's origin for the view. public var y: CGFloat { get { return self.frame.origin.y } set(value) { self.frame = CGRect(x: self.x, y: value, width: self.w, height: self.h) } } /// EZSE: variable to get the width of the view. public var w: CGFloat { get { return self.frame.size.width } set(value) { self.frame = CGRect(x: self.x, y: self.y, width: value, height: self.h) } } /// EZSE: variable to get the height of the view. public var h: CGFloat { get { return self.frame.size.height } set(value) { self.frame = CGRect(x: self.x, y: self.y, width: self.w, height: value) } } /// EZSE: getter and setter for the x coordinate of leftmost edge of the view. public var left: CGFloat { get { return self.x } set(value) { self.x = value } } /// EZSE: getter and setter for the x coordinate of the rightmost edge of the view. public var right: CGFloat { get { return self.x + self.w } set(value) { self.x = value - self.w } } /// EZSE: getter and setter for the y coordinate for the topmost edge of the view. public var top: CGFloat { get { return self.y } set(value) { self.y = value } } /// EZSE: getter and setter for the y coordinate of the bottom most edge of the view. public var bottom: CGFloat { get { return self.y + self.h } set(value) { self.y = value - self.h } } /// EZSE: getter and setter the frame's origin point of the view. public var origin: CGPoint { get { return self.frame.origin } set(value) { self.frame = CGRect(origin: value, size: self.frame.size) } } /// EZSE: getter and setter for the X coordinate of the center of a view. public var centerX: CGFloat { get { return self.center.x } set(value) { self.center.x = value } } /// EZSE: getter and setter for the Y coordinate for the center of a view. public var centerY: CGFloat { get { return self.center.y } set(value) { self.center.y = value } } /// EZSE: getter and setter for frame size for the view. public var size: CGSize { get { return self.frame.size } set(value) { self.frame = CGRect(origin: self.frame.origin, size: value) } } /// EZSE: getter for an leftwards offset position from the leftmost edge. public func leftOffset(_ offset: CGFloat) -> CGFloat { return self.left - offset } /// EZSE: getter for an rightwards offset position from the rightmost edge. public func rightOffset(_ offset: CGFloat) -> CGFloat { return self.right + offset } /// EZSE: aligns the view to the top by a given offset. public func topOffset(_ offset: CGFloat) -> CGFloat { return self.top - offset } /// EZSE: align the view to the bottom by a given offset. public func bottomOffset(_ offset: CGFloat) -> CGFloat { return self.bottom + offset } //TODO: Add to readme /// EZSE: align the view widthwise to the right by a given offset. public func alignRight(_ offset: CGFloat) -> CGFloat { return self.w - offset } /// EZSwiftExtensions public func reorderSubViews(_ reorder: Bool = false, tagsToIgnore: [Int] = []) -> CGFloat { var currentHeight: CGFloat = 0 for someView in subviews { if !tagsToIgnore.contains(someView.tag) && !(someView ).isHidden { if reorder { let aView = someView aView.frame = CGRect(x: aView.frame.origin.x, y: currentHeight, width: aView.frame.width, height: aView.frame.height) } currentHeight += someView.frame.height } } return currentHeight } public func removeSubviews() { for subview in subviews { subview.removeFromSuperview() } } /// EZSE: Centers view in superview horizontally public func centerXInSuperView() { guard let parentView = superview else { assertionFailure("EZSwiftExtensions Error: The view \(self) doesn't have a superview") return } self.x = parentView.w/2 - self.w/2 } /// EZSE: Centers view in superview vertically public func centerYInSuperView() { guard let parentView = superview else { assertionFailure("EZSwiftExtensions Error: The view \(self) doesn't have a superview") return } self.y = parentView.h/2 - self.h/2 } /// EZSE: Centers view in superview horizontally & vertically public func centerInSuperView() { self.centerXInSuperView() self.centerYInSuperView() } } // MARK: Transform Extensions extension UIView { /// EZSwiftExtensions public func setRotationX(_ x: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DRotate(transform, x.degreesToRadians(), 1.0, 0.0, 0.0) self.layer.transform = transform } /// EZSwiftExtensions public func setRotationY(_ y: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DRotate(transform, y.degreesToRadians(), 0.0, 1.0, 0.0) self.layer.transform = transform } /// EZSwiftExtensions public func setRotationZ(_ z: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DRotate(transform, z.degreesToRadians(), 0.0, 0.0, 1.0) self.layer.transform = transform } /// EZSwiftExtensions public func setRotation(x: CGFloat, y: CGFloat, z: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DRotate(transform, x.degreesToRadians(), 1.0, 0.0, 0.0) transform = CATransform3DRotate(transform, y.degreesToRadians(), 0.0, 1.0, 0.0) transform = CATransform3DRotate(transform, z.degreesToRadians(), 0.0, 0.0, 1.0) self.layer.transform = transform } /// EZSwiftExtensions public func setScale(x: CGFloat, y: CGFloat) { var transform = CATransform3DIdentity transform.m34 = 1.0 / -1000.0 transform = CATransform3DScale(transform, x, y, 1) self.layer.transform = transform } } // MARK: Layer Extensions extension UIView { /// EZSwiftExtensions public func setCornerRadius(radius: CGFloat) { self.layer.cornerRadius = radius self.layer.masksToBounds = true } //TODO: add this to readme /// EZSwiftExtensions public func addShadow(offset: CGSize, radius: CGFloat, color: UIColor, opacity: Float, cornerRadius: CGFloat? = nil) { self.layer.shadowOffset = offset self.layer.shadowRadius = radius self.layer.shadowOpacity = opacity self.layer.shadowColor = color.cgColor if let r = cornerRadius { self.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: r).cgPath } } /// EZSwiftExtensions public func addBorder(width: CGFloat, color: UIColor) { layer.borderWidth = width layer.borderColor = color.cgColor layer.masksToBounds = true } /// EZSwiftExtensions public func addBorderTop(size: CGFloat, color: UIColor) { addBorderUtility(x: 0, y: 0, width: frame.width, height: size, color: color) } //TODO: add to readme /// EZSwiftExtensions public func addBorderTopWithPadding(size: CGFloat, color: UIColor, padding: CGFloat) { addBorderUtility(x: padding, y: 0, width: frame.width - padding*2, height: size, color: color) } /// EZSwiftExtensions public func addBorderBottom(size: CGFloat, color: UIColor) { addBorderUtility(x: 0, y: frame.height - size, width: frame.width, height: size, color: color) } /// EZSwiftExtensions public func addBorderLeft(size: CGFloat, color: UIColor) { addBorderUtility(x: 0, y: 0, width: size, height: frame.height, color: color) } /// EZSwiftExtensions public func addBorderRight(size: CGFloat, color: UIColor) { addBorderUtility(x: frame.width - size, y: 0, width: size, height: frame.height, color: color) } /// EZSwiftExtensions fileprivate func addBorderUtility(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) { let border = CALayer() border.backgroundColor = color.cgColor border.frame = CGRect(x: x, y: y, width: width, height: height) layer.addSublayer(border) } //TODO: add this to readme /// EZSwiftExtensions public func drawCircle(fillColor: UIColor, strokeColor: UIColor, strokeWidth: CGFloat) { let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.w, height: self.w), cornerRadius: self.w/2) let shapeLayer = CAShapeLayer() shapeLayer.path = path.cgPath shapeLayer.fillColor = fillColor.cgColor shapeLayer.strokeColor = strokeColor.cgColor shapeLayer.lineWidth = strokeWidth self.layer.addSublayer(shapeLayer) } //TODO: add this to readme /// EZSwiftExtensions public func drawStroke(width: CGFloat, color: UIColor) { let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.w, height: self.w), cornerRadius: self.w/2) let shapeLayer = CAShapeLayer () shapeLayer.path = path.cgPath shapeLayer.fillColor = UIColor.clear.cgColor shapeLayer.strokeColor = color.cgColor shapeLayer.lineWidth = width self.layer.addSublayer(shapeLayer) } } private let UIViewAnimationDuration: TimeInterval = 1 private let UIViewAnimationSpringDamping: CGFloat = 0.5 private let UIViewAnimationSpringVelocity: CGFloat = 0.5 //TODO: add this to readme // MARK: Animation Extensions extension UIView { /// EZSwiftExtensions public func spring(animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) { spring(duration: UIViewAnimationDuration, animations: animations, completion: completion) } /// EZSwiftExtensions public func spring(duration: TimeInterval, animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) { UIView.animate( withDuration: UIViewAnimationDuration, delay: 0, usingSpringWithDamping: UIViewAnimationSpringDamping, initialSpringVelocity: UIViewAnimationSpringVelocity, options: UIViewAnimationOptions.allowAnimatedContent, animations: animations, completion: completion ) } /// EZSwiftExtensions public func animate(duration: TimeInterval, animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) { UIView.animate(withDuration: duration, animations: animations, completion: completion) } /// EZSwiftExtensions public func animate(animations: @escaping (() -> Void), completion: ((Bool) -> Void)? = nil) { animate(duration: UIViewAnimationDuration, animations: animations, completion: completion) } /// EZSwiftExtensions public func pop() { setScale(x: 1.1, y: 1.1) spring(duration: 0.2, animations: { [unowned self] () -> Void in self.setScale(x: 1, y: 1) }) } /// EZSwiftExtensions public func popBig() { setScale(x: 1.25, y: 1.25) spring(duration: 0.2, animations: { [unowned self] () -> Void in self.setScale(x: 1, y: 1) }) } //EZSE: Reverse pop, good for button animations public func reversePop() { setScale(x: 0.9, y: 0.9) UIView.animate(withDuration: 0.05, delay: 0, options: .allowUserInteraction, animations: {[weak self] in self?.setScale(x: 1, y: 1) }, completion: { (_) in }) } } //TODO: add this to readme // MARK: Render Extensions extension UIView { /// EZSwiftExtensions public func toImage () -> UIImage { UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0) drawHierarchy(in: bounds, afterScreenUpdates: false) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } } // MARK: Gesture Extensions extension UIView { /// http://stackoverflow.com/questions/4660371/how-to-add-a-touch-event-to-a-uiview/32182866#32182866 /// EZSwiftExtensions public func addTapGesture(tapNumber: Int = 1, target: AnyObject, action: Selector) { let tap = UITapGestureRecognizer(target: target, action: action) tap.numberOfTapsRequired = tapNumber addGestureRecognizer(tap) isUserInteractionEnabled = true } /// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak public func addTapGesture(tapNumber: Int = 1, action: ((UITapGestureRecognizer) -> Void)?) { let tap = BlockTap(tapCount: tapNumber, fingerCount: 1, action: action) addGestureRecognizer(tap) isUserInteractionEnabled = true } /// EZSwiftExtensions public func addSwipeGesture(direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, target: AnyObject, action: Selector) { let swipe = UISwipeGestureRecognizer(target: target, action: action) swipe.direction = direction #if os(iOS) swipe.numberOfTouchesRequired = numberOfTouches #endif addGestureRecognizer(swipe) isUserInteractionEnabled = true } /// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak public func addSwipeGesture(direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, action: ((UISwipeGestureRecognizer) -> Void)?) { let swipe = BlockSwipe(direction: direction, fingerCount: numberOfTouches, action: action) addGestureRecognizer(swipe) isUserInteractionEnabled = true } /// EZSwiftExtensions public func addPanGesture(target: AnyObject, action: Selector) { let pan = UIPanGestureRecognizer(target: target, action: action) addGestureRecognizer(pan) isUserInteractionEnabled = true } /// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak public func addPanGesture(action: ((UIPanGestureRecognizer) -> Void)?) { let pan = BlockPan(action: action) addGestureRecognizer(pan) isUserInteractionEnabled = true } #if os(iOS) /// EZSwiftExtensions public func addPinchGesture(target: AnyObject, action: Selector) { let pinch = UIPinchGestureRecognizer(target: target, action: action) addGestureRecognizer(pinch) isUserInteractionEnabled = true } #endif #if os(iOS) /// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak public func addPinchGesture(action: ((UIPinchGestureRecognizer) -> Void)?) { let pinch = BlockPinch(action: action) addGestureRecognizer(pinch) isUserInteractionEnabled = true } #endif /// EZSwiftExtensions public func addLongPressGesture(target: AnyObject, action: Selector) { let longPress = UILongPressGestureRecognizer(target: target, action: action) addGestureRecognizer(longPress) isUserInteractionEnabled = true } /// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak public func addLongPressGesture(action: ((UILongPressGestureRecognizer) -> Void)?) { let longPress = BlockLongPress(action: action) addGestureRecognizer(longPress) isUserInteractionEnabled = true } } //TODO: add to readme extension UIView { /// EZSwiftExtensions [UIRectCorner.TopLeft, UIRectCorner.TopRight] public 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 } /// EZSwiftExtensions - Mask square/rectangle UIView with a circular/capsule cover, with a border of desired color and width around it public func roundView(withBorderColor color: UIColor? = nil, withBorderWidth width: CGFloat? = nil) { self.setCornerRadius(radius: min(self.frame.size.height, self.frame.size.width) / 2) self.layer.borderWidth = width ?? 0 self.layer.borderColor = color?.cgColor ?? UIColor.clear.cgColor } /// EZSwiftExtensions - Remove all masking around UIView public func nakedView() { self.layer.mask = nil self.layer.borderWidth = 0 } } extension UIView { ///EZSE: Shakes the view for as many number of times as given in the argument. public func shakeViewForTimes(_ times: Int) { let anim = CAKeyframeAnimation(keyPath: "transform") anim.values = [ NSValue(caTransform3D: CATransform3DMakeTranslation(-5, 0, 0 )), NSValue(caTransform3D: CATransform3DMakeTranslation( 5, 0, 0 )) ] anim.autoreverses = true anim.repeatCount = Float(times) anim.duration = 7/100 self.layer.add(anim, forKey: nil) } } extension UIView { ///EZSE: Loops until it finds the top root view. //TODO: Add to readme func rootView() -> UIView { guard let parentView = superview else { return self } return parentView.rootView() } } // MARK: Fade Extensions public let UIViewDefaultFadeDuration: TimeInterval = 0.4 extension UIView { ///EZSE: Fade in with duration, delay and completion block. public func fadeIn(_ duration: TimeInterval? = UIViewDefaultFadeDuration, delay: TimeInterval? = 0.0, completion: ((Bool) -> Void)? = nil) { fadeTo(1.0, duration: duration, delay: delay, completion: completion) } /// EZSwiftExtensions public func fadeOut(_ duration: TimeInterval? = UIViewDefaultFadeDuration, delay: TimeInterval? = 0.0, completion: ((Bool) -> Void)? = nil) { fadeTo(0.0, duration: duration, delay: delay, completion: completion) } /// Fade to specific value with duration, delay and completion block. public func fadeTo(_ value: CGFloat, duration: TimeInterval? = UIViewDefaultFadeDuration, delay: TimeInterval? = 0.0, completion: ((Bool) -> Void)? = nil) { UIView.animate(withDuration: duration ?? UIViewDefaultFadeDuration, delay: delay ?? UIViewDefaultFadeDuration, options: .curveEaseInOut, animations: { self.alpha = value }, completion: completion) } } #endif
mit
911911266d404ca92266142c6abbed97
34.704581
160
0.634529
4.478106
false
false
false
false
Lves/LLRefresh
LLRefreshDemo/ViewController.swift
1
2291
// // ViewController.swift // LLRefreshDemo // // Created by 李兴乐 on 2016/12/3. // Copyright © 2016年 com.lvesli. All rights reserved. // import UIKit extension UIViewController{ class func instanceViewControllerInStoryboardWithName(_ name: String, storyboardName: String? = "Main") -> UIViewController? { if let storyboardName = storyboardName, storyboardName.ll_length > 0 { let story = UIStoryboard(name: storyboardName, bundle: nil) if (story.value(forKey: "identifierToNibNameMap") as AnyObject).object(forKey: name) != nil { return story.instantiateViewController(withIdentifier: name) } } return nil } } class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var dataArray:[String]? override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() dataArray = ["StateRefreshViewController", "NormalRefreshViewController", "GifRefreshViewController", "BgImageRefreshViewController", "ArrowRefreshViewController", "CustomRefreshTableViewController"] } //MARK: delegate&datasource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "RootCell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "RootCell") } cell?.textLabel?.text = dataArray?[indexPath.row] return cell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let vc = UIViewController.instanceViewControllerInStoryboardWithName(dataArray?[indexPath.row] ?? "") navigationController?.pushViewController(vc!, animated: true) } }
mit
8119284374dab3ccce08762e06f278b5
32.072464
130
0.65206
5.306977
false
false
false
false
Anvics/Amber
Example/Pods/ReactiveKit/Sources/SignalProtocol.swift
1
58709
// // The MIT License (MIT) // // Copyright (c) 2016 Srdan Rasic (@srdanrasic) // // 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 Dispatch import Foundation // MARK: - SignalProtocol /// Represents a sequence of events. public protocol SignalProtocol { /// The type of elements generated by the signal. associatedtype Element /// The type of error that can terminate the signal. associatedtype Error: Swift.Error /// Register the given observer. /// - Parameter observer: A function that will receive events. /// - Returns: A disposable that can be used to cancel the observation. func observe(with observer: @escaping Observer<Element, Error>) -> Disposable } extension SignalProtocol { /// Register an observer that will receive events from a signal. public func observe<O: ObserverProtocol>(with observer: O) -> Disposable where O.Element == Element, O.Error == Error { return observe(with: observer.on) } /// Register an observer that will receive elements from `.next` events of the signal. public func observeNext(with observer: @escaping (Element) -> Void) -> Disposable { return observe { event in if case .next(let element) = event { observer(element) } } } /// Register an observer that will receive elements from `.failed` events of the signal. public func observeFailed(with observer: @escaping (Error) -> Void) -> Disposable { return observe { event in if case .failed(let error) = event { observer(error) } } } /// Register an observer that will be executed on `.completed` event. public func observeCompleted(with observer: @escaping () -> Void) -> Disposable { return observe { event in if case .completed = event { observer() } } } } // MARK: - Extensions // MARK: Creating a signal public extension SignalProtocol { /// Create a signal that emits given element and then completes. public static func just(_ element: Element) -> Signal<Element, Error> { return Signal { observer in observer.next(element) observer.completed() return NonDisposable.instance } } /// Create a signal that emits given sequence of elements and then completes. public static func sequence<S: Sequence>(_ sequence: S) -> Signal<Element, Error> where S.Iterator.Element == Element { return Signal { observer in sequence.forEach(observer.next) observer.completed() return NonDisposable.instance } } /// Create a signal that completes without emitting any elements. public static func completed() -> Signal<Element, Error> { return Signal { observer in observer.completed() return NonDisposable.instance } } /// Create a signal that just terminates with the given error. public static func failed(_ error: Error) -> Signal<Element, Error> { return Signal { observer in observer.failed(error) return NonDisposable.instance } } /// Create a signal that never completes. public static func never() -> Signal<Element, Error> { return Signal { observer in return NonDisposable.instance } } /// Create a signal that emits an integer every `interval` time on a given dispatch queue. public static func interval(_ interval: Double, queue: DispatchQueue = DispatchQueue(label: "com.reactivekit.interval")) -> Signal<Int, Error> { return Signal { observer in var number = 0 var dispatch: (() -> Void)! let disposable = SimpleDisposable() dispatch = { queue.after(when: interval) { guard !disposable.isDisposed else { dispatch = nil; return } observer.next(number) number = number + 1 dispatch() } } dispatch() return disposable } } /// Create a signal that emits given element after `time` time on a given queue. public static func timer(element: Element, time: Double, queue: DispatchQueue = DispatchQueue(label: "com.reactivekit.timer")) -> Signal<Element, Error> { return Signal { observer in let disposable = SimpleDisposable() queue.after(when: time) { guard !disposable.isDisposed else { return } observer.next(element) observer.completed() } return disposable } } } // MARK: Transforming signals public extension SignalProtocol { /// Batch the elements into arrays of given size. public func buffer(size: Int) -> Signal<[Element], Error> { return Signal { observer in var buffer: [Element] = [] return self.observe { event in switch event { case .next(let element): buffer.append(element) if buffer.count == size { observer.next(buffer) buffer.removeAll() } case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } /// Maps each element into an optional type and propagates unwrapped .some results. /// Shorthand for ```map().ignoreNil()```. public func flatMap<U>(_ transform: @escaping (Element) -> U?) -> Signal<U, Error> { return Signal { observer in return self.observe { event in switch event { case .next(let element): if let element = transform(element) { observer.next(element) } case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } /// Map each event into a signal and then flatten inner signals. public func flatMapLatest<O: SignalProtocol>(_ transform: @escaping (Element) -> O) -> Signal<O.Element, Error> where O.Error == Error { return map(transform).switchToLatest() } /// Map each event into a signal and then flatten inner signals. public func flatMapMerge<O: SignalProtocol>(_ transform: @escaping (Element) -> O) -> Signal<O.Element, Error> where O.Error == Error { return map(transform).merge() } /// Map each event into a signal and then flatten inner signals. public func flatMapConcat<O: SignalProtocol>(_ transform: @escaping (Element) -> O) -> Signal<O.Element, Error> where O.Error == Error { return map(transform).concat() } /// Map failure event into another operation and continue with that operation. Also called `catch`. public func flatMapError<S: SignalProtocol>(_ recover: @escaping (Error) -> S) -> Signal<Element, S.Error> where S.Element == Element { return Signal { observer in let serialDisposable = SerialDisposable(otherDisposable: nil) serialDisposable.otherDisposable = self.observe { taskEvent in switch taskEvent { case .next(let value): observer.next(value) case .completed: observer.completed() case .failed(let error): serialDisposable.otherDisposable = recover(error).observe(with: observer.on) } } return serialDisposable } } /// Transform each element by applying `transform` on it. public func map<U>(_ transform: @escaping (Element) -> U) -> Signal<U, Error> { return Signal { observer in return self.observe { event in switch event { case .next(let element): observer.next(transform(element)) case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } /// Transform error by applying `transform` on it. public func mapError<F>(_ transform: @escaping (Error) -> F) -> Signal<Element, F> { return Signal { observer in return self.observe { event in switch event { case .next(let element): observer.next(element) case .failed(let error): observer.failed(transform(error)) case .completed: observer.completed() } } } } /// Replace all emitted elements with the given element. public func replace<T>(with element: T) -> Signal<T, Error> { return map { _ in element } } /// Map elements to Void. public func eraseType() -> Signal<Void, Error> { return map { _ in } } /// Apply `combine` to each element starting with `initial` and emit each /// intermediate result. This differs from `reduce` which emits only final result. public func scan<U>(_ initial: U, _ combine: @escaping (U, Element) -> U) -> Signal<U, Error> { return Signal { observer in var accumulator = initial observer.next(accumulator) return self.observe { event in switch event { case .next(let element): accumulator = combine(accumulator, element) observer.next(accumulator) case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } /// Transform each element by applying `transform` on it. public func tryMap<U>(_ transform: @escaping (Element) -> Result<U, Error>) -> Signal<U, Error> { return Signal { observer in return self.observe { event in switch event { case .next(let element): switch transform(element) { case .success(let value): observer.next(value) case .failure(let error): observer.failed(error) } case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } /// Convert the receiver to a concrete signal. public func toSignal() -> Signal<Element, Error> { if let signal = self as? Signal<Element, Error> { return signal } else { return Signal { observer in return self.observe(with: observer.on) } } } /// Branches out error into another signal. public func branchOutError() -> (Signal<Element, NoError>, Signal<Error, NoError>) { let shared = shareReplay() return (shared.suppressError(logging: false), shared.toErrorSignal()) } /// Branches out mapped error into another signal. public func branchOutError<F>(_ mapError: @escaping (Error) -> F) -> (Signal<Element, NoError>, Signal<F, NoError>) { let shared = shareReplay() return (shared.suppressError(logging: false), shared.toErrorSignal().map(mapError)) } /// Converts signal into non-failable signal by suppressing the error. public func suppressError(logging: Bool, file: String = #file, line: Int = #line) -> Signal<Element, NoError> { return Signal { observer in return self.observe { event in switch event { case .next(let element): observer.next(element) case .failed(let error): observer.completed() if logging { print("Signal at \(file):\(line) encountered an error: \(error)") } case .completed: observer.completed() } } } } /// Converts signal into non-failable signal by feeding suppressed error into a subject. public func suppressAndFeedError<S: SubjectProtocol>(into listener: S, logging: Bool = true, file: String = #file, line: Int = #line) -> Signal<Element, NoError> where S.Element == Error { return feedError(into: listener).suppressError(logging: logging, file: file, line: line) } /// Recovers the signal by propagating default element if error happens. public func recover(with element: Element) -> Signal<Element, NoError> { return Signal { observer in return self.observe { event in switch event { case .next(let element): observer.next(element) case .failed: observer.next(element) observer.completed() case .completed: observer.completed() } } } } /// Maps failable signal into a non-failable signal of errors. Ignores `.next` events. public func toErrorSignal() -> Signal<Error, NoError> { return Signal { observer in return self.observe { taskEvent in switch taskEvent { case .next: break case .completed: observer.completed() case .failed(let error): observer.next(error) } } } } /// Batch each `size` elements into another signal. public func window(size: Int) -> Signal<Signal<Element, Error>, Error> { return buffer(size: size).map { Signal.sequence($0) } } } extension SignalProtocol where Element: OptionalProtocol { /// Apply `transform` to all non-nil elements. public func flatMap<U>(_ transform: @escaping (Element.Wrapped) -> U?) -> Signal<U?, Error> { return Signal { observer in return self.observe { event in switch event { case .next(let element): if let element = element._unbox { observer.next(transform(element)) } else { observer.next(nil) } case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } } extension SignalProtocol where Element: Sequence { /// Map each emitted sequence. public func flatMap<U>(_ transform: @escaping (Element.Iterator.Element) -> U) -> Signal<[U], Error> { return Signal { observer in return self.observe { event in switch event { case .next(let element): observer.next(element.map(transform)) case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } /// Unwraps elements from each emitted sequence into an events of their own. public func unwrap() -> Signal<Element.Iterator.Element, Error> { return Signal { observer in return self.observe { event in switch event { case .next(let sequence): sequence.forEach(observer.next) case .completed: observer.completed() case .failed(let error): observer.failed(error) } } } } } // MARK: Filtering signals public extension SignalProtocol { /// Emit an element only if `interval` time passes without emitting another element. public func debounce(interval: Double, on queue: DispatchQueue = DispatchQueue(label: "com.reactivekit.debounce")) -> Signal<Element, Error> { return Signal { observer in var timerSubscription: Disposable? = nil var previousElement: Element? = nil return self.observe { event in timerSubscription?.dispose() switch event { case .next(let element): previousElement = element timerSubscription = queue.disposableAfter(when: interval) { if let _element = previousElement { observer.next(_element) previousElement = nil } } case .failed(let error): observer.failed(error) case .completed: if let previousElement = previousElement { observer.next(previousElement) observer.completed() } } } } } /// Emit first element and then all elements that are not equal to their predecessor(s). public func distinct(areDistinct: @escaping (Element, Element) -> Bool) -> Signal<Element, Error> { return Signal { observer in var lastElement: Element? = nil return self.observe { event in switch event { case .next(let element): let prevLastElement = lastElement lastElement = element if prevLastElement == nil || areDistinct(prevLastElement!, element) { observer.next(element) } default: observer.on(event) } } } } /// Emit only element at given index if such element is produced. public func element(at index: Int) -> Signal<Element, Error> { return Signal { observer in var currentIndex = 0 return self.observe { event in switch event { case .next(let element): if currentIndex == index { observer.next(element) observer.completed() } else { currentIndex += 1 } default: observer.on(event) } } } } /// Emit only elements that pass `include` test. public func filter(_ isIncluded: @escaping (Element) -> Bool) -> Signal<Element, Error> { return Signal { observer in return self.observe { event in switch event { case .next(let element): if isIncluded(element) { observer.next(element) } default: observer.on(event) } } } } /// Filters the signal by executing `isIncluded` in each element and /// propagates that element only if the returned signal fires `true`. public func filter(_ isIncluded: @escaping (Element) -> SafeSignal<Bool>) -> Signal<Element, Error> { return flatMapLatest { element -> Signal<Element, Error> in return isIncluded(element) .first() .map { isIncluded -> Element? in if isIncluded { return element } else { return nil } } .ignoreNil() .castError() } } /// Emit only the first element generated by the signal and then complete. public func first() -> Signal<Element, Error> { return take(first: 1) } /// Ignore all elements (just propagate terminal events). public func ignoreElements() -> Signal<Element, Error> { return filter { _ in false } } /// Ignore all terminal events (just propagate next events). public func ignoreTerminal() -> Signal<Element, Error> { return Signal { observer in return self.observe { event in if case .next(let element) = event { observer.next(element) } } } } /// Emit only last element generated by the signal and then complete. public func last() -> Signal<Element, Error> { return take(last: 1) } /// Periodically sample the signal and emit latest element from each interval. public func sample(interval: Double, on queue: DispatchQueue = DispatchQueue(label: "com.reactivekit.sample")) -> Signal<Element, Error> { return Signal { observer in let serialDisposable = SerialDisposable(otherDisposable: nil) var latestElement: Element? = nil var dispatch: (() -> Void)! dispatch = { queue.after(when: interval) { guard !serialDisposable.isDisposed else { dispatch = nil; return } if let element = latestElement { observer.next(element) latestElement = nil } dispatch() } } serialDisposable.otherDisposable = self.observe { event in switch event { case .next(let element): latestElement = element default: observer.on(event) serialDisposable.dispose() } } dispatch() return serialDisposable } } /// Suppress first `count` elements generated by the signal. public func skip(first count: Int) -> Signal<Element, Error> { return Signal { observer in var count = count return self.observe { event in switch event { case .next(let element): if count > 0 { count -= 1 } else { observer.next(element) } default: observer.on(event) } } } } /// Suppress last `count` elements generated by the signal. public func skip(last count: Int) -> Signal<Element, Error> { guard count > 0 else { return self.toSignal() } return Signal { observer in var buffer: [Element] = [] return self.observe { event in switch event { case .next(let element): buffer.append(element) if buffer.count > count { observer.next(buffer.removeFirst()) } default: observer.on(event) } } } } /// Suppress elements for first `interval` seconds. public func skip(interval: Double) -> Signal<Element, Error> { return Signal { observer in let startTime = Date().addingTimeInterval(interval) return self.observe { event in switch event { case .next: if startTime < Date() { observer.on(event) } case .completed, .failed: observer.on(event) } } } } /// Emit only first `count` elements of the signal and then complete. public func take(first count: Int) -> Signal<Element, Error> { return Signal { observer in guard count > 0 else { observer.completed() return NonDisposable.instance } var taken = 0 let serialDisposable = SerialDisposable(otherDisposable: nil) serialDisposable.otherDisposable = self.observe { event in switch event { case .next(let element): if taken < count { taken += 1 observer.next(element) } if taken == count { observer.completed() serialDisposable.otherDisposable?.dispose() } default: observer.on(event) } } return serialDisposable } } /// Emit only last `count` elements of the signal and then complete. public func take(last count: Int) -> Signal<Element, Error> { return Signal { observer in var values: [Element] = [] values.reserveCapacity(count) return self.observe(with: { (event) in switch event { case .completed: values.forEach(observer.next) observer.completed() case .failed(let error): observer.failed(error) case .next(let element): if event.isTerminal { observer.on(event) } else { if values.count + 1 > count { values.removeFirst(values.count - count + 1) } values.append(element) } } }) } } /// Emit elements of the reciver until given signal completes and then complete the receiver. public func take<S: SignalProtocol>(until signal: S) -> Signal<Element, Error> { return Signal { observer in let disposable = CompositeDisposable() disposable += signal.observe { event in observer.completed() } disposable += self.observe { event in switch event { case .completed: observer.completed() case .failed(let error): observer.failed(error) case .next(let element): observer.next(element) } } return disposable } } /// Throttle the signal to emit at most one element per given `seconds` interval. public func throttle(seconds: Double) -> Signal<Element, Error> { return Signal { observer in var lastEventTime: DispatchTime? return self.observe { event in switch event { case .next(let element): let now = DispatchTime.now() if lastEventTime == nil || now.rawValue > (lastEventTime! + seconds).rawValue { lastEventTime = now observer.next(element) } default: observer.on(event) } } } } } public extension SignalProtocol where Element: Equatable { /// Emit first element and then all elements that are not equal to their predecessor(s). public func distinct() -> Signal<Element, Error> { return distinct(areDistinct: !=) } } public extension SignalProtocol where Element: OptionalProtocol, Element.Wrapped: Equatable { /// Emit first element and then all elements that are not equal to their predecessor(s). public func distinct() -> Signal<Element, Error> { return distinct(areDistinct: !=) } } public extension SignalProtocol where Element: OptionalProtocol { /// Suppress all `nil`-elements. public func ignoreNil() -> Signal<Element.Wrapped, Error> { return Signal { observer in return self.observe { event in switch event { case .next(let element): if let element = element._unbox { observer.next(element) } case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } /// Replace all `nil`-elements with the provided replacement. public func replaceNil(with replacement: Element.Wrapped) -> Signal<Element.Wrapped, Error> { return Signal { observer in return self.observe { event in switch event { case .next(let element): if let element = element._unbox { observer.next(element) } else { observer.next(replacement) } case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } } // MARK: Utilities extension SignalProtocol { /// Set the execution context in which to execute the signal (i.e. in which to run /// the signal's producer). public func executeIn(_ context: ExecutionContext) -> Signal<Element, Error> { return Signal { observer in let serialDisposable = SerialDisposable(otherDisposable: nil) context.execute { if !serialDisposable.isDisposed { serialDisposable.otherDisposable = self.observe(with: observer.on) } } return serialDisposable } } /// Set the dispatch queue on which to execute the signal (i.e. in which to run /// the signal's producer). public func executeOn(_ queue: DispatchQueue) -> Signal<Element, Error> { return Signal { observer in let serialDisposable = SerialDisposable(otherDisposable: nil) queue.async { if !serialDisposable.isDisposed { serialDisposable.otherDisposable = self.observe(with: observer.on) } } return serialDisposable } } /// Delay signal events for `interval` time. public func delay(interval: Double, on queue: DispatchQueue = DispatchQueue(label: "com.reactivekit.delay")) -> Signal<Element, Error> { return Signal { observer in return self.observe { event in queue.after(when: interval) { observer.on(event) } } } } /// Do side-effect upon various events. public func doOn(next: ((Element) -> ())? = nil, start: (() -> Void)? = nil, failed: ((Error) -> Void)? = nil, completed: (() -> Void)? = nil, disposed: (() -> ())? = nil) -> Signal<Element, Error> { return Signal { observer in start?() let disposable = self.observe { event in switch event { case .next(let value): next?(value) case .failed(let error): failed?(error) case .completed: completed?() } observer.on(event) } return BlockDisposable { disposable.dispose() disposed?() } } } /// Log various signal events. If title is not provided, source file and function names are printed instead. public func debug(_ title: String? = nil, file: String = #file, function: String = #function, line: Int = #line) -> Signal<Element, Error> { let prefix: String if let title = title { prefix = "[\(title)]" } else { let filename = file.components(separatedBy: "/").last ?? file prefix = "[\(filename):\(function):\(line)]" } return doOn(next: { element in print("\(prefix) next(\(element))") }, start: { print("\(prefix) started") }, failed: { error in print("\(prefix) failed: \(error)") }, completed: { print("\(prefix) completed") }, disposed: { print("\(prefix) disposed") }) } /// Set the execution context used to dispatch events (i.e. to run the observers). public func observeIn(_ context: ExecutionContext) -> Signal<Element, Error> { return Signal { observer in return self.observe { event in context.execute { observer.on(event) } } } } /// Set the dispatch queue used to dispatch events (i.e. to run the observers). public func observeOn(_ queue: DispatchQueue) -> Signal<Element, Error> { return Signal { observer in return self.observe { event in queue.async { observer.on(event) } } } } /// Supress events while last event generated on other signal is `false`. public func pausable<O: SignalProtocol>(by: O) -> Signal<Element, Error> where O.Element == Bool { return Signal { observer in var allowed: Bool = true let compositeDisposable = CompositeDisposable() compositeDisposable += by.observeNext { value in allowed = value } compositeDisposable += self.observe { event in if event.isTerminal || allowed { observer.on(event) } } return compositeDisposable } } /// Restart the operation in case of failure at most `times` number of times. public func retry(times: Int) -> Signal<Element, Error> { guard times > 0 else { return toSignal() } return Signal { observer in var remainingAttempts = times let serialDisposable = SerialDisposable(otherDisposable: nil) var attempt: (() -> Void)? attempt = { serialDisposable.otherDisposable?.dispose() serialDisposable.otherDisposable = self.observe { event in switch event { case .next(let element): observer.next(element) case .failed(let error): if remainingAttempts > 0 { remainingAttempts -= 1 attempt?() } else { attempt = nil observer.failed(error) } case .completed: attempt = nil observer.completed() } } } attempt?() return BlockDisposable { serialDisposable.dispose() attempt = nil } } } /// Retries the failed signal when other signal produces an element. public func retry<S: SignalProtocol>(when other: S) -> Signal<Element, Error> where S.Error == NoError { return Signal { observer in let serialDisposable = SerialDisposable(otherDisposable: nil) var attempt: (() -> Void)? attempt = { serialDisposable.otherDisposable?.dispose() let compositeDisposable = CompositeDisposable() serialDisposable.otherDisposable = compositeDisposable compositeDisposable += self.observe { event in switch event { case .next(let element): observer.next(element) case .completed: attempt = nil observer.completed() case .failed(let error): compositeDisposable += other.observe { otherEvent in switch otherEvent { case .next: attempt?() case .completed, .failed: attempt = nil observer.failed(error) } } } } } attempt?() return serialDisposable } } /// Error-out if `interval` time passes with no emitted elements. public func timeout(after interval: Double, with error: Error, on queue: DispatchQueue = DispatchQueue(label: "com.reactivekit.timeout")) -> Signal<Element, Error> { return Signal { observer in var completed = false let timeoutWhenCan: () -> Disposable = { return queue.disposableAfter(when: interval) { if !completed { completed = true observer.failed(error) } } } var lastSubscription = timeoutWhenCan() return self.observe { event in lastSubscription.dispose() observer.on(event) completed = event.isTerminal lastSubscription = timeoutWhenCan() } } } /// Collect all elements into an array and emit just that array. public func collect() -> Signal<[Element], Error> { return reduce([], { memo, new in memo + [new] }) } /// First emit events from source and then from `other` signal. public func concat(with other: Signal<Element, Error>) -> Signal<Element, Error> { return Signal { observer in let serialDisposable = SerialDisposable(otherDisposable: nil) serialDisposable.otherDisposable = self.observe { event in switch event { case .next(let element): observer.next(element) case .failed(let error): observer.failed(error) case .completed: serialDisposable.otherDisposable = other.observe(with: observer.on) } } return serialDisposable } } /// Emit default element if signal completes without emitting any element. public func defaultIfEmpty(_ element: Element) -> Signal<Element, Error> { return Signal { observer in var didEmitNonTerminal = false return self.observe { event in switch event { case .next(let element): didEmitNonTerminal = true observer.next(element) case .failed(let error): observer.failed(error) case .completed: if !didEmitNonTerminal { observer.next(element) } observer.completed() } } } } /// Reduce signal events to a single event by applying given function on each emission. public func reduce<U>(_ initial: U, _ combine: @escaping (U, Element) -> U) -> Signal<U, Error> { return scan(initial, combine).take(last: 1) } /// Replays the latest element when other signal fires an element. public func replayLatest<S: SignalProtocol>(when other: S) -> Signal<Element, Error> where S.Error == NoError { return Signal { observer in var latest: Element? = nil let disposable = CompositeDisposable() disposable += other.observe { event in switch event { case .next: if let latest = latest { observer.next(latest) } case .failed, .completed: break } } disposable += self.observe { event in switch event { case .next(let element): latest = element observer.next(element) case .failed(let error): observer.failed(error) case .completed: observer.completed() } } return disposable } } /// Prepend the given element to the signal emission. public func start(with element: Element) -> Signal<Element, Error> { return Signal { observer in observer.next(element) return self.observe { event in observer.on(event) } } } /// Par each element with its predecessor. First element is paired with `nil`. public func zipPrevious() -> Signal<(Element?, Element), Error> { return Signal { observer in var previous: Element? = nil return self.observe { event in switch event { case .next(let element): let lastPrevious = previous previous = element observer.next((lastPrevious, element)) case .failed(let error): observer.failed(error) case .completed: observer.completed() } } } } /// Wrap events into elements. public func materialize() -> Signal<Event<Element, Error>, NoError> { return Signal { observer in return self.observe { event in switch event { case .next(let element): observer.next(.next(element)) case .failed(let error): observer.next(.failed(error)) observer.completed() case .completed: observer.next(.completed) observer.completed() } } } } } // MARK: Injections extension SignalProtocol { /// Update the given subject with `true` when the receiver starts and with `false` when the receiver terminates. public func feedActivity<S: SubjectProtocol>(into listener: S) -> Signal<Element, Error> where S.Element == Bool { return doOn(start: { listener.next(true) }, disposed: { listener.next(false) }) } /// Update the given subject with `.next` elements. public func feedNext<S: SubjectProtocol>(into listener: S) -> Signal<Element, Error> where S.Element == Element { return doOn(next: { e in listener.next(e) }) } /// Update the given subject with mapped `.next` element whenever the element satisfies the given constraint. public func feedNext<S: SubjectProtocol>(into listener: S, when: @escaping (Element) -> Bool = { _ in true }, map: @escaping (Element) -> S.Element) -> Signal<Element, Error> { return doOn(next: { e in if when(e) { listener.next(map(e)) } }) } /// Updates the given subject with error from .failed event is such occurs. public func feedError<S: SubjectProtocol>(into listener: S) -> Signal<Element, Error> where S.Element == Error { return doOn(failed: { e in listener.next(e) }) } } // MARK: Signals that emit other signals public extension SignalProtocol where Element: SignalProtocol, Element.Error == Error { public typealias InnerElement = Element.Element /// Flatten the signal by observing all inner signals and propagate events from each one as they come. public func merge() -> Signal<InnerElement, Error> { return Signal { observer in let lock = NSRecursiveLock(name: "com.reactivekit.merge") let compositeDisposable = CompositeDisposable() var numberOfOperations = 1 // 1 for outer signal func decrementNumberOfOperations() { numberOfOperations -= 1 if numberOfOperations == 0 { observer.completed() } } compositeDisposable += self.observe { outerEvent in switch outerEvent { case .next(let innerSignal): lock.lock() numberOfOperations += 1 compositeDisposable += innerSignal.observe { innerEvent in switch innerEvent { case .next(let element): observer.next(element) case .failed(let error): observer.failed(error) case .completed: decrementNumberOfOperations() } } lock.unlock() case .failed(let error): observer.failed(error) case .completed: lock.lock() decrementNumberOfOperations() lock.unlock() } } return compositeDisposable } } /// Flatten the signal by observing and propagating emissions only from latest signal. public func switchToLatest() -> Signal<InnerElement, Error> { return Signal { observer in let serialDisposable = SerialDisposable(otherDisposable: nil) let compositeDisposable = CompositeDisposable([serialDisposable]) var completions = (outer: false, inner: false) let lock = NSRecursiveLock(name: "com.reactivekit.switchtolatest") compositeDisposable += self.observe { outerEvent in switch outerEvent { case .next(let innerSignal): lock.lock() completions.inner = false serialDisposable.otherDisposable?.dispose() serialDisposable.otherDisposable = innerSignal.observe { innerEvent in switch innerEvent { case .next(let element): observer.next(element) case .failed(let error): observer.failed(error) case .completed: lock.lock() completions.inner = true if completions.outer { observer.completed() } lock.unlock() } } lock.unlock() case .failed(let error): observer.failed(error) case .completed: lock.lock() completions.outer = true if completions.inner { observer.completed() } lock.unlock() } } return compositeDisposable } } /// Flatten the signal by sequentially observing inner signals in order in which they /// arrive, starting next observation only after previous one completes. public func concat() -> Signal<InnerElement, Error> { return Signal { observer in let lock = NSRecursiveLock(name: "com.reactivekit.concat") let serialDisposable = SerialDisposable(otherDisposable: nil) let compositeDisposable = CompositeDisposable([serialDisposable]) var completions = (outer: false, inner: true) var innerSignalQueue: [Element] = [] func startNextOperation() { completions.inner = false let innerSignal = innerSignalQueue.removeFirst() serialDisposable.otherDisposable?.dispose() serialDisposable.otherDisposable = innerSignal.observe { event in switch event { case .next(let element): observer.next(element) case .failed(let error): observer.failed(error) case .completed: lock.lock() completions.inner = true if !innerSignalQueue.isEmpty { startNextOperation() } else if completions.outer { observer.completed() } lock.unlock() } } } func addToQueue(signal: Element) { lock.lock() innerSignalQueue.append(signal) if completions.inner { startNextOperation() } lock.unlock() } compositeDisposable += self.observe { outerEvent in switch outerEvent { case .next(let innerSignal): addToQueue(signal: innerSignal) case .failed(let error): observer.failed(error) case .completed: lock.lock() completions.outer = true if completions.inner { observer.completed() } lock.unlock() } } return compositeDisposable } } } // MARK: Combinational extension SignalProtocol { fileprivate func _amb<O: SignalProtocol>(with other: O) -> Signal<Element, Error> where O.Element == Element, O.Error == Error { return Signal { observer in let lock = NSRecursiveLock(name: "com.reactivekit.amb") let disposable = (my: SerialDisposable(otherDisposable: nil), other: SerialDisposable(otherDisposable: nil)) var dispatching = (me: false, other: false) disposable.my.otherDisposable = self.observe { event in lock.lock(); defer { lock.unlock() } guard !dispatching.other else { return } dispatching.me = true observer.on(event) if !disposable.other.isDisposed { disposable.other.dispose() } } disposable.other.otherDisposable = other.observe { event in lock.lock(); defer { lock.unlock() } guard !dispatching.me else { return } dispatching.other = true observer.on(event) if !disposable.my.isDisposed { disposable.my.dispose() } } return CompositeDisposable([disposable.my, disposable.other]) } } /// Propagate events only from a signal that starts emitting first. public func amb<O: SignalProtocol>(with other: O) -> Signal<Element, Error> where O.Element == Element, O.Error == Error { return _amb(with: other) } fileprivate func _combineLatest<O: SignalProtocol, U>(with other: O, combine: @escaping (Element, O.Element) -> U) -> Signal<U, Error> where O.Error == Error { return Signal { observer in let lock = NSRecursiveLock(name: "com.reactivekit.combinelatestwith") var elements: (my: Element?, other: O.Element?) var completions: (me: Bool, other: Bool) = (false, false) let compositeDisposable = CompositeDisposable() func onAnyNext() { if let myElement = elements.my, let otherElement = elements.other { let combination = combine(myElement, otherElement) observer.next(combination) } } func onAnyCompleted() { if completions.me == true && completions.other == true { observer.completed() } } compositeDisposable += self.observe { event in lock.lock(); defer { lock.unlock() } switch event { case .next(let element): elements.my = element onAnyNext() case .failed(let error): observer.failed(error) case .completed: completions.me = true onAnyCompleted() } } compositeDisposable += other.observe { event in lock.lock(); defer { lock.unlock() } switch event { case .next(let element): elements.other = element onAnyNext() case .failed(let error): observer.failed(error) case .completed: completions.other = true onAnyCompleted() } } return compositeDisposable } } /// Emit a combination of latest elements from each signal. Starts when both signals emit at least one element, /// and emits `.next` when either signal generates an element by calling `combine` on the two latest elements. public func combineLatest<O: SignalProtocol, U>(with other: O, combine: @escaping (Element, O.Element) -> U) -> Signal<U, Error> where O.Error == Error { return _combineLatest(with: other, combine: combine) } /// Emit a pair of latest elements from each signal. Starts when both signals emit at least one element, /// and emits `.next` when either signal generates an element. public func combineLatest<O: SignalProtocol>(with other: O) -> Signal<(Element, O.Element), Error> where O.Error == Error { return _combineLatest(with: other, combine: { ($0, $1) }) } /// Merge emissions from both the receiver and the other signal into one signal. public func merge<O: SignalProtocol>(with other: O) -> Signal<Element, Error> where O.Element == Element, O.Error == Error { return Signal.sequence([self.toSignal(), other.toSignal()]).merge() } fileprivate func _zip<O: SignalProtocol, U>(with other: O, combine: @escaping (Element, O.Element) -> U) -> Signal<U, Error> where O.Error == Error { return Signal { observer in let lock = NSRecursiveLock(name: "zip") var buffers: (my: [Element], other: [O.Element]) = ([], []) var completions: (me: Bool, other: Bool) = (false, false) let compositeDisposable = CompositeDisposable() let dispatchIfPossible = { while !buffers.my.isEmpty && !buffers.other.isEmpty { let element = combine(buffers.my[0], buffers.other[0]) observer.next(element) buffers.my.removeFirst() buffers.other.removeFirst() } } func completeIfPossible() { if (buffers.my.isEmpty && completions.me) || (buffers.other.isEmpty && completions.other) { observer.completed() } } compositeDisposable += self.observe { event in lock.lock(); defer { lock.unlock() } switch event { case .next(let element): buffers.my.append(element) case .failed(let error): observer.failed(error) case .completed: completions.me = true } dispatchIfPossible() completeIfPossible() } compositeDisposable += other.observe { event in lock.lock(); defer { lock.unlock() } switch event { case .next(let element): buffers.other.append(element) case .failed(let error): observer.failed(error) case .completed: completions.other = true } dispatchIfPossible() completeIfPossible() } return compositeDisposable } } /// Emit elements from the receiver and the other signal in pairs. /// This differs from `combineLatest` in that the combinations are produced from elements at same positions. public func zip<O: SignalProtocol, U>(with other: O, combine: @escaping (Element, O.Element) -> U) -> Signal<U, Error> where O.Error == Error { return _zip(with: other, combine: combine) } /// Emit elements from the receiver and the other signal in pairs. /// This differs from `combineLatest` in that the pairs are produced from elements at same positions. public func zip<O: SignalProtocol>(with other: O) -> Signal<(Element, O.Element), Error> where O.Error == Error { return _zip(with: other, combine: { ($0, $1) }) } fileprivate func _with<O: SignalProtocol, U>(latestFrom other: O, combine: @escaping (Element, O.Element) -> U) -> Signal<U, Error> where O.Error == Error { return Signal { observer in var latest: O.Element? = nil let compositeDisposable = CompositeDisposable() compositeDisposable += other.observe { event in switch event { case .next(let element): latest = element case .failed(let error): observer.failed(error) case .completed: break } } compositeDisposable += self.observe { event in switch event { case .completed: observer.completed() case .failed(let error): observer.failed(error) case .next(let element): if let latest = latest { observer.next(combine(element, latest)) } } } return compositeDisposable } } /// Combines the receiver and the other signal into a signal of combinations of elements whenever the /// receiver emits an element with the latest element from the other signal. public func with<O: SignalProtocol, U>(latestFrom other: O, combine: @escaping (Element, O.Element) -> U) -> Signal<U, Error> where O.Error == Error { return _with(latestFrom: other, combine: combine) } /// Combines the receiver and the other signal into a signal of pairs of elements whenever the /// receiver emits an element with the latest element from the other signal. public func with<O: SignalProtocol>(latestFrom other: O) -> Signal<(Element, O.Element), Error> where O.Error == Error { return _with(latestFrom: other, combine: { ($0, $1) }) } } extension SignalProtocol where Error == NoError { /// Safe error casting from NoError to some Error type. public func castError<E>() -> Signal<Element, E> { return Signal { observer in return self.observe { event in switch event { case .next(let element): observer.next(element) case .completed: observer.completed() case .failed: break // will never happen because of NoError constraint } } } } /// Map each event into a signal and then flatten inner signals. public func flatMapLatest<O: SignalProtocol>(_ transform: @escaping (Element) -> O) -> Signal<O.Element, O.Error> { return castError().map(transform).switchToLatest() } /// Map each event into a signal and then flatten inner signals. public func flatMapMerge<O: SignalProtocol>(_ transform: @escaping (Element) -> O) -> Signal<O.Element, O.Error> { return castError().map(transform).merge() } /// Map each event into a signal and then flatten inner signals. public func flatMapConcat<O: SignalProtocol>(_ transform: @escaping (Element) -> O) -> Signal<O.Element, O.Error> { return castError().map(transform).concat() } /// Transform each element by applying `transform` on it. public func tryMap<U, E>(_ transform: @escaping (Element) -> Result<U, E>) -> Signal<U, E> { return Signal { observer in return self.observe { event in switch event { case .next(let element): switch transform(element) { case .success(let value): observer.next(value) case .failure(let error): observer.failed(error) } case .failed: break // will never happen because of NoError constraint case .completed: observer.completed() } } } } /// Propagate events only from a signal that starts emitting first. public func amb<O: SignalProtocol>(with other: O) -> Signal<Element, O.Error> where O.Element == Element { return castError()._amb(with: other) } /// Emit a combination of latest elements from each signal. Starts when both signals emit at least one element, /// and emits `.next` when either signal generates an element by calling `combine` on the two latest elements. public func combineLatest<O: SignalProtocol, U>(with other: O, combine: @escaping (Element, O.Element) -> U) -> Signal<U, O.Error> { return castError()._combineLatest(with: other, combine: combine) } /// Emit a pair of latest elements from each signal. Starts when both signals emit at least one element, /// and emits `.next` when either signal generates an element. public func combineLatest<O: SignalProtocol>(with other: O) -> Signal<(Element, O.Element), O.Error> { return castError()._combineLatest(with: other, combine: { ($0, $1) }) } /// Merge emissions from both the receiver and the other signal into one signal. public func merge<O: SignalProtocol>(with other: O) -> Signal<Element, O.Error> where O.Element == Element { return Signal.sequence([toSignal().castError(), other.toSignal()]).merge() } /// Emit elements from the receiver and the other signal in pairs. /// This differs from `combineLatest` in that the combinations are produced from elements at same positions. public func zip<O: SignalProtocol, U>(with other: O, combine: @escaping (Element, O.Element) -> U) -> Signal<U, O.Error> { return castError()._zip(with: other, combine: combine) } /// Emit elements from the receiver and the other signal in pairs. /// This differs from `combineLatest` in that the pairs are produced from elements at same positions. public func zip<O: SignalProtocol>(with other: O) -> Signal<(Element, O.Element), O.Error> { return castError()._zip(with: other, combine: { ($0, $1) }) } /// Combines the receiver and the other signal into a signal of combinations of elements whenever the /// receiver emits an element with the latest element from the other signal. public func with<O: SignalProtocol, U>(latestFrom other: O, combine: @escaping (Element, O.Element) -> U) -> Signal<U, O.Error> { return castError()._with(latestFrom: other, combine: combine) } /// Combines the receiver and the other signal into a signal of pairs of elements whenever the /// receiver emits an element with the latest element from the other signal. public func with<O: SignalProtocol>(latestFrom other: O) -> Signal<(Element, O.Element), O.Error> { return castError()._with(latestFrom: other, combine: { ($0, $1) }) } /// Returns an observable sequence containing only the unwrapped elements from `.next` events. /// Usually used on the Signal resulting from `materialize()`. /// - SeeAlso: `errors()`, `materialize()` public func elements<U, E>() -> Signal<U, NoError> where Element == Event<U, E> { return flatMap { $0.element } } /// Returns an observable sequence containing only the unwrapped errors from `.failed` events. /// Usually used on the Signal resulting from `materialize()`. /// - SeeAlso: `elements()`, `materialize()` public func errors<U, E>() -> Signal<E, NoError> where Element == Event<U, E> { return flatMap { $0.error } } } // MARK: Standalone functions /// Combine an array of signals into one. See `combineLatest(with:)` for more info. public func combineLatest<Element, Result, Error>(_ signals: [Signal<Element, Error>], combine: @escaping ([Element]) -> Result) -> Signal<Result, Error> { return Signal { observer in let disposable = CompositeDisposable() var elements = Array<Element?>(repeating: nil, count: signals.count) var completions = Array(repeating: false, count: signals.count) for (idx, signal) in signals.enumerated() { disposable += signal.observe { event in switch event { case .next(let element): elements[idx] = element if elements.reduce(true, { $0 && ($1 != nil) }) { observer.next(combine(elements.map { $0! })) } case .failed(let error): observer.failed(error) case .completed: completions[idx] = true if completions.reduce(true, { $0 && $1 }) { observer.completed() } } } } return disposable } } /// Merge an array of signals into one. See `merge(with:)` for more info. public func merge<Element, Error>(_ signals: [Signal<Element, Error>]) -> Signal<Element, Error> { return Signal { observer in guard signals.count > 0 else { observer.completed() return NonDisposable.instance } let disposable = CompositeDisposable() var completions = Array(repeating: false, count: signals.count) for (idx, signal) in signals.enumerated() { disposable += signal.observe { event in switch event { case .next(let element): observer.next(element) case .failed(let error): observer.failed(error) case .completed: completions[idx] = true if completions.reduce(true, { $0 && $1 }) { observer.completed() } } } } return disposable } }
mit
e123d2be6d3cd1e710d95679cd32a089
31.890196
190
0.616175
4.58306
false
false
false
false
slightair/SwiftUtilities
SwiftUtilities/Foundation Extensions/String+Foundation.swift
2
2761
// // String+Extensions.swift // SwiftUtilities // // Created by Jonathan Wight on 3/23/15. // // Copyright (c) 2014, Jonathan Wight // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import Foundation /** * Set of helper methods to convert String ranges to/from NSString ranges * * NSString indices are UTF16 based * String indices are Grapheme Cluster based * This allows you convert between the two * Converting is useful when using Cocoa APIs that use NSRanges (for example * text view selection ranges or regular expression result ranges). */ public extension String { func convert(index: NSInteger) -> String.Index? { let utf16Index = utf16.startIndex.advancedBy(index) return utf16Index.samePositionIn(self) } func convert(range: NSRange) -> Range <String.Index>? { let swiftRange = range.asRange if let startIndex = convert(swiftRange.startIndex), let endIndex = convert(swiftRange.endIndex) { return startIndex..<endIndex } else { return nil } } func convert(index: String.Index) -> NSInteger { let utf16Index = index.samePositionIn(utf16) return utf16.startIndex.distanceTo(utf16Index) } func convert(range: Range <String.Index>) -> NSRange { let startIndex = convert(range.startIndex) let endIndex = convert(range.endIndex) return NSMakeRange(startIndex, endIndex - startIndex) } }
bsd-2-clause
592be442e03356d173f07683169b7c5e
37.901408
105
0.717856
4.467638
false
false
false
false
M0rph3v5/AFDateHelper
AFDateHelper/AFDateExtension.swift
1
28798
// // AFDateExtension.swift // // Version 2.0.4 // // Created by Melvin Rivera on 7/15/14. // Copyright (c) 2014. All rights reserved. // import Foundation let DefaultFormat = "EEE MMM dd HH:mm:ss Z yyyy" let ISO8601Format = "yyyy-MM-dd'T'HH:mm:ssZZZ" let RSSFormat = "EEE, d MMM yyyy HH:mm:ss ZZZ" let AltRSSFormat = "d MMM yyyy HH:mm:ss ZZZ" public enum DateFormat { case ISO8601, DotNet, RSS, AltRSS case Custom(String) } public extension NSDate { // MARK: Intervals In Seconds private class func minuteInSeconds() -> Double { return 60 } private class func hourInSeconds() -> Double { return 3600 } private class func dayInSeconds() -> Double { return 86400 } private class func weekInSeconds() -> Double { return 604800 } private class func yearInSeconds() -> Double { return 31556926 } // MARK: Components private class func componentFlags() -> NSCalendarUnit { return NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay | NSCalendarUnit.CalendarUnitWeekOfYear | NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute | NSCalendarUnit.CalendarUnitSecond | NSCalendarUnit.CalendarUnitWeekday | NSCalendarUnit.CalendarUnitWeekdayOrdinal | NSCalendarUnit.CalendarUnitWeekOfYear } private class func components(#fromDate: NSDate) -> NSDateComponents! { return NSCalendar.currentCalendar().components(NSDate.componentFlags(), fromDate: fromDate) } private func components() -> NSDateComponents { return NSDate.components(fromDate: self)! } // MARK: Date From String /** Returns a new NSDate object based on a date string and a specified format. :param: fromString :String Date string i.e. "16 July 1972 6:12:00". :param: format :DateFormat Format of date. Can be .ISO8601("1972-07-16T08:15:30-05:00"), DotNet("/Date(1268123281843)/"), RSS("Fri, 09 Sep 2011 15:26:08 +0200"), AltRSS("09 Sep 2011 15:26:08 +0200") or Custom("16 July 1972 6:12:00"). :returns: NSDate */ convenience init(fromString string: String, format:DateFormat) { if string.isEmpty { self.init() return } let string = string as NSString switch format { case .DotNet: let startIndex = string.rangeOfString("(").location + 1 let endIndex = string.rangeOfString(")").location let range = NSRange(location: startIndex, length: endIndex-startIndex) let milliseconds = (string.substringWithRange(range) as NSString).longLongValue let interval = NSTimeInterval(milliseconds / 1000) self.init(timeIntervalSince1970: interval) case .ISO8601: var s = string if string.hasSuffix(" 00:00") { s = s.substringToIndex(s.length-6) + "GMT" } else if string.hasSuffix("Z") { s = s.substringToIndex(s.length-1) + "GMT" } var formatter = NSDate.formatter(format: ISO8601Format) if let date = formatter.dateFromString(string as String) { self.init(timeInterval:0, sinceDate:date) } else { self.init() } case .RSS: var s = string if string.hasSuffix("Z") { s = s.substringToIndex(s.length-1) + "GMT" } var formatter = NSDate.formatter(format: RSSFormat) if let date = formatter.dateFromString(string as String) { self.init(timeInterval:0, sinceDate:date) } else { self.init() } case .AltRSS: var s = string if string.hasSuffix("Z") { s = s.substringToIndex(s.length-1) + "GMT" } var formatter = NSDate.formatter(format: AltRSSFormat) if let date = formatter.dateFromString(string as String) { self.init(timeInterval:0, sinceDate:date) } else { self.init() } case .Custom(let dateFormat): var formatter = NSDate.formatter(format: dateFormat) if let date = formatter.dateFromString(string as String) { self.init(timeInterval:0, sinceDate:date) } else { self.init() } } } // MARK: Comparing Dates /** Compares dates without while ignoring time. :param: date :NSDate Date to compare. :returns: :Bool Returns true if dates are equal. */ func isEqualToDateIgnoringTime(date: NSDate) -> Bool { let comp1 = NSDate.components(fromDate: self) let comp2 = NSDate.components(fromDate: date) return ((comp1.year == comp2.year) && (comp1.month == comp2.month) && (comp1.day == comp2.day)) } /** Checks if date is today. :returns: :Bool Returns true if date is today. */ func isToday() -> Bool { return self.isEqualToDateIgnoringTime(NSDate()) } /** Checks if date is tomorrow. :returns: :Bool Returns true if date is tomorrow. */ func isTomorrow() -> Bool { return self.isEqualToDateIgnoringTime(NSDate().dateByAddingDays(1)) } /** Checks if date is yesterday. :returns: :Bool Returns true if date is yesterday. */ func isYesterday() -> Bool { return self.isEqualToDateIgnoringTime(NSDate().dateBySubtractingDays(1)) } /** Compares dates to see if they are in the same week. :param: date :NSDate Date to compare. :returns: :Bool Returns true if date is tomorrow. */ func isSameWeekAsDate(date: NSDate) -> Bool { let comp1 = NSDate.components(fromDate: self) let comp2 = NSDate.components(fromDate: date) // Must be same week. 12/31 and 1/1 will both be week "1" if they are in the same week if comp1.weekOfYear != comp2.weekOfYear { return false } // Must have a time interval under 1 week return abs(self.timeIntervalSinceDate(date)) < NSDate.weekInSeconds() } /** Checks if date is this week. :returns: :Bool Returns true if date is this week. */ func isThisWeek() -> Bool { return self.isSameWeekAsDate(NSDate()) } /** Checks if date is next week. :returns: :Bool Returns true if date is next week. */ func isNextWeek() -> Bool { let interval: NSTimeInterval = NSDate().timeIntervalSinceReferenceDate + NSDate.weekInSeconds() let date = NSDate(timeIntervalSinceReferenceDate: interval) return self.isSameWeekAsDate(date) } /** Checks if date is last week. :returns: :Bool Returns true if date is last week. */ func isLastWeek() -> Bool { let interval: NSTimeInterval = NSDate().timeIntervalSinceReferenceDate - NSDate.weekInSeconds() let date = NSDate(timeIntervalSinceReferenceDate: interval) return self.isSameWeekAsDate(date) } /** Compares dates to see if they are in the same year. :param: date :NSDate Date to compare. :returns: :Bool Returns true if date is this week. */ func isSameYearAsDate(date: NSDate) -> Bool { let comp1 = NSDate.components(fromDate: self) let comp2 = NSDate.components(fromDate: date) return (comp1.year == comp2.year) } /** Checks if date is this year. :returns: :Bool Returns true if date is this year. */ func isThisYear() -> Bool { return self.isSameYearAsDate(NSDate()) } /** Checks if date is next year. :returns: :Bool Returns true if date is next year. */ func isNextYear() -> Bool { let comp1 = NSDate.components(fromDate: self) let comp2 = NSDate.components(fromDate: NSDate()) return (comp1.year == comp2.year + 1) } /** Checks if date is last year. :returns: :Bool Returns true if date is last year. */ func isLastYear() -> Bool { let comp1 = NSDate.components(fromDate: self) let comp2 = NSDate.components(fromDate: NSDate()) return (comp1.year == comp2.year - 1) } /** Compares dates to see if it's an earlier date. :param: date :NSDate Date to compare. :returns: :Bool Returns true if date is earlier. */ func isEarlierThanDate(date: NSDate) -> Bool { return self.earlierDate(date) == self } /** Compares dates to see if it's a later date. :param: date :NSDate Date to compare. :returns: :Bool Returns true if date is later. */ func isLaterThanDate(date: NSDate) -> Bool { return self.laterDate(date) == self } // MARK: Adjusting Dates /** Returns a new NSDate object by a adding days. :param: days :Int Days to add. :returns: NSDate */ func dateByAddingDays(days: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.day = days return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(0))! } /** Returns a new NSDate object by a substracting days. :param: days :Int Days to substract. :returns: NSDate */ func dateBySubtractingDays(days: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.day = (days * -1) return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(0))! } /** Returns a new NSDate object by a adding hours. :param: days :Int Hours to add. :returns: NSDate */ func dateByAddingHours(hours: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.hour = hours return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(0))! } /** Returns a new NSDate object by a substracting hours. :param: days :Int Hours to substract. :returns: NSDate */ func dateBySubtractingHours(hours: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.hour = (hours * -1) return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(0))! } /** Returns a new NSDate object by a adding minutes. :param: days :Int Minutes to add. :returns: NSDate */ func dateByAddingMinutes(minutes: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.minute = minutes return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(0))! } /** Returns a new NSDate object by a adding minutes. :param: days :Int Minutes to add. :returns: NSDate */ func dateBySubtractingMinutes(minutes: Int) -> NSDate { let dateComp = NSDateComponents() dateComp.minute = (minutes * -1) return NSCalendar.currentCalendar().dateByAddingComponents(dateComp, toDate: self, options: NSCalendarOptions(0))! } /** Returns a new NSDate object from the start of the day. :returns: NSDate */ func dateAtStartOfDay() -> NSDate { var components = self.components() components.hour = 0 components.minute = 0 components.second = 0 return NSCalendar.currentCalendar().dateFromComponents(components)! } /** Returns a new NSDate object from the end of the day. :returns: NSDate */ func dateAtEndOfDay() -> NSDate { var components = self.components() components.hour = 23 components.minute = 59 components.second = 59 return NSCalendar.currentCalendar().dateFromComponents(components)! } /** Returns a new NSDate object from the start of the week. :returns: NSDate */ func dateAtStartOfWeek() -> NSDate { let flags :NSCalendarUnit = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitWeekOfYear | NSCalendarUnit.CalendarUnitWeekday var components = NSCalendar.currentCalendar().components(flags, fromDate: self) components.weekday = NSCalendar.currentCalendar().firstWeekday components.hour = 0 components.minute = 0 components.second = 0 return NSCalendar.currentCalendar().dateFromComponents(components)! } /** Returns a new NSDate object from the end of the week. :returns: NSDate */ func dateAtEndOfWeek() -> NSDate { let flags :NSCalendarUnit = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitWeekOfYear | NSCalendarUnit.CalendarUnitWeekday var components = NSCalendar.currentCalendar().components(flags, fromDate: self) components.weekday = NSCalendar.currentCalendar().firstWeekday + 7 components.hour = 0 components.minute = 0 components.second = 0 return NSCalendar.currentCalendar().dateFromComponents(components)! } /** Return a new NSDate object of the first day of the month :returns: NSDate */ func dateAtTheStartOfMonth() -> NSDate { //Create the date components var components = self.components() components.day = 1 //Builds the first day of the month let firstDayOfMonthDate :NSDate = NSCalendar.currentCalendar().dateFromComponents(components)! return firstDayOfMonthDate } /** Return a new NSDate object of the last day of the month :returns: NSDate */ func dateAtTheEndOfMonth() -> NSDate { //Create the date components var components = self.components() //Set the last day of this month components.month += 1 components.day = 0 //Builds the first day of the month let lastDayOfMonth :NSDate = NSCalendar.currentCalendar().dateFromComponents(components)! return lastDayOfMonth } // MARK: Retrieving Intervals /** Returns the interval in minutes after a date. :param: date :NSDate Date to compare. :returns: Int */ func minutesAfterDate(date: NSDate) -> Int { let interval = self.timeIntervalSinceDate(date) return Int(interval / NSDate.minuteInSeconds()) } /** Returns the interval in minutes before a date. :param: date :NSDate Date to compare. :returns: Int */ func minutesBeforeDate(date: NSDate) -> Int { let interval = date.timeIntervalSinceDate(self) return Int(interval / NSDate.minuteInSeconds()) } /** Returns the interval in hours after a date. :param: date :NSDate Date to compare. :returns: Int */ func hoursAfterDate(date: NSDate) -> Int { let interval = self.timeIntervalSinceDate(date) return Int(interval / NSDate.hourInSeconds()) } /** Returns the interval in hours before a date. :param: date :NSDate Date to compare. :returns: Int */ func hoursBeforeDate(date: NSDate) -> Int { let interval = date.timeIntervalSinceDate(self) return Int(interval / NSDate.hourInSeconds()) } /** Returns the interval in days after a date. :param: date :NSDate Date to compare. :returns: Int */ func daysAfterDate(date: NSDate) -> Int { let interval = self.timeIntervalSinceDate(date) return Int(interval / NSDate.dayInSeconds()) } /** Returns the interval in days before a date. :param: date :NSDate Date to compare. :returns: Int */ func daysBeforeDate(date: NSDate) -> Int { let interval = date.timeIntervalSinceDate(self) return Int(interval / NSDate.dayInSeconds()) } // MARK: Decomposing Dates /** Returns the nearest hour. :returns: Int */ func nearestHour () -> Int { let halfHour = NSDate.minuteInSeconds() * 30 var interval = self.timeIntervalSinceReferenceDate if self.seconds() < 30 { interval -= halfHour } else { interval += halfHour } let date = NSDate(timeIntervalSinceReferenceDate: interval) return date.hour() } /** Returns the year component. :returns: Int */ func year () -> Int { return self.components().year } /** Returns the month component. :returns: Int */ func month () -> Int { return self.components().month } /** Returns the week of year component. :returns: Int */ func week () -> Int { return self.components().weekOfYear } /** Returns the day component. :returns: Int */ func day () -> Int { return self.components().day } /** Returns the hour component. :returns: Int */ func hour () -> Int { return self.components().hour } /** Returns the minute component. :returns: Int */ func minute () -> Int { return self.components().minute } /** Returns the seconds component. :returns: Int */ func seconds () -> Int { return self.components().second } /** Returns the weekday component. :returns: Int */ func weekday () -> Int { return self.components().weekday } /** Returns the nth days component. e.g. 2nd Tuesday of the month is 2. :returns: Int */ func nthWeekday () -> Int { return self.components().weekdayOrdinal } /** Returns the days of the month. :returns: Int */ func monthDays () -> Int { return NSCalendar.currentCalendar().rangeOfUnit(NSCalendarUnit.CalendarUnitDay, inUnit: NSCalendarUnit.CalendarUnitMonth, forDate: self).length } /** Returns the first day of the week. :returns: Int */ func firstDayOfWeek () -> Int { let distanceToStartOfWeek = NSDate.dayInSeconds() * Double(self.components().weekday - 1) let interval: NSTimeInterval = self.timeIntervalSinceReferenceDate - distanceToStartOfWeek return NSDate(timeIntervalSinceReferenceDate: interval).day() } /** Returns the last day of the week. :returns: Int */ func lastDayOfWeek () -> Int { let distanceToStartOfWeek = NSDate.dayInSeconds() * Double(self.components().weekday - 1) let distanceToEndOfWeek = NSDate.dayInSeconds() * Double(7) let interval: NSTimeInterval = self.timeIntervalSinceReferenceDate - distanceToStartOfWeek + distanceToEndOfWeek return NSDate(timeIntervalSinceReferenceDate: interval).day() } /** Checks to see if the date is a weekdday. :returns: :Bool Returns true if weekday. */ func isWeekday() -> Bool { return !self.isWeekend() } /** Checks to see if the date is a weekdend. :returns: :Bool Returns true if weekend. */ func isWeekend() -> Bool { let range = NSCalendar.currentCalendar().maximumRangeOfUnit(NSCalendarUnit.CalendarUnitWeekday) return (self.weekday() == range.location || self.weekday() == range.length) } // MARK: To String /** Returns a new String object using .ShortStyle date style and .ShortStyle time style. :returns: :String */ func toString() -> String { return self.toString(dateStyle: .ShortStyle, timeStyle: .ShortStyle, doesRelativeDateFormatting: false) } /** Returns a new String object based on a specified date format. :param: format :DateFormat Format of date. Can be .ISO8601("1972-07-16T08:15:30-05:00"), DotNet("/Date(1268123281843)/"), RSS("Fri, 09 Sep 2011 15:26:08 +0200"), AltRSS("09 Sep 2011 15:26:08 +0200") or Custom("16 July 1972 6:12:00"). :returns: String */ func toString(#format: DateFormat) -> String { var dateFormat: String switch format { case .DotNet: let offset = NSTimeZone.defaultTimeZone().secondsFromGMT / 3600 let nowMillis = 1000 * self.timeIntervalSince1970 return "/Date(\(nowMillis)\(offset))/" case .ISO8601: dateFormat = ISO8601Format case .RSS: dateFormat = RSSFormat case .AltRSS: dateFormat = AltRSSFormat case .Custom(let string): dateFormat = string } var formatter = NSDate.formatter(format: dateFormat) return formatter.stringFromDate(self) } /** Returns a new String object based on a date style, time style and optional relative flag. :param: dateStyle :NSDateFormatterStyle :param: timeStyle :NSDateFormatterStyle :param: doesRelativeDateFormatting :Bool :returns: String */ func toString(#dateStyle: NSDateFormatterStyle, timeStyle: NSDateFormatterStyle, doesRelativeDateFormatting: Bool = false) -> String { var formatter = NSDate.formatter(dateStyle: dateStyle, timeStyle: timeStyle, doesRelativeDateFormatting: doesRelativeDateFormatting) return formatter.stringFromDate(self) } /** Returns a new String object based on a relative time language. i.e. just now, 1 minute ago etc.. :returns: String */ func relativeTimeToString() -> String { let time = self.timeIntervalSince1970 let now = NSDate().timeIntervalSince1970 let seconds = now - time let minutes = round(seconds/60) let hours = round(minutes/60) let days = round(hours/24) if seconds < 10 { return NSLocalizedString("just now", comment: "Show the relative time from a date") } else if seconds < 60 { let relativeTime = NSLocalizedString("%.f seconds ago", comment: "Show the relative time from a date") return String(format: relativeTime, seconds) } if minutes < 60 { if minutes == 1 { return NSLocalizedString("1 minute ago", comment: "Show the relative time from a date") } else { let relativeTime = NSLocalizedString("%.f minutes ago", comment: "Show the relative time from a date") return String(format: relativeTime, minutes) } } if hours < 24 { if hours == 1 { return NSLocalizedString("1 hour ago", comment: "Show the relative time from a date") } else { let relativeTime = NSLocalizedString("%.f hours ago", comment: "Show the relative time from a date") return String(format: relativeTime, hours) } } if days < 7 { if days == 1 { return NSLocalizedString("1 day ago", comment: "Show the relative time from a date") } else { let relativeTime = NSLocalizedString("%.f days ago", comment: "Show the relative time from a date") return String(format: relativeTime, days) } } return self.toString() } /** Returns the weekday as a new String object. :returns: String */ func weekdayToString() -> String { var formatter = NSDate.formatter() return formatter.weekdaySymbols[self.weekday()-1] as! String } /** Returns the short weekday as a new String object. :returns: String */ func shortWeekdayToString() -> String { var formatter = NSDate.formatter() return formatter.shortWeekdaySymbols[self.weekday()-1] as! String } /** Returns the very short weekday as a new String object. :returns: String */ func veryShortWeekdayToString() -> String { var formatter = NSDate.formatter() return formatter.veryShortWeekdaySymbols[self.weekday()-1] as! String } /** Returns the month as a new String object. :returns: String */ func monthToString() -> String { var formatter = NSDate.formatter() return formatter.monthSymbols[self.month()-1] as! String } /** Returns the short month as a new String object. :returns: String */ func shortMonthToString() -> String { var formatter = NSDate.formatter() return formatter.shortMonthSymbols[self.month()-1] as! String } /** Returns the very short month as a new String object. :returns: String */ func veryShortMonthToString() -> String { var formatter = NSDate.formatter() return formatter.veryShortMonthSymbols[self.month()-1] as! String } // MARK: Static Cached Formatters /** Returns a static singleton array of NSDateFormatters so that thy are only created once. :returns: [String: NSDateFormatter] Array of NSDateFormatters */ private class func sharedDateFormatters() -> [String: NSDateFormatter] { struct Static { static var formatters: [String: NSDateFormatter]? = nil static var once: dispatch_once_t = 0 } dispatch_once(&Static.once) { Static.formatters = [String: NSDateFormatter]() } return Static.formatters! } /** Returns a singleton formatter based on the format, timeZone and locale. Formatters are cached in a singleton array using hashkeys generated by format, timeZone and locale. :param: format :String :param: timeZone :NSTimeZone Uses local time zone as the default :param: locale :NSLocale Uses current locale as the default :returns: [String: NSDateFormatter] Singleton of NSDateFormatters */ private class func formatter(format:String = DefaultFormat, timeZone: NSTimeZone = NSTimeZone.localTimeZone(), locale: NSLocale = NSLocale.currentLocale()) -> NSDateFormatter { let hashKey = "\(format.hashValue)\(timeZone.hashValue)\(locale.hashValue)" var formatters = NSDate.sharedDateFormatters() if let cachedDateFormatter = formatters[hashKey] { return cachedDateFormatter } else { let formatter = NSDateFormatter() formatter.dateFormat = format formatter.timeZone = timeZone formatter.locale = locale formatters[hashKey] = formatter return formatter } } /** Returns a singleton formatter based on date style, time style and relative date. Formatters are cached in a singleton array using hashkeys generated by date style, time style, relative date, timeZone and locale. :param: dateStyle :NSDateFormatterStyle :param: timeStyle :NSDateFormatterStyle :param: doesRelativeDateFormatting :Bool :param: timeZone :NSTimeZone :param: locale :NSLocale :returns: [String: NSDateFormatter] Singleton array of NSDateFormatters */ private class func formatter(#dateStyle: NSDateFormatterStyle, timeStyle: NSDateFormatterStyle, doesRelativeDateFormatting: Bool, timeZone: NSTimeZone = NSTimeZone.localTimeZone(), locale: NSLocale = NSLocale.currentLocale()) -> NSDateFormatter { var formatters = NSDate.sharedDateFormatters() let hashKey = "\(dateStyle.hashValue)\(timeStyle.hashValue)\(doesRelativeDateFormatting.hashValue)\(timeZone.hashValue)\(locale.hashValue)" if let cachedDateFormatter = formatters[hashKey] { return cachedDateFormatter } else { let formatter = NSDateFormatter() formatter.dateStyle = dateStyle formatter.timeStyle = timeStyle formatter.doesRelativeDateFormatting = doesRelativeDateFormatting formatter.timeZone = timeZone formatter.locale = locale formatters[hashKey] = formatter return formatter } } }
mit
f985afdbe744f7ec78e00dcc1a1e3df2
30.997778
436
0.608271
4.899285
false
false
false
false
grpc/grpc-swift
Sources/GRPC/GRPCTimeout.swift
1
5171
/* * Copyright 2019, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Dispatch import NIOCore /// A timeout for a gRPC call. /// /// Timeouts must be positive and at most 8-digits long. public struct GRPCTimeout: CustomStringConvertible, Equatable { /// Creates an infinite timeout. This is a sentinel value which must __not__ be sent to a gRPC service. public static let infinite = GRPCTimeout( nanoseconds: Int64.max, wireEncoding: "infinite" ) /// The largest amount of any unit of time which may be represented by a gRPC timeout. internal static let maxAmount: Int64 = 99_999_999 /// The wire encoding of this timeout as described in the gRPC protocol. /// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md. public let wireEncoding: String public let nanoseconds: Int64 public var description: String { return self.wireEncoding } /// Creates a timeout from the given deadline. /// /// - Parameter deadline: The deadline to create a timeout from. internal init(deadline: NIODeadline, testingOnlyNow: NIODeadline? = nil) { switch deadline { case .distantFuture: self = .infinite default: let timeAmountUntilDeadline = deadline - (testingOnlyNow ?? .now()) self.init(rounding: timeAmountUntilDeadline.nanoseconds, unit: .nanoseconds) } } private init(nanoseconds: Int64, wireEncoding: String) { self.nanoseconds = nanoseconds self.wireEncoding = wireEncoding } /// Creates a `GRPCTimeout`. /// /// - Precondition: The amount should be greater than or equal to zero and less than or equal /// to `GRPCTimeout.maxAmount`. internal init(amount: Int64, unit: GRPCTimeoutUnit) { precondition(amount >= 0 && amount <= GRPCTimeout.maxAmount) // See "Timeout" in https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests // If we overflow at this point, which is certainly possible if `amount` is sufficiently large // and `unit` is `.hours`, clamp the nanosecond timeout to `Int64.max`. It's about 292 years so // it should be long enough for the user not to notice the difference should the rpc time out. let (partial, overflow) = amount.multipliedReportingOverflow(by: unit.asNanoseconds) self.init( nanoseconds: overflow ? Int64.max : partial, wireEncoding: "\(amount)\(unit.rawValue)" ) } /// Create a timeout by rounding up the timeout so that it may be represented in the gRPC /// wire format. internal init(rounding amount: Int64, unit: GRPCTimeoutUnit) { var roundedAmount = amount var roundedUnit = unit if roundedAmount <= 0 { roundedAmount = 0 } else { while roundedAmount > GRPCTimeout.maxAmount { switch roundedUnit { case .nanoseconds: roundedAmount = roundedAmount.quotientRoundedUp(dividingBy: 1000) roundedUnit = .microseconds case .microseconds: roundedAmount = roundedAmount.quotientRoundedUp(dividingBy: 1000) roundedUnit = .milliseconds case .milliseconds: roundedAmount = roundedAmount.quotientRoundedUp(dividingBy: 1000) roundedUnit = .seconds case .seconds: roundedAmount = roundedAmount.quotientRoundedUp(dividingBy: 60) roundedUnit = .minutes case .minutes: roundedAmount = roundedAmount.quotientRoundedUp(dividingBy: 60) roundedUnit = .hours case .hours: roundedAmount = GRPCTimeout.maxAmount roundedUnit = .hours } } } self.init(amount: roundedAmount, unit: roundedUnit) } } extension Int64 { /// Returns the quotient of this value when divided by `divisor` rounded up to the nearest /// multiple of `divisor` if the remainder is non-zero. /// /// - Parameter divisor: The value to divide this value by. fileprivate func quotientRoundedUp(dividingBy divisor: Int64) -> Int64 { let (quotient, remainder) = self.quotientAndRemainder(dividingBy: divisor) return quotient + (remainder != 0 ? 1 : 0) } } internal enum GRPCTimeoutUnit: String { case hours = "H" case minutes = "M" case seconds = "S" case milliseconds = "m" case microseconds = "u" case nanoseconds = "n" internal var asNanoseconds: Int64 { switch self { case .hours: return 60 * 60 * 1000 * 1000 * 1000 case .minutes: return 60 * 1000 * 1000 * 1000 case .seconds: return 1000 * 1000 * 1000 case .milliseconds: return 1000 * 1000 case .microseconds: return 1000 case .nanoseconds: return 1 } } }
apache-2.0
af807670f4351bb937043bd8950d22f6
32.36129
105
0.684587
4.221224
false
false
false
false
netguru/inbbbox-ios
Unit Tests/ShotsOnboardingStateHandlerSpec.swift
1
3766
// // ShotsOnboardingStateHandlerSpec.swift // Inbbbox // // Copyright © 2017 Netguru Sp. z o.o. All rights reserved. // import Quick import Nimble @testable import Inbbbox class ShotsOnboardingStateHandlerSpec: QuickSpec { override func spec() { var sut: ShotsOnboardingStateHandler! var collectionViewController: ShotsCollectionViewController! beforeEach { sut = ShotsOnboardingStateHandler() collectionViewController = ShotsCollectionViewController() } afterEach { sut = nil collectionViewController = nil } describe("when initialized") { context("should have initial values") { it("number of sections and items should be accurate") { expect(sut.collectionView(collectionViewController.collectionView!, numberOfItemsInSection: 0)).to(equal(5)) } it("onboarding steps have proper actions") { let actions: [ShotCollectionViewCell.Action] = [.like, .bucket, .comment, .follow, .doNothing] for (index, element) in sut.onboardingSteps.enumerated() { expect(element.action).to(equal(actions[index])) } } it("validate states") { expect(sut.state).to(equal(ShotsCollectionViewController.State.onboarding)) expect(sut.nextState).to(equal(ShotsCollectionViewController.State.normal)) } } context("cells handling") { it("swiping cells with proper action should move to next steps") { let collectionView = collectionViewController.collectionView! let likeCell = sut.collectionView(collectionView, cellForItemAt: IndexPath(item: 0, section: 0)) as! ShotCollectionViewCell let bucketCell = sut.collectionView(collectionView, cellForItemAt: IndexPath(item: 1, section: 0)) as! ShotCollectionViewCell let commentCell = sut.collectionView(collectionView, cellForItemAt: IndexPath(item: 2, section: 0)) as! ShotCollectionViewCell let followCell = sut.collectionView(collectionView, cellForItemAt: IndexPath(item: 3, section: 0)) as! ShotCollectionViewCell likeCell.swipeCompletion!(.like) expect(collectionView.contentOffset.y).toEventually(beCloseTo(667)) bucketCell.swipeCompletion!(.bucket) expect(collectionView.contentOffset.y).toEventually(beCloseTo(1334)) commentCell.swipeCompletion!(.comment) expect(collectionView.contentOffset.y).toEventually(beCloseTo(2001)) followCell.swipeCompletion!(.follow) expect(collectionView.contentOffset.y).toEventually(beCloseTo(2668)) } it("only proper action should move to next step") { let collectionView = collectionViewController.collectionView! let likeCell = sut.collectionView(collectionView, cellForItemAt: IndexPath(item: 0, section: 0)) as! ShotCollectionViewCell expect(collectionView.contentOffset.y).to(beCloseTo(0)) likeCell.swipeCompletion!(.bucket) likeCell.swipeCompletion!(.comment) likeCell.swipeCompletion!(.follow) expect(collectionView.contentOffset.y).to(beCloseTo(0)) } } } } }
gpl-3.0
6f36f7c468f462ffcc3f79682972c3f1
44.914634
146
0.584861
5.892019
false
false
false
false
avito-tech/Marshroute
Example/NavigationDemo/VIPER/Application/Router/ApplicationRouterIpad.swift
1
2310
import UIKit import Marshroute final class ApplicationRouterIpad: BaseDemoRouter, ApplicationRouter { // MARK: - Private properties private let authorizationModuleTrackingService: AuthorizationModuleTrackingService // MARK: - Init init(authorizationModuleTrackingService: AuthorizationModuleTrackingService, assemblyFactory: AssemblyFactory, routerSeed: RouterSeed) { self.authorizationModuleTrackingService = authorizationModuleTrackingService super.init(assemblyFactory: assemblyFactory, routerSeed: routerSeed) } // MARK: - ApplicationRouter func authorizationStatus(_ completion: ((_ isPresented: Bool) -> ())) { let isAuthorizationModulePresented = authorizationModuleTrackingService.isAuthorizationModulePresented() completion(isAuthorizationModulePresented) } func showAuthorization(_ prepareForTransition: ((_ moduleInput: AuthorizationModuleInput) -> ())) { let animator = ModalNavigationTransitionsAnimator() animator.targetModalPresentationStyle = .formSheet presentModalNavigationControllerWithRootViewControllerDerivedFrom( { routerSeed -> UIViewController in let authorizationAssembly = assemblyFactory.authorizationAssembly() let (viewController, moduleInput) = authorizationAssembly.module( routerSeed: routerSeed ) prepareForTransition(moduleInput) return viewController }, animator: animator) } func showCategories() { pushViewControllerDerivedFrom { routerSeed -> UIViewController in let subcategoriesAssembly = assemblyFactory.categoriesAssembly() let viewController = subcategoriesAssembly.ipadModule( routerSeed: routerSeed ) return viewController } } func showRecursion() { pushViewControllerDerivedFrom { routerSeed -> UIViewController in let recursionAssembly = assemblyFactory.recursionAssembly() let viewController = recursionAssembly.ipadModule(routerSeed: routerSeed) return viewController } } }
mit
2db874fb85e9cec69ea81143fc2536c5
36.258065
112
0.669264
6.957831
false
false
false
false
anama118118/BezierCurve
BezierCurve/BezierCurve/Views/CoolView.swift
1
2041
// // CoolView.swift // BezierCurve // // Created by Ana Ma on 3/28/17. // Copyright © 2017 C4Q. All rights reserved. // import UIKit //Tools to get point //http://www.victoriakirst.com/beziertool/ //How to make a star with Bezier Star //http://stackoverflow.com/questions/38343458/how-to-make-star-shape-with-bezier-path-in-ios @IBDesignable class CoolStarView: UIView { @IBInspectable var fillColor: UIColor = UIColor.gray @IBInspectable var points: Int = 5 override func draw(_ rect: CGRect) { let starPath = starPathInRect(rect: rect) UIColor.gray.setStroke() starPath.stroke() fillColor.setFill() starPath.fill() } func starPathInRect(rect: CGRect) -> UIBezierPath { let path = UIBezierPath() let starExtrusion:CGFloat = 30.0 let center = CGPoint(x: rect.width / 2.0, y: rect.height / 2.0) let pointsOnStar = points var angle:CGFloat = -CGFloat(M_PI / 2.0) let angleIncrement = CGFloat(M_PI * 2.0 / Double(pointsOnStar)) let radius = rect.width / 2.0 var firstPoint = true for _ in 1...pointsOnStar { let point = pointFrom(angle: angle, radius: radius, offset: center) let nextPoint = pointFrom(angle: angle + angleIncrement, radius: radius, offset: center) let midPoint = pointFrom(angle: angle + angleIncrement / 2.0, radius: starExtrusion, offset: center) if firstPoint { firstPoint = false path.move(to: point) } path.addLine(to: midPoint) path.addLine(to: nextPoint) angle += angleIncrement } path.close() return path } func pointFrom(angle: CGFloat, radius: CGFloat, offset: CGPoint) -> CGPoint { return CGPoint(x: radius * cos(angle) + offset.x, y: radius * sin(angle) + offset.y) } }
mit
67421c005a41ffc4689c50a5f286d48c
29
112
0.57598
4.112903
false
false
false
false
marc-medley/004.65.sql-sqlite-in-5-minutes
SQLiteIn5MinutesWithSwift/SQLiteIn5MinutesWithSwift/ClosureBasic.swift
1
2553
// // ClosureBasic.swift // SQLiteIn5MinutesWithSwift // // Created by marc on 2016.06.04. // Copyright © 2016 --marc. All rights reserved. // import Foundation /** - parameter argc: C-style argument count - parameter argv: C-style argument values array - returns: integer result code. 0 for success. */ func sqlQueryClosureBasic(argc: Int, argv: [String]) -> Int { var db: sqlite3? = nil var zErrMsg:CCharPointer? = nil var rc: Int32 = 0 if argc != 3 { print(String(format: "ERROR: Usage: %s DATABASE SQL-STATEMENT", argv[0])) return 1 } rc = sqlite3_open(argv[1], &db) if rc != 0 { print("ERROR: sqlite3_open " + String(cString: sqlite3_errmsg(db)) ) sqlite3_close(db) return 1 } rc = sqlite3_exec( db, // opened database: sqlite3* … OpaquePointer argv[2], // SQL statement: const char *sql … UnsafePointer<CChar> … UnsafePointer<Int8> { // callback, non-capturing closure: int (*callback)(void*,int,char**,char**) resultVoidPointer, // void* columnCount, // int values, // char** … UnsafeMutablePointer< UnsafeMutablePointer<CChar>? >? names // char** … UnsafeMutablePointer< UnsafeMutablePointer<CChar>? >? in // resultVoidPointer is unused if let names = names, let values = values { for i in 0 ..< Int(columnCount) { guard let columnValue = values[i], let columnValueStr = String(validatingUTF8: columnValue) else { print("No UTF8 column value") continue } guard let columnName = names[i], let columnNameStr = String(validatingUTF8: columnName) else { print("No column name") continue } print("\(columnNameStr) = \(columnValueStr)") } } return 0 // -> Int32 }, nil, // param, 1st argument to callback: void* … UnsafeMutableRawPointer? &zErrMsg // Error msg written here: char **errmsg ) if rc != SQLITE_OK { let errorMsg = String(cString: zErrMsg!) print("ERROR: sqlite3_exec \(errorMsg)") sqlite3_free(zErrMsg) } sqlite3_close(db) return 0 }
unlicense
c06740e3cf2dfecac376b2fdbbf346f8
32.866667
96
0.519291
4.495575
false
false
false
false
slavapestov/swift
test/Prototypes/CollectionsMoveIndices.swift
1
39286
// RUN: %target-run-simple-swift // REQUIRES: executable_test // https://bugs.swift.org/browse/SR-122 // // Summary // ======= // // This file implements a prototype for a collection model where // indices can't move themselves forward or backward. Instead, the // corresponding collection moves the indices. // // Problem // ======= // // Swift standard library defines three kinds of collection indices: // forward, bidirectional and random access. A collection uses one of // these indices based on the capabilities of the backing data // structure. For example, a singly-linked list can only have forward // indices, a tree with parent pointers has bidirectional indices, and // Array and Deque has random access indices. // // It turned out that in practice, every one of the non-random-access // indices holds a reference to the collection it traverses, or to // some part of it, to implement `.successor()` and `.predecessor()`. // This introduces extra complexity in implementations and presumably // translates into less-efficient code that does reference counting on // indices. Indices referencing collections also conflicts with COW // -- a live index makes a collection non-uniquely referenced, causing // unnecessary copies (see `Dictionary` and `Set`, that have to use a // double-indirection trick to avoid these extra copies). We should // consider other schemes that don't require these tricks. // // Eliminating all reference-countable members from indices implies that // indices need to essentially encode the path to the element within the data // structure. Since one is free to choose the encoding, we think that it // should be possible to choose it in such a way that indices are cheaply // comparable. // // In this new model, indices don't have any method or property // requirements (these APIs were moved to Collection), so index // protocols were eliminated. Instead, we are introducing // `CollectionType`, `BidirectionalCollectionType` and // `RandomAccessCollectionType`. These protocols naturally compose // with `MutableCollectionType` and `RangeReplaceableCollectionType`: // // protocol SequenceType {} // protocol CollectionType : SequenceType {} // // protocol MutableCollectionType : CollectionType {} // protocol RangeReplaceableCollectionType : CollectionType {} // // protocol BidirectionalCollectionType : CollectionType {} // protocol RandomAccessCollectionType : BidirectionalCollectionType {} // // Proposed Solution // ================= // // Change indices so that they can't be moved forward or backward by // themselves (`i.successor()` is not allowed). Then indices can // store the minimal amount of information only about the element // position in the collection. Usually index can be represented as // one or a couple of integers that encode the "path" in the // data structure from the root to the element. In this // representation, only a collection can move indices (e.g., // `c.next(i)`). // // Advantages: // * indices don't need to keep a reference to the collection. // - indices are simpler to implement. // - indices are not reference-countable, and thus cheaper to // handle. // * the hierarchy of index protocols is removed, and instead we add // protocols for forward, bidirectional and random-access // collections. This is closer to how people generally talk about // collections. Writing a generic constraint for bidirectional and // random-access collections becomes simpler. // // Disadvantages: // * a value-typed linked list can't conform to CollectionType. A // reference-typed one can. // Issues // ====== // // 1. Conflicting requirements for `MyRange`: // // * range bounds need to be comparable and incrementable, in order for // `MyRange` to conform to `MyForwardCollectionType`, // // * we frequently want to use `MyRange` as a "transport" data type, just // to carry a pair of indices around. Indices are neither comparable nor // incrementable. // // Possible solution: conditional conformance for `MyRange` to // `MyForwardCollectionType` when the bounds are comparable and // incrementable (when the bounds conform to // `MyRandomAccessCollectionType`?). // // 2. We can't specify constraints on associated types. This forces many // trivial algorithms to specify useless constraints. infix operator ...* { associativity none precedence 135 } infix operator ..<* { associativity none precedence 135 } public protocol MyGeneratorType { associatedtype Element mutating func next() -> Element? } public protocol MySequenceType { associatedtype Generator : MyGeneratorType associatedtype SubSequence /* : MySequenceType */ func generate() -> Generator @warn_unused_result func map<T>( @noescape transform: (Generator.Element) throws -> T ) rethrows -> [T] @warn_unused_result func dropFirst(n: Int) -> SubSequence @warn_unused_result func dropLast(n: Int) -> SubSequence @warn_unused_result func prefix(maxLength: Int) -> SubSequence @warn_unused_result func suffix(maxLength: Int) -> SubSequence } extension MySequenceType { @warn_unused_result public func map<T>( @noescape transform: (Generator.Element) throws -> T ) rethrows -> [T] { var result: [T] = [] for element in OldSequence(self) { result.append(try transform(element)) } return result } @warn_unused_result public func dropFirst(n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") fatalError("implement") } @warn_unused_result public func dropLast(n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") fatalError("implement") } @warn_unused_result public func prefix(maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a prefix of negative length from a collection") fatalError("implement") } @warn_unused_result public func suffix(maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a collection") fatalError("implement") } } //------------------------------------------------------------------------ // Bridge between the old world and the new world struct OldSequence<S : MySequenceType> : SequenceType { let _base: S init(_ base: S) { self._base = base } func generate() -> OldGenerator<S.Generator> { return OldGenerator(_base.generate()) } } struct OldGenerator<G : MyGeneratorType> : GeneratorType { var _base: G init(_ base: G) { self._base = base } mutating func next() -> G.Element? { return _base.next() } } // End of the bridge //------------------------------------------------------------------------ public protocol MyIndexableType { associatedtype Index : Comparable associatedtype _Element associatedtype UnownedHandle var startIndex: Index { get } var endIndex: Index { get } subscript(i: Index) -> _Element { get } init(from handle: UnownedHandle) var unownedHandle: UnownedHandle { get } @warn_unused_result func next(i: Index) -> Index func _nextInPlace(inout i: Index) func _failEarlyRangeCheck(index: Index, bounds: MyRange<Index>) func _failEarlyRangeCheck2( rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index) } extension MyIndexableType { @inline(__always) public func _nextInPlace(inout i: Index) { i = next(i) } } public protocol MyForwardCollectionType : MySequenceType, MyIndexableType { associatedtype Generator = DefaultGenerator<Self> associatedtype Index : Comparable associatedtype SubSequence : MySequenceType /* : MyForwardCollectionType */ = MySlice<Self> associatedtype UnownedHandle = Self // DefaultUnownedForwardCollection<Self> associatedtype IndexRange : MyIndexRangeType, MySequenceType, MyIndexableType /* : MyForwardCollectionType */ // FIXME: where IndexRange.Generator.Element == Index // FIXME: where IndexRange.Index == Index = DefaultForwardIndexRange<Self> associatedtype IndexDistance : SignedIntegerType = Int var startIndex: Index { get } var endIndex: Index { get } subscript(i: Index) -> Generator.Element { get } subscript(bounds: MyRange<Index>) -> SubSequence { get } init(from handle: UnownedHandle) var unownedHandle: UnownedHandle { get } @warn_unused_result func next(i: Index) -> Index @warn_unused_result func advance(i: Index, by: IndexDistance) -> Index @warn_unused_result func advance(i: Index, by: IndexDistance, limit: Index) -> Index @warn_unused_result func distanceFrom(start: Index, to: Index) -> IndexDistance func _failEarlyRangeCheck(index: Index, bounds: MyRange<Index>) func _failEarlyRangeCheck2( rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index) var indices: IndexRange { get } @warn_unused_result func _customIndexOfEquatableElement(element: Generator.Element) -> Index?? var first: Generator.Element? { get } var isEmpty: Bool { get } var count: IndexDistance { get } } extension MyForwardCollectionType { /// Do not use this method directly; call advancedBy(n) instead. @inline(__always) @warn_unused_result internal func _advanceForward(i: Index, by n: IndexDistance) -> Index { _precondition(n >= 0, "Only BidirectionalIndexType can be advanced by a negative amount") var i = i for var offset: IndexDistance = 0; offset != n; offset = offset + 1 { _nextInPlace(&i) } return i } /// Do not use this method directly; call advancedBy(n, limit) instead. @inline(__always) @warn_unused_result internal func _advanceForward( i: Index, by n: IndexDistance, limit: Index ) -> Index { _precondition(n >= 0, "Only BidirectionalIndexType can be advanced by a negative amount") var i = i for var offset: IndexDistance = 0; offset != n && i != limit; offset = offset + 1 { _nextInPlace(&i) } return i } @warn_unused_result public func advance(i: Index, by n: IndexDistance) -> Index { return self._advanceForward(i, by: n) } @warn_unused_result public func advance(i: Index, by n: IndexDistance, limit: Index) -> Index { return self._advanceForward(i, by: n, limit: limit) } @warn_unused_result public func distanceFrom(start: Index, to end: Index) -> IndexDistance { var start = start var count: IndexDistance = 0 while start != end { count = count + 1 _nextInPlace(&start) } return count } public func _failEarlyRangeCheck( index: Index, bounds: MyRange<Index>) { // Can't perform range checks in O(1) on forward indices. } public func _failEarlyRangeCheck2( rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index ) { // Can't perform range checks in O(1) on forward indices. } @warn_unused_result public func _customIndexOfEquatableElement( element: Generator.Element ) -> Index?? { return nil } public var first: Generator.Element? { return isEmpty ? nil : self[startIndex] } public var isEmpty: Bool { return startIndex == endIndex } public var count: IndexDistance { return distanceFrom(startIndex, to: endIndex) } @warn_unused_result public func dropFirst(n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") /* let start = advance(startIndex, by: numericCast(n), limit: endIndex) return self[start..<endIndex] */ fatalError() } @warn_unused_result public func dropLast(n: Int) -> SubSequence { _precondition(n >= 0, "Can't drop a negative number of elements from a collection") let amount = max(0, numericCast(count) - n) let end = advance(startIndex, by: numericCast(amount), limit: endIndex) return self[startIndex..<*end] } @warn_unused_result public func prefix(maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a prefix of negative length from a collection") let end = advance(startIndex, by: numericCast(maxLength), limit: endIndex) return self[startIndex..<*end] } @warn_unused_result public func suffix(maxLength: Int) -> SubSequence { _precondition(maxLength >= 0, "Can't take a suffix of negative length from a collection") let amount = max(0, numericCast(count) - maxLength) let start = advance(startIndex, by: numericCast(amount), limit: endIndex) return self[start..<*endIndex] } } extension MyForwardCollectionType where Generator == DefaultGenerator<Self> { public func generate() -> DefaultGenerator<Self> { return DefaultGenerator(self) } } extension MyForwardCollectionType where UnownedHandle == Self // where UnownedHandle == DefaultUnownedForwardCollection<Self> { public init(from handle: UnownedHandle) { self = handle } public var unownedHandle: UnownedHandle { return self } } extension MyForwardCollectionType where SubSequence == MySlice<Self> { public subscript(bounds: MyRange<Index>) -> SubSequence { return MySlice(base: self, start: bounds.startIndex, end: bounds.endIndex) } } extension MyForwardCollectionType where IndexRange == DefaultForwardIndexRange<Self> { public var indices: IndexRange { return DefaultForwardIndexRange( collection: self, startIndex: startIndex, endIndex: endIndex) } } extension MyForwardCollectionType where Index : MyStrideable, Index.Distance == IndexDistance { @warn_unused_result public func next(i: Index) -> Index { return advance(i, by: 1) } @warn_unused_result public func advance(i: Index, by n: IndexDistance) -> Index { _precondition(n >= 0, "Can't advance an Index of MyForwardCollectionType by a negative amount") return i.advancedBy(n) } @warn_unused_result public func advance(i: Index, by n: IndexDistance, limit: Index) -> Index { _precondition(n >= 0, "Can't advance an Index of MyForwardCollectionType by a negative amount") let d = i.distanceTo(limit) _precondition(d >= 0, "The specified limit is behind the index") if d <= n { return limit } return i.advancedBy(n) } } extension MyForwardCollectionType where Generator.Element : Equatable, IndexRange.Generator.Element == Index // FIXME { public func indexOf(element: Generator.Element) -> Index? { if let result = _customIndexOfEquatableElement(element) { return result } for i in OldSequence(self.indices) { if self[i] == element { return i } } return nil } public func indexOf_optimized(element: Generator.Element) -> Index? { if let result = _customIndexOfEquatableElement(element) { return result } var i = startIndex while i != endIndex { if self[i] == element { return i } _nextInPlace(&i) } return nil } } extension MyForwardCollectionType where SubSequence == Self { @warn_unused_result public mutating func popFirst() -> Generator.Element? { guard !isEmpty else { return nil } let element = first! self = self[MyRange(start: self.next(startIndex), end: endIndex)] return element } } public protocol MyBidirectionalCollectionType : MyForwardCollectionType { @warn_unused_result func previous(i: Index) -> Index func _previousInPlace(inout i: Index) } extension MyBidirectionalCollectionType { @inline(__always) public func _previousInPlace(inout i: Index) { i = previous(i) } @warn_unused_result public func advance(i: Index, by n: IndexDistance) -> Index { if n >= 0 { return _advanceForward(i, by: n) } var i = i for var offset: IndexDistance = n; offset != 0; offset = offset + 1 { _previousInPlace(&i) } return i } @warn_unused_result public func advance(i: Index, by n: IndexDistance, limit: Index) -> Index { if n >= 0 { return _advanceForward(i, by: n, limit: limit) } var i = i for var offset: IndexDistance = n; offset != 0 && i != limit; offset = offset + 1 { _previousInPlace(&i) } return i } } extension MyBidirectionalCollectionType where Index : MyStrideable, Index.Distance == IndexDistance { @warn_unused_result public func previous(i: Index) -> Index { return advance(i, by: -1) } @warn_unused_result public func advance(i: Index, by n: IndexDistance) -> Index { return i.advancedBy(n) } @warn_unused_result public func advance(i: Index, by n: IndexDistance, limit: Index) -> Index { let d = i.distanceTo(limit) if d == 0 || (d > 0 ? d <= n : d >= n) { return limit } return i.advancedBy(n) } } public protocol MyRandomAccessCollectionType : MyBidirectionalCollectionType { associatedtype Index : MyStrideable // FIXME: where Index.Distance == IndexDistance } public struct DefaultUnownedForwardCollection<Collection : MyForwardCollectionType> { internal let _collection: Collection public init(_ collection: Collection) { self._collection = collection } } public struct DefaultForwardIndexRange<Collection : MyIndexableType /* MyForwardCollectionType */> : MyForwardCollectionType, MyIndexRangeType { internal let _unownedCollection: Collection.UnownedHandle public let startIndex: Collection.Index public let endIndex: Collection.Index // FIXME: remove explicit typealiases. public typealias _Element = Collection.Index public typealias Generator = DefaultForwardIndexRangeGenerator<Collection> public typealias Index = Collection.Index public typealias SubSequence = DefaultForwardIndexRange<Collection> public typealias UnownedHandle = DefaultForwardIndexRange<Collection> internal init( _unownedCollection: Collection.UnownedHandle, startIndex: Collection.Index, endIndex: Collection.Index ) { self._unownedCollection = _unownedCollection self.startIndex = startIndex self.endIndex = endIndex } public init( collection: Collection, startIndex: Collection.Index, endIndex: Collection.Index ) { self._unownedCollection = collection.unownedHandle self.startIndex = startIndex self.endIndex = endIndex } // FIXME: use DefaultGenerator when the type checker bug is fixed. public func generate() -> Generator { return DefaultForwardIndexRangeGenerator( Collection(from: _unownedCollection), start: startIndex, end: endIndex) } public subscript(i: Collection.Index) -> Collection.Index { return i } public subscript(bounds: MyRange<Index>) -> DefaultForwardIndexRange<Collection> { fatalError("implement") } public init(from handle: UnownedHandle) { self = handle } public var unownedHandle: UnownedHandle { return self } @warn_unused_result public func next(i: Index) -> Index { return Collection(from: _unownedCollection).next(i) } } // FIXME: use DefaultGenerator when the type checker bug is fixed. public struct DefaultForwardIndexRangeGenerator<Collection : MyIndexableType /* MyForwardCollectionType */> : MyGeneratorType { internal let _collection: Collection internal var _i: Collection.Index internal var _endIndex: Collection.Index public init( _ collection: Collection, start: Collection.Index, end: Collection.Index ) { self._collection = collection self._i = collection.startIndex self._endIndex = end } public mutating func next() -> Collection.Index? { if _i == _endIndex { return nil } let result = _i _i = _collection.next(_i) return result } } public struct MyRange<Index : Comparable> : MyIndexRangeType { public let startIndex: Index public let endIndex: Index public init(start: Index, end: Index) { _precondition(start <= end, "Can't form a backwards MyRange") self.startIndex = start self.endIndex = end } public subscript(i: Index) -> Index { return i } } public func ..<* <Index : Comparable>(lhs: Index, rhs: Index) -> MyRange<Index> { return MyRange(start: lhs, end: rhs) } // FIXME: replace this type with a conditional conformance on MyRange. public struct MyIterableRange<Index : MyStrideable> : MyBidirectionalCollectionType { public let startIndex: Index public let endIndex: Index public init(start: Index, end: Index) { _precondition(start <= end, "Can't form a backwards MyIterableRange") self.startIndex = start self.endIndex = end } @warn_unused_result public func next(i: Index) -> Index { let result = i.advancedBy(1) _precondition(startIndex <= result, "can't advance past endIndex") return i.advancedBy(1) } @warn_unused_result public func previous(i: Index) -> Index { let result = i.advancedBy(-1) _precondition(result <= endIndex, "can't advance before startIndex") return result } public subscript(i: Index) -> Index { return i } } public func ..<* <Index : MyStrideable>(lhs: Index, rhs: Index) -> MyIterableRange<Index> { return MyIterableRange(start: lhs, end: rhs) } // FIXME: in order for all this to be usable, we need to unify MyRange and // MyHalfOpenInterval. We can do that by constraining the Bound to comparable, // and providing a conditional conformance to collection when the Bound is // strideable. public struct MyHalfOpenInterval<Bound : Comparable> { public let start: Bound public let end: Bound } public struct MySlice<Collection : MyIndexableType /* : MyForwardCollectionType */> : MyForwardCollectionType // : MyIndexableType { internal let _base: Collection public let startIndex: Collection.Index public let endIndex: Collection.Index // FIXME: remove explicit typealiases. public typealias _Element = Collection._Element public typealias Index = Collection.Index public init( base: Collection, start: Collection.Index, end: Collection.Index) { self._base = base self.startIndex = start self.endIndex = end } public subscript(i: Collection.Index) -> Collection._Element { _base._failEarlyRangeCheck( i, bounds: MyRange(start: startIndex, end: endIndex)) return _base[i] } public typealias Generator = DefaultGenerator<MySlice> public func generate() -> Generator { return DefaultGenerator(self) } public typealias SubSequence = MySlice public subscript(bounds: MyRange<Index>) -> SubSequence { _base._failEarlyRangeCheck2( bounds.startIndex, rangeEnd: bounds.endIndex, boundsStart: startIndex, boundsEnd: endIndex) return MySlice(base: _base, start: bounds.startIndex, end: bounds.endIndex) } @warn_unused_result public func next(i: Index) -> Index { return _base.next(i) } public func _failEarlyRangeCheck(index: Index, bounds: MyRange<Index>) { fatalError("FIXME") } public func _failEarlyRangeCheck2( rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index) { fatalError("FIXME") } // FIXME: use Collection.UnownedHandle instead. public typealias UnownedHandle = MySlice public var unownedHandle: UnownedHandle { return self } public init(from handle: UnownedHandle) { self = handle } // FIXME: use DefaultForwardIndexRange instead. public typealias IndexRange = MySliceIndexRange<MySlice> public var indices: IndexRange { return MySliceIndexRange( collection: self, startIndex: startIndex, endIndex: endIndex) } } public struct MySliceIndexRange<Collection : MyIndexableType /* MyForwardCollectionType */> //: MyForwardCollectionType : MyIndexRangeType, MySequenceType, MyIndexableType { internal let _unownedCollection: Collection.UnownedHandle public let startIndex: Collection.Index public let endIndex: Collection.Index // FIXME: remove explicit typealiases. public typealias _Element = Collection.Index public typealias Generator = DefaultForwardIndexRangeGenerator<Collection> public typealias Index = Collection.Index public typealias SubSequence = MySliceIndexRange<Collection> public typealias UnownedHandle = MySliceIndexRange<Collection> internal init( _unownedCollection: Collection.UnownedHandle, startIndex: Collection.Index, endIndex: Collection.Index ) { self._unownedCollection = _unownedCollection self.startIndex = startIndex self.endIndex = endIndex } public init( collection: Collection, startIndex: Collection.Index, endIndex: Collection.Index ) { self._unownedCollection = collection.unownedHandle self.startIndex = startIndex self.endIndex = endIndex } public func generate() -> Generator { return DefaultForwardIndexRangeGenerator( Collection(from: _unownedCollection), start: startIndex, end: endIndex) } public subscript(i: Collection.Index) -> Collection.Index { return i } public subscript(bounds: MyRange<Index>) -> MySliceIndexRange<Collection> { fatalError("implement") } public init(from handle: UnownedHandle) { self = handle } public var unownedHandle: UnownedHandle { return self } @warn_unused_result public func next(i: Index) -> Index { return Collection(from: _unownedCollection).next(i) } public func _failEarlyRangeCheck(index: Index, bounds: MyRange<Index>) { } public func _failEarlyRangeCheck2( rangeStart: Index, rangeEnd: Index, boundsStart: Index, boundsEnd: Index) { } public typealias IndexRange = MySliceIndexRange public var indices: IndexRange { return self } } public struct MyMutableSlice<Collection : MyMutableCollectionType> {} public struct MyAnyGenerator<Element> : MyGeneratorType { public init<G : MyGeneratorType>(_ g: G) { fatalError("FIXME") } public mutating func next() -> Element? { fatalError("FIXME") } } public struct MyAnySequence<Element> : MySequenceType { public typealias SubSequence = MyAnySequence<Element> public init<S : MySequenceType>(_ s: S) { fatalError("FIXME") } public func generate() -> MyAnyGenerator<Element> { fatalError("FIXME") } } public struct DefaultGenerator<Collection : MyIndexableType> : MyGeneratorType { internal let _collection: Collection internal var _i: Collection.Index public init(_ collection: Collection) { self._collection = collection self._i = collection.startIndex } public mutating func next() -> Collection._Element? { if _i == _collection.endIndex { return nil } let result = _collection[_i] _i = _collection.next(_i) return result } } public protocol MyMutableCollectionType : MyForwardCollectionType { associatedtype SubSequence : MyForwardCollectionType = MyMutableSlice<Self> subscript(i: Index) -> Generator.Element { get set } } public protocol MyIndexRangeType : Equatable { associatedtype Index : Equatable var startIndex: Index { get } var endIndex: Index { get } } public func == <IR : MyIndexRangeType> (lhs: IR, rhs: IR) -> Bool { return lhs.startIndex == rhs.startIndex && lhs.endIndex == rhs.endIndex } /* public protocol MyRandomAccessIndexType : MyBidirectionalIndexType, MyStrideable, _RandomAccessAmbiguity { @warn_unused_result func distanceTo(other: Self) -> Distance @warn_unused_result func advancedBy(n: Distance) -> Self @warn_unused_result func advancedBy(n: Distance, limit: Self) -> Self } extension MyRandomAccessIndexType { public func _failEarlyRangeCheck(index: Self, bounds: MyRange<Self>) { _precondition( bounds.startIndex <= index, "index is out of bounds: index designates a position before bounds.startIndex") _precondition( index < bounds.endIndex, "index is out of bounds: index designates the bounds.endIndex position or a position after it") } public func _failEarlyRangeCheck2( rangeStart: Self, rangeEnd: Self, boundsStart: Self, boundsEnd: Self ) { let range = MyRange(startIndex: rangeStart, endIndex: rangeEnd) let bounds = MyRange(startIndex: boundsStart, endIndex: boundsEnd) _precondition( bounds.startIndex <= range.startIndex, "range.startIndex is out of bounds: index designates a position before bounds.startIndex") _precondition( bounds.startIndex <= range.endIndex, "range.endIndex is out of bounds: index designates a position before bounds.startIndex") _precondition( range.startIndex <= bounds.endIndex, "range.startIndex is out of bounds: index designates a position after bounds.endIndex") _precondition( range.endIndex <= bounds.endIndex, "range.startIndex is out of bounds: index designates a position after bounds.endIndex") } @transparent @warn_unused_result public func advancedBy(n: Distance, limit: Self) -> Self { let d = self.distanceTo(limit) if d == 0 || (d > 0 ? d <= n : d >= n) { return limit } return self.advancedBy(n) } } */ //------------------------------------------------------------------------ // Bubble sort extension MyMutableCollectionType where IndexRange.Generator.Element == Index, IndexRange.Index == Index { public mutating func bubbleSortInPlace( @noescape isOrderedBefore: (Generator.Element, Generator.Element) -> Bool ) { if isEmpty { return } if next(startIndex) == endIndex { return } while true { var swapped = false for i in OldSequence(indices) { if i == endIndex { break } let ni = next(i) if ni == endIndex { break } if isOrderedBefore(self[ni], self[i]) { swap(&self[i], &self[ni]) swapped = true } } if !swapped { break } } } } extension MyMutableCollectionType where Generator.Element : Comparable, IndexRange.Generator.Element == Index, IndexRange.Index == Index { public mutating func bubbleSortInPlace() { bubbleSortInPlace { $0 < $1 } } } //------------------------------------------------------------------------ // Bubble sort extension MyRandomAccessCollectionType where IndexRange.Generator.Element == Index, IndexRange.Index == Index { public func lowerBoundOf( element: Generator.Element, @noescape isOrderedBefore: (Generator.Element, Generator.Element) -> Bool ) -> Index { var low = startIndex var subrangeCount = count while subrangeCount != 0 { let midOffset = subrangeCount / 2 let mid = advance(low, by: midOffset) if isOrderedBefore(self[mid], element) { low = next(mid) subrangeCount -= midOffset + 1 } else { subrangeCount = midOffset } } return low } } extension MyRandomAccessCollectionType where Generator.Element : Comparable, IndexRange.Generator.Element == Index, IndexRange.Index == Index { public func lowerBoundOf(element: Generator.Element) -> Index { return lowerBoundOf(element) { $0 < $1 } } } //------------ public protocol MyStrideable : Comparable { associatedtype Distance : SignedNumberType @warn_unused_result func distanceTo(other: Self) -> Distance @warn_unused_result func advancedBy(n: Distance) -> Self } extension Int : MyStrideable {} //------------------------------------------------------------------------ // Array public struct MyArray<Element> : MyForwardCollectionType, MyRandomAccessCollectionType, MyMutableCollectionType { internal var _elements: [Element] = [] init() {} init(_ elements: [Element]) { self._elements = elements } public var startIndex: Int { return _elements.startIndex } public var endIndex: Int { return _elements.endIndex } public subscript(i: Int) -> Element { get { return _elements[i] } set { _elements[i] = newValue } } } //------------------------------------------------------------------------ // Simplest Forward Collection public struct MySimplestForwardCollection<Element> : MyForwardCollectionType { internal let _elements: [Element] public init(_ elements: [Element]) { self._elements = elements } public var startIndex: MySimplestForwardCollectionIndex { return MySimplestForwardCollectionIndex(_elements.startIndex) } public var endIndex: MySimplestForwardCollectionIndex { return MySimplestForwardCollectionIndex(_elements.endIndex) } @warn_unused_result public func next(i: MySimplestForwardCollectionIndex) -> MySimplestForwardCollectionIndex { return MySimplestForwardCollectionIndex(i._index + 1) } public subscript(i: MySimplestForwardCollectionIndex) -> Element { return _elements[i._index] } } public struct MySimplestForwardCollectionIndex : Comparable { internal let _index: Int internal init(_ index: Int) { self._index = index } } public func == ( lhs: MySimplestForwardCollectionIndex, rhs: MySimplestForwardCollectionIndex ) -> Bool { return lhs._index == rhs._index } public func < ( lhs: MySimplestForwardCollectionIndex, rhs: MySimplestForwardCollectionIndex ) -> Bool { return lhs._index < rhs._index } //------------------------------------------------------------------------ // Simplest Bidirectional Collection public struct MySimplestBidirectionalCollection<Element> : MyBidirectionalCollectionType { internal let _elements: [Element] public init(_ elements: [Element]) { self._elements = elements } public var startIndex: MySimplestBidirectionalCollectionIndex { return MySimplestBidirectionalCollectionIndex(_elements.startIndex) } public var endIndex: MySimplestBidirectionalCollectionIndex { return MySimplestBidirectionalCollectionIndex(_elements.endIndex) } @warn_unused_result public func next(i: MySimplestBidirectionalCollectionIndex) -> MySimplestBidirectionalCollectionIndex { return MySimplestBidirectionalCollectionIndex(i._index + 1) } @warn_unused_result public func previous(i: MySimplestBidirectionalCollectionIndex) -> MySimplestBidirectionalCollectionIndex { return MySimplestBidirectionalCollectionIndex(i._index - 1) } public subscript(i: MySimplestBidirectionalCollectionIndex) -> Element { return _elements[i._index] } } public struct MySimplestBidirectionalCollectionIndex : Comparable { internal let _index: Int internal init(_ index: Int) { self._index = index } } public func == ( lhs: MySimplestBidirectionalCollectionIndex, rhs: MySimplestBidirectionalCollectionIndex ) -> Bool { return lhs._index == rhs._index } public func < ( lhs: MySimplestBidirectionalCollectionIndex, rhs: MySimplestBidirectionalCollectionIndex ) -> Bool { return lhs._index < rhs._index } //------------------------------------------------------------------------ // Simplest Bidirectional Collection public struct MySimplestRandomAccessCollection<Element> : MyRandomAccessCollectionType { internal let _elements: [Element] public init(_ elements: [Element]) { self._elements = elements } // FIXME: 'typealias Index' should be inferred. public typealias Index = MySimplestRandomAccessCollectionIndex public var startIndex: MySimplestRandomAccessCollectionIndex { return MySimplestRandomAccessCollectionIndex(_elements.startIndex) } public var endIndex: MySimplestRandomAccessCollectionIndex { return MySimplestRandomAccessCollectionIndex(_elements.endIndex) } public subscript(i: MySimplestRandomAccessCollectionIndex) -> Element { return _elements[i._index] } } public struct MySimplestRandomAccessCollectionIndex : MyStrideable { internal let _index: Int internal init(_ index: Int) { self._index = index } @warn_unused_result public func distanceTo(other: MySimplestRandomAccessCollectionIndex) -> Int { return other._index - _index } @warn_unused_result public func advancedBy(n: Int) -> MySimplestRandomAccessCollectionIndex { return MySimplestRandomAccessCollectionIndex(_index + n) } } public func == ( lhs: MySimplestRandomAccessCollectionIndex, rhs: MySimplestRandomAccessCollectionIndex ) -> Bool { return lhs._index == rhs._index } public func < ( lhs: MySimplestRandomAccessCollectionIndex, rhs: MySimplestRandomAccessCollectionIndex ) -> Bool { return lhs._index < rhs._index } //------------------------------------------------------------------------ // Simplest Strideable public struct MySimplestStrideable : MyStrideable { internal let _value: Int internal init(_ value: Int) { self._value = value } @warn_unused_result public func distanceTo(other: MySimplestStrideable) -> Int { return _value.distanceTo(other._value) } @warn_unused_result public func advancedBy(n: Int) -> MySimplestStrideable { return MySimplestStrideable(_value.advancedBy(n)) } } public func == ( lhs: MySimplestStrideable, rhs: MySimplestStrideable ) -> Bool { return lhs._value == rhs._value } public func < ( lhs: MySimplestStrideable, rhs: MySimplestStrideable ) -> Bool { return lhs._value < rhs._value } //------------------------------------------------------------------------ // FIXME: how does AnyCollection look like in the new scheme? import StdlibUnittest // Also import modules which are used by StdlibUnittest internally. This // workaround is needed to link all required libraries in case we compile // StdlibUnittest with -sil-serialize-all. import SwiftPrivate #if _runtime(_ObjC) import ObjectiveC #endif var NewCollection = TestSuite("NewCollection") NewCollection.test("indexOf") { expectEqual(1, MyArray([1,2,3]).indexOf(2)) expectEmpty(MyArray([1,2,3]).indexOf(42)) } NewCollection.test("bubbleSortInPlace") { var a = MyArray([4,3,2,1]) a.bubbleSortInPlace() expectEqual([1,2,3,4], a._elements) } NewCollection.test("lowerBoundOf/empty") { var a = MyArray<Int>([]) expectEqual(0, a.lowerBoundOf(3)) } NewCollection.test("lowerBoundOf/one") { var a = MyArray<Int>([10]) expectEqual(0, a.lowerBoundOf(9)) expectEqual(0, a.lowerBoundOf(10)) expectEqual(1, a.lowerBoundOf(11)) } NewCollection.test("lowerBoundOf") { var a = MyArray([1,2,2,3,3,3,3,3,3,3,3,4,5,6,7]) expectEqual(3, a.lowerBoundOf(3)) } NewCollection.test("first") { expectOptionalEqual(1, MyArray([1,2,3]).first) expectEmpty(MyArray<Int>().first) } NewCollection.test("count") { expectEqual(3, MyArray([1,2,3]).count) expectEqual(0, MyArray<Int>().count) } NewCollection.test("isEmpty") { expectFalse(MyArray([1,2,3]).isEmpty) expectTrue(MyArray<Int>().isEmpty) } NewCollection.test("popFirst") { let c = MyArray([1,2,3]) var s0 = c[c.startIndex..<*c.endIndex] var s = c[MyRange(start: c.startIndex, end: c.endIndex)] expectOptionalEqual(1, s.popFirst()) expectOptionalEqual(2, s.popFirst()) expectOptionalEqual(3, s.popFirst()) expectEmpty(s.popFirst()) } NewCollection.test("RangeLiterals") { let comparable = MinimalComparableValue(0) let strideable = MySimplestStrideable(0) var comparableRange = comparable..<*comparable expectType(MyRange<MinimalComparableValue>.self, &comparableRange) var strideableRange = strideable..<*strideable expectType(MyIterableRange<MySimplestStrideable>.self, &strideableRange) for _ in OldSequence(0..<*10) {} } runAllTests()
apache-2.0
83e8710ac77cc9e4e8b3fa8146e5bfbf
27.447502
111
0.694471
4.224755
false
false
false
false
Ehrippura/firefox-ios
Sync/StorageClient.swift
2
31990
/* 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 Alamofire import Shared import Account import XCGLogger import Deferred import SwiftyJSON private let log = Logger.syncLogger // Not an error that indicates a server problem, but merely an // error that encloses a StorageResponse. open class StorageResponseError<T>: MaybeErrorType, SyncPingFailureFormattable { open let response: StorageResponse<T> open var failureReasonName: SyncPingFailureReasonName { return .httpError } public init(_ response: StorageResponse<T>) { self.response = response } open var description: String { return "Error." } } open class RequestError: MaybeErrorType, SyncPingFailureFormattable { open var failureReasonName: SyncPingFailureReasonName { return .httpError } open var description: String { return "Request error." } } open class BadRequestError<T>: StorageResponseError<T> { open let request: URLRequest? public init(request: URLRequest?, response: StorageResponse<T>) { self.request = request super.init(response) } override open var description: String { return "Bad request." } } open class ServerError<T>: StorageResponseError<T> { override open var description: String { return "Server error." } override public init(_ response: StorageResponse<T>) { super.init(response) } } open class NotFound<T>: StorageResponseError<T> { override open var description: String { return "Not found. (\(T.self))" } override public init(_ response: StorageResponse<T>) { super.init(response) } } open class RecordParseError: MaybeErrorType, SyncPingFailureFormattable { open var description: String { return "Failed to parse record." } open var failureReasonName: SyncPingFailureReasonName { return .otherError } } open class MalformedMetaGlobalError: MaybeErrorType, SyncPingFailureFormattable { open var description: String { return "Supplied meta/global for upload did not serialize to valid JSON." } open var failureReasonName: SyncPingFailureReasonName { return .otherError } } open class RecordTooLargeError: MaybeErrorType, SyncPingFailureFormattable { open let guid: GUID open let size: ByteCount open var failureReasonName: SyncPingFailureReasonName { return .otherError } public init(size: ByteCount, guid: GUID) { self.size = size self.guid = guid } open var description: String { return "Record \(self.guid) too large: \(size) bytes." } } /** * Raised when the storage client is refusing to make a request due to a known * server backoff. * If you want to bypass this, remove the backoff from the BackoffStorage that * the storage client is using. */ open class ServerInBackoffError: MaybeErrorType, SyncPingFailureFormattable { fileprivate let until: Timestamp open var failureReasonName: SyncPingFailureReasonName { return .otherError } open var description: String { let formatter = DateFormatter() formatter.dateStyle = DateFormatter.Style.short formatter.timeStyle = DateFormatter.Style.medium let s = formatter.string(from: Date.fromTimestamp(self.until)) return "Server in backoff until \(s)." } public init(until: Timestamp) { self.until = until } } // Returns milliseconds. Handles decimals. private func optionalSecondsHeader(_ input: AnyObject?) -> Timestamp? { if input == nil { return nil } if let val = input as? String { if let timestamp = decimalSecondsStringToTimestamp(val) { return timestamp } } if let seconds: Double = input as? Double { // Oh for a BigDecimal library. return Timestamp(seconds * 1000) } if let seconds: NSNumber = input as? NSNumber { // Who knows. return seconds.uint64Value * 1000 } return nil } private func optionalIntegerHeader(_ input: AnyObject?) -> Int64? { if input == nil { return nil } if let val = input as? String { return Scanner(string: val).scanLongLong() } if let val: Double = input as? Double { // Oh for a BigDecimal library. return Int64(val) } if let val: NSNumber = input as? NSNumber { // Who knows. return val.int64Value } return nil } private func optionalUIntegerHeader(_ input: AnyObject?) -> Timestamp? { if input == nil { return nil } if let val = input as? String { return Scanner(string: val).scanUnsignedLongLong() } if let val: Double = input as? Double { // Oh for a BigDecimal library. return Timestamp(val) } if let val: NSNumber = input as? NSNumber { // Who knows. return val.uint64Value } return nil } public enum SortOption: String { case NewestFirst = "newest" case OldestFirst = "oldest" case Index = "index" } public struct ResponseMetadata { public let status: Int public let alert: String? public let nextOffset: String? public let records: UInt64? public let quotaRemaining: Int64? public let timestampMilliseconds: Timestamp // Non-optional. Server timestamp when handling request. public let lastModifiedMilliseconds: Timestamp? // Included for all success responses. Collection or record timestamp. public let backoffMilliseconds: UInt64? public let retryAfterMilliseconds: UInt64? public init(response: HTTPURLResponse) { self.init(status: response.statusCode, headers: response.allHeaderFields) } init(status: Int, headers: [AnyHashable: Any]) { self.status = status alert = headers["X-Weave-Alert"] as? String nextOffset = headers["X-Weave-Next-Offset"] as? String records = optionalUIntegerHeader(headers["X-Weave-Records"] as AnyObject?) quotaRemaining = optionalIntegerHeader(headers["X-Weave-Quota-Remaining"] as AnyObject?) timestampMilliseconds = optionalSecondsHeader(headers["X-Weave-Timestamp"] as AnyObject?) ?? 0 lastModifiedMilliseconds = optionalSecondsHeader(headers["X-Last-Modified"] as AnyObject?) backoffMilliseconds = optionalSecondsHeader(headers["X-Weave-Backoff"] as AnyObject?) ?? optionalSecondsHeader(headers["X-Backoff"] as AnyObject?) retryAfterMilliseconds = optionalSecondsHeader(headers["Retry-After"] as AnyObject?) } } public struct StorageResponse<T> { public let value: T public let metadata: ResponseMetadata init(value: T, metadata: ResponseMetadata) { self.value = value self.metadata = metadata } init(value: T, response: HTTPURLResponse) { self.value = value self.metadata = ResponseMetadata(response: response) } } public typealias BatchToken = String public typealias ByteCount = Int public struct POSTResult { public let success: [GUID] public let failed: [GUID: String] public let batchToken: BatchToken? public init(success: [GUID], failed: [GUID: String], batchToken: BatchToken? = nil) { self.success = success self.failed = failed self.batchToken = batchToken } public static func fromJSON(_ json: JSON) -> POSTResult? { if json.isError() { return nil } let batchToken = json["batch"].string if let s = json["success"].array, let f = json["failed"].dictionary { var failed = false let stringOrFail: (JSON) -> String = { $0.string ?? { failed = true; return "" }() } // That's the basic structure. Now let's transform the contents. let successGUIDs = s.map(stringOrFail) if failed { return nil } let failedGUIDs = mapValues(f, f: stringOrFail) if failed { return nil } return POSTResult(success: successGUIDs, failed: failedGUIDs, batchToken: batchToken) } return nil } } public typealias Authorizer = (URLRequest) -> URLRequest // TODO: don't be so naïve. Use a combination of uptime and wall clock time. public protocol BackoffStorage { var serverBackoffUntilLocalTimestamp: Timestamp? { get set } func clearServerBackoff() func isInBackoff(_ now: Timestamp) -> Timestamp? // Returns 'until' for convenience. } // Don't forget to batch downloads. open class Sync15StorageClient { fileprivate let authorizer: Authorizer fileprivate let serverURI: URL open static let maxRecordSizeBytes: Int = 262_140 // A shade under 256KB. open static let maxPayloadSizeBytes: Int = 1_000_000 // A shade under 1MB. open static let maxPayloadItemCount: Int = 100 // Bug 1250747 will raise this. var backoff: BackoffStorage let workQueue: DispatchQueue let resultQueue: DispatchQueue public init(token: TokenServerToken, workQueue: DispatchQueue, resultQueue: DispatchQueue, backoff: BackoffStorage) { self.workQueue = workQueue self.resultQueue = resultQueue self.backoff = backoff // This is a potentially dangerous assumption, but failable initializers up the stack are a giant pain. // We want the serverURI to *not* have a trailing slash: to efficiently wipe a user's storage, we delete // the user root (like /1.5/1234567) and not an "empty collection" (like /1.5/1234567/); the storage // server treats the first like a DROP table and the latter like a DELETE *, and the former is more // efficient than the latter. self.serverURI = URL(string: token.api_endpoint.endsWith("/") ? token.api_endpoint.substring(to: token.api_endpoint.index(before: token.api_endpoint.endIndex)) : token.api_endpoint)! self.authorizer = { (r: URLRequest) -> URLRequest in var req = r let helper = HawkHelper(id: token.id, key: token.key.data(using: String.Encoding.utf8, allowLossyConversion: false)!) req.setValue(helper.getAuthorizationValueFor(r), forHTTPHeaderField: "Authorization") return req } } public init(serverURI: URL, authorizer: @escaping Authorizer, workQueue: DispatchQueue, resultQueue: DispatchQueue, backoff: BackoffStorage) { self.serverURI = serverURI self.authorizer = authorizer self.workQueue = workQueue self.resultQueue = resultQueue self.backoff = backoff } func updateBackoffFromResponse<T>(_ response: StorageResponse<T>) { // N.B., we would not have made this request if a backoff were set, so // we can safely avoid doing the write if there's no backoff in the // response. // This logic will have to change if we ever invalidate that assumption. if let ms = response.metadata.backoffMilliseconds ?? response.metadata.retryAfterMilliseconds { log.info("Backing off for \(ms)ms.") self.backoff.serverBackoffUntilLocalTimestamp = ms + Date.now() } } func errorWrap<T, U>(_ deferred: Deferred<Maybe<T>>, handler: @escaping (DataResponse<U>) -> Void) -> (DataResponse<U>) -> Void { return { response in log.verbose("Response is \(response.response ??? "nil").") /** * Returns true if handled. */ func failFromResponse(_ HTTPResponse: HTTPURLResponse?) -> Bool { guard let HTTPResponse = HTTPResponse else { // TODO: better error. log.error("No response") let result = Maybe<T>(failure: RecordParseError()) deferred.fill(result) return true } log.debug("Status code: \(HTTPResponse.statusCode).") let storageResponse = StorageResponse(value: HTTPResponse, metadata: ResponseMetadata(response: HTTPResponse)) self.updateBackoffFromResponse(storageResponse) if HTTPResponse.statusCode >= 500 { log.debug("ServerError.") let result = Maybe<T>(failure: ServerError(storageResponse)) deferred.fill(result) return true } if HTTPResponse.statusCode == 404 { log.debug("NotFound<\(T.self)>.") let result = Maybe<T>(failure: NotFound(storageResponse)) deferred.fill(result) return true } if HTTPResponse.statusCode >= 400 { log.debug("BadRequestError.") let result = Maybe<T>(failure: BadRequestError(request: response.request, response: storageResponse)) deferred.fill(result) return true } return false } // Check for an error from the request processor. if response.result.isFailure { log.error("Response: \(response.response?.statusCode ?? 0). Got error \(response.result.error ??? "nil").") // If we got one, we don't want to hit the response nil case above and // return a RecordParseError, because a RequestError is more fitting. if let response = response.response { if failFromResponse(response) { log.error("This was a failure response. Filled specific error type.") return } } log.error("Filling generic RequestError.") deferred.fill(Maybe<T>(failure: RequestError())) return } if failFromResponse(response.response) { return } handler(response) } } lazy fileprivate var alamofire: SessionManager = { let ua = UserAgent.syncUserAgent let configuration = URLSessionConfiguration.ephemeral return SessionManager.managerWithUserAgent(ua, configuration: configuration) }() func requestGET(_ url: URL) -> DataRequest { var req = URLRequest(url: url as URL) req.httpMethod = URLRequest.Method.get.rawValue req.setValue("application/json", forHTTPHeaderField: "Accept") let authorized: URLRequest = self.authorizer(req) return alamofire.request(authorized) .validate(contentType: ["application/json"]) } func requestDELETE(_ url: URL) -> DataRequest { var req = URLRequest(url: url as URL) req.httpMethod = URLRequest.Method.delete.rawValue req.setValue("1", forHTTPHeaderField: "X-Confirm-Delete") let authorized: URLRequest = self.authorizer(req) return alamofire.request(authorized) } func requestWrite(_ url: URL, method: String, body: String, contentType: String, ifUnmodifiedSince: Timestamp?) -> Request { var req = URLRequest(url: url as URL) req.httpMethod = method req.setValue(contentType, forHTTPHeaderField: "Content-Type") if let ifUnmodifiedSince = ifUnmodifiedSince { req.setValue(millisecondsToDecimalSeconds(ifUnmodifiedSince), forHTTPHeaderField: "X-If-Unmodified-Since") } req.httpBody = body.data(using: String.Encoding.utf8)! let authorized: URLRequest = self.authorizer(req) return alamofire.request(authorized) } func requestPUT(_ url: URL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request { return self.requestWrite(url, method: URLRequest.Method.put.rawValue, body: body.stringValue()!, contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince) } func requestPOST(_ url: URL, body: JSON, ifUnmodifiedSince: Timestamp?) -> Request { return self.requestWrite(url, method: URLRequest.Method.post.rawValue, body: body.stringValue()!, contentType: "application/json;charset=utf-8", ifUnmodifiedSince: ifUnmodifiedSince) } func requestPOST(_ url: URL, body: [String], ifUnmodifiedSince: Timestamp?) -> Request { let content = body.joined(separator: "\n") return self.requestWrite(url, method: URLRequest.Method.post.rawValue, body: content, contentType: "application/newlines", ifUnmodifiedSince: ifUnmodifiedSince) } func requestPOST(_ url: URL, body: [JSON], ifUnmodifiedSince: Timestamp?) -> Request { return self.requestPOST(url, body: body.map { $0.stringValue()! }, ifUnmodifiedSince: ifUnmodifiedSince) } /** * Returns true and fills the provided Deferred if our state shows that we're in backoff. * Returns false otherwise. */ fileprivate func checkBackoff<T>(_ deferred: Deferred<Maybe<T>>) -> Bool { if let until = self.backoff.isInBackoff(Date.now()) { deferred.fill(Maybe<T>(failure: ServerInBackoffError(until: until))) return true } return false } fileprivate func doOp<T>(_ op: (URL) -> DataRequest, path: String, f: @escaping (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> { let deferred = Deferred<Maybe<StorageResponse<T>>>(defaultQueue: self.resultQueue) if self.checkBackoff(deferred) { return deferred } // Special case "": we want /1.5/1234567 and not /1.5/1234567/. See note about trailing slashes above. let url: URL if path == "" { url = self.serverURI // No trailing slash. } else { url = self.serverURI.appendingPathComponent(path) } let req = op(url) let handler = self.errorWrap(deferred) { (response: DataResponse<JSON>) in if let json: JSON = response.result.value { if let v = f(json) { let storageResponse = StorageResponse<T>(value: v, response: response.response!) deferred.fill(Maybe(success: storageResponse)) } else { deferred.fill(Maybe(failure: RecordParseError())) } return } deferred.fill(Maybe(failure: RecordParseError())) } _ = req.responseParsedJSON(true, completionHandler: handler) return deferred } // Sync storage responds with a plain timestamp to a PUT, not with a JSON body. fileprivate func putResource<T>(_ path: String, body: JSON, ifUnmodifiedSince: Timestamp?, parser: @escaping (String) -> T?) -> Deferred<Maybe<StorageResponse<T>>> { let url = self.serverURI.appendingPathComponent(path) return self.putResource(url, body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: parser) } fileprivate func putResource<T>(_ URL: Foundation.URL, body: JSON, ifUnmodifiedSince: Timestamp?, parser: @escaping (String) -> T?) -> Deferred<Maybe<StorageResponse<T>>> { let deferred = Deferred<Maybe<StorageResponse<T>>>(defaultQueue: self.resultQueue) if self.checkBackoff(deferred) { return deferred } let req = self.requestPUT(URL, body: body, ifUnmodifiedSince: ifUnmodifiedSince) as! DataRequest let handler = self.errorWrap(deferred) { (response: DataResponse<String>) in if let data = response.result.value { if let v = parser(data) { let storageResponse = StorageResponse<T>(value: v, response: response.response!) deferred.fill(Maybe(success: storageResponse)) } else { deferred.fill(Maybe(failure: RecordParseError())) } return } deferred.fill(Maybe(failure: RecordParseError())) } req.responseString(completionHandler: handler) return deferred } fileprivate func getResource<T>(_ path: String, f: @escaping (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> { return doOp(self.requestGET, path: path, f: f) } fileprivate func deleteResource<T>(_ path: String, f: @escaping (JSON) -> T?) -> Deferred<Maybe<StorageResponse<T>>> { return doOp(self.requestDELETE, path: path, f: f) } func wipeStorage() -> Deferred<Maybe<StorageResponse<JSON>>> { // In Sync 1.5 it's preferred that we delete the root, not /storage. return deleteResource("", f: { $0 }) } func getInfoCollections() -> Deferred<Maybe<StorageResponse<InfoCollections>>> { return getResource("info/collections", f: InfoCollections.fromJSON) } func getMetaGlobal() -> Deferred<Maybe<StorageResponse<MetaGlobal>>> { return getResource("storage/meta/global") { json in // We have an envelope. Parse the meta/global record embedded in the 'payload' string. let envelope = EnvelopeJSON(json) if envelope.isValid() { return MetaGlobal.fromJSON(JSON(parseJSON: envelope.payload)) } return nil } } func getCryptoKeys(_ syncKeyBundle: KeyBundle, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Record<KeysPayload>>>> { let syncKey = Keys(defaultBundle: syncKeyBundle) let encoder = RecordEncoder<KeysPayload>(decode: { KeysPayload($0) }, encode: { $0.json }) let encrypter = syncKey.encrypter("keys", encoder: encoder) let client = self.clientForCollection("crypto", encrypter: encrypter) return client.get("keys") } func uploadMetaGlobal(_ metaGlobal: MetaGlobal, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> { let payload = metaGlobal.asPayload() if payload.json.isError() { return Deferred(value: Maybe(failure: MalformedMetaGlobalError())) } let record: JSON = JSON(object: ["payload": payload.json.stringValue() ?? JSON.null as Any, "id": "global"]) return putResource("storage/meta/global", body: record, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp) } // The crypto/keys record is a special snowflake: it is encrypted with the Sync key bundle. All other records are // encrypted with the bulk key bundle (including possibly a per-collection bulk key) stored in crypto/keys. func uploadCryptoKeys(_ keys: Keys, withSyncKeyBundle syncKeyBundle: KeyBundle, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> { let syncKey = Keys(defaultBundle: syncKeyBundle) let encoder = RecordEncoder<KeysPayload>(decode: { KeysPayload($0) }, encode: { $0.json }) let encrypter = syncKey.encrypter("keys", encoder: encoder) let client = self.clientForCollection("crypto", encrypter: encrypter) let record = Record(id: "keys", payload: keys.asPayload()) return client.put(record, ifUnmodifiedSince: ifUnmodifiedSince) } // It would be convenient to have the storage client manage Keys, but of course we need to use a different set of // keys to fetch crypto/keys itself. See uploadCryptoKeys. func clientForCollection<T>(_ collection: String, encrypter: RecordEncrypter<T>) -> Sync15CollectionClient<T> { let storage = self.serverURI.appendingPathComponent("storage", isDirectory: true) return Sync15CollectionClient(client: self, serverURI: storage, collection: collection, encrypter: encrypter) } } private let DefaultInfoConfiguration = InfoConfiguration(maxRequestBytes: 1_048_576, maxPostRecords: 100, maxPostBytes: 1_048_576, maxTotalRecords: 10_000, maxTotalBytes: 104_857_600) /** * We'd love to nest this in the overall storage client, but Swift * forbids the nesting of a generic class inside another class. */ open class Sync15CollectionClient<T: CleartextPayloadJSON> { fileprivate let client: Sync15StorageClient fileprivate let encrypter: RecordEncrypter<T> fileprivate let collectionURI: URL fileprivate let collectionQueue = DispatchQueue(label: "com.mozilla.sync.collectionclient", attributes: []) fileprivate let infoConfig = DefaultInfoConfiguration public init(client: Sync15StorageClient, serverURI: URL, collection: String, encrypter: RecordEncrypter<T>) { self.client = client self.encrypter = encrypter self.collectionURI = serverURI.appendingPathComponent(collection, isDirectory: false) } var maxBatchPostRecords: Int { get { return infoConfig.maxPostRecords } } fileprivate func uriForRecord(_ guid: String) -> URL { return self.collectionURI.appendingPathComponent(guid) } open func newBatch(ifUnmodifiedSince: Timestamp? = nil, onCollectionUploaded: @escaping (POSTResult, Timestamp?) -> DeferredTimestamp) -> Sync15BatchClient<T> { return Sync15BatchClient(config: infoConfig, ifUnmodifiedSince: ifUnmodifiedSince, serializeRecord: self.serializeRecord, uploader: self.post, onCollectionUploaded: onCollectionUploaded) } // Exposed so we can batch by size. open func serializeRecord(_ record: Record<T>) -> String? { return self.encrypter.serializer(record)?.stringValue() } open func post(_ lines: [String], ifUnmodifiedSince: Timestamp?, queryParams: [URLQueryItem]? = nil) -> Deferred<Maybe<StorageResponse<POSTResult>>> { let deferred = Deferred<Maybe<StorageResponse<POSTResult>>>(defaultQueue: client.resultQueue) if self.client.checkBackoff(deferred) { return deferred } let requestURI: URL if let queryParams = queryParams { requestURI = self.collectionURI.withQueryParams(queryParams) } else { requestURI = self.collectionURI } let req = client.requestPOST(requestURI, body: lines, ifUnmodifiedSince: ifUnmodifiedSince) as! DataRequest _ = req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (response: DataResponse<JSON>) in if let json: JSON = response.result.value, let result = POSTResult.fromJSON(json) { let storageResponse = StorageResponse(value: result, response: response.response!) deferred.fill(Maybe(success: storageResponse)) return } else { log.warning("Couldn't parse JSON response.") } deferred.fill(Maybe(failure: RecordParseError())) }) return deferred } open func post(_ records: [Record<T>], ifUnmodifiedSince: Timestamp?, queryParams: [URLQueryItem]? = nil) -> Deferred<Maybe<StorageResponse<POSTResult>>> { // TODO: charset // TODO: if any of these fail, we should do _something_. Right now we just ignore them. let lines = optFilter(records.map(self.serializeRecord)) return self.post(lines, ifUnmodifiedSince: ifUnmodifiedSince, queryParams: queryParams) } open func put(_ record: Record<T>, ifUnmodifiedSince: Timestamp?) -> Deferred<Maybe<StorageResponse<Timestamp>>> { if let body = self.encrypter.serializer(record) { return self.client.putResource(uriForRecord(record.id), body: body, ifUnmodifiedSince: ifUnmodifiedSince, parser: decimalSecondsStringToTimestamp) } return deferMaybe(RecordParseError()) } open func get(_ guid: String) -> Deferred<Maybe<StorageResponse<Record<T>>>> { let deferred = Deferred<Maybe<StorageResponse<Record<T>>>>(defaultQueue: client.resultQueue) if self.client.checkBackoff(deferred) { return deferred } let req = client.requestGET(uriForRecord(guid)) _ = req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (response: DataResponse<JSON>) in if let json: JSON = response.result.value { let envelope = EnvelopeJSON(json) let record = Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory) if let record = record { let storageResponse = StorageResponse(value: record, response: response.response!) deferred.fill(Maybe(success: storageResponse)) return } } else { log.warning("Couldn't parse JSON response.") } deferred.fill(Maybe(failure: RecordParseError())) }) return deferred } /** * Unlike every other Sync client, we use the application/json format for fetching * multiple requests. The others use application/newlines. We don't want to write * another Serializer, and we're loading everything into memory anyway. * * It is the caller's responsibility to check whether the returned payloads are invalid. * * Only non-JSON and malformed envelopes will be dropped. */ open func getSince(_ since: Timestamp, sort: SortOption?=nil, limit: Int?=nil, offset: String?=nil) -> Deferred<Maybe<StorageResponse<[Record<T>]>>> { let deferred = Deferred<Maybe<StorageResponse<[Record<T>]>>>(defaultQueue: client.resultQueue) // Fills the Deferred for us. if self.client.checkBackoff(deferred) { return deferred } var params: [URLQueryItem] = [ URLQueryItem(name: "full", value: "1"), URLQueryItem(name: "newer", value: millisecondsToDecimalSeconds(since)), ] if let offset = offset { params.append(URLQueryItem(name: "offset", value: offset)) } if let limit = limit { params.append(URLQueryItem(name: "limit", value: "\(limit)")) } if let sort = sort { params.append(URLQueryItem(name: "sort", value: sort.rawValue)) } log.debug("Issuing GET with newer = \(since), offset = \(offset ??? "nil"), sort = \(sort ??? "nil").") let req = client.requestGET(self.collectionURI.withQueryParams(params)) _ = req.responsePartialParsedJSON(queue: collectionQueue, completionHandler: self.client.errorWrap(deferred) { (response: DataResponse<JSON>) in log.verbose("Response is \(response).") guard let json: JSON = response.result.value else { log.warning("Non-JSON response.") deferred.fill(Maybe(failure: RecordParseError())) return } guard let arr = json.array else { log.warning("Non-array response.") deferred.fill(Maybe(failure: RecordParseError())) return } func recordify(_ json: JSON) -> Record<T>? { let envelope = EnvelopeJSON(json) return Record<T>.fromEnvelope(envelope, payloadFactory: self.encrypter.factory) } let records = arr.flatMap(recordify) let response = StorageResponse(value: records, response: response.response!) deferred.fill(Maybe(success: response)) }) return deferred } }
mpl-2.0
917e8e9165c67819a7dcd44e74bd38d7
38.154223
190
0.634812
4.856384
false
false
false
false
exevil/Keys-For-Sketch
Source/Controller/Outline View/Cell/Shortcut View/ShortcutValidator.swift
1
2371
// // ShortcutValidator.swift // KeysForSketch // // Created by Vyacheslav Dubovitsky on 02/04/2017. // Copyright © 2017 Vyacheslav Dubovitsky. All rights reserved. // import Foundation class ShortcutValidator : MASShortcutValidator { static let sharedInstance = ShortcutValidator() // Return the same shared instance to override Obj-C superclass singleton method override static func shared() -> ShortcutValidator { return ShortcutValidator.sharedInstance } func isShortcutValid(_ shortcut: MASShortcut!, validWithoutModifiers: Bool) -> Bool { let keyCode = Int(shortcut.keyCode) let modifiers = shortcut.modifierFlags // Allow any function key with any combination of modifiers let includesFunctionKey: Bool = { let fKeyCodes = [kVK_F1, kVK_F2, kVK_F3, kVK_F4, kVK_F5, kVK_F6, kVK_F7, kVK_F8, kVK_F9, kVK_F10, kVK_F11, kVK_F12, kVK_F13, kVK_F14, kVK_F15, kVK_F16, kVK_F17, kVK_F18, kVK_F19, kVK_F20] for fKeyCode in fKeyCodes { if fKeyCode == keyCode { return true } } return false }() if includesFunctionKey { return true } // Check for modifiers let hasModifierFlags = modifiers > 0 if !hasModifierFlags && validWithoutModifiers { return true } // Allow any hotkey containing Control or Command modifier let includesCmd = modifiers & NSEvent.ModifierFlags.command.rawValue > 0 let includesCtrl = modifiers & NSEvent.ModifierFlags.control.rawValue > 0 // Allow Option key only in selected cases let includesCorrectOption: Bool = { if modifiers & NSEvent.ModifierFlags.control.rawValue > 0 { // Always allow Option-Space and Option-Escape because they do not have any bind system commands if keyCode == kVK_Space || keyCode == kVK_Escape { return true } // Allow Option modifier with any key even if it will break the system binding if self.allowAnyShortcutWithOptionModifier { return true } } return false }() if includesCmd || includesCtrl || includesCorrectOption { return true } // The hotkey violates system bindings return false } }
mit
b818061fcfae3b54918974a4e4dec3c1
39.862069
199
0.63038
4.628906
false
false
false
false
think-dev/MadridBUS
MadridBUS/Source/Business/LocationHelper.swift
1
1916
import Foundation import CoreLocation protocol LocationHelper { var isLocationAvailable: Bool {get} func acquireLocation(success: @escaping (CLLocation) -> ()) func stopAcquiringLocation() } class LocationHelperBase: NSObject, LocationHelper { var isLocationAvailable: Bool = false private let locationManager = CLLocationManager() internal var locationAcquiredSuccessBlock: ((CLLocation) -> ())? override init() { super.init() if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == .authorizedAlways { isLocationAvailable = true } else { if CLLocationManager.authorizationStatus() == .notDetermined { manageLocationAuthorization() } else { isLocationAvailable = false } } } func acquireLocation(success: @escaping (CLLocation) -> ()) { locationManager.desiredAccuracy = 100 locationAcquiredSuccessBlock = success locationManager.delegate = self locationManager.startUpdatingLocation() } func stopAcquiringLocation() { locationManager.delegate = nil locationManager.stopUpdatingLocation() } private func manageLocationAuthorization() { locationManager.requestAlwaysAuthorization() } } extension LocationHelperBase: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { for aLocation in locations { if aLocation.horizontalAccuracy <= 65 { stopAcquiringLocation() locationAcquiredSuccessBlock!(aLocation) break } } } }
mit
5c93696650376ef0b8fd02ac5da0563a
29.412698
120
0.652401
6.141026
false
false
false
false
testpress/ios-app
ios-app/Extensions/Misc.swift
1
498
import Foundation enum Debounce<T: Equatable> { static func input(_ input: T, delay: TimeInterval = 0.3, current: @escaping @autoclosure () -> T, perform: @escaping (T) -> Void) { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { guard input == current() else { return } perform(input) } } } extension RangeExpression where Bound == String.Index { func nsRange<S: StringProtocol>(in string: S) -> NSRange { .init(self, in: string) } }
mit
25b1ae8cbdaf44ef30ae51ba56b99852
34.571429
135
0.62249
3.890625
false
false
false
false
vector-im/vector-ios
Riot/Modules/Room/TimelineCells/KeyVerification/KeyVerificationConclusionCell.swift
1
3670
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit @objcMembers class KeyVerificationConclusionCell: KeyVerificationBaseCell { // MARK: - Constants private enum Sizing { static let view = KeyVerificationConclusionCell(style: .default, reuseIdentifier: nil) } // MARK: - Setup override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.commonInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { self.keyVerificationCellInnerContentView?.isButtonsHidden = true self.keyVerificationCellInnerContentView?.isRequestStatusHidden = true } // MARK: - Overrides override func render(_ cellData: MXKCellData!) { super.render(cellData) guard let keyVerificationCellInnerContentView = self.keyVerificationCellInnerContentView, let bubbleData = self.bubbleData as? RoomBubbleCellData, let viewData = self.viewData(from: bubbleData) else { MXLog.debug("[KeyVerificationConclusionBubbleCell] Fail to render \(String(describing: cellData))") return } keyVerificationCellInnerContentView.badgeImage = viewData.badgeImage keyVerificationCellInnerContentView.title = viewData.title keyVerificationCellInnerContentView.updateSenderInfo(with: viewData.senderId, userDisplayName: viewData.senderDisplayName) } override class func sizingView() -> KeyVerificationBaseCell { return self.Sizing.view } // MARK: - Private private func viewData(from roomBubbleData: RoomBubbleCellData) -> KeyVerificationConclusionViewData? { guard let event = roomBubbleData.bubbleComponents.first?.event else { return nil } let viewData: KeyVerificationConclusionViewData? let senderId = self.senderId(from: bubbleData) let senderDisplayName = self.senderDisplayName(from: bubbleData) let title: String? let badgeImage: UIImage? switch event.eventType { case .keyVerificationDone: badgeImage = Asset.Images.encryptionTrusted.image title = VectorL10n.keyVerificationTileConclusionDoneTitle case .keyVerificationCancel: badgeImage = Asset.Images.encryptionWarning.image title = VectorL10n.keyVerificationTileConclusionWarningTitle default: badgeImage = nil title = nil } if let title = title, let badgeImage = badgeImage { viewData = KeyVerificationConclusionViewData(badgeImage: badgeImage, title: title, senderId: senderId, senderDisplayName: senderDisplayName) } else { viewData = nil } return viewData } }
apache-2.0
4a5dde0a7dcbda3c18c59ff752bd3629
34.980392
130
0.656131
5.552194
false
false
false
false
oper0960/GWExtensions
GWExtensions/Classes/UIViewExtension.swift
1
5365
// // UIViewExtension.swift // Pods // // Created by Ryu on 2017. 4. 18.. // // let defaults = UserDefaults.standard let screenWidth = UIScreen.main.bounds.width let screenHeight = UIScreen.main.bounds.height import UIKit public extension UIView { public class func copyView() -> AnyObject { return NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: self))! as AnyObject } public func nextY() -> CGFloat { return self.frame.origin.y + self.frame.size.height } public func nextX() -> CGFloat { return self.frame.origin.x + self.frame.size.width } // Set imageview square public func setSquareImage() { self.clipsToBounds = true self.layer.cornerRadius = self.frame.size.width / 2 } // All subview remove public func removeAllSubviews() { for subview in self.subviews { subview.removeFromSuperview() } } // Screen capture of the view public func capture(_ shadow: Bool = false) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0) self.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let snapshotImageView = UIImageView(image: image) if shadow { snapshotImageView.layer.masksToBounds = false snapshotImageView.layer.cornerRadius = 0.0 snapshotImageView.layer.shadowOffset = CGSize(width: -0.5, height: 0.0) snapshotImageView.layer.shadowRadius = 5.0 snapshotImageView.layer.shadowOpacity = 0.4 } // return image 면 UIImage, return snapshotImageView 면 UIImageView return image! } // Only at the corner want radius public func selectCornerRadius(direction : UIRectCorner, cornerSize: CGSize) { let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: direction, cornerRadii: cornerSize) let maskLayer = CAShapeLayer() maskLayer.frame = self.bounds; maskLayer.path = maskPath.cgPath; self.layer.mask = maskLayer } } public extension UIWebView { // Screen capture of the Webview public func capture() -> UIImage { UIGraphicsBeginImageContextWithOptions(scrollView.contentSize, scrollView.isOpaque, 0) let currentContentOffset = scrollView.contentOffset let currentFrame = scrollView.frame scrollView.contentOffset = CGPoint.zero scrollView.frame = CGRect(x: 0, y: 0, width: scrollView.contentSize.width, height: scrollView.contentSize.height) scrollView.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext()! scrollView.contentOffset = currentContentOffset scrollView.frame = currentFrame UIGraphicsEndImageContext() return image } } public extension UITableView { // TableviewCell all select public func setAsSelectAll(section: Int) { for row in 0 ..< self.numberOfRows(inSection: section) { self.selectRow(at: IndexPath(row: row, section: section), animated: false, scrollPosition: .none) } } // TableviewCell all deselect public func setAsDeselectAll(section: Int) { for row in 0 ..< self.numberOfRows(inSection: section) { self.deselectRow(at: IndexPath(row: row, section: section), animated: false) } } } public extension UILabel { // get UILabel Height public func getLabelHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat { let lbl = UILabel(frame: .zero) lbl.frame.size.width = width lbl.font = font lbl.numberOfLines = 0 lbl.text = text lbl.sizeToFit() return lbl.frame.size.height } } public extension UITextField { enum PaddingType { case all case left case right } // get UITextView Height public func getTextViewHeight(text: String, width: CGFloat, font: UIFont) -> CGFloat { let tv = UITextView(frame: .zero) tv.frame.size.width = width tv.font = font tv.text = text tv.sizeToFit() return tv.frame.size.height } // UITextField add Padding func setPadding(_ direction: PaddingType, width: CGFloat) { let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: self.frame.height)) switch direction { case .all: self.leftView = paddingView self.rightView = paddingView self.leftViewMode = .always self.rightViewMode = .always case .left: self.leftView = paddingView self.leftViewMode = .always case .right: self.rightView = paddingView self.rightViewMode = .always } } } public extension UIActivityIndicatorView { public func start(){ DispatchQueue.main.async { self.isHidden = false self.startAnimating() } } public func stop(){ DispatchQueue.main.async { self.isHidden = true self.stopAnimating() } } }
mit
c58182c19636c4ce576281faed18bee6
28.618785
125
0.631412
4.922865
false
false
false
false
MiezelKat/AWSense
AWSenseConnectTest/AWSenseConnectTest/MainViewController.swift
1
5747
// // ViewController.swift // AWSenseConnectTest // // Created by Katrin Haensel on 22/02/2017. // Copyright © 2017 Katrin Haensel. All rights reserved. // import UIKit import HealthKit import CoreMotion import AWSenseShared import AWSenseConnectPhone class MainViewController: UITableViewController, RemoteSensingEventHandler { @IBOutlet weak var heartRateSwitch: UISwitch! @IBOutlet weak var accelerometerSwitch: UISwitch! @IBOutlet weak var deviceMotionSwitch: UISwitch! @IBOutlet weak var intervallSlider: UISlider! @IBOutlet weak var intervallSecondLabel: UILabel! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var startSensingButton: UIButton! @IBOutlet weak var sessionStatusLabel: UILabel! @IBOutlet weak var sessionTimeLabel: UILabel! @IBOutlet weak var stopSessionButton: UIButton! @IBOutlet var beforeStartCollection: [UISwitch]! @IBOutlet weak var hrLabel: UILabel! @IBOutlet weak var accelLabel: UILabel! @IBOutlet weak var deviceMLabel: UILabel! @IBOutlet weak var messageCountLabel: UILabel! var timer : Timer? let sessionManager = SessionManager.instance var sessionStartDate : Date? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. sessionManager.subscribe(handler: self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func startButtonPressed(_ sender: Any) { disableStartSessionElements() var enabledSensors = [AWSSensorType]() if(heartRateSwitch.isOn){ enabledSensors.append(.heart_rate) } if(accelerometerSwitch.isOn){ enabledSensors.append(.accelerometer) } if(deviceMotionSwitch.isOn){ enabledSensors.append(.device_motion) } let transmissionIntervall = DataTransmissionInterval(Double(intervallSlider.value)) do { // TODO: test sensor settings try sessionManager.startSensingSession(withName: nameTextField.text, configuration: enabledSensors, sensorSettings: [RawAccelerometerSensorSettings(withIntervall_Hz: 50.0), DeviceMotionSensorSettings(withIntervall_Hz: 50.0)], transmissionIntervall: transmissionIntervall) }catch let error as Error{ print(error) } } func disableStartSessionElements(){ beforeStartCollection.forEach({ (s) in s.isEnabled = false }) startSensingButton.isEnabled = false nameTextField.isEnabled = false } func enableSessionRunningElements(){ // todo } @IBAction func stopButtonPressed(_ sender: Any) { if(timer != nil){ timer!.invalidate() } do{ try sessionManager.stopSensing() }catch let error as Error{ print(error) } } public func handle(withType type: RemoteSensingEventType, forSession session: RemoteSensingSession?, withData data: [AWSSensorData]?) { if(type == .sessionCreated){ self.sessionStatusLabel.text = "session created" }else if(type == .sessionStateChanged){ DispatchQueue.main.async { self.sessionStatusLabel.text = session!.state.rawValue if(session!.state == .running){ self.sessionStartDate = Date() self.timer = Timer.init(timeInterval: 1, target: self, selector: #selector(self.updateTimerLabel), userInfo: nil, repeats: true) } } }else if(type == .remoteSessionDataReceived){ if(data!.count < 1){ return }else{ messageCount += 1 DispatchQueue.main.async { self.messageCountLabel.text = self.messageCount.description } } if(data![0].sensorType == .heart_rate){ DispatchQueue.main.async { self.hrLabel.text = data!.last!.prettyPrint } }else if(data![0].sensorType == .accelerometer){ DispatchQueue.main.async { self.accelLabel.text = data!.last!.prettyPrint } }else if(data![0].sensorType == .device_motion){ DispatchQueue.main.async { self.deviceMLabel.text = data!.last!.prettyPrint } } } } var messageCount = 0 public func updateTimerLabel(){ DispatchQueue.main.async { self.sessionTimeLabel.text = Date().timeIntervalSince(self.sessionStartDate!).description } } @IBAction func intervallValueChanged(_ sender: Any) { let roundedValue = lroundf(intervallSlider.value) intervallSlider.setValue(Float(roundedValue), animated: true) intervallSecondLabel.text = roundedValue.description } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = event?.allTouches?.first if (nameTextField.isFirstResponder && touch?.view != nameTextField){ nameTextField.resignFirstResponder() } super.touchesBegan(touches, with: event) } }
mit
7e0a459e86f7753abf40e2830f2ed1c3
30.571429
176
0.594849
5.2
false
false
false
false
RobotRebels/SwiftLessons
chapter1/lesson2/28_03_2017.playground/Contents.swift
1
1922
import UIKit /* - классы - экземпляры класса - модификаторы свойств (public, private, open, protected) - методы (класс-методы, приватные методы) - инкапсуляция, аггрегация Задание: - создать класс части машины Plane: - не менее 5 свойств, 2 приватных - 2 публичных метода, 1 приватный - 1 метод класса - 1 свойства класса - (Engine, Pilot, Fusiluazh, Shassi) - попытаться создать свою ветку в репозитории и закоммитить пустой файл */ class Engine { var horsePower: Int = 0 } class Car { var engine: Engine = Engine() static var creationPlanet = "Earth" static func getCreationPlanet() -> String { return "Earth" } public var brand: String = "No brand" public var name: String = "" var weight: Int = 0 private var mainVtulkaDiameter: Int = 0 /*{ set { self.mainVtulkaDiameter = newValue } get { return self.mainVtulkaDiameter } }*/ func setMainVtulkaDiameter(diameter: Int) { self.mainVtulkaDiameter = diameter } private func insertGasIntoEngine() { print(self.name + ": ps ps ps gas") } var type: String = "" func powerOn() { insertGasIntoEngine() print(self.name + ": Vzhvhzhzh") } /* init(dict: [String: AnyObject]) { } */ /* init() { brand = "No brand" } */ } var car = Car() car.brand = "Honda" car.name = "MySuperCar" car.weight = 1000 car.engine.horsePower = 100 var car2 = Car() print(car.brand) car.powerOn() car2.powerOn() car2.setMainVtulkaDiameter(diameter: 10) Car.creationPlanet = "Mars" print(Car.creationPlanet) print(Car.getCreationPlanet())
mit
144475b1121664bbc0413acacf5fbc35
14.560748
72
0.635435
2.957371
false
false
false
false
shahmishal/swift
stdlib/public/core/KeyPath.swift
1
131614
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims internal func _abstract( methodName: StaticString = #function, file: StaticString = #file, line: UInt = #line ) -> Never { #if INTERNAL_CHECKS_ENABLED _fatalErrorMessage("abstract method", methodName, file: file, line: line, flags: _fatalErrorFlags()) #else _conditionallyUnreachable() #endif } // MARK: Type-erased abstract base classes // NOTE: older runtimes had Swift.AnyKeyPath as the ObjC name. // The two must coexist, so it was renamed. The old name must not be // used in the new runtime. _TtCs11_AnyKeyPath is the mangled name for // Swift._AnyKeyPath. @_objcRuntimeName(_TtCs11_AnyKeyPath) /// A type-erased key path, from any root type to any resulting value /// type. public class AnyKeyPath: Hashable, _AppendKeyPath { /// The root type for this key path. @inlinable public static var rootType: Any.Type { return _rootAndValueType.root } /// The value type for this key path. @inlinable public static var valueType: Any.Type { return _rootAndValueType.value } internal final var _kvcKeyPathStringPtr: UnsafePointer<CChar>? /// The hash value. final public var hashValue: Int { return _hashValue(for: self) } /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @_effects(releasenone) final public func hash(into hasher: inout Hasher) { ObjectIdentifier(type(of: self)).hash(into: &hasher) return withBuffer { var buffer = $0 if buffer.data.isEmpty { return } while true { let (component, type) = buffer.next() hasher.combine(component.value) if let type = type { hasher.combine(unsafeBitCast(type, to: Int.self)) } else { break } } } } public static func ==(a: AnyKeyPath, b: AnyKeyPath) -> Bool { // Fast-path identical objects if a === b { return true } // Short-circuit differently-typed key paths if type(of: a) != type(of: b) { return false } return a.withBuffer { var aBuffer = $0 return b.withBuffer { var bBuffer = $0 // Two equivalent key paths should have the same reference prefix if aBuffer.hasReferencePrefix != bBuffer.hasReferencePrefix { return false } // Identity is equal to identity if aBuffer.data.isEmpty { return bBuffer.data.isEmpty } while true { let (aComponent, aType) = aBuffer.next() let (bComponent, bType) = bBuffer.next() if aComponent.header.endOfReferencePrefix != bComponent.header.endOfReferencePrefix || aComponent.value != bComponent.value || aType != bType { return false } if aType == nil { return true } } } } } // SPI for the Foundation overlay to allow interop with KVC keypath-based // APIs. public var _kvcKeyPathString: String? { guard let ptr = _kvcKeyPathStringPtr else { return nil } return String(validatingUTF8: ptr) } // MARK: Implementation details // Prevent normal initialization. We use tail allocation via // allocWithTailElems(). internal init() { _internalInvariantFailure("use _create(...)") } @usableFromInline internal class var _rootAndValueType: (root: Any.Type, value: Any.Type) { _abstract() } internal static func _create( capacityInBytes bytes: Int, initializedBy body: (UnsafeMutableRawBufferPointer) -> Void ) -> Self { _internalInvariant(bytes > 0 && bytes % 4 == 0, "capacity must be multiple of 4 bytes") let result = Builtin.allocWithTailElems_1(self, (bytes/4)._builtinWordValue, Int32.self) result._kvcKeyPathStringPtr = nil let base = UnsafeMutableRawPointer(Builtin.projectTailElems(result, Int32.self)) body(UnsafeMutableRawBufferPointer(start: base, count: bytes)) return result } internal func withBuffer<T>(_ f: (KeyPathBuffer) throws -> T) rethrows -> T { defer { _fixLifetime(self) } let base = UnsafeRawPointer(Builtin.projectTailElems(self, Int32.self)) return try f(KeyPathBuffer(base: base)) } @usableFromInline // Exposed as public API by MemoryLayout<Root>.offset(of:) internal var _storedInlineOffset: Int? { return withBuffer { var buffer = $0 // The identity key path is effectively a stored keypath of type Self // at offset zero if buffer.data.isEmpty { return 0 } var offset = 0 while true { let (rawComponent, optNextType) = buffer.next() switch rawComponent.header.kind { case .struct: offset += rawComponent._structOrClassOffset case .class, .computed, .optionalChain, .optionalForce, .optionalWrap, .external: return .none } if optNextType == nil { return .some(offset) } } } } } /// A partially type-erased key path, from a concrete root type to any /// resulting value type. public class PartialKeyPath<Root>: AnyKeyPath { } // MARK: Concrete implementations internal enum KeyPathKind { case readOnly, value, reference } /// A key path from a specific root type to a specific resulting value type. public class KeyPath<Root, Value>: PartialKeyPath<Root> { @usableFromInline internal final override class var _rootAndValueType: ( root: Any.Type, value: Any.Type ) { return (Root.self, Value.self) } // MARK: Implementation internal typealias Kind = KeyPathKind internal class var kind: Kind { return .readOnly } internal static func appendedType<AppendedValue>( with t: KeyPath<Value, AppendedValue>.Type ) -> KeyPath<Root, AppendedValue>.Type { let resultKind: Kind switch (self.kind, t.kind) { case (_, .reference): resultKind = .reference case (let x, .value): resultKind = x default: resultKind = .readOnly } switch resultKind { case .readOnly: return KeyPath<Root, AppendedValue>.self case .value: return WritableKeyPath.self case .reference: return ReferenceWritableKeyPath.self } } @usableFromInline internal final func _projectReadOnly(from root: Root) -> Value { // TODO: For perf, we could use a local growable buffer instead of Any var curBase: Any = root return withBuffer { var buffer = $0 if buffer.data.isEmpty { return unsafeBitCast(root, to: Value.self) } while true { let (rawComponent, optNextType) = buffer.next() let valueType = optNextType ?? Value.self let isLast = optNextType == nil func project<CurValue>(_ base: CurValue) -> Value? { func project2<NewValue>(_: NewValue.Type) -> Value? { switch rawComponent._projectReadOnly(base, to: NewValue.self, endingWith: Value.self) { case .continue(let newBase): if isLast { _internalInvariant(NewValue.self == Value.self, "key path does not terminate in correct type") return unsafeBitCast(newBase, to: Value.self) } else { curBase = newBase return nil } case .break(let result): return result } } return _openExistential(valueType, do: project2) } if let result = _openExistential(curBase, do: project) { return result } } } } deinit { withBuffer { $0.destroy() } } } /// A key path that supports reading from and writing to the resulting value. public class WritableKeyPath<Root, Value>: KeyPath<Root, Value> { // MARK: Implementation detail internal override class var kind: Kind { return .value } // `base` is assumed to be undergoing a formal access for the duration of the // call, so must not be mutated by an alias @usableFromInline internal func _projectMutableAddress(from base: UnsafePointer<Root>) -> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) { var p = UnsafeRawPointer(base) var type: Any.Type = Root.self var keepAlive: AnyObject? return withBuffer { var buffer = $0 _internalInvariant(!buffer.hasReferencePrefix, "WritableKeyPath should not have a reference prefix") if buffer.data.isEmpty { return ( UnsafeMutablePointer<Value>( mutating: p.assumingMemoryBound(to: Value.self)), nil) } while true { let (rawComponent, optNextType) = buffer.next() let nextType = optNextType ?? Value.self func project<CurValue>(_: CurValue.Type) { func project2<NewValue>(_: NewValue.Type) { p = rawComponent._projectMutableAddress(p, from: CurValue.self, to: NewValue.self, isRoot: p == UnsafeRawPointer(base), keepAlive: &keepAlive) } _openExistential(nextType, do: project2) } _openExistential(type, do: project) if optNextType == nil { break } type = nextType } // TODO: With coroutines, it would be better to yield here, so that // we don't need the hack of the keepAlive reference to manage closing // accesses. let typedPointer = p.assumingMemoryBound(to: Value.self) return (pointer: UnsafeMutablePointer(mutating: typedPointer), owner: keepAlive) } } } /// A key path that supports reading from and writing to the resulting value /// with reference semantics. public class ReferenceWritableKeyPath< Root, Value >: WritableKeyPath<Root, Value> { // MARK: Implementation detail internal final override class var kind: Kind { return .reference } internal final override func _projectMutableAddress( from base: UnsafePointer<Root> ) -> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) { // Since we're a ReferenceWritableKeyPath, we know we don't mutate the base // in practice. return _projectMutableAddress(from: base.pointee) } @usableFromInline internal final func _projectMutableAddress(from origBase: Root) -> (pointer: UnsafeMutablePointer<Value>, owner: AnyObject?) { var keepAlive: AnyObject? var address: UnsafeMutablePointer<Value> = withBuffer { var buffer = $0 // Project out the reference prefix. var base: Any = origBase while buffer.hasReferencePrefix { let (rawComponent, optNextType) = buffer.next() _internalInvariant(optNextType != nil, "reference prefix should not go to end of buffer") let nextType = optNextType.unsafelyUnwrapped func project<NewValue>(_: NewValue.Type) -> Any { func project2<CurValue>(_ base: CurValue) -> Any { return rawComponent._projectReadOnly( base, to: NewValue.self, endingWith: Value.self) .assumingContinue } return _openExistential(base, do: project2) } base = _openExistential(nextType, do: project) } // Start formal access to the mutable value, based on the final base // value. func formalMutation<MutationRoot>(_ base: MutationRoot) -> UnsafeMutablePointer<Value> { var base2 = base return withUnsafeBytes(of: &base2) { baseBytes in var p = baseBytes.baseAddress.unsafelyUnwrapped var curType: Any.Type = MutationRoot.self while true { let (rawComponent, optNextType) = buffer.next() let nextType = optNextType ?? Value.self func project<CurValue>(_: CurValue.Type) { func project2<NewValue>(_: NewValue.Type) { p = rawComponent._projectMutableAddress(p, from: CurValue.self, to: NewValue.self, isRoot: p == baseBytes.baseAddress, keepAlive: &keepAlive) } _openExistential(nextType, do: project2) } _openExistential(curType, do: project) if optNextType == nil { break } curType = nextType } let typedPointer = p.assumingMemoryBound(to: Value.self) return UnsafeMutablePointer(mutating: typedPointer) } } return _openExistential(base, do: formalMutation) } return (address, keepAlive) } } // MARK: Implementation details internal enum KeyPathComponentKind { /// The keypath references an externally-defined property or subscript whose /// component describes how to interact with the key path. case external /// The keypath projects within the storage of the outer value, like a /// stored property in a struct. case `struct` /// The keypath projects from the referenced pointer, like a /// stored property in a class. case `class` /// The keypath projects using a getter/setter pair. case computed /// The keypath optional-chains, returning nil immediately if the input is /// nil, or else proceeding by projecting the value inside. case optionalChain /// The keypath optional-forces, trapping if the input is /// nil, or else proceeding by projecting the value inside. case optionalForce /// The keypath wraps a value in an optional. case optionalWrap } internal struct ComputedPropertyID: Hashable { internal var value: Int internal var kind: KeyPathComputedIDKind internal static func ==( x: ComputedPropertyID, y: ComputedPropertyID ) -> Bool { return x.value == y.value && x.kind == y.kind } internal func hash(into hasher: inout Hasher) { hasher.combine(value) hasher.combine(kind) } } internal struct ComputedArgumentWitnesses { internal typealias Destroy = @convention(thin) (_ instanceArguments: UnsafeMutableRawPointer, _ size: Int) -> () internal typealias Copy = @convention(thin) (_ srcInstanceArguments: UnsafeRawPointer, _ destInstanceArguments: UnsafeMutableRawPointer, _ size: Int) -> () internal typealias Equals = @convention(thin) (_ xInstanceArguments: UnsafeRawPointer, _ yInstanceArguments: UnsafeRawPointer, _ size: Int) -> Bool // FIXME(hasher) Combine to an inout Hasher instead internal typealias Hash = @convention(thin) (_ instanceArguments: UnsafeRawPointer, _ size: Int) -> Int internal let destroy: Destroy? internal let copy: Copy internal let equals: Equals internal let hash: Hash } internal enum KeyPathComponent: Hashable { internal struct ArgumentRef { internal init( data: UnsafeRawBufferPointer, witnesses: UnsafePointer<ComputedArgumentWitnesses>, witnessSizeAdjustment: Int ) { self.data = data self.witnesses = witnesses self.witnessSizeAdjustment = witnessSizeAdjustment } internal var data: UnsafeRawBufferPointer internal var witnesses: UnsafePointer<ComputedArgumentWitnesses> internal var witnessSizeAdjustment: Int } /// The keypath projects within the storage of the outer value, like a /// stored property in a struct. case `struct`(offset: Int) /// The keypath projects from the referenced pointer, like a /// stored property in a class. case `class`(offset: Int) /// The keypath projects using a getter. case get(id: ComputedPropertyID, get: UnsafeRawPointer, argument: ArgumentRef?) /// The keypath projects using a getter/setter pair. The setter can mutate /// the base value in-place. case mutatingGetSet(id: ComputedPropertyID, get: UnsafeRawPointer, set: UnsafeRawPointer, argument: ArgumentRef?) /// The keypath projects using a getter/setter pair that does not mutate its /// base. case nonmutatingGetSet(id: ComputedPropertyID, get: UnsafeRawPointer, set: UnsafeRawPointer, argument: ArgumentRef?) /// The keypath optional-chains, returning nil immediately if the input is /// nil, or else proceeding by projecting the value inside. case optionalChain /// The keypath optional-forces, trapping if the input is /// nil, or else proceeding by projecting the value inside. case optionalForce /// The keypath wraps a value in an optional. case optionalWrap internal static func ==(a: KeyPathComponent, b: KeyPathComponent) -> Bool { switch (a, b) { case (.struct(offset: let a), .struct(offset: let b)), (.class (offset: let a), .class (offset: let b)): return a == b case (.optionalChain, .optionalChain), (.optionalForce, .optionalForce), (.optionalWrap, .optionalWrap): return true case (.get(id: let id1, get: _, argument: let argument1), .get(id: let id2, get: _, argument: let argument2)), (.mutatingGetSet(id: let id1, get: _, set: _, argument: let argument1), .mutatingGetSet(id: let id2, get: _, set: _, argument: let argument2)), (.nonmutatingGetSet(id: let id1, get: _, set: _, argument: let argument1), .nonmutatingGetSet(id: let id2, get: _, set: _, argument: let argument2)): if id1 != id2 { return false } if let arg1 = argument1, let arg2 = argument2 { return arg1.witnesses.pointee.equals( arg1.data.baseAddress.unsafelyUnwrapped, arg2.data.baseAddress.unsafelyUnwrapped, arg1.data.count - arg1.witnessSizeAdjustment) } // If only one component has arguments, that should indicate that the // only arguments in that component were generic captures and therefore // not affecting equality. return true case (.struct, _), (.class, _), (.optionalChain, _), (.optionalForce, _), (.optionalWrap, _), (.get, _), (.mutatingGetSet, _), (.nonmutatingGetSet, _): return false } } @_effects(releasenone) internal func hash(into hasher: inout Hasher) { func appendHashFromArgument( _ argument: KeyPathComponent.ArgumentRef? ) { if let argument = argument { let hash = argument.witnesses.pointee.hash( argument.data.baseAddress.unsafelyUnwrapped, argument.data.count - argument.witnessSizeAdjustment) // Returning 0 indicates that the arguments should not impact the // hash value of the overall key path. // FIXME(hasher): hash witness should just mutate hasher directly if hash != 0 { hasher.combine(hash) } } } switch self { case .struct(offset: let a): hasher.combine(0) hasher.combine(a) case .class(offset: let b): hasher.combine(1) hasher.combine(b) case .optionalChain: hasher.combine(2) case .optionalForce: hasher.combine(3) case .optionalWrap: hasher.combine(4) case .get(id: let id, get: _, argument: let argument): hasher.combine(5) hasher.combine(id) appendHashFromArgument(argument) case .mutatingGetSet(id: let id, get: _, set: _, argument: let argument): hasher.combine(6) hasher.combine(id) appendHashFromArgument(argument) case .nonmutatingGetSet(id: let id, get: _, set: _, argument: let argument): hasher.combine(7) hasher.combine(id) appendHashFromArgument(argument) } } } // A class that maintains ownership of another object while a mutable projection // into it is underway. The lifetime of the instance of this class is also used // to begin and end exclusive 'modify' access to the projected address. internal final class ClassHolder<ProjectionType> { /// The type of the scratch record passed to the runtime to record /// accesses to guarantee exlcusive access. internal typealias AccessRecord = Builtin.UnsafeValueBuffer internal var previous: AnyObject? internal var instance: AnyObject internal init(previous: AnyObject?, instance: AnyObject) { self.previous = previous self.instance = instance } internal final class func _create( previous: AnyObject?, instance: AnyObject, accessingAddress address: UnsafeRawPointer, type: ProjectionType.Type ) -> ClassHolder { // Tail allocate the UnsafeValueBuffer used as the AccessRecord. // This avoids a second heap allocation since there is no source-level way to // initialize a Builtin.UnsafeValueBuffer type and thus we cannot have a // stored property of that type. let holder: ClassHolder = Builtin.allocWithTailElems_1(self, 1._builtinWordValue, AccessRecord.self) // Initialize the ClassHolder's instance variables. This is done via // withUnsafeMutablePointer(to:) because the instance was just allocated with // allocWithTailElems_1 and so we need to make sure to use an initialization // rather than an assignment. withUnsafeMutablePointer(to: &holder.previous) { $0.initialize(to: previous) } withUnsafeMutablePointer(to: &holder.instance) { $0.initialize(to: instance) } let accessRecordPtr = Builtin.projectTailElems(holder, AccessRecord.self) // Begin a 'modify' access to the address. This access is ended in // ClassHolder's deinitializer. Builtin.beginUnpairedModifyAccess(address._rawValue, accessRecordPtr, type) return holder } deinit { let accessRecordPtr = Builtin.projectTailElems(self, AccessRecord.self) // Ends the access begun in _create(). Builtin.endUnpairedAccess(accessRecordPtr) } } // A class that triggers writeback to a pointer when destroyed. internal final class MutatingWritebackBuffer<CurValue, NewValue> { internal let previous: AnyObject? internal let base: UnsafeMutablePointer<CurValue> internal let set: @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer, Int) -> () internal let argument: UnsafeRawPointer internal let argumentSize: Int internal var value: NewValue deinit { set(value, &base.pointee, argument, argumentSize) } internal init(previous: AnyObject?, base: UnsafeMutablePointer<CurValue>, set: @escaping @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer, Int) -> (), argument: UnsafeRawPointer, argumentSize: Int, value: NewValue) { self.previous = previous self.base = base self.set = set self.argument = argument self.argumentSize = argumentSize self.value = value } } // A class that triggers writeback to a non-mutated value when destroyed. internal final class NonmutatingWritebackBuffer<CurValue, NewValue> { internal let previous: AnyObject? internal let base: CurValue internal let set: @convention(thin) (NewValue, CurValue, UnsafeRawPointer, Int) -> () internal let argument: UnsafeRawPointer internal let argumentSize: Int internal var value: NewValue deinit { set(value, base, argument, argumentSize) } internal init(previous: AnyObject?, base: CurValue, set: @escaping @convention(thin) (NewValue, CurValue, UnsafeRawPointer, Int) -> (), argument: UnsafeRawPointer, argumentSize: Int, value: NewValue) { self.previous = previous self.base = base self.set = set self.argument = argument self.argumentSize = argumentSize self.value = value } } internal typealias KeyPathComputedArgumentLayoutFn = @convention(thin) (_ patternArguments: UnsafeRawPointer?) -> (size: Int, alignmentMask: Int) internal typealias KeyPathComputedArgumentInitializerFn = @convention(thin) (_ patternArguments: UnsafeRawPointer?, _ instanceArguments: UnsafeMutableRawPointer) -> () internal enum KeyPathComputedIDKind { case pointer case storedPropertyIndex case vtableOffset } internal enum KeyPathComputedIDResolution { case resolved case indirectPointer case functionCall } internal struct RawKeyPathComponent { internal init(header: Header, body: UnsafeRawBufferPointer) { self.header = header self.body = body } internal var header: Header internal var body: UnsafeRawBufferPointer internal struct Header { internal static var payloadMask: UInt32 { return _SwiftKeyPathComponentHeader_PayloadMask } internal static var discriminatorMask: UInt32 { return _SwiftKeyPathComponentHeader_DiscriminatorMask } internal static var discriminatorShift: UInt32 { return _SwiftKeyPathComponentHeader_DiscriminatorShift } internal static var externalTag: UInt32 { return _SwiftKeyPathComponentHeader_ExternalTag } internal static var structTag: UInt32 { return _SwiftKeyPathComponentHeader_StructTag } internal static var computedTag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedTag } internal static var classTag: UInt32 { return _SwiftKeyPathComponentHeader_ClassTag } internal static var optionalTag: UInt32 { return _SwiftKeyPathComponentHeader_OptionalTag } internal static var optionalChainPayload: UInt32 { return _SwiftKeyPathComponentHeader_OptionalChainPayload } internal static var optionalWrapPayload: UInt32 { return _SwiftKeyPathComponentHeader_OptionalWrapPayload } internal static var optionalForcePayload: UInt32 { return _SwiftKeyPathComponentHeader_OptionalForcePayload } internal static var endOfReferencePrefixFlag: UInt32 { return _SwiftKeyPathComponentHeader_EndOfReferencePrefixFlag } internal static var storedMutableFlag: UInt32 { return _SwiftKeyPathComponentHeader_StoredMutableFlag } internal static var storedOffsetPayloadMask: UInt32 { return _SwiftKeyPathComponentHeader_StoredOffsetPayloadMask } internal static var outOfLineOffsetPayload: UInt32 { return _SwiftKeyPathComponentHeader_OutOfLineOffsetPayload } internal static var unresolvedFieldOffsetPayload: UInt32 { return _SwiftKeyPathComponentHeader_UnresolvedFieldOffsetPayload } internal static var unresolvedIndirectOffsetPayload: UInt32 { return _SwiftKeyPathComponentHeader_UnresolvedIndirectOffsetPayload } internal static var maximumOffsetPayload: UInt32 { return _SwiftKeyPathComponentHeader_MaximumOffsetPayload } internal var isStoredMutable: Bool { _internalInvariant(kind == .struct || kind == .class) return _value & Header.storedMutableFlag != 0 } internal static var computedMutatingFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedMutatingFlag } internal var isComputedMutating: Bool { _internalInvariant(kind == .computed) return _value & Header.computedMutatingFlag != 0 } internal static var computedSettableFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedSettableFlag } internal var isComputedSettable: Bool { _internalInvariant(kind == .computed) return _value & Header.computedSettableFlag != 0 } internal static var computedIDByStoredPropertyFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDByStoredPropertyFlag } internal static var computedIDByVTableOffsetFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDByVTableOffsetFlag } internal var computedIDKind: KeyPathComputedIDKind { let storedProperty = _value & Header.computedIDByStoredPropertyFlag != 0 let vtableOffset = _value & Header.computedIDByVTableOffsetFlag != 0 switch (storedProperty, vtableOffset) { case (true, true): _internalInvariantFailure("not allowed") case (true, false): return .storedPropertyIndex case (false, true): return .vtableOffset case (false, false): return .pointer } } internal static var computedHasArgumentsFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedHasArgumentsFlag } internal var hasComputedArguments: Bool { _internalInvariant(kind == .computed) return _value & Header.computedHasArgumentsFlag != 0 } // If a computed component is instantiated from an external property // descriptor, and both components carry arguments, we need to carry some // extra matter to be able to map between the client and external generic // contexts. internal static var computedInstantiatedFromExternalWithArgumentsFlag: UInt32 { return _SwiftKeyPathComponentHeader_ComputedInstantiatedFromExternalWithArgumentsFlag } internal var isComputedInstantiatedFromExternalWithArguments: Bool { get { _internalInvariant(kind == .computed) return _value & Header.computedInstantiatedFromExternalWithArgumentsFlag != 0 } set { _internalInvariant(kind == .computed) _value = _value & ~Header.computedInstantiatedFromExternalWithArgumentsFlag | (newValue ? Header.computedInstantiatedFromExternalWithArgumentsFlag : 0) } } internal static var externalWithArgumentsExtraSize: Int { return MemoryLayout<Int>.size } internal static var computedIDResolutionMask: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDResolutionMask } internal static var computedIDResolved: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDResolved } internal static var computedIDUnresolvedIndirectPointer: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedIndirectPointer } internal static var computedIDUnresolvedFunctionCall: UInt32 { return _SwiftKeyPathComponentHeader_ComputedIDUnresolvedFunctionCall } internal var computedIDResolution: KeyPathComputedIDResolution { switch payload & Header.computedIDResolutionMask { case Header.computedIDResolved: return .resolved case Header.computedIDUnresolvedIndirectPointer: return .indirectPointer case Header.computedIDUnresolvedFunctionCall: return .functionCall default: _internalInvariantFailure("invalid key path resolution") } } internal var _value: UInt32 internal var discriminator: UInt32 { get { return (_value & Header.discriminatorMask) >> Header.discriminatorShift } set { let shifted = newValue << Header.discriminatorShift _internalInvariant(shifted & Header.discriminatorMask == shifted, "discriminator doesn't fit") _value = _value & ~Header.discriminatorMask | shifted } } internal var payload: UInt32 { get { return _value & Header.payloadMask } set { _internalInvariant(newValue & Header.payloadMask == newValue, "payload too big") _value = _value & ~Header.payloadMask | newValue } } internal var storedOffsetPayload: UInt32 { get { _internalInvariant(kind == .struct || kind == .class, "not a stored component") return _value & Header.storedOffsetPayloadMask } set { _internalInvariant(kind == .struct || kind == .class, "not a stored component") _internalInvariant(newValue & Header.storedOffsetPayloadMask == newValue, "payload too big") _value = _value & ~Header.storedOffsetPayloadMask | newValue } } internal var endOfReferencePrefix: Bool { get { return _value & Header.endOfReferencePrefixFlag != 0 } set { if newValue { _value |= Header.endOfReferencePrefixFlag } else { _value &= ~Header.endOfReferencePrefixFlag } } } internal var kind: KeyPathComponentKind { switch (discriminator, payload) { case (Header.externalTag, _): return .external case (Header.structTag, _): return .struct case (Header.classTag, _): return .class case (Header.computedTag, _): return .computed case (Header.optionalTag, Header.optionalChainPayload): return .optionalChain case (Header.optionalTag, Header.optionalWrapPayload): return .optionalWrap case (Header.optionalTag, Header.optionalForcePayload): return .optionalForce default: _internalInvariantFailure("invalid header") } } // The component header is 4 bytes, but may be followed by an aligned // pointer field for some kinds of component, forcing padding. internal static var pointerAlignmentSkew: Int { return MemoryLayout<Int>.size - MemoryLayout<Int32>.size } internal var isTrivialPropertyDescriptor: Bool { return _value == _SwiftKeyPathComponentHeader_TrivialPropertyDescriptorMarker } /// If this is the header for a component in a key path pattern, return /// the size of the body of the component. internal var patternComponentBodySize: Int { return _componentBodySize(forPropertyDescriptor: false) } /// If this is the header for a property descriptor, return /// the size of the body of the component. internal var propertyDescriptorBodySize: Int { if isTrivialPropertyDescriptor { return 0 } return _componentBodySize(forPropertyDescriptor: true) } internal func _componentBodySize(forPropertyDescriptor: Bool) -> Int { switch kind { case .struct, .class: if storedOffsetPayload == Header.unresolvedFieldOffsetPayload || storedOffsetPayload == Header.outOfLineOffsetPayload || storedOffsetPayload == Header.unresolvedIndirectOffsetPayload { // A 32-bit offset is stored in the body. return MemoryLayout<UInt32>.size } // Otherwise, there's no body. return 0 case .external: // The body holds a pointer to the external property descriptor, // and some number of substitution arguments, the count of which is // in the payload. return 4 * (1 + Int(payload)) case .computed: // The body holds at minimum the id and getter. var size = 8 // If settable, it also holds the setter. if isComputedSettable { size += 4 } // If there are arguments, there's also a layout function, // witness table, and initializer function. // Property descriptors never carry argument information, though. if !forPropertyDescriptor && hasComputedArguments { size += 12 } return size case .optionalForce, .optionalChain, .optionalWrap: // Otherwise, there's no body. return 0 } } init(discriminator: UInt32, payload: UInt32) { _value = 0 self.discriminator = discriminator self.payload = payload } init(optionalForce: ()) { self.init(discriminator: Header.optionalTag, payload: Header.optionalForcePayload) } init(optionalWrap: ()) { self.init(discriminator: Header.optionalTag, payload: Header.optionalWrapPayload) } init(optionalChain: ()) { self.init(discriminator: Header.optionalTag, payload: Header.optionalChainPayload) } init(stored kind: KeyPathStructOrClass, mutable: Bool, inlineOffset: UInt32) { let discriminator: UInt32 switch kind { case .struct: discriminator = Header.structTag case .class: discriminator = Header.classTag } _internalInvariant(inlineOffset <= Header.maximumOffsetPayload) let payload = inlineOffset | (mutable ? Header.storedMutableFlag : 0) self.init(discriminator: discriminator, payload: payload) } init(storedWithOutOfLineOffset kind: KeyPathStructOrClass, mutable: Bool) { let discriminator: UInt32 switch kind { case .struct: discriminator = Header.structTag case .class: discriminator = Header.classTag } let payload = Header.outOfLineOffsetPayload | (mutable ? Header.storedMutableFlag : 0) self.init(discriminator: discriminator, payload: payload) } init(computedWithIDKind kind: KeyPathComputedIDKind, mutating: Bool, settable: Bool, hasArguments: Bool, instantiatedFromExternalWithArguments: Bool) { let discriminator = Header.computedTag var payload = (mutating ? Header.computedMutatingFlag : 0) | (settable ? Header.computedSettableFlag : 0) | (hasArguments ? Header.computedHasArgumentsFlag : 0) | (instantiatedFromExternalWithArguments ? Header.computedInstantiatedFromExternalWithArgumentsFlag : 0) switch kind { case .pointer: break case .storedPropertyIndex: payload |= Header.computedIDByStoredPropertyFlag case .vtableOffset: payload |= Header.computedIDByVTableOffsetFlag } self.init(discriminator: discriminator, payload: payload) } } internal var bodySize: Int { let ptrSize = MemoryLayout<Int>.size switch header.kind { case .struct, .class: if header.storedOffsetPayload == Header.outOfLineOffsetPayload { return 4 // overflowed } return 0 case .external: _internalInvariantFailure("should be instantiated away") case .optionalChain, .optionalForce, .optionalWrap: return 0 case .computed: // align to pointer, minimum two pointers for id and get var total = Header.pointerAlignmentSkew + ptrSize * 2 // additional word for a setter if header.isComputedSettable { total += ptrSize } // include the argument size if header.hasComputedArguments { // two words for argument header: size, witnesses total += ptrSize * 2 // size of argument area total += _computedArgumentSize if header.isComputedInstantiatedFromExternalWithArguments { total += Header.externalWithArgumentsExtraSize } } return total } } internal var _structOrClassOffset: Int { _internalInvariant(header.kind == .struct || header.kind == .class, "no offset for this kind") // An offset too large to fit inline is represented by a signal and stored // in the body. if header.storedOffsetPayload == Header.outOfLineOffsetPayload { // Offset overflowed into body _internalInvariant(body.count >= MemoryLayout<UInt32>.size, "component not big enough") return Int(body.load(as: UInt32.self)) } return Int(header.storedOffsetPayload) } internal var _computedIDValue: Int { _internalInvariant(header.kind == .computed, "not a computed property") return body.load(fromByteOffset: Header.pointerAlignmentSkew, as: Int.self) } internal var _computedID: ComputedPropertyID { _internalInvariant(header.kind == .computed, "not a computed property") return ComputedPropertyID( value: _computedIDValue, kind: header.computedIDKind) } internal var _computedGetter: UnsafeRawPointer { _internalInvariant(header.kind == .computed, "not a computed property") return body.load( fromByteOffset: Header.pointerAlignmentSkew + MemoryLayout<Int>.size, as: UnsafeRawPointer.self) } internal var _computedSetter: UnsafeRawPointer { _internalInvariant(header.isComputedSettable, "not a settable property") return body.load( fromByteOffset: Header.pointerAlignmentSkew + MemoryLayout<Int>.size * 2, as: UnsafeRawPointer.self) } internal var _computedArgumentHeaderPointer: UnsafeRawPointer { _internalInvariant(header.hasComputedArguments, "no arguments") return body.baseAddress.unsafelyUnwrapped + Header.pointerAlignmentSkew + MemoryLayout<Int>.size * (header.isComputedSettable ? 3 : 2) } internal var _computedArgumentSize: Int { return _computedArgumentHeaderPointer.load(as: Int.self) } internal var _computedArgumentWitnesses: UnsafePointer<ComputedArgumentWitnesses> { return _computedArgumentHeaderPointer.load( fromByteOffset: MemoryLayout<Int>.size, as: UnsafePointer<ComputedArgumentWitnesses>.self) } internal var _computedArguments: UnsafeRawPointer { var base = _computedArgumentHeaderPointer + MemoryLayout<Int>.size * 2 // If the component was instantiated from an external property descriptor // with its own arguments, we include some additional capture info to // be able to map to the original argument context by adjusting the size // passed to the witness operations. if header.isComputedInstantiatedFromExternalWithArguments { base += Header.externalWithArgumentsExtraSize } return base } internal var _computedMutableArguments: UnsafeMutableRawPointer { return UnsafeMutableRawPointer(mutating: _computedArguments) } internal var _computedArgumentWitnessSizeAdjustment: Int { if header.isComputedInstantiatedFromExternalWithArguments { return _computedArguments.load( fromByteOffset: -Header.externalWithArgumentsExtraSize, as: Int.self) } return 0 } internal var value: KeyPathComponent { switch header.kind { case .struct: return .struct(offset: _structOrClassOffset) case .class: return .class(offset: _structOrClassOffset) case .optionalChain: return .optionalChain case .optionalForce: return .optionalForce case .optionalWrap: return .optionalWrap case .computed: let isSettable = header.isComputedSettable let isMutating = header.isComputedMutating let id = _computedID let get = _computedGetter // Argument value is unused if there are no arguments. let argument: KeyPathComponent.ArgumentRef? if header.hasComputedArguments { argument = KeyPathComponent.ArgumentRef( data: UnsafeRawBufferPointer(start: _computedArguments, count: _computedArgumentSize), witnesses: _computedArgumentWitnesses, witnessSizeAdjustment: _computedArgumentWitnessSizeAdjustment) } else { argument = nil } switch (isSettable, isMutating) { case (false, false): return .get(id: id, get: get, argument: argument) case (true, false): return .nonmutatingGetSet(id: id, get: get, set: _computedSetter, argument: argument) case (true, true): return .mutatingGetSet(id: id, get: get, set: _computedSetter, argument: argument) case (false, true): _internalInvariantFailure("impossible") } case .external: _internalInvariantFailure("should have been instantiated away") } } internal func destroy() { switch header.kind { case .struct, .class, .optionalChain, .optionalForce, .optionalWrap: // trivial break case .computed: // Run destructor, if any if header.hasComputedArguments, let destructor = _computedArgumentWitnesses.pointee.destroy { destructor(_computedMutableArguments, _computedArgumentSize - _computedArgumentWitnessSizeAdjustment) } case .external: _internalInvariantFailure("should have been instantiated away") } } internal func clone(into buffer: inout UnsafeMutableRawBufferPointer, endOfReferencePrefix: Bool) { var newHeader = header newHeader.endOfReferencePrefix = endOfReferencePrefix var componentSize = MemoryLayout<Header>.size buffer.storeBytes(of: newHeader, as: Header.self) switch header.kind { case .struct, .class: if header.storedOffsetPayload == Header.outOfLineOffsetPayload { let overflowOffset = body.load(as: UInt32.self) buffer.storeBytes(of: overflowOffset, toByteOffset: 4, as: UInt32.self) componentSize += 4 } case .optionalChain, .optionalForce, .optionalWrap: break case .computed: // Fields are pointer-aligned after the header componentSize += Header.pointerAlignmentSkew buffer.storeBytes(of: _computedIDValue, toByteOffset: componentSize, as: Int.self) componentSize += MemoryLayout<Int>.size buffer.storeBytes(of: _computedGetter, toByteOffset: componentSize, as: UnsafeRawPointer.self) componentSize += MemoryLayout<Int>.size if header.isComputedSettable { buffer.storeBytes(of: _computedSetter, toByteOffset: MemoryLayout<Int>.size * 3, as: UnsafeRawPointer.self) componentSize += MemoryLayout<Int>.size } if header.hasComputedArguments { let arguments = _computedArguments let argumentSize = _computedArgumentSize buffer.storeBytes(of: argumentSize, toByteOffset: componentSize, as: Int.self) componentSize += MemoryLayout<Int>.size buffer.storeBytes(of: _computedArgumentWitnesses, toByteOffset: componentSize, as: UnsafePointer<ComputedArgumentWitnesses>.self) componentSize += MemoryLayout<Int>.size if header.isComputedInstantiatedFromExternalWithArguments { // Include the extra matter for components instantiated from // external property descriptors with arguments. buffer.storeBytes(of: _computedArgumentWitnessSizeAdjustment, toByteOffset: componentSize, as: Int.self) componentSize += MemoryLayout<Int>.size } let adjustedSize = argumentSize - _computedArgumentWitnessSizeAdjustment let argumentDest = buffer.baseAddress.unsafelyUnwrapped + componentSize _computedArgumentWitnesses.pointee.copy( arguments, argumentDest, adjustedSize) if header.isComputedInstantiatedFromExternalWithArguments { // The extra information for external property descriptor arguments // can always be memcpy'd. _memcpy(dest: argumentDest + adjustedSize, src: arguments + adjustedSize, size: UInt(_computedArgumentWitnessSizeAdjustment)) } componentSize += argumentSize } case .external: _internalInvariantFailure("should have been instantiated away") } buffer = UnsafeMutableRawBufferPointer( start: buffer.baseAddress.unsafelyUnwrapped + componentSize, count: buffer.count - componentSize) } internal enum ProjectionResult<NewValue, LeafValue> { /// Continue projecting the key path with the given new value. case `continue`(NewValue) /// Stop projecting the key path and use the given value as the final /// result of the projection. case `break`(LeafValue) internal var assumingContinue: NewValue { switch self { case .continue(let x): return x case .break: _internalInvariantFailure("should not have stopped key path projection") } } } internal func _projectReadOnly<CurValue, NewValue, LeafValue>( _ base: CurValue, to: NewValue.Type, endingWith: LeafValue.Type ) -> ProjectionResult<NewValue, LeafValue> { switch value { case .struct(let offset): var base2 = base return .continue(withUnsafeBytes(of: &base2) { let p = $0.baseAddress.unsafelyUnwrapped.advanced(by: offset) // The contents of the struct should be well-typed, so we can assume // typed memory here. return p.assumingMemoryBound(to: NewValue.self).pointee }) case .class(let offset): _internalInvariant(CurValue.self is AnyObject.Type, "base is not a class") let baseObj = unsafeBitCast(base, to: AnyObject.self) let basePtr = UnsafeRawPointer(Builtin.bridgeToRawPointer(baseObj)) defer { _fixLifetime(baseObj) } let offsetAddress = basePtr.advanced(by: offset) // Perform an instaneous record access on the address in order to // ensure that the read will not conflict with an already in-progress // 'modify' access. Builtin.performInstantaneousReadAccess(offsetAddress._rawValue, NewValue.self) return .continue(offsetAddress .assumingMemoryBound(to: NewValue.self) .pointee) case .get(id: _, get: let rawGet, argument: let argument), .mutatingGetSet(id: _, get: let rawGet, set: _, argument: let argument), .nonmutatingGetSet(id: _, get: let rawGet, set: _, argument: let argument): typealias Getter = @convention(thin) (CurValue, UnsafeRawPointer, Int) -> NewValue let get = unsafeBitCast(rawGet, to: Getter.self) return .continue(get(base, argument?.data.baseAddress ?? rawGet, argument?.data.count ?? 0)) case .optionalChain: _internalInvariant(CurValue.self == Optional<NewValue>.self, "should be unwrapping optional value") _internalInvariant(_isOptional(LeafValue.self), "leaf result should be optional") if let baseValue = unsafeBitCast(base, to: Optional<NewValue>.self) { return .continue(baseValue) } else { // TODO: A more efficient way of getting the `none` representation // of a dynamically-optional type... return .break((Optional<()>.none as Any) as! LeafValue) } case .optionalForce: _internalInvariant(CurValue.self == Optional<NewValue>.self, "should be unwrapping optional value") return .continue(unsafeBitCast(base, to: Optional<NewValue>.self)!) case .optionalWrap: _internalInvariant(NewValue.self == Optional<CurValue>.self, "should be wrapping optional value") return .continue( unsafeBitCast(base as Optional<CurValue>, to: NewValue.self)) } } internal func _projectMutableAddress<CurValue, NewValue>( _ base: UnsafeRawPointer, from _: CurValue.Type, to _: NewValue.Type, isRoot: Bool, keepAlive: inout AnyObject? ) -> UnsafeRawPointer { switch value { case .struct(let offset): return base.advanced(by: offset) case .class(let offset): // A class dereference should only occur at the root of a mutation, // since otherwise it would be part of the reference prefix. _internalInvariant(isRoot, "class component should not appear in the middle of mutation") // AnyObject memory can alias any class reference memory, so we can // assume type here let object = base.assumingMemoryBound(to: AnyObject.self).pointee let offsetAddress = UnsafeRawPointer(Builtin.bridgeToRawPointer(object)) .advanced(by: offset) // Keep the base alive for the duration of the derived access and also // enforce exclusive access to the address. keepAlive = ClassHolder._create(previous: keepAlive, instance: object, accessingAddress: offsetAddress, type: NewValue.self) return offsetAddress case .mutatingGetSet(id: _, get: let rawGet, set: let rawSet, argument: let argument): typealias Getter = @convention(thin) (CurValue, UnsafeRawPointer, Int) -> NewValue typealias Setter = @convention(thin) (NewValue, inout CurValue, UnsafeRawPointer, Int) -> () let get = unsafeBitCast(rawGet, to: Getter.self) let set = unsafeBitCast(rawSet, to: Setter.self) let baseTyped = UnsafeMutablePointer( mutating: base.assumingMemoryBound(to: CurValue.self)) let argValue = argument?.data.baseAddress ?? rawGet let argSize = argument?.data.count ?? 0 let writeback = MutatingWritebackBuffer(previous: keepAlive, base: baseTyped, set: set, argument: argValue, argumentSize: argSize, value: get(baseTyped.pointee, argValue, argSize)) keepAlive = writeback // A maximally-abstracted, final, stored class property should have // a stable address. return UnsafeRawPointer(Builtin.addressof(&writeback.value)) case .nonmutatingGetSet(id: _, get: let rawGet, set: let rawSet, argument: let argument): // A nonmutating property should only occur at the root of a mutation, // since otherwise it would be part of the reference prefix. _internalInvariant(isRoot, "nonmutating component should not appear in the middle of mutation") typealias Getter = @convention(thin) (CurValue, UnsafeRawPointer, Int) -> NewValue typealias Setter = @convention(thin) (NewValue, CurValue, UnsafeRawPointer, Int) -> () let get = unsafeBitCast(rawGet, to: Getter.self) let set = unsafeBitCast(rawSet, to: Setter.self) let baseValue = base.assumingMemoryBound(to: CurValue.self).pointee let argValue = argument?.data.baseAddress ?? rawGet let argSize = argument?.data.count ?? 0 let writeback = NonmutatingWritebackBuffer(previous: keepAlive, base: baseValue, set: set, argument: argValue, argumentSize: argSize, value: get(baseValue, argValue, argSize)) keepAlive = writeback // A maximally-abstracted, final, stored class property should have // a stable address. return UnsafeRawPointer(Builtin.addressof(&writeback.value)) case .optionalForce: _internalInvariant(CurValue.self == Optional<NewValue>.self, "should be unwrapping an optional value") // Optional's layout happens to always put the payload at the start // address of the Optional value itself, if a value is present at all. let baseOptionalPointer = base.assumingMemoryBound(to: Optional<NewValue>.self) // Assert that a value exists _ = baseOptionalPointer.pointee! return base case .optionalChain, .optionalWrap, .get: _internalInvariantFailure("not a mutable key path component") } } } internal func _pop<T>(from: inout UnsafeRawBufferPointer, as type: T.Type) -> T { let buffer = _pop(from: &from, as: type, count: 1) return buffer.baseAddress.unsafelyUnwrapped.pointee } internal func _pop<T>(from: inout UnsafeRawBufferPointer, as: T.Type, count: Int) -> UnsafeBufferPointer<T> { _internalInvariant(_isPOD(T.self), "should be POD") from = MemoryLayout<T>._roundingUpBaseToAlignment(from) let byteCount = MemoryLayout<T>.stride * count let result = UnsafeBufferPointer( start: from.baseAddress.unsafelyUnwrapped.assumingMemoryBound(to: T.self), count: count) from = UnsafeRawBufferPointer( start: from.baseAddress.unsafelyUnwrapped + byteCount, count: from.count - byteCount) return result } internal struct KeyPathBuffer { internal var data: UnsafeRawBufferPointer internal var trivial: Bool internal var hasReferencePrefix: Bool internal var mutableData: UnsafeMutableRawBufferPointer { return UnsafeMutableRawBufferPointer(mutating: data) } internal struct Header { internal var _value: UInt32 internal static var sizeMask: UInt32 { return _SwiftKeyPathBufferHeader_SizeMask } internal static var reservedMask: UInt32 { return _SwiftKeyPathBufferHeader_ReservedMask } internal static var trivialFlag: UInt32 { return _SwiftKeyPathBufferHeader_TrivialFlag } internal static var hasReferencePrefixFlag: UInt32 { return _SwiftKeyPathBufferHeader_HasReferencePrefixFlag } internal init(size: Int, trivial: Bool, hasReferencePrefix: Bool) { _internalInvariant(size <= Int(Header.sizeMask), "key path too big") _value = UInt32(size) | (trivial ? Header.trivialFlag : 0) | (hasReferencePrefix ? Header.hasReferencePrefixFlag : 0) } internal var size: Int { return Int(_value & Header.sizeMask) } internal var trivial: Bool { return _value & Header.trivialFlag != 0 } internal var hasReferencePrefix: Bool { get { return _value & Header.hasReferencePrefixFlag != 0 } set { if newValue { _value |= Header.hasReferencePrefixFlag } else { _value &= ~Header.hasReferencePrefixFlag } } } // In a key path pattern, the "trivial" flag is used to indicate // "instantiable in-line" internal var instantiableInLine: Bool { return trivial } internal func validateReservedBits() { _precondition(_value & Header.reservedMask == 0, "Reserved bits set to an unexpected bit pattern") } } internal init(base: UnsafeRawPointer) { let header = base.load(as: Header.self) data = UnsafeRawBufferPointer( start: base + MemoryLayout<Int>.size, count: header.size) trivial = header.trivial hasReferencePrefix = header.hasReferencePrefix } internal init(partialData: UnsafeRawBufferPointer, trivial: Bool = false, hasReferencePrefix: Bool = false) { self.data = partialData self.trivial = trivial self.hasReferencePrefix = hasReferencePrefix } internal func destroy() { // Short-circuit if nothing in the object requires destruction. if trivial { return } var bufferToDestroy = self while true { let (component, type) = bufferToDestroy.next() component.destroy() guard let _ = type else { break } } } internal mutating func next() -> (RawKeyPathComponent, Any.Type?) { let header = _pop(from: &data, as: RawKeyPathComponent.Header.self) // Track if this is the last component of the reference prefix. if header.endOfReferencePrefix { _internalInvariant(self.hasReferencePrefix, "beginMutation marker in non-reference-writable key path?") self.hasReferencePrefix = false } var component = RawKeyPathComponent(header: header, body: data) // Shrinkwrap the component buffer size. let size = component.bodySize component.body = UnsafeRawBufferPointer(start: component.body.baseAddress, count: size) _ = _pop(from: &data, as: Int8.self, count: size) // fetch type, which is in the buffer unless it's the final component let nextType: Any.Type? if data.isEmpty { nextType = nil } else { nextType = _pop(from: &data, as: Any.Type.self) } return (component, nextType) } } // MARK: Library intrinsics for projecting key paths. @_silgen_name("swift_getAtPartialKeyPath") public // COMPILER_INTRINSIC func _getAtPartialKeyPath<Root>( root: Root, keyPath: PartialKeyPath<Root> ) -> Any { func open<Value>(_: Value.Type) -> Any { return _getAtKeyPath(root: root, keyPath: unsafeDowncast(keyPath, to: KeyPath<Root, Value>.self)) } return _openExistential(type(of: keyPath).valueType, do: open) } @_silgen_name("swift_getAtAnyKeyPath") public // COMPILER_INTRINSIC func _getAtAnyKeyPath<RootValue>( root: RootValue, keyPath: AnyKeyPath ) -> Any? { let (keyPathRoot, keyPathValue) = type(of: keyPath)._rootAndValueType func openRoot<KeyPathRoot>(_: KeyPathRoot.Type) -> Any? { guard let rootForKeyPath = root as? KeyPathRoot else { return nil } func openValue<Value>(_: Value.Type) -> Any { return _getAtKeyPath(root: rootForKeyPath, keyPath: unsafeDowncast(keyPath, to: KeyPath<KeyPathRoot, Value>.self)) } return _openExistential(keyPathValue, do: openValue) } return _openExistential(keyPathRoot, do: openRoot) } @_silgen_name("swift_getAtKeyPath") public // COMPILER_INTRINSIC func _getAtKeyPath<Root, Value>( root: Root, keyPath: KeyPath<Root, Value> ) -> Value { return keyPath._projectReadOnly(from: root) } // The release that ends the access scope is guaranteed to happen // immediately at the end_apply call because the continuation is a // runtime call with a manual release (access scopes cannot be extended). @_silgen_name("_swift_modifyAtWritableKeyPath_impl") public // runtime entrypoint func _modifyAtWritableKeyPath_impl<Root, Value>( root: inout Root, keyPath: WritableKeyPath<Root, Value> ) -> (UnsafeMutablePointer<Value>, AnyObject?) { return keyPath._projectMutableAddress(from: &root) } // The release that ends the access scope is guaranteed to happen // immediately at the end_apply call because the continuation is a // runtime call with a manual release (access scopes cannot be extended). @_silgen_name("_swift_modifyAtReferenceWritableKeyPath_impl") public // runtime entrypoint func _modifyAtReferenceWritableKeyPath_impl<Root, Value>( root: Root, keyPath: ReferenceWritableKeyPath<Root, Value> ) -> (UnsafeMutablePointer<Value>, AnyObject?) { return keyPath._projectMutableAddress(from: root) } @_silgen_name("swift_setAtWritableKeyPath") public // COMPILER_INTRINSIC func _setAtWritableKeyPath<Root, Value>( root: inout Root, keyPath: WritableKeyPath<Root, Value>, value: __owned Value ) { // TODO: we should be able to do this more efficiently than projecting. let (addr, owner) = keyPath._projectMutableAddress(from: &root) addr.pointee = value _fixLifetime(owner) // FIXME: this needs a deallocation barrier to ensure that the // release isn't extended, along with the access scope. } @_silgen_name("swift_setAtReferenceWritableKeyPath") public // COMPILER_INTRINSIC func _setAtReferenceWritableKeyPath<Root, Value>( root: Root, keyPath: ReferenceWritableKeyPath<Root, Value>, value: __owned Value ) { // TODO: we should be able to do this more efficiently than projecting. let (addr, owner) = keyPath._projectMutableAddress(from: root) addr.pointee = value _fixLifetime(owner) // FIXME: this needs a deallocation barrier to ensure that the // release isn't extended, along with the access scope. } // MARK: Appending type system // FIXME(ABI): The type relationships between KeyPath append operands are tricky // and don't interact well with our overriding rules. Hack things by injecting // a bunch of `appending` overloads as protocol extensions so they aren't // constrained by being overrides, and so that we can use exact-type constraints // on `Self` to prevent dynamically-typed methods from being inherited by // statically-typed key paths. /// An implementation detail of key path expressions; do not use this protocol /// directly. @_show_in_interface public protocol _AppendKeyPath {} extension _AppendKeyPath where Self == AnyKeyPath { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Appending the key path passed as `path` is successful only if the /// root type for `path` matches this key path's value type. This example /// creates key paths from `Array<Int>` to `String` and from `String` to /// `Int`, and then tries appending each to the other: /// /// let arrayDescription: AnyKeyPath = \Array<Int>.description /// let stringLength: AnyKeyPath = \String.count /// /// // Creates a key path from `Array<Int>` to `Int` /// let arrayDescriptionLength = arrayDescription.appending(path: stringLength) /// /// let invalidKeyPath = stringLength.appending(path: arrayDescription) /// // invalidKeyPath == nil /// /// The second call to `appending(path:)` returns `nil` /// because the root type of `arrayDescription`, `Array<Int>`, does not /// match the value type of `stringLength`, `Int`. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path and the value type /// of `path`, if `path` can be appended. If `path` can't be appended, /// returns `nil`. @inlinable public func appending(path: AnyKeyPath) -> AnyKeyPath? { return _tryToAppendKeyPaths(root: self, leaf: path) } } extension _AppendKeyPath /* where Self == PartialKeyPath<T> */ { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Appending the key path passed as `path` is successful only if the /// root type for `path` matches this key path's value type. This example /// creates key paths from `Array<Int>` to `String` and from `String` to /// `Int`, and then tries appending each to the other: /// /// let arrayDescription: PartialKeyPath<Array<Int>> = \.description /// let stringLength: PartialKeyPath<String> = \.count /// /// // Creates a key path from `Array<Int>` to `Int` /// let arrayDescriptionLength = arrayDescription.appending(path: stringLength) /// /// let invalidKeyPath = stringLength.appending(path: arrayDescription) /// // invalidKeyPath == nil /// /// The second call to `appending(path:)` returns `nil` /// because the root type of `arrayDescription`, `Array<Int>`, does not /// match the value type of `stringLength`, `Int`. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path and the value type /// of `path`, if `path` can be appended. If `path` can't be appended, /// returns `nil`. @inlinable public func appending<Root>(path: AnyKeyPath) -> PartialKeyPath<Root>? where Self == PartialKeyPath<Root> { return _tryToAppendKeyPaths(root: self, leaf: path) } /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Appending the key path passed as `path` is successful only if the /// root type for `path` matches this key path's value type. This example /// creates a key path from `Array<Int>` to `String`, and then tries /// appending compatible and incompatible key paths: /// /// let arrayDescription: PartialKeyPath<Array<Int>> = \.description /// /// // Creates a key path from `Array<Int>` to `Int` /// let arrayDescriptionLength = arrayDescription.appending(path: \String.count) /// /// let invalidKeyPath = arrayDescription.appending(path: \Double.isZero) /// // invalidKeyPath == nil /// /// The second call to `appending(path:)` returns `nil` because the root type /// of the `path` parameter, `Double`, does not match the value type of /// `arrayDescription`, `String`. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type /// of `path`, if `path` can be appended. If `path` can't be appended, /// returns `nil`. @inlinable public func appending<Root, AppendedRoot, AppendedValue>( path: KeyPath<AppendedRoot, AppendedValue> ) -> KeyPath<Root, AppendedValue>? where Self == PartialKeyPath<Root> { return _tryToAppendKeyPaths(root: self, leaf: path) } /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Appending the key path passed as `path` is successful only if the /// root type for `path` matches this key path's value type. /// /// - Parameter path: The reference writeable key path to append. /// - Returns: A key path from the root of this key path to the value type /// of `path`, if `path` can be appended. If `path` can't be appended, /// returns `nil`. @inlinable public func appending<Root, AppendedRoot, AppendedValue>( path: ReferenceWritableKeyPath<AppendedRoot, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue>? where Self == PartialKeyPath<Root> { return _tryToAppendKeyPaths(root: self, leaf: path) } } extension _AppendKeyPath /* where Self == KeyPath<T,U> */ { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. In the following /// example, `keyPath1` and `keyPath2` are equivalent: /// /// let arrayDescription = \Array<Int>.description /// let keyPath1 = arrayDescription.appending(path: \String.count) /// /// let keyPath2 = \Array<Int>.description.count /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @inlinable public func appending<Root, Value, AppendedValue>( path: KeyPath<Value, AppendedValue> ) -> KeyPath<Root, AppendedValue> where Self: KeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } /* TODO public func appending<Root, Value, Leaf>( path: Leaf, // FIXME: Satisfy "Value generic param not used in signature" constraint _: Value.Type = Value.self ) -> PartialKeyPath<Root>? where Self: KeyPath<Root, Value>, Leaf == AnyKeyPath { return _tryToAppendKeyPaths(root: self, leaf: path) } */ /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @inlinable public func appending<Root, Value, AppendedValue>( path: ReferenceWritableKeyPath<Value, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue> where Self == KeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } } extension _AppendKeyPath /* where Self == WritableKeyPath<T,U> */ { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @inlinable public func appending<Root, Value, AppendedValue>( path: WritableKeyPath<Value, AppendedValue> ) -> WritableKeyPath<Root, AppendedValue> where Self == WritableKeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @inlinable public func appending<Root, Value, AppendedValue>( path: ReferenceWritableKeyPath<Value, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue> where Self == WritableKeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } } extension _AppendKeyPath /* where Self == ReferenceWritableKeyPath<T,U> */ { /// Returns a new key path created by appending the given key path to this /// one. /// /// Use this method to extend this key path to the value type of another key /// path. Calling `appending(path:)` results in the same key path as if the /// given key path had been specified using dot notation. /// /// - Parameter path: The key path to append. /// - Returns: A key path from the root of this key path to the value type of /// `path`. @inlinable public func appending<Root, Value, AppendedValue>( path: WritableKeyPath<Value, AppendedValue> ) -> ReferenceWritableKeyPath<Root, AppendedValue> where Self == ReferenceWritableKeyPath<Root, Value> { return _appendingKeyPaths(root: self, leaf: path) } } @usableFromInline internal func _tryToAppendKeyPaths<Result: AnyKeyPath>( root: AnyKeyPath, leaf: AnyKeyPath ) -> Result? { let (rootRoot, rootValue) = type(of: root)._rootAndValueType let (leafRoot, leafValue) = type(of: leaf)._rootAndValueType if rootValue != leafRoot { return nil } func open<Root>(_: Root.Type) -> Result { func open2<Value>(_: Value.Type) -> Result { func open3<AppendedValue>(_: AppendedValue.Type) -> Result { let typedRoot = unsafeDowncast(root, to: KeyPath<Root, Value>.self) let typedLeaf = unsafeDowncast(leaf, to: KeyPath<Value, AppendedValue>.self) let result = _appendingKeyPaths(root: typedRoot, leaf: typedLeaf) return unsafeDowncast(result, to: Result.self) } return _openExistential(leafValue, do: open3) } return _openExistential(rootValue, do: open2) } return _openExistential(rootRoot, do: open) } @usableFromInline internal func _appendingKeyPaths< Root, Value, AppendedValue, Result: KeyPath<Root, AppendedValue> >( root: KeyPath<Root, Value>, leaf: KeyPath<Value, AppendedValue> ) -> Result { let resultTy = type(of: root).appendedType(with: type(of: leaf)) return root.withBuffer { var rootBuffer = $0 return leaf.withBuffer { var leafBuffer = $0 // If either operand is the identity key path, then we should return // the other operand back untouched. if leafBuffer.data.isEmpty { return unsafeDowncast(root, to: Result.self) } if rootBuffer.data.isEmpty { return unsafeDowncast(leaf, to: Result.self) } // Reserve room for the appended KVC string, if both key paths are // KVC-compatible. let appendedKVCLength: Int, rootKVCLength: Int, leafKVCLength: Int if let rootPtr = root._kvcKeyPathStringPtr, let leafPtr = leaf._kvcKeyPathStringPtr { rootKVCLength = Int(_swift_stdlib_strlen(rootPtr)) leafKVCLength = Int(_swift_stdlib_strlen(leafPtr)) // root + "." + leaf appendedKVCLength = rootKVCLength + 1 + leafKVCLength + 1 } else { rootKVCLength = 0 leafKVCLength = 0 appendedKVCLength = 0 } // Result buffer has room for both key paths' components, plus the // header, plus space for the middle type. // Align up the root so that we can put the component type after it. let rootSize = MemoryLayout<Int>._roundingUpToAlignment(rootBuffer.data.count) let resultSize = rootSize + leafBuffer.data.count + 2 * MemoryLayout<Int>.size // Tail-allocate space for the KVC string. let totalResultSize = MemoryLayout<Int32> ._roundingUpToAlignment(resultSize + appendedKVCLength) var kvcStringBuffer: UnsafeMutableRawPointer? = nil let result = resultTy._create(capacityInBytes: totalResultSize) { var destBuffer = $0 // Remember where the tail-allocated KVC string buffer begins. if appendedKVCLength > 0 { kvcStringBuffer = destBuffer.baseAddress.unsafelyUnwrapped .advanced(by: resultSize) destBuffer = .init(start: destBuffer.baseAddress, count: resultSize) } func pushRaw(size: Int, alignment: Int) -> UnsafeMutableRawBufferPointer { var baseAddress = destBuffer.baseAddress.unsafelyUnwrapped var misalign = Int(bitPattern: baseAddress) % alignment if misalign != 0 { misalign = alignment - misalign baseAddress = baseAddress.advanced(by: misalign) } let result = UnsafeMutableRawBufferPointer( start: baseAddress, count: size) destBuffer = UnsafeMutableRawBufferPointer( start: baseAddress + size, count: destBuffer.count - size - misalign) return result } func push<T>(_ value: T) { let buf = pushRaw(size: MemoryLayout<T>.size, alignment: MemoryLayout<T>.alignment) buf.storeBytes(of: value, as: T.self) } // Save space for the header. let leafIsReferenceWritable = type(of: leaf).kind == .reference let header = KeyPathBuffer.Header( size: resultSize - MemoryLayout<Int>.size, trivial: rootBuffer.trivial && leafBuffer.trivial, hasReferencePrefix: rootBuffer.hasReferencePrefix || leafIsReferenceWritable ) push(header) // Start the components at pointer alignment _ = pushRaw(size: RawKeyPathComponent.Header.pointerAlignmentSkew, alignment: 4) let leafHasReferencePrefix = leafBuffer.hasReferencePrefix // Clone the root components into the buffer. while true { let (component, type) = rootBuffer.next() let isLast = type == nil // If the leaf appended path has a reference prefix, then the // entire root is part of the reference prefix. let endOfReferencePrefix: Bool if leafHasReferencePrefix { endOfReferencePrefix = false } else if isLast && leafIsReferenceWritable { endOfReferencePrefix = true } else { endOfReferencePrefix = component.header.endOfReferencePrefix } component.clone( into: &destBuffer, endOfReferencePrefix: endOfReferencePrefix) if let type = type { push(type) } else { // Insert our endpoint type between the root and leaf components. push(Value.self as Any.Type) break } } // Clone the leaf components into the buffer. while true { let (component, type) = leafBuffer.next() component.clone( into: &destBuffer, endOfReferencePrefix: component.header.endOfReferencePrefix) if let type = type { push(type) } else { break } } _internalInvariant(destBuffer.isEmpty, "did not fill entire result buffer") } // Build the KVC string if there is one. if let kvcStringBuffer = kvcStringBuffer { let rootPtr = root._kvcKeyPathStringPtr.unsafelyUnwrapped let leafPtr = leaf._kvcKeyPathStringPtr.unsafelyUnwrapped _memcpy(dest: kvcStringBuffer, src: rootPtr, size: UInt(rootKVCLength)) kvcStringBuffer.advanced(by: rootKVCLength) .storeBytes(of: 0x2E /* '.' */, as: CChar.self) _memcpy(dest: kvcStringBuffer.advanced(by: rootKVCLength + 1), src: leafPtr, size: UInt(leafKVCLength)) result._kvcKeyPathStringPtr = UnsafePointer(kvcStringBuffer.assumingMemoryBound(to: CChar.self)) kvcStringBuffer.advanced(by: rootKVCLength + leafKVCLength + 1) .storeBytes(of: 0 /* '\0' */, as: CChar.self) } return unsafeDowncast(result, to: Result.self) } } } // The distance in bytes from the address point of a KeyPath object to its // buffer header. Includes the size of the Swift heap object header and the // pointer to the KVC string. internal var keyPathObjectHeaderSize: Int { return MemoryLayout<HeapObject>.size + MemoryLayout<Int>.size } internal var keyPathPatternHeaderSize: Int { return 16 } // Runtime entry point to instantiate a key path object. // Note that this has a compatibility override shim in the runtime so that // future compilers can backward-deploy support for instantiating new key path // pattern features. @_cdecl("swift_getKeyPathImpl") public func _swift_getKeyPath(pattern: UnsafeMutableRawPointer, arguments: UnsafeRawPointer) -> UnsafeRawPointer { // The key path pattern is laid out like a key path object, with a few // modifications: // - Pointers in the instantiated object are compressed into 32-bit // relative offsets in the pattern. // - The pattern begins with a field that's either zero, for a pattern that // depends on instantiation arguments, or that's a relative reference to // a global mutable pointer variable, which can be initialized to a single // shared instantiation of this pattern. // - Instead of the two-word object header with isa and refcount, two // pointers to metadata accessors are provided for the root and leaf // value types of the key path. // - Components may have unresolved forms that require instantiation. // - Type metadata and protocol conformance pointers are replaced with // relative-referenced accessor functions that instantiate the // needed generic argument when called. // // The pattern never precomputes the capabilities of the key path (readonly/ // writable/reference-writable), nor does it encode the reference prefix. // These are resolved dynamically, so that they always reflect the dynamic // capability of the properties involved. let oncePtrPtr = pattern let patternPtr = pattern.advanced(by: 4) let bufferHeader = patternPtr.load(fromByteOffset: keyPathPatternHeaderSize, as: KeyPathBuffer.Header.self) bufferHeader.validateReservedBits() // If the first word is nonzero, it relative-references a cache variable // we can use to reference a single shared instantiation of this key path. let oncePtrOffset = oncePtrPtr.load(as: Int32.self) let oncePtr: UnsafeRawPointer? if oncePtrOffset != 0 { let theOncePtr = _resolveRelativeAddress(oncePtrPtr, oncePtrOffset) oncePtr = theOncePtr // See whether we already instantiated this key path. // This is a non-atomic load because the instantiated pointer will be // written with a release barrier, and loads of the instantiated key path // ought to carry a dependency through this loaded pointer. let existingInstance = theOncePtr.load(as: UnsafeRawPointer?.self) if let existingInstance = existingInstance { // Return the instantiated object at +1. let object = Unmanaged<AnyKeyPath>.fromOpaque(existingInstance) // TODO: This retain will be unnecessary once we support global objects // with inert refcounting. _ = object.retain() return existingInstance } } else { oncePtr = nil } // Instantiate a new key path object modeled on the pattern. // Do a pass to determine the class of the key path we'll be instantiating // and how much space we'll need for it. let (keyPathClass, rootType, size, _) = _getKeyPathClassAndInstanceSizeFromPattern(patternPtr, arguments) // Allocate the instance. let instance = keyPathClass._create(capacityInBytes: size) { instanceData in // Instantiate the pattern into the instance. _instantiateKeyPathBuffer(patternPtr, instanceData, rootType, arguments) } // Adopt the KVC string from the pattern. let kvcStringBase = patternPtr.advanced(by: 12) let kvcStringOffset = kvcStringBase.load(as: Int32.self) if kvcStringOffset == 0 { // Null pointer. instance._kvcKeyPathStringPtr = nil } else { let kvcStringPtr = _resolveRelativeAddress(kvcStringBase, kvcStringOffset) instance._kvcKeyPathStringPtr = kvcStringPtr.assumingMemoryBound(to: CChar.self) } // If we can cache this instance as a shared instance, do so. if let oncePtr = oncePtr { // Try to replace a null pointer in the cache variable with the instance // pointer. let instancePtr = Unmanaged.passRetained(instance) while true { let (oldValue, won) = Builtin.cmpxchg_seqcst_seqcst_Word( oncePtr._rawValue, 0._builtinWordValue, UInt(bitPattern: instancePtr.toOpaque())._builtinWordValue) // If the exchange succeeds, then the instance we formed is the canonical // one. if Bool(won) { break } // Otherwise, someone raced with us to instantiate the key path pattern // and won. Their instance should be just as good as ours, so we can take // that one and let ours get deallocated. if let existingInstance = UnsafeRawPointer(bitPattern: Int(oldValue)) { // Return the instantiated object at +1. let object = Unmanaged<AnyKeyPath>.fromOpaque(existingInstance) // TODO: This retain will be unnecessary once we support global objects // with inert refcounting. _ = object.retain() // Release the instance we created. instancePtr.release() return existingInstance } else { // Try the cmpxchg again if it spuriously failed. continue } } } return UnsafeRawPointer(Unmanaged.passRetained(instance).toOpaque()) } // A reference to metadata, which is a pointer to a mangled name. internal typealias MetadataReference = UnsafeRawPointer // Determine the length of the given mangled name. internal func _getSymbolicMangledNameLength(_ base: UnsafeRawPointer) -> Int { var end = base while let current = Optional(end.load(as: UInt8.self)), current != 0 { // Skip the current character end = end + 1 // Skip over a symbolic reference if current >= 0x1 && current <= 0x17 { end += 4 } else if current >= 0x18 && current <= 0x1F { end += MemoryLayout<Int>.size } } return end - base } // Resolve a mangled name in a generic environment, described by either a // flat GenericEnvironment * (if the bottom tag bit is 0) or possibly-nested // ContextDescriptor * (if the bottom tag bit is 1) internal func _getTypeByMangledNameInEnvironmentOrContext( _ name: UnsafePointer<UInt8>, _ nameLength: UInt, genericEnvironmentOrContext: UnsafeRawPointer?, genericArguments: UnsafeRawPointer?) -> Any.Type? { let taggedPointer = UInt(bitPattern: genericEnvironmentOrContext) if taggedPointer & 1 == 0 { return _getTypeByMangledNameInEnvironment(name, nameLength, genericEnvironment: genericEnvironmentOrContext, genericArguments: genericArguments) } else { let context = UnsafeRawPointer(bitPattern: taggedPointer & ~1) return _getTypeByMangledNameInContext(name, nameLength, genericContext: context, genericArguments: genericArguments) } } // Resolve the given generic argument reference to a generic argument. internal func _resolveKeyPathGenericArgReference( _ reference: UnsafeRawPointer, genericEnvironment: UnsafeRawPointer?, arguments: UnsafeRawPointer?) -> UnsafeRawPointer { // If the low bit is clear, it's a direct reference to the argument. if (UInt(bitPattern: reference) & 0x01 == 0) { return reference } // Adjust the reference. let referenceStart = reference - 1 let nameLength = _getSymbolicMangledNameLength(referenceStart) let namePtr = referenceStart.bindMemory(to: UInt8.self, capacity: nameLength + 1) // FIXME: Could extract this information from the mangled name. guard let result = _getTypeByMangledNameInEnvironmentOrContext(namePtr, UInt(nameLength), genericEnvironmentOrContext: genericEnvironment, genericArguments: arguments) else { let nameStr = String._fromUTF8Repairing( UnsafeBufferPointer(start: namePtr, count: nameLength) ).0 fatalError("could not demangle keypath type from '\(nameStr)'") } return unsafeBitCast(result, to: UnsafeRawPointer.self) } // Resolve the given metadata reference to (type) metadata. internal func _resolveKeyPathMetadataReference( _ reference: UnsafeRawPointer, genericEnvironment: UnsafeRawPointer?, arguments: UnsafeRawPointer?) -> Any.Type { return unsafeBitCast( _resolveKeyPathGenericArgReference( reference, genericEnvironment: genericEnvironment, arguments: arguments), to: Any.Type.self) } internal enum KeyPathStructOrClass { case `struct`, `class` } internal enum KeyPathPatternStoredOffset { case inline(UInt32) case outOfLine(UInt32) case unresolvedFieldOffset(UInt32) case unresolvedIndirectOffset(UnsafePointer<UInt>) } internal struct KeyPathPatternComputedArguments { var getLayout: KeyPathComputedArgumentLayoutFn var witnesses: UnsafePointer<ComputedArgumentWitnesses> var initializer: KeyPathComputedArgumentInitializerFn } internal protocol KeyPathPatternVisitor { mutating func visitHeader(genericEnvironment: UnsafeRawPointer?, rootMetadataRef: MetadataReference, leafMetadataRef: MetadataReference, kvcCompatibilityString: UnsafeRawPointer?) mutating func visitStoredComponent(kind: KeyPathStructOrClass, mutable: Bool, offset: KeyPathPatternStoredOffset) mutating func visitComputedComponent(mutating: Bool, idKind: KeyPathComputedIDKind, idResolution: KeyPathComputedIDResolution, idValueBase: UnsafeRawPointer, idValue: Int32, getter: UnsafeRawPointer, setter: UnsafeRawPointer?, arguments: KeyPathPatternComputedArguments?, externalArgs: UnsafeBufferPointer<Int32>?) mutating func visitOptionalChainComponent() mutating func visitOptionalForceComponent() mutating func visitOptionalWrapComponent() mutating func visitIntermediateComponentType(metadataRef: MetadataReference) mutating func finish() } internal func _resolveRelativeAddress(_ base: UnsafeRawPointer, _ offset: Int32) -> UnsafeRawPointer { // Sign-extend the offset to pointer width and add with wrap on overflow. return UnsafeRawPointer(bitPattern: Int(bitPattern: base) &+ Int(offset)) .unsafelyUnwrapped } internal func _resolveRelativeIndirectableAddress(_ base: UnsafeRawPointer, _ offset: Int32) -> UnsafeRawPointer { // Low bit indicates whether the reference is indirected or not. if offset & 1 != 0 { let ptrToPtr = _resolveRelativeAddress(base, offset - 1) return ptrToPtr.load(as: UnsafeRawPointer.self) } return _resolveRelativeAddress(base, offset) } internal func _loadRelativeAddress<T>(at: UnsafeRawPointer, fromByteOffset: Int = 0, as: T.Type) -> T { let offset = at.load(fromByteOffset: fromByteOffset, as: Int32.self) return unsafeBitCast(_resolveRelativeAddress(at + fromByteOffset, offset), to: T.self) } internal func _walkKeyPathPattern<W: KeyPathPatternVisitor>( _ pattern: UnsafeRawPointer, walker: inout W) { // Visit the header. let genericEnvironment = _loadRelativeAddress(at: pattern, as: UnsafeRawPointer.self) let rootMetadataRef = _loadRelativeAddress(at: pattern, fromByteOffset: 4, as: MetadataReference.self) let leafMetadataRef = _loadRelativeAddress(at: pattern, fromByteOffset: 8, as: MetadataReference.self) let kvcString = _loadRelativeAddress(at: pattern, fromByteOffset: 12, as: UnsafeRawPointer.self) walker.visitHeader(genericEnvironment: genericEnvironment, rootMetadataRef: rootMetadataRef, leafMetadataRef: leafMetadataRef, kvcCompatibilityString: kvcString) func visitStored(header: RawKeyPathComponent.Header, componentBuffer: inout UnsafeRawBufferPointer) { // Decode a stored property. A small offset may be stored inline in the // header word, or else be stored out-of-line, or need instantiation of some // kind. let offset: KeyPathPatternStoredOffset switch header.storedOffsetPayload { case RawKeyPathComponent.Header.outOfLineOffsetPayload: offset = .outOfLine(_pop(from: &componentBuffer, as: UInt32.self)) case RawKeyPathComponent.Header.unresolvedFieldOffsetPayload: offset = .unresolvedFieldOffset(_pop(from: &componentBuffer, as: UInt32.self)) case RawKeyPathComponent.Header.unresolvedIndirectOffsetPayload: let base = componentBuffer.baseAddress.unsafelyUnwrapped let relativeOffset = _pop(from: &componentBuffer, as: Int32.self) let ptr = _resolveRelativeIndirectableAddress(base, relativeOffset) offset = .unresolvedIndirectOffset( ptr.assumingMemoryBound(to: UInt.self)) default: offset = .inline(header.storedOffsetPayload) } let kind: KeyPathStructOrClass = header.kind == .struct ? .struct : .class walker.visitStoredComponent(kind: kind, mutable: header.isStoredMutable, offset: offset) } func popComputedAccessors(header: RawKeyPathComponent.Header, componentBuffer: inout UnsafeRawBufferPointer) -> (idValueBase: UnsafeRawPointer, idValue: Int32, getter: UnsafeRawPointer, setter: UnsafeRawPointer?) { let idValueBase = componentBuffer.baseAddress.unsafelyUnwrapped let idValue = _pop(from: &componentBuffer, as: Int32.self) let getterBase = componentBuffer.baseAddress.unsafelyUnwrapped let getterRef = _pop(from: &componentBuffer, as: Int32.self) let getter = _resolveRelativeAddress(getterBase, getterRef) let setter: UnsafeRawPointer? if header.isComputedSettable { let setterBase = componentBuffer.baseAddress.unsafelyUnwrapped let setterRef = _pop(from: &componentBuffer, as: Int32.self) setter = _resolveRelativeAddress(setterBase, setterRef) } else { setter = nil } return (idValueBase: idValueBase, idValue: idValue, getter: getter, setter: setter) } func popComputedArguments(header: RawKeyPathComponent.Header, componentBuffer: inout UnsafeRawBufferPointer) -> KeyPathPatternComputedArguments? { if header.hasComputedArguments { let getLayoutBase = componentBuffer.baseAddress.unsafelyUnwrapped let getLayoutRef = _pop(from: &componentBuffer, as: Int32.self) let getLayoutRaw = _resolveRelativeAddress(getLayoutBase, getLayoutRef) let getLayout = unsafeBitCast(getLayoutRaw, to: KeyPathComputedArgumentLayoutFn.self) let witnessesBase = componentBuffer.baseAddress.unsafelyUnwrapped let witnessesRef = _pop(from: &componentBuffer, as: Int32.self) let witnesses: UnsafeRawPointer if witnessesRef == 0 { witnesses = __swift_keyPathGenericWitnessTable_addr() } else { witnesses = _resolveRelativeAddress(witnessesBase, witnessesRef) } let initializerBase = componentBuffer.baseAddress.unsafelyUnwrapped let initializerRef = _pop(from: &componentBuffer, as: Int32.self) let initializerRaw = _resolveRelativeAddress(initializerBase, initializerRef) let initializer = unsafeBitCast(initializerRaw, to: KeyPathComputedArgumentInitializerFn.self) return KeyPathPatternComputedArguments(getLayout: getLayout, witnesses: witnesses.assumingMemoryBound(to: ComputedArgumentWitnesses.self), initializer: initializer) } else { return nil } } // We declare this down here to avoid the temptation to use it within // the functions above. let bufferPtr = pattern.advanced(by: keyPathPatternHeaderSize) let bufferHeader = bufferPtr.load(as: KeyPathBuffer.Header.self) var buffer = UnsafeRawBufferPointer(start: bufferPtr + 4, count: bufferHeader.size) while !buffer.isEmpty { let header = _pop(from: &buffer, as: RawKeyPathComponent.Header.self) // Ensure that we pop an amount of data consistent with what // RawKeyPathComponent.Header.patternComponentBodySize computes. var bufferSizeBefore = 0 var expectedPop = 0 _internalInvariant({ bufferSizeBefore = buffer.count expectedPop = header.patternComponentBodySize return true }()) switch header.kind { case .class, .struct: visitStored(header: header, componentBuffer: &buffer) case .computed: let (idValueBase, idValue, getter, setter) = popComputedAccessors(header: header, componentBuffer: &buffer) // If there are arguments, gather those too. let arguments = popComputedArguments(header: header, componentBuffer: &buffer) walker.visitComputedComponent(mutating: header.isComputedMutating, idKind: header.computedIDKind, idResolution: header.computedIDResolution, idValueBase: idValueBase, idValue: idValue, getter: getter, setter: setter, arguments: arguments, externalArgs: nil) case .optionalChain: walker.visitOptionalChainComponent() case .optionalWrap: walker.visitOptionalWrapComponent() case .optionalForce: walker.visitOptionalForceComponent() case .external: // Look at the external property descriptor to see if we should take it // over the component given in the pattern. let genericParamCount = Int(header.payload) let descriptorBase = buffer.baseAddress.unsafelyUnwrapped let descriptorOffset = _pop(from: &buffer, as: Int32.self) let descriptor = _resolveRelativeIndirectableAddress(descriptorBase, descriptorOffset) let descriptorHeader = descriptor.load(as: RawKeyPathComponent.Header.self) if descriptorHeader.isTrivialPropertyDescriptor { // If the descriptor is trivial, then use the local candidate. // Skip the external generic parameter accessors to get to it. _ = _pop(from: &buffer, as: Int32.self, count: genericParamCount) continue } // Grab the generic parameter accessors to pass to the external component. let externalArgs = _pop(from: &buffer, as: Int32.self, count: genericParamCount) // Grab the header for the local candidate in case we need it for // a computed property. let localCandidateHeader = _pop(from: &buffer, as: RawKeyPathComponent.Header.self) let localCandidateSize = localCandidateHeader.patternComponentBodySize _internalInvariant({ expectedPop += localCandidateSize + 4 return true }()) let descriptorSize = descriptorHeader.propertyDescriptorBodySize var descriptorBuffer = UnsafeRawBufferPointer(start: descriptor + 4, count: descriptorSize) // Look at what kind of component the external property has. switch descriptorHeader.kind { case .struct, .class: // A stored component. We can instantiate it // without help from the local candidate. _ = _pop(from: &buffer, as: UInt8.self, count: localCandidateSize) visitStored(header: descriptorHeader, componentBuffer: &descriptorBuffer) case .computed: // A computed component. The accessors come from the descriptor. let (idValueBase, idValue, getter, setter) = popComputedAccessors(header: descriptorHeader, componentBuffer: &descriptorBuffer) // Get the arguments from the external descriptor and/or local candidate // component. let arguments: KeyPathPatternComputedArguments? if localCandidateHeader.kind == .computed && localCandidateHeader.hasComputedArguments { // If both have arguments, then we have to build a bit of a chimera. // The canonical identity and accessors come from the descriptor, // but the argument equality/hash handling is still as described // in the local candidate. // We don't need the local candidate's accessors. _ = popComputedAccessors(header: localCandidateHeader, componentBuffer: &buffer) // We do need the local arguments. arguments = popComputedArguments(header: localCandidateHeader, componentBuffer: &buffer) } else { // If the local candidate doesn't have arguments, we don't need // anything from it at all. _ = _pop(from: &buffer, as: UInt8.self, count: localCandidateSize) arguments = nil } walker.visitComputedComponent( mutating: descriptorHeader.isComputedMutating, idKind: descriptorHeader.computedIDKind, idResolution: descriptorHeader.computedIDResolution, idValueBase: idValueBase, idValue: idValue, getter: getter, setter: setter, arguments: arguments, externalArgs: genericParamCount > 0 ? externalArgs : nil) case .optionalChain, .optionalWrap, .optionalForce, .external: _internalInvariantFailure("not possible for property descriptor") } } // Check that we consumed the expected amount of data from the pattern. _internalInvariant( { // Round the amount of data we read up to alignment. let popped = MemoryLayout<Int32>._roundingUpToAlignment( bufferSizeBefore - buffer.count) return expectedPop == popped }(), """ component size consumed during pattern walk does not match \ component size returned by patternComponentBodySize """) // Break if this is the last component. if buffer.isEmpty { break } // Otherwise, pop the intermediate component type accessor and // go around again. let componentTypeBase = buffer.baseAddress.unsafelyUnwrapped let componentTypeOffset = _pop(from: &buffer, as: Int32.self) let componentTypeRef = _resolveRelativeAddress(componentTypeBase, componentTypeOffset) walker.visitIntermediateComponentType(metadataRef: componentTypeRef) _internalInvariant(!buffer.isEmpty) } // We should have walked the entire pattern. _internalInvariant(buffer.isEmpty, "did not walk entire pattern buffer") walker.finish() } internal struct GetKeyPathClassAndInstanceSizeFromPattern : KeyPathPatternVisitor { var size: Int = MemoryLayout<Int>.size // start with one word for the header var capability: KeyPathKind = .value var didChain: Bool = false var root: Any.Type! var leaf: Any.Type! var genericEnvironment: UnsafeRawPointer? let patternArgs: UnsafeRawPointer? init(patternArgs: UnsafeRawPointer?) { self.patternArgs = patternArgs } mutating func roundUpToPointerAlignment() { size = MemoryLayout<Int>._roundingUpToAlignment(size) } mutating func visitHeader(genericEnvironment: UnsafeRawPointer?, rootMetadataRef: MetadataReference, leafMetadataRef: MetadataReference, kvcCompatibilityString: UnsafeRawPointer?) { self.genericEnvironment = genericEnvironment // Get the root and leaf type metadata so we can form the class type // for the entire key path. root = _resolveKeyPathMetadataReference( rootMetadataRef, genericEnvironment: genericEnvironment, arguments: patternArgs) leaf = _resolveKeyPathMetadataReference( leafMetadataRef, genericEnvironment: genericEnvironment, arguments: patternArgs) } mutating func visitStoredComponent(kind: KeyPathStructOrClass, mutable: Bool, offset: KeyPathPatternStoredOffset) { // Mutable class properties can be the root of a reference mutation. // Mutable struct properties pass through the existing capability. if mutable { switch kind { case .class: capability = .reference case .struct: break } } else { // Immutable properties can only be read. capability = .readOnly } // The size of the instantiated component depends on whether we can fit // the offset inline. switch offset { case .inline: size += 4 case .outOfLine, .unresolvedFieldOffset, .unresolvedIndirectOffset: size += 8 } } mutating func visitComputedComponent(mutating: Bool, idKind: KeyPathComputedIDKind, idResolution: KeyPathComputedIDResolution, idValueBase: UnsafeRawPointer, idValue: Int32, getter: UnsafeRawPointer, setter: UnsafeRawPointer?, arguments: KeyPathPatternComputedArguments?, externalArgs: UnsafeBufferPointer<Int32>?) { let settable = setter != nil switch (settable, mutating) { case (false, false): // If the property is get-only, the capability becomes read-only, unless // we get another reference-writable component. capability = .readOnly case (true, false): capability = .reference case (true, true): // Writable if the base is. No effect. break case (false, true): _internalInvariantFailure("unpossible") } // Save space for the header... size += 4 roundUpToPointerAlignment() // ...id, getter, and maybe setter... size += MemoryLayout<Int>.size * 2 if settable { size += MemoryLayout<Int>.size } // ...and the arguments, if any. let argumentHeaderSize = MemoryLayout<Int>.size * 2 switch (arguments, externalArgs) { case (nil, nil): break case (let arguments?, nil): size += argumentHeaderSize // If we have arguments, calculate how much space they need by invoking // the layout function. let (addedSize, addedAlignmentMask) = arguments.getLayout(patternArgs) // TODO: Handle over-aligned values _internalInvariant(addedAlignmentMask < MemoryLayout<Int>.alignment, "overaligned computed property element not supported") size += addedSize case (let arguments?, let externalArgs?): // If we're referencing an external declaration, and it takes captured // arguments, then we have to build a bit of a chimera. The canonical // identity and accessors come from the descriptor, but the argument // handling is still as described in the local candidate. size += argumentHeaderSize let (addedSize, addedAlignmentMask) = arguments.getLayout(patternArgs) // TODO: Handle over-aligned values _internalInvariant(addedAlignmentMask < MemoryLayout<Int>.alignment, "overaligned computed property element not supported") size += addedSize // We also need to store the size of the local arguments so we can // find the external component arguments. roundUpToPointerAlignment() size += RawKeyPathComponent.Header.externalWithArgumentsExtraSize size += MemoryLayout<Int>.size * externalArgs.count case (nil, let externalArgs?): // If we're instantiating an external property with a local // candidate that has no arguments, then things are a little // easier. We only need to instantiate the generic // arguments for the external component's accessors. size += argumentHeaderSize size += MemoryLayout<Int>.size * externalArgs.count } } mutating func visitOptionalChainComponent() { // Optional chaining forces the entire keypath to be read-only, even if // there are further reference-writable components. didChain = true capability = .readOnly size += 4 } mutating func visitOptionalWrapComponent() { // Optional chaining forces the entire keypath to be read-only, even if // there are further reference-writable components. didChain = true capability = .readOnly size += 4 } mutating func visitOptionalForceComponent() { // Force-unwrapping passes through the mutability of the preceding keypath. size += 4 } mutating func visitIntermediateComponentType(metadataRef _: MetadataReference) { // The instantiated component type will be stored in the instantiated // object. roundUpToPointerAlignment() size += MemoryLayout<Int>.size } mutating func finish() { } } internal func _getKeyPathClassAndInstanceSizeFromPattern( _ pattern: UnsafeRawPointer, _ arguments: UnsafeRawPointer ) -> ( keyPathClass: AnyKeyPath.Type, rootType: Any.Type, size: Int, alignmentMask: Int ) { var walker = GetKeyPathClassAndInstanceSizeFromPattern(patternArgs: arguments) _walkKeyPathPattern(pattern, walker: &walker) // Chaining always renders the whole key path read-only. if walker.didChain { walker.capability = .readOnly } // Grab the class object for the key path type we'll end up with. func openRoot<Root>(_: Root.Type) -> AnyKeyPath.Type { func openLeaf<Leaf>(_: Leaf.Type) -> AnyKeyPath.Type { switch walker.capability { case .readOnly: return KeyPath<Root, Leaf>.self case .value: return WritableKeyPath<Root, Leaf>.self case .reference: return ReferenceWritableKeyPath<Root, Leaf>.self } } return _openExistential(walker.leaf!, do: openLeaf) } let classTy = _openExistential(walker.root!, do: openRoot) return (keyPathClass: classTy, rootType: walker.root!, size: walker.size, // FIXME: Handle overalignment alignmentMask: MemoryLayout<Int>._alignmentMask) } internal struct InstantiateKeyPathBuffer: KeyPathPatternVisitor { var destData: UnsafeMutableRawBufferPointer var genericEnvironment: UnsafeRawPointer? let patternArgs: UnsafeRawPointer? var base: Any.Type init(destData: UnsafeMutableRawBufferPointer, patternArgs: UnsafeRawPointer?, root: Any.Type) { self.destData = destData self.patternArgs = patternArgs self.base = root } // Track the triviality of the resulting object data. var isTrivial: Bool = true // Track where the reference prefix begins. var endOfReferencePrefixComponent: UnsafeMutableRawPointer? = nil var previousComponentAddr: UnsafeMutableRawPointer? = nil mutating func pushDest<T>(_ value: T) { _internalInvariant(_isPOD(T.self)) let size = MemoryLayout<T>.size let alignment = MemoryLayout<T>.alignment var baseAddress = destData.baseAddress.unsafelyUnwrapped var misalign = Int(bitPattern: baseAddress) % alignment if misalign != 0 { misalign = alignment - misalign baseAddress = baseAddress.advanced(by: misalign) } withUnsafeBytes(of: value) { _memcpy(dest: baseAddress, src: $0.baseAddress.unsafelyUnwrapped, size: UInt(size)) } destData = UnsafeMutableRawBufferPointer( start: baseAddress + size, count: destData.count - size - misalign) } mutating func updatePreviousComponentAddr() -> UnsafeMutableRawPointer? { let oldValue = previousComponentAddr previousComponentAddr = destData.baseAddress.unsafelyUnwrapped return oldValue } mutating func visitHeader(genericEnvironment: UnsafeRawPointer?, rootMetadataRef: MetadataReference, leafMetadataRef: MetadataReference, kvcCompatibilityString: UnsafeRawPointer?) { self.genericEnvironment = genericEnvironment } mutating func visitStoredComponent(kind: KeyPathStructOrClass, mutable: Bool, offset: KeyPathPatternStoredOffset) { let previous = updatePreviousComponentAddr() switch kind { case .class: // A mutable class property can end the reference prefix. if mutable { endOfReferencePrefixComponent = previous } fallthrough case .struct: // Resolve the offset. switch offset { case .inline(let value): let header = RawKeyPathComponent.Header(stored: kind, mutable: mutable, inlineOffset: value) pushDest(header) case .outOfLine(let offset): let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind, mutable: mutable) pushDest(header) pushDest(offset) case .unresolvedFieldOffset(let offsetOfOffset): // Look up offset in the type metadata. The value in the pattern is // the offset within the metadata object. let metadataPtr = unsafeBitCast(base, to: UnsafeRawPointer.self) let offset: UInt32 switch kind { case .class: offset = UInt32(metadataPtr.load(fromByteOffset: Int(offsetOfOffset), as: UInt.self)) case .struct: offset = UInt32(metadataPtr.load(fromByteOffset: Int(offsetOfOffset), as: UInt32.self)) } let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind, mutable: mutable) pushDest(header) pushDest(offset) case .unresolvedIndirectOffset(let pointerToOffset): // Look up offset in the indirectly-referenced variable we have a // pointer. assert(pointerToOffset.pointee <= UInt32.max) let offset = UInt32(truncatingIfNeeded: pointerToOffset.pointee) let header = RawKeyPathComponent.Header(storedWithOutOfLineOffset: kind, mutable: mutable) pushDest(header) pushDest(offset) } } } mutating func visitComputedComponent(mutating: Bool, idKind: KeyPathComputedIDKind, idResolution: KeyPathComputedIDResolution, idValueBase: UnsafeRawPointer, idValue: Int32, getter: UnsafeRawPointer, setter: UnsafeRawPointer?, arguments: KeyPathPatternComputedArguments?, externalArgs: UnsafeBufferPointer<Int32>?) { let previous = updatePreviousComponentAddr() let settable = setter != nil // A nonmutating settable property can end the reference prefix. if settable && !mutating { endOfReferencePrefixComponent = previous } // Resolve the ID. let resolvedID: UnsafeRawPointer? switch idKind { case .storedPropertyIndex, .vtableOffset: _internalInvariant(idResolution == .resolved) // Zero-extend the integer value to get the instantiated id. let value = UInt(UInt32(bitPattern: idValue)) resolvedID = UnsafeRawPointer(bitPattern: value) case .pointer: // Resolve the sign-extended relative reference. var absoluteID: UnsafeRawPointer? = idValueBase + Int(idValue) // If the pointer ID is unresolved, then it needs work to get to // the final value. switch idResolution { case .resolved: break case .indirectPointer: // The pointer in the pattern is an indirect pointer to the real // identifier pointer. absoluteID = absoluteID.unsafelyUnwrapped .load(as: UnsafeRawPointer?.self) case .functionCall: // The pointer in the pattern is to a function that generates the // identifier pointer. typealias Resolver = @convention(c) (UnsafeRawPointer?) -> UnsafeRawPointer? let resolverFn = unsafeBitCast(absoluteID.unsafelyUnwrapped, to: Resolver.self) absoluteID = resolverFn(patternArgs) } resolvedID = absoluteID } // Bring over the header, getter, and setter. let header = RawKeyPathComponent.Header(computedWithIDKind: idKind, mutating: mutating, settable: settable, hasArguments: arguments != nil || externalArgs != nil, instantiatedFromExternalWithArguments: arguments != nil && externalArgs != nil) pushDest(header) pushDest(resolvedID) pushDest(getter) if let setter = setter { pushDest(setter) } if let arguments = arguments { // Instantiate the arguments. let (baseSize, alignmentMask) = arguments.getLayout(patternArgs) _internalInvariant(alignmentMask < MemoryLayout<Int>.alignment, "overaligned computed arguments not implemented yet") // The real buffer stride will be rounded up to alignment. var totalSize = (baseSize + alignmentMask) & ~alignmentMask // If an external property descriptor also has arguments, they'll be // added to the end with pointer alignment. if let externalArgs = externalArgs { totalSize = MemoryLayout<Int>._roundingUpToAlignment(totalSize) totalSize += MemoryLayout<Int>.size * externalArgs.count } pushDest(totalSize) pushDest(arguments.witnesses) // A nonnull destructor in the witnesses file indicates the instantiated // payload is nontrivial. if let _ = arguments.witnesses.pointee.destroy { isTrivial = false } // If the descriptor has arguments, store the size of its specific // arguments here, so we can drop them when trying to invoke // the component's witnesses. if let externalArgs = externalArgs { pushDest(externalArgs.count * MemoryLayout<Int>.size) } // Initialize the local candidate arguments here. _internalInvariant(Int(bitPattern: destData.baseAddress) & alignmentMask == 0, "argument destination not aligned") arguments.initializer(patternArgs, destData.baseAddress.unsafelyUnwrapped) destData = UnsafeMutableRawBufferPointer( start: destData.baseAddress.unsafelyUnwrapped + baseSize, count: destData.count - baseSize) } if let externalArgs = externalArgs { if arguments == nil { // If we're instantiating an external property without any local // arguments, then we only need to instantiate the arguments to the // property descriptor. let stride = MemoryLayout<Int>.size * externalArgs.count pushDest(stride) pushDest(__swift_keyPathGenericWitnessTable_addr()) } // Write the descriptor's generic arguments, which should all be relative // references to metadata accessor functions. for i in externalArgs.indices { let base = externalArgs.baseAddress.unsafelyUnwrapped + i let offset = base.pointee let metadataRef = UnsafeRawPointer(base) + Int(offset) let result = _resolveKeyPathGenericArgReference( metadataRef, genericEnvironment: genericEnvironment, arguments: patternArgs) pushDest(result) } } } mutating func visitOptionalChainComponent() { let _ = updatePreviousComponentAddr() let header = RawKeyPathComponent.Header(optionalChain: ()) pushDest(header) } mutating func visitOptionalWrapComponent() { let _ = updatePreviousComponentAddr() let header = RawKeyPathComponent.Header(optionalWrap: ()) pushDest(header) } mutating func visitOptionalForceComponent() { let _ = updatePreviousComponentAddr() let header = RawKeyPathComponent.Header(optionalForce: ()) pushDest(header) } mutating func visitIntermediateComponentType(metadataRef: MetadataReference) { // Get the metadata for the intermediate type. let metadata = _resolveKeyPathMetadataReference( metadataRef, genericEnvironment: genericEnvironment, arguments: patternArgs) pushDest(metadata) base = metadata } mutating func finish() { // Should have filled the entire buffer by the time we reach the end of the // pattern. _internalInvariant(destData.isEmpty, "should have filled entire destination buffer") } } #if INTERNAL_CHECKS_ENABLED // In debug builds of the standard library, check that instantiation produces // components whose sizes are consistent with the sizing visitor pass. internal struct ValidatingInstantiateKeyPathBuffer: KeyPathPatternVisitor { var sizeVisitor: GetKeyPathClassAndInstanceSizeFromPattern var instantiateVisitor: InstantiateKeyPathBuffer let origDest: UnsafeMutableRawPointer init(sizeVisitor: GetKeyPathClassAndInstanceSizeFromPattern, instantiateVisitor: InstantiateKeyPathBuffer) { self.sizeVisitor = sizeVisitor self.instantiateVisitor = instantiateVisitor origDest = self.instantiateVisitor.destData.baseAddress.unsafelyUnwrapped } mutating func visitHeader(genericEnvironment: UnsafeRawPointer?, rootMetadataRef: MetadataReference, leafMetadataRef: MetadataReference, kvcCompatibilityString: UnsafeRawPointer?) { sizeVisitor.visitHeader(genericEnvironment: genericEnvironment, rootMetadataRef: rootMetadataRef, leafMetadataRef: leafMetadataRef, kvcCompatibilityString: kvcCompatibilityString) instantiateVisitor.visitHeader(genericEnvironment: genericEnvironment, rootMetadataRef: rootMetadataRef, leafMetadataRef: leafMetadataRef, kvcCompatibilityString: kvcCompatibilityString) } mutating func visitStoredComponent(kind: KeyPathStructOrClass, mutable: Bool, offset: KeyPathPatternStoredOffset) { sizeVisitor.visitStoredComponent(kind: kind, mutable: mutable, offset: offset) instantiateVisitor.visitStoredComponent(kind: kind, mutable: mutable, offset: offset) checkSizeConsistency() } mutating func visitComputedComponent(mutating: Bool, idKind: KeyPathComputedIDKind, idResolution: KeyPathComputedIDResolution, idValueBase: UnsafeRawPointer, idValue: Int32, getter: UnsafeRawPointer, setter: UnsafeRawPointer?, arguments: KeyPathPatternComputedArguments?, externalArgs: UnsafeBufferPointer<Int32>?) { sizeVisitor.visitComputedComponent(mutating: mutating, idKind: idKind, idResolution: idResolution, idValueBase: idValueBase, idValue: idValue, getter: getter, setter: setter, arguments: arguments, externalArgs: externalArgs) instantiateVisitor.visitComputedComponent(mutating: mutating, idKind: idKind, idResolution: idResolution, idValueBase: idValueBase, idValue: idValue, getter: getter, setter: setter, arguments: arguments, externalArgs: externalArgs) checkSizeConsistency() } mutating func visitOptionalChainComponent() { sizeVisitor.visitOptionalChainComponent() instantiateVisitor.visitOptionalChainComponent() checkSizeConsistency() } mutating func visitOptionalWrapComponent() { sizeVisitor.visitOptionalWrapComponent() instantiateVisitor.visitOptionalWrapComponent() checkSizeConsistency() } mutating func visitOptionalForceComponent() { sizeVisitor.visitOptionalForceComponent() instantiateVisitor.visitOptionalForceComponent() checkSizeConsistency() } mutating func visitIntermediateComponentType(metadataRef: MetadataReference) { sizeVisitor.visitIntermediateComponentType(metadataRef: metadataRef) instantiateVisitor.visitIntermediateComponentType(metadataRef: metadataRef) checkSizeConsistency() } mutating func finish() { sizeVisitor.finish() instantiateVisitor.finish() checkSizeConsistency() } func checkSizeConsistency() { let nextDest = instantiateVisitor.destData.baseAddress.unsafelyUnwrapped let curSize = nextDest - origDest + MemoryLayout<Int>.size _internalInvariant(curSize == sizeVisitor.size, "size and instantiation visitors out of sync") } } #endif // INTERNAL_CHECKS_ENABLED internal func _instantiateKeyPathBuffer( _ pattern: UnsafeRawPointer, _ origDestData: UnsafeMutableRawBufferPointer, _ rootType: Any.Type, _ arguments: UnsafeRawPointer ) { let destHeaderPtr = origDestData.baseAddress.unsafelyUnwrapped var destData = UnsafeMutableRawBufferPointer( start: destHeaderPtr.advanced(by: MemoryLayout<Int>.size), count: origDestData.count - MemoryLayout<Int>.size) #if INTERNAL_CHECKS_ENABLED // If checks are enabled, use a validating walker that ensures that the // size pre-walk and instantiation walk are in sync. let sizeWalker = GetKeyPathClassAndInstanceSizeFromPattern( patternArgs: arguments) let instantiateWalker = InstantiateKeyPathBuffer( destData: destData, patternArgs: arguments, root: rootType) var walker = ValidatingInstantiateKeyPathBuffer(sizeVisitor: sizeWalker, instantiateVisitor: instantiateWalker) #else var walker = InstantiateKeyPathBuffer( destData: destData, patternArgs: arguments, root: rootType) #endif _walkKeyPathPattern(pattern, walker: &walker) #if INTERNAL_CHECKS_ENABLED let isTrivial = walker.instantiateVisitor.isTrivial let endOfReferencePrefixComponent = walker.instantiateVisitor.endOfReferencePrefixComponent #else let isTrivial = walker.isTrivial let endOfReferencePrefixComponent = walker.endOfReferencePrefixComponent #endif // Write out the header. let destHeader = KeyPathBuffer.Header( size: origDestData.count - MemoryLayout<Int>.size, trivial: isTrivial, hasReferencePrefix: endOfReferencePrefixComponent != nil) destHeaderPtr.storeBytes(of: destHeader, as: KeyPathBuffer.Header.self) // Mark the reference prefix if there is one. if let endOfReferencePrefixComponent = endOfReferencePrefixComponent { var componentHeader = endOfReferencePrefixComponent .load(as: RawKeyPathComponent.Header.self) componentHeader.endOfReferencePrefix = true endOfReferencePrefixComponent.storeBytes(of: componentHeader, as: RawKeyPathComponent.Header.self) } }
apache-2.0
37de2e422ebfb61804484c25355379b9
36.668575
96
0.652362
5.010049
false
false
false
false
roambotics/swift
test/Sema/diag_non_ephemeral.swift
3
38704
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-library-evolution -parse-as-library -o %t -module-name=ModuleA %S/Inputs/diag_non_ephemeral_module1.swift // RUN: %target-swift-frontend -emit-module -enable-library-evolution -parse-as-library -o %t -module-name=ModuleB %S/Inputs/diag_non_ephemeral_module2.swift // RUN: cp %s %t/main.swift // RUN: %target-swift-frontend -typecheck -verify -enable-invalid-ephemeralness-as-error -I %t %t/main.swift %S/Inputs/diag_non_ephemeral_globals.swift import ModuleA import ModuleB func takesMutableRaw(@_nonEphemeral _ x: UnsafeMutableRawPointer, _ y: Int) {} func takesConst(@_nonEphemeral _ x: UnsafePointer<Int8>, _ y: Int) {} func takesRaw(@_nonEphemeral _ x: UnsafeRawPointer) {} func takesMutable(@_nonEphemeral _ x: UnsafeMutablePointer<Int8>) {} func takesOptMutableRaw(@_nonEphemeral _ x: UnsafeMutableRawPointer?) {} func takesOptConst(@_nonEphemeral _ x: UnsafePointer<Int8>?) {} var str = "" var optionalStr: String? var arr: [Int8] = [5] var optionalArr: [Int8]? // We cannot use array-to-pointer and string-to-pointer conversions with // non-ephemeral parameters. takesMutableRaw(&arr, 5) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesMutableRaw'}} {{educational-notes=temporary-pointers}} // expected-note@-1 {{implicit argument conversion from '[Int8]' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRaw'}} // expected-note@-2 {{use the 'withUnsafeMutableBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesConst(str, 5) // expected-error {{cannot pass 'String' to parameter; argument #1 must be a pointer that outlives the call to 'takesConst'}} {{educational-notes=temporary-pointers}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'takesConst'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} takesConst(arr, 5) // expected-error {{cannot pass '[Int8]' to parameter; argument #1 must be a pointer that outlives the call to 'takesConst'}} // expected-note@-1 {{implicit argument conversion from '[Int8]' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'takesConst'}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&arr) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from '[Int8]' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesMutable(&arr) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesMutable'}} // expected-note@-1 {{implicit argument conversion from '[Int8]' to 'UnsafeMutablePointer<Int8>' produces a pointer valid only for the duration of the call to 'takesMutable'}} // expected-note@-2 {{use the 'withUnsafeMutableBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesOptMutableRaw(&arr) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesOptMutableRaw'}} // expected-note@-1 {{implicit argument conversion from '[Int8]' to 'UnsafeMutableRawPointer?' produces a pointer valid only for the duration of the call to 'takesOptMutableRaw'}} // expected-note@-2 {{use the 'withUnsafeMutableBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} // FIXME: This currently uses inout-to-pointer instead of array-to-pointer // (https://github.com/apple/swift/issues/51597). takesOptMutableRaw(&optionalArr) takesOptConst(arr) // expected-error {{cannot pass '[Int8]' to parameter; argument #1 must be a pointer that outlives the call to 'takesOptConst'}} // expected-note@-1 {{implicit argument conversion from '[Int8]' to 'UnsafePointer<Int8>?' produces a pointer valid only for the duration of the call to 'takesOptConst'}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesOptConst(optionalArr) // expected-error {{cannot pass '[Int8]?' to parameter; argument #1 must be a pointer that outlives the call to 'takesOptConst'}} // expected-note@-1 {{implicit argument conversion from '[Int8]?' to 'UnsafePointer<Int8>?' produces a pointer valid only for the duration of the call to 'takesOptConst'}} takesOptConst(str) // expected-error {{cannot pass 'String' to parameter; argument #1 must be a pointer that outlives the call to 'takesOptConst'}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>?' produces a pointer valid only for the duration of the call to 'takesOptConst'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} takesOptConst(optionalStr) // expected-error {{cannot pass 'String?' to parameter; argument #1 must be a pointer that outlives the call to 'takesOptConst'}} // expected-note@-1 {{implicit argument conversion from 'String?' to 'UnsafePointer<Int8>?' produces a pointer valid only for the duration of the call to 'takesOptConst'}} struct S { static var staticStoredProperty: Int8 = 0 var storedProperty: Int8 = 0 var storedFinalC = FinalC() var storedPropertyWithObservers: Int8 = 0 { didSet {} } var computedProperty: Int8 { get { return 0 } set {} } subscript() -> Int8 { get { return 0 } set {} } } class C { static var staticStoredProperty = S() var storedProperty: Int8 = 0 var storedPropertyWithObservers: Int8 = 0 { didSet {} } var computedProperty: Int8 { get { return 0 } set {} } subscript() -> Int8 { get { return 0 } set {} } } final class FinalC { static var staticStoredProperty = S() var storedProperty: Int8 = 0 var storedPropertyWithObservers: Int8 = 0 { didSet {} } var computedProperty: Int8 { get { return 0 } set {} } subscript() -> Int8 { get { return 0 } set {} } } protocol P { static var staticProperty: Int8 { get set } var property: Int8 { get set } subscript() -> Int8 { get set } } func makeP() -> P { while true {} } var value: Int8 = 5 var topLevelS = S() var topLevelC = C() var topLevelFinalC = FinalC() var topLevelP = makeP() var topLevelTupleOfS = (S(), S()) var topLevelOptOfS: S? var topLevelWithObservers: Int8 = 0 { didSet {} } var topLevelResilientS = ResilientStruct() var topLevelOptOfResilientS: ResilientStruct? var topLevelFragileS = FragileStruct() var topLevelResilientFinalC = ResilientFinalClass() var topLevelFragileFinalC = FragileFinalClass() let metatypeOfC = C.self // We can get stable pointer values from fragile global and static stored // variables, as long as they don't have property observers. takesMutableRaw(&value, 5) takesMutableRaw(&str, 5) takesMutableRaw(&topLevelS, 5) takesRaw(&topLevelC) takesRaw(&S.staticStoredProperty) takesRaw(&C.staticStoredProperty) takesRaw(&FinalC.staticStoredProperty) takesRaw(&metatypeOfC.staticStoredProperty) takesRaw(&type(of: topLevelC).staticStoredProperty) takesRaw(&FragileStruct.staticStoredProperty) takesRaw(&type(of: topLevelFragileS).staticStoredProperty) takesRaw(&globalFragile) takesRaw(&globalS) takesRaw(&topLevelResilientS) takesRaw(&topLevelFragileS) takesRaw(&topLevelP) takesRaw(&value) takesRaw(&str) takesMutable(&value) takesOptMutableRaw(&value) takesOptMutableRaw(&str) extension C { static func foo() { takesRaw(&staticStoredProperty) } } // We can also project stable pointer values from stored properties on such // global and static stored variables, as long as the base type is a fragile // struct or a tuple. takesRaw(&C.staticStoredProperty.storedProperty) takesRaw(&FinalC.staticStoredProperty.storedProperty) takesRaw(&metatypeOfC.staticStoredProperty.storedProperty) takesRaw(&type(of: topLevelC).staticStoredProperty.storedProperty) takesRaw(&topLevelS.storedProperty) takesRaw(&globalS.storedProperty) takesRaw(&topLevelTupleOfS.0) takesRaw(&topLevelTupleOfS.0.storedProperty) takesRaw(&topLevelFragileS.storedProperty) extension C { static func bar() { takesRaw(&staticStoredProperty.storedProperty) } } // We can also project through force unwraps. takesRaw(&topLevelOptOfS!) takesRaw(&topLevelOptOfS!.storedProperty) takesRaw(&topLevelOptOfResilientS!) // But we cannot do the same for: // - Class bases takesMutableRaw(&topLevelC.storedProperty, 5) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesMutableRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRaw'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesMutableRaw(&topLevelFinalC.storedProperty, 5) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesMutableRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRaw'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesMutableRaw(&topLevelFragileFinalC.storedProperty, 5) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesMutableRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRaw'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesMutableRaw(&topLevelS.storedFinalC.storedProperty, 5) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesMutableRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRaw'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} // - Resilient global or static variables takesMutableRaw(&globalResilient, 5) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesMutableRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRaw'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesMutableRaw(&ResilientStruct.staticStoredProperty, 5) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesMutableRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRaw'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} // FIXME: This should also produce an error. takesMutableRaw(&type(of: topLevelResilientS).staticStoredProperty, 5) // - Resilient struct or class bases takesMutableRaw(&topLevelResilientS.storedProperty, 5) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesMutableRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRaw'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesMutableRaw(&topLevelResilientFinalC.storedProperty, 5) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesMutableRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRaw'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesMutableRaw(&topLevelOptOfResilientS!.storedProperty, 5) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesMutableRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRaw'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} // - Protocol bases takesRaw(&topLevelP.property) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} // FIXME: This should also produce an error. takesRaw(&type(of: topLevelP).staticProperty) takesRaw(&topLevelP[]) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} // - Properties with observers takesRaw(&topLevelWithObservers) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&topLevelS.storedPropertyWithObservers) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&topLevelOptOfS!.storedPropertyWithObservers) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&topLevelC.storedPropertyWithObservers) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&topLevelFinalC.storedPropertyWithObservers) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&topLevelTupleOfS.0.storedPropertyWithObservers) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} // - Computed properties takesRaw(&topLevelOptOfS!.computedProperty) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&topLevelC.computedProperty) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&topLevelFinalC.computedProperty) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&topLevelTupleOfS.0.computedProperty) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} // - Subscripts takesRaw(&topLevelS[]) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&topLevelC[]) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&topLevelFinalC[]) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} // - Local variables func testInoutToPointerOfLocal() { var local: Int8 = 0 takesMutableRaw(&local, 5) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesMutableRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRaw'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&local) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesMutable(&local) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesMutable'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeMutablePointer<Int8>' produces a pointer valid only for the duration of the call to 'takesMutable'}} // expected-note@-2 {{use 'withUnsafeMutablePointer' in order to explicitly convert argument to pointer valid for a defined scope}} } // - Instance members within types struct S1 { var property: Int8 = 0 mutating func foo() { takesRaw(&property) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&self.property) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} } } final class C1 { var property: Int8 = 0 func foo() { takesRaw(&property) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} takesRaw(&self.property) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'takesRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int8' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'takesRaw'}} // expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} } } // Check that @_nonEphemeral is preserved through type inference. let f1 = takesMutableRaw f1(&arr, 5) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'f1'}} // expected-note@-1 {{implicit argument conversion from '[Int8]' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'f1'}} // expected-note@-2 {{use the 'withUnsafeMutableBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} let f2 = takesConst f2(arr, 5) // expected-error {{cannot pass '[Int8]' to parameter; argument #1 must be a pointer that outlives the call to 'f2'}} // expected-note@-1 {{implicit argument conversion from '[Int8]' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'f2'}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} let f3 = takesRaw f3(&arr) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'f3'}} // expected-note@-1 {{implicit argument conversion from '[Int8]' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'f3'}} // expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} let f4 = takesMutable f4(&arr) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'f4'}} // expected-note@-1 {{implicit argument conversion from '[Int8]' to 'UnsafeMutablePointer<Int8>' produces a pointer valid only for the duration of the call to 'f4'}} // expected-note@-2 {{use the 'withUnsafeMutableBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} struct S2 { static var selfProp = S2() static var selfPropWithObserver = S2() { didSet {} } static func takesConstStaticAndReturns<T>(@_nonEphemeral _ ptr: UnsafePointer<T>) -> S2 { return S2() } static func takesMutableRawStatic(_ x: String = "", @_nonEphemeral ptr: UnsafeMutableRawPointer) {} func takesMutableRaw(@_nonEphemeral ptr: UnsafeMutableRawPointer = UnsafeMutableRawPointer(&topLevelS)) {} subscript(@_nonEphemeral takesConstInt8 ptr: UnsafePointer<Int8>) -> Int { get { return 0 } set {} } } func testNonEphemeralInMembers() { var local = 0 let _: S2 = .takesConstStaticAndReturns([1, 2, 3]) // expected-error {{cannot pass '[Int]' to parameter; argument #1 must be a pointer that outlives the call to 'takesConstStaticAndReturns'}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'takesConstStaticAndReturns'}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} S2.takesMutableRawStatic(ptr: &local) // expected-error {{cannot use inout expression here; argument 'ptr' must be a pointer that outlives the call to 'takesMutableRawStatic(_:ptr:)'}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRawStatic(_:ptr:)'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} S2.takesMutableRawStatic("", ptr: &local) // expected-error {{cannot use inout expression here; argument 'ptr' must be a pointer that outlives the call to 'takesMutableRawStatic(_:ptr:)'}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRawStatic(_:ptr:)'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} var s2 = S2() s2.takesMutableRaw() s2.takesMutableRaw(ptr: &local) // expected-error {{cannot use inout expression here; argument 'ptr' must be a pointer that outlives the call to 'takesMutableRaw(ptr:)'}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'takesMutableRaw(ptr:)'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = s2[takesConstInt8: ""] // expected-error {{cannot pass 'String' to parameter; argument 'takesConstInt8' must be a pointer that outlives the call to 'subscript(takesConstInt8:)'}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'subscript(takesConstInt8:)'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} s2[takesConstInt8: ""] += 1 // expected-error {{cannot pass 'String' to parameter; argument 'takesConstInt8' must be a pointer that outlives the call to 'subscript(takesConstInt8:)'}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'subscript(takesConstInt8:)'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} _ = \S2.[takesConstInt8: ""] // expected-error {{cannot pass 'String' to parameter; argument 'takesConstInt8' must be a pointer that outlives the call to 'subscript(takesConstInt8:)'}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'subscript(takesConstInt8:)'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} } func testNonEphemeralInDotMember() { func takesMutableS2(@_nonEphemeral _ ptr: UnsafeMutablePointer<S2>) {} takesMutableS2(&.selfProp) // FIXME: This should also produce an error. takesMutableS2(&.selfPropWithObserver) } func testNonEphemeralWithVarOverloads() { takesRaw(&overloadedVar) // expected-error {{ambiguous use of 'overloadedVar'}} // Even though only one of the overloads produces an ephemeral pointer, the // diagnostic doesn't affect solver behaviour, so we diagnose an ambiguity. takesRaw(&overloadedVarOnlyOneResilient) // expected-error {{ambiguous use of 'overloadedVarOnlyOneResilient'}} takesRaw(&overloadedVarDifferentTypes) // expected-error {{ambiguous use of 'overloadedVarDifferentTypes'}} func takesIntPtr(@_nonEphemeral _ ptr: UnsafePointer<Int>) {} takesIntPtr(&overloadedVarDifferentTypes) func takesStringPtr(@_nonEphemeral _ ptr: UnsafePointer<String>) {} takesStringPtr(&overloadedVarDifferentTypes) } infix operator ^^^ func ^^^ (@_nonEphemeral lhs: UnsafeMutableRawPointer, rhs: Int) {} func testNonEphemeralInOperators() { var local = 0 &value ^^^ 1 &local ^^^ 1 // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to '^^^'}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to '^^^'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} } struct S3 { var ptr1: UnsafeMutableRawPointer lazy var ptr2 = UnsafeMutableRawPointer(&topLevelS) } enum E { case mutableRaw(UnsafeMutableRawPointer) case const(UnsafePointer<Int8>) } func testNonEphemeralInMemberwiseInits() { var local = 0 _ = S3(ptr1: &topLevelS, ptr2: &local) // expected-error {{cannot use inout expression here; argument 'ptr2' must be a pointer that outlives the call to 'init(ptr1:ptr2:)'}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer?' produces a pointer valid only for the duration of the call to 'init(ptr1:ptr2:)'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = S3.init(ptr1: &local, ptr2: &topLevelS) // expected-error {{cannot use inout expression here; argument 'ptr1' must be a pointer that outlives the call to 'init(ptr1:ptr2:)'}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'init(ptr1:ptr2:)'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = E.mutableRaw(&local) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to 'mutableRaw'}} // expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'mutableRaw'}} // expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = E.const([1, 2, 3]) // expected-error {{cannot pass '[Int8]' to parameter; argument #1 must be a pointer that outlives the call to 'const'}} // expected-note@-1 {{implicit argument conversion from '[Int8]' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'const'}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} _ = E.const("hello") // expected-error {{cannot pass 'String' to parameter; argument #1 must be a pointer that outlives the call to 'const'}} // expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'const'}} // expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}} } // Allow the stripping of @_nonEphemeral. This is unfortunate, but ensures we don't force the user to write things // like `func higherOrder(_ fn: (@_nonEphemeral UnsafeMutableRawPointer) -> Void) {}`, given that the attribute is non-user-facing. let f5: (UnsafeMutableRawPointer, Int) -> Void = takesMutableRaw let f6: (UnsafePointer<Int8>, Int) -> Void = takesConst let f7: (UnsafeRawPointer) -> Void = takesRaw let f8: (UnsafeMutablePointer<Int8>) -> Void = takesMutable func higherOrder(_ fn: (UnsafeMutableRawPointer, Int) -> Void) {} higherOrder(takesMutableRaw) // @_nonEphemeral ambiguities func takesPointerOverload(x: Int = 0, @_nonEphemeral _ ptr: UnsafePointer<Int>) {} // expected-note {{candidate expects pointer that outlives the call for parameter #2}} func takesPointerOverload(x: Int = 0, @_nonEphemeral _ ptr: UnsafeMutablePointer<Int>) {} // expected-note {{candidate expects pointer that outlives the call for parameter #2}} func testAmbiguity() { var arr = [1, 2, 3] takesPointerOverload(&arr) // expected-error {{no exact matches in call to global function 'takesPointerOverload'}} } func takesPointerOverload2(@_nonEphemeral _ ptr: UnsafePointer<Int>) {} func takesPointerOverload2<T>(_ x: T?) {} func takesPointerOverload2(_ x: Any) {} func takesPointerOverload2(_ x: [Int]?) {} func testNonEphemeralErrorDoesntAffectOverloadResolution() { // Make sure we always pick the pointer overload, even though the other // overloads are all viable. var arr = [1, 2, 3] takesPointerOverload2(arr) // expected-error {{cannot pass '[Int]' to parameter; argument #1 must be a pointer that outlives the call to 'takesPointerOverload2'}} // expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'takesPointerOverload2'}} // expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} } func takesTwoPointers(@_nonEphemeral ptr _: UnsafePointer<Int>, @_nonEphemeral ptr _: UnsafePointer<Int>) {} func testArgumentLabelReferencing() { // Because takesTwoPointers has two argument labels with the same name, refer // to the argument by position. var arr = [1, 2, 3] takesTwoPointers(ptr: arr, ptr: arr) // expected-error@-1 {{cannot pass '[Int]' to parameter; argument #1 must be a pointer that outlives the call to 'takesTwoPointers(ptr:ptr:)'}} // expected-note@-2 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'takesTwoPointers(ptr:ptr:)'}} // expected-note@-3 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} // expected-error@-4 {{cannot pass '[Int]' to parameter; argument #2 must be a pointer that outlives the call to 'takesTwoPointers(ptr:ptr:)'}} // expected-note@-5 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'takesTwoPointers(ptr:ptr:)'}} // expected-note@-6 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}} } func ambiguous_fn(@_nonEphemeral _ ptr: UnsafePointer<Int>) {} // expected-note {{found this candidate}} func ambiguous_fn(_ ptr: UnsafeRawPointer) {} // expected-note {{found this candidate}} func test_ambiguity_with_function_instead_of_argument(_ x: inout Int) { ambiguous_fn(&x) // expected-error {{ambiguous use of 'ambiguous_fn'}} } func tuplify<Ts>(_ fn: @escaping (Ts) -> Void) -> (Ts) -> Void { fn } func testTuplingNonEphemeral(_ ptr: UnsafePointer<Int>) { // Make sure we drop @_nonEphemeral when imploding params. This is to ensure // we don't accidently break any potentially valid code. let fn = tuplify(takesTwoPointers) fn((ptr, ptr)) // Note we can't perform X-to-pointer conversions in this case even if we // wanted to. fn(([1], ptr)) // expected-error {{tuple type '([Int], UnsafePointer<Int>)' is not convertible to tuple type '(UnsafePointer<Int>, UnsafePointer<Int>)'}} }
apache-2.0
f4fa4c3a45674617b14758695751707a
70.54159
195
0.758242
4.267255
false
false
false
false
hanwanjie853710069/Easy-living
易持家/Class/Class_project/ELHomePage/Controller/ELASingleSetOfLinearGraphVC.swift
1
2756
// // ELASingleSetOfLinearGraphVC.swift // EasyLiving // // Created by 王木木 on 16/5/27. // Copyright © 2016年 王木木. All rights reserved. // import UIKit class ELASingleSetOfLinearGraphVC: CMBaseViewController , ZFGenericChartDataSource, ZFLineChartDelegate{ var timeData = [String]() var xfMonary = [String]() var information = [Information]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.whiteColor() self.edgesForExtendedLayout = .None; getData() } func getData(){ let arrayData = queryDataInformation() information = arrayData for temp:Information in arrayData { let timeS = temp.xfTime let timeGet = timeS?.componentsSeparatedByString("^_^") timeData.append(timeGet![0]) xfMonary.append(temp.xfAllMoney!) } if timeData.count == 0 { SVProgressHUD.showInfoWithStatus("未查询到数据") return } creatZFBarChart() } func creatZFBarChart(){ let lineChart = ZFLineChart.init(frame: CGRectMake(0, 0, ScreenWidth, ScreenHeight-64)) lineChart.dataSource = self; lineChart.delegate = self; lineChart.topic = "消费图"; lineChart.unit = "元"; lineChart.isResetYLineMinValue = true; self.view.addSubview(lineChart) lineChart.strokePath() } /// mark - ZFGenericChartDataSource func valueArrayInGenericChart(chart: ZFGenericChart!) -> [AnyObject]! { return xfMonary } func nameArrayInGenericChart(chart: ZFGenericChart!) -> [AnyObject]! { return timeData } func colorArrayInGenericChart(chart: ZFGenericChart!) -> [AnyObject]! { return [UIColor.greenColor()] } func yLineMaxValueInGenericChart(chart: ZFGenericChart!) -> CGFloat { return CGFloat(100) } func yLineSectionCountInGenericChart(chart: ZFGenericChart!) -> Int { return 20 } func yLineMinValueInGenericChart(chart: ZFGenericChart!) -> CGFloat { return CGFloat(-100) } /// mark - ZFBarChartDelegate func lineChart(lineChart: ZFLineChart!, didSelectCircleAtLineIndex lineIndex: Int, circleIndex: Int) { print(lineChart) } func lineChart(lineChart: ZFLineChart!, didSelectPopoverLabelAtLineIndex lineIndex: Int, circleIndex: Int) { let vc = ELCheckTheDetailsVC() vc.infDetails = information[circleIndex] self.navigationController?.pushViewController(vc, animated: true) } }
apache-2.0
4f323bda758f1fcc5d127a865c8550e3
26.765306
112
0.63065
4.519934
false
false
false
false
IngmarStein/swift
test/Sema/object_literals_osx.swift
4
1521
// RUN: %target-parse-verify-swift // REQUIRES: OS=macosx struct S: _ExpressibleByColorLiteral { init(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float) {} } let y: S = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) let y2 = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) // expected-error{{could not infer type of color literal}} expected-note{{import AppKit to use 'NSColor' as the default color literal type}} let y3 = #colorLiteral(red: 1, bleen: 0, grue: 0, alpha: 1) // expected-error{{cannot convert value of type '(red: Int, bleen: Int, grue: Int, alpha: Int)' to expected argument type '(red: Float, green: Float, blue: Float, alpha: Float)'}} struct I: _ExpressibleByImageLiteral { init(imageLiteralResourceName: String) {} } let z: I = #imageLiteral(resourceName: "hello.png") let z2 = #imageLiteral(resourceName: "hello.png") // expected-error{{could not infer type of image literal}} expected-note{{import AppKit to use 'NSImage' as the default image literal type}} struct Path: _ExpressibleByFileReferenceLiteral { init(fileReferenceLiteralResourceName: String) {} } let p1: Path = #fileLiteral(resourceName: "what.txt") let p2 = #fileLiteral(resourceName: "what.txt") // expected-error{{could not infer type of file reference literal}} expected-note{{import Foundation to use 'URL' as the default file reference literal type}} let text = #fileLiteral(resourceName: "TextFile.txt").relativeString! // expected-error{{type of expression is ambiguous without more context}}
apache-2.0
db87fdf2e6dcb268cbe4e5960e604686
57.5
239
0.734385
3.764851
false
false
false
false
crazypoo/PTools
Pods/SwifterSwift/Sources/SwifterSwift/UIKit/UIStackViewExtensions.swift
1
1886
// // UIStackViewExtensions.swift // SwifterSwift-iOS // // Created by Benjamin Meyer on 2/18/18. // Copyright © 2018 SwifterSwift // #if canImport(UIKit) && !os(watchOS) import UIKit // MARK: - Initializers public extension UIStackView { /// SwifterSwift: Initialize an UIStackView with an array of UIView and common parameters. /// /// let stackView = UIStackView(arrangedSubviews: [UIView(), UIView()], axis: .vertical) /// /// - Parameters: /// - arrangedSubviews: The UIViews to add to the stack. /// - axis: The axis along which the arranged views are laid out. /// - spacing: The distance in points between the adjacent edges of the stack view’s arranged views.(default: 0.0) /// - alignment: The alignment of the arranged subviews perpendicular to the stack view’s axis. (default: .fill) /// - distribution: The distribution of the arranged views along the stack view’s axis.(default: .fill) convenience init( arrangedSubviews: [UIView], axis: NSLayoutConstraint.Axis, spacing: CGFloat = 0.0, alignment: UIStackView.Alignment = .fill, distribution: UIStackView.Distribution = .fill) { self.init(arrangedSubviews: arrangedSubviews) self.axis = axis self.spacing = spacing self.alignment = alignment self.distribution = distribution } /// SwifterSwift: Adds array of views to the end of the arrangedSubviews array. /// /// - Parameter views: views array. func addArrangedSubviews(_ views: [UIView]) { for view in views { addArrangedSubview(view) } } /// SwifterSwift: Removes all views in stack’s array of arranged subviews. func removeArrangedSubviews() { for view in arrangedSubviews { removeArrangedSubview(view) } } } #endif
mit
601233421c069665a65bc17f26e72fec
31.929825
120
0.651039
4.623153
false
false
false
false
aperechnev/SwiftPGN
SwiftPGNTests/GameMetaTest.swift
1
1907
// // GameMetaTest.swift // SwiftPGN // // Created by Alexander Perechnev on 01.04.17. // Copyright © 2017 Alexander Perechnev. All rights reserved. // import XCTest @testable import SwiftPGN class GameMetaTest: XCTestCase { func testInitialization() { let bundle = Bundle(for: type(of: self)) let testFilePath = bundle.path(forResource: "one_game", ofType: "pgn") let fileContent = try! String(contentsOfFile: testFilePath!) var meta = GameMeta(pgnString: fileContent) XCTAssertEqual(meta.value(forMetaKey: .event), "IBM Kasparov vs. Deep Blue Rematch") XCTAssertEqual(meta.value(forMetaKey: .site), "New York, NY USA") XCTAssertEqual(meta.value(forMetaKey: .date), "1997.05.11") XCTAssertEqual(meta.value(forMetaKey: .round), "6") XCTAssertEqual(meta.value(forMetaKey: .white), "Deep Blue") XCTAssertEqual(meta.value(forMetaKey: .black), "Kasparov, Garry") XCTAssertEqual(meta.value(forMetaKey: .opening), "Caro-Kann: 4...Nd7") XCTAssertEqual(meta.value(forMetaKey: .eco), "B17") XCTAssertEqual(meta.value(forMetaKey: .result), "1-0") meta.set(value: nil, forMetaKey: .result) XCTAssertNil(meta.value(forMetaKey: .result)) } func testInitializationWithEmptyString() { let meta = GameMeta(pgnString: "") XCTAssertNil(meta.value(forMetaKey: .event)) } func testInitializationWithWrongString() { XCTAssertNil(GameMeta(pgnString: "[Event IBM Kasparov vs. Deep Blue Rematch]").value(forMetaKey: .event)) XCTAssertNil(GameMeta(pgnString: "[ \"IBM Kasparov vs. Deep Blue Rematch\"]").value(forMetaKey: .event)) } func testInitializationWithWrongKey() { XCTAssertNil(GameMeta(pgnString: "[WrongKey \"Some value\"]").value(forMetaKey: .event)) } }
mit
34fc22cd7c525adb451039879b8b1feb
35.653846
113
0.652676
3.744597
false
true
false
false
brightdigit/tubeswift
TubeSwift/ChannelClient.swift
1
4377
// // ChannelsClient.swift // TubeSwift // // Created by Leo G Dion on 4/27/15. // Copyright (c) 2015 Leo G Dion. All rights reserved. // import UIKit public let channel_url = "https://www.googleapis.com/youtube/v3/channels" public struct Response<T> { typealias ItemFactory = [String:AnyObject] -> T? public let etag:String public let items:[T] public let prevPageToken:String? public let nextPageToken:String? public let pageInfo:PageInfo public let kind:YouTubeKind public init?(kind: YouTubeKind, result: AnyObject?, itemFactory : ItemFactory) { if let dictionary = result as? [String:AnyObject], let etag = dictionary["etag"] as? String, let pageInfo = PageInfo(result:dictionary["pageInfo"]), let itemObjs = (dictionary["items"] as? [[String:AnyObject]]){ var items = [T]() for obj in itemObjs { if let channel = itemFactory(obj) { items.append(channel) } else { return nil } } self.kind = kind self.etag = etag self.pageInfo = pageInfo self.items = items self.prevPageToken = dictionary["prevPageToken"] as? String self.nextPageToken = dictionary["nextPageToken"] as? String } else { return nil } } } public enum YouTubeKind:String { case ChannelListResponse = "youtube#channelListResponse" case Channel = "youtube#channel" case PlaylistListResponse = "youtube#playlistListResponse" case SubscriptionListResponse = "youtube#subscriptionListResponse" case Playlist = "youtube#playlist" case Subscription = "youtube#subscription" } public struct RelatedPlaylists { public let favoritesId:String public let likesId:String public let uploadsId:String public let watchHistoryId:String public let watchLaterId:String public init?(result: [String:String]?) { if let dictionary = result, let favoritesId = dictionary["favorites"], let likesId = dictionary["likes"], let uploadsId = dictionary["uploads"], let watchHistoryId = dictionary["watchHistory"], let watchLaterId = dictionary["watchLater"]{ self.favoritesId = favoritesId self.likesId = likesId self.uploadsId = uploadsId self.watchHistoryId = watchHistoryId self.watchLaterId = watchLaterId } else { return nil } } } public struct ChannelContentDetails { public let googlePlusUserId:String public let relatedPlaylists:RelatedPlaylists public init?(result: [String:AnyObject]?) { if let dictionary = result, let googlePlusUserId = dictionary["googlePlusUserId"] as? String, let relatedPlaylists = RelatedPlaylists(result: dictionary["relatedPlaylists"] as? [String:String]) { self.googlePlusUserId = googlePlusUserId self.relatedPlaylists = relatedPlaylists } else { return nil } } } public struct Channel { public let etag:String public let id:String public let contentDetails:ChannelContentDetails public let kind:YouTubeKind = YouTubeKind.Channel public init?(result: [String:AnyObject]) { if let etag = result["etag"] as? String, let id = result["id"] as? String, let contentDetails = ChannelContentDetails(result: result["contentDetails"] as? [String:AnyObject]) { self.etag = etag self.id = id self.contentDetails = contentDetails } else { return nil } } } public struct PageInfo { public let resultsPerPage:Int public let totalResults:Int public init?(result : AnyObject?) { if let dictionary = result as? [String :Int], let resultsPerPage = dictionary["resultsPerPage"], let totalResults = dictionary["totalResults"] { self.resultsPerPage = resultsPerPage self.totalResults = totalResults } else { return nil } } } public class ChannelClient: NSObject { public let client: TubeSwiftClient public init (client: TubeSwiftClient) { self.client = client } public func list (query: ResourceQuery, completion: (NSURLRequest, NSURLResponse?, Response<Channel>?, NSError?) -> Void) { request(.GET, channel_url, parameters: query.parameters).responseJSON(options: .allZeros) { (request, response, result, error) -> Void in if let aError = error { completion(request, response, nil, aError) } else if let clRes = Response<Channel>(kind: YouTubeKind.ChannelListResponse,result: result, itemFactory: {Channel(result: $0)}) { completion(request, response, clRes, nil) } else { completion(request, response, nil, NSError()) } } } }
mit
2519a7f5d9a6f1e86f9bb46db029e9c3
28.375839
139
0.718529
3.632365
false
false
false
false
payjp/payjp-ios
Tests/Views/Mock.swift
1
5984
// // Mock.swift // PAYJP // // Created by Tadashi Wakayanagi on 2019/12/06. // Copyright © 2019 PAY, Inc. All rights reserved. // import XCTest import PassKit import AVFoundation @testable import PAYJP class MockCardFormScreenDelegate: CardFormScreenDelegate { var fetchedBrands: [CardBrand] = [] var showIndicatorCalled = false var dismissIndicatorCalled = false var enableSubmitButtonCalled = false var disableSubmitButtonCalled = false var showErrorViewMessage: String? var showErrorViewButtonHidden = false var dismissErrorViewCalled = false var showErrorAlertMessage: String? var presentVerificationScreenToken: Token? var didCompleteCardFormCalled = false var didProducedCalled = false let error: Error? let expectation: XCTestExpectation? init(error: Error? = nil, expectation: XCTestExpectation? = nil) { self.error = error self.expectation = expectation } func reloadBrands(brands: [CardBrand]) { fetchedBrands = brands expectation?.fulfill() } func showIndicator() { showIndicatorCalled = true } func dismissIndicator() { dismissIndicatorCalled = true } func enableSubmitButton() { enableSubmitButtonCalled = true } func disableSubmitButton() { disableSubmitButtonCalled = true } func showErrorView(message: String, buttonHidden: Bool) { showErrorViewMessage = message showErrorViewButtonHidden = buttonHidden expectation?.fulfill() } func dismissErrorView() { dismissErrorViewCalled = true } func showErrorAlert(message: String) { showErrorAlertMessage = message expectation?.fulfill() } func presentVerificationScreen(token: Token) { presentVerificationScreenToken = token expectation?.fulfill() } func didCompleteCardForm(with result: CardFormResult) { didCompleteCardFormCalled = true expectation?.fulfill() } func didProduced(with token: Token, completionHandler: @escaping (Error?) -> Void) { didProducedCalled = true completionHandler(error) } } class MockTokenService: TokenServiceType { var createTokenResult: Result<Token, APIError>? var createTokenTenantId: String? var finishTokenThreeDSecureResult: Result<Token, APIError>? var finishTokenThreeDSecureTokenId: String? var getTokenResult: Result<Token, APIError>? var getTokenTokenId: String? let tokenOperationObserver: TokenOperationObserverType = MockTokenOperationObserverType() // swiftlint:disable function_parameter_count func createToken(cardNumber: String, cvc: String, expirationMonth: String, expirationYear: String, name: String?, tenantId: String?, completion: @escaping (Result<Token, APIError>) -> Void) -> URLSessionDataTask? { self.createTokenTenantId = tenantId guard let result = createTokenResult else { fatalError("Set createTokenResult before invoked.") } completion(result) return nil } // swiftlint:enable function_parameter_count func createTokenForApplePay(paymentToken: PKPaymentToken, completion: @escaping (Result<Token, APIError>) -> Void) -> URLSessionDataTask? { return nil } func finishTokenThreeDSecure(tokenId: String, completion: @escaping (Result<Token, APIError>) -> Void) -> URLSessionDataTask? { self.finishTokenThreeDSecureTokenId = tokenId guard let result = finishTokenThreeDSecureResult else { fatalError("Set finishTokenThreeDSecureResult before invoked.") } completion(result) return nil } func getToken(with tokenId: String, completion: @escaping (Result<Token, APIError>) -> Void) -> URLSessionDataTask? { self.getTokenTokenId = tokenId guard let result = getTokenResult else { fatalError("Set getTokenResult before invoked.") } completion(result) return nil } } class MockAccountService: AccountsServiceType { let brands: [CardBrand] let error: APIError? var calledTenantId: String? init(brands: [CardBrand], error: APIError? = nil) { self.brands = brands self.error = error } func getAcceptedBrands(tenantId: String?, completion: CardBrandsResult?) -> URLSessionDataTask? { self.calledTenantId = tenantId if let error = error { completion?(.failure(error)) } else { completion?(.success(brands)) } return nil } } class MockPermissionFetcher: PermissionFetcherType { let status: AVAuthorizationStatus let shouldAccess: Bool // var completion : (() -> Void)? init(status: AVAuthorizationStatus = .notDetermined, shouldAccess: Bool = false) { self.status = status self.shouldAccess = shouldAccess } func checkCamera() -> AVAuthorizationStatus { return self.status } func requestCamera(completion: @escaping () -> Void) { if shouldAccess { completion() } } } class MockCardFormViewModelDelegate: CardFormViewModelDelegate { var startScannerCalled = false var showPermissionAlertCalled = false let expectation: XCTestExpectation? init(expectation: XCTestExpectation? = nil) { self.expectation = expectation } func startScanner() { startScannerCalled = true expectation?.fulfill() } func showPermissionAlert() { showPermissionAlertCalled = true } } class MockTokenOperationObserverType: TokenOperationObserverType { var status: TokenOperationStatus = .acceptable }
mit
78fed7b0336be6dffb234460816bc567
27.490476
114
0.651847
5.229895
false
false
false
false
cuzv/PullToRefresh
Example/SampleViewController.swift
2
4465
// // SampleViewController.swift // CHXRefreshControl // // Created by Shaw on 6/17/15. // Copyright © 2015 ReadRain. All rights reserved. // import UIKit class SampleViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { deinit { debugPrint("\(#file):\(#line):\(#function)") } @IBOutlet weak var tableView: UITableView! private lazy var data: [Data] = { var array: [Data] = [] for i in 0 ..< 10 { let data = DataGenerator.generatorSignleRow() array.append(data) } return array }() private var numberOfRows = 15 override func viewDidLoad() { super.viewDidLoad() // Top tableView.addTopRefreshContainerView(height: CGFloat(60.0)) { [unowned self] (scrollView: UIScrollView) -> Void in let time = DispatchTime.now() + Double(Int64(1 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time, execute: { // let range = Range(start: 0, end: 10) // self.data = Array(self.data[range]) for _ in 0 ..< 5 { let data = DataGenerator.generatorSignleRow() self.data.insert(data, at: 0) } self.tableView.reloadData() scrollView.endTopPullToRefresh() }) } let topRefreshView: LoosenRefreshView = LoosenRefreshView(frame: CGRect(x: 0, y: 0, width: 24, height: 24)) tableView.topRefreshContainerView?.delegate = topRefreshView tableView.topRefreshContainerView?.addSubview(topRefreshView) tableView.topRefreshContainerView?.scrollToTopAfterEndRefreshing = true // Bottom tableView.addBottomRefreshContainerView(height: 60) { [unowned self] (scrollView: UIScrollView) -> Void in DispatchQueue.global().async(execute: { for _ in 0 ..< 5 { let data = DataGenerator.generatorSignleRow() self.data.append(data) } let time = DispatchTime.now() + Double(Int64(1 * NSEC_PER_SEC)) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time, execute: { () -> Void in self.tableView.reloadData() scrollView.endBottomPullToRefresh() }) }) } let bottomRefreshView: InfiniteScrollView = InfiniteScrollView(frame: CGRect(x: 0, y: 0, width: 24, height: 24)) tableView.bottomRefreshContainerView?.addSubview(bottomRefreshView) } // MARK: Actions @IBAction func insert(_ sender: UIBarButtonItem) { let previousContentOffSetHeight = self.tableView.contentOffset.y let previousContentHeight = self.tableView.contentSize.height // - self.tableView.contentInset.top + self.tableView.contentInset.bottom debugPrint("previousContentHeight: \(previousContentHeight)") for _ in 0 ..< 5 { let data = DataGenerator.generatorSignleRow() self.data.insert(data, at: 0) } self.tableView.reloadData() let nowcontentHeight = self.tableView.contentSize.height // - self.tableView.contentInset.top + self.tableView.contentInset.bottom debugPrint("nowcontentHeight: \(nowcontentHeight)") self.tableView.contentOffset = CGPoint(x: 0, y: nowcontentHeight - previousContentHeight + previousContentOffSetHeight) } // MARK: UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: "Cell") if nil == cell { cell = UITableViewCell(style: .default, reuseIdentifier: "Cell") } cell!.textLabel?.text = data[(indexPath as NSIndexPath).row].text return cell! } // MARK: UITableViewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return data[(indexPath as NSIndexPath).row].height } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } }
mit
fec0db6d33cea0e86dcd10a45a651831
37.482759
127
0.612903
4.92172
false
false
false
false
cuappdev/tcat-ios
TCAT/Model/LocationObject.swift
1
1504
// // BusLocation.swift // TCAT // // Created by Matthew Barker on 9/6/17. // Copyright © 2017 cuappdev. All rights reserved. // import MapKit import UIKit /// Generic location object for locations with identifiers and names class LocationObject: NSObject, Codable { /// The name of the location var name: String /// The identifier associated with the location /// Used mainly for stopID for bus stop locations. var id: String /// The latitude coordinate of the location var latitude: Double /// The longitude coordinate of the location var longitude: Double init(name: String, id: String, latitude: Double, longitude: Double) { self.name = name self.id = id self.latitude = latitude self.longitude = longitude } private enum CodingKeys: String, CodingKey { case latitude = "lat" case longitude = "long" case name case id = "stopID" } /// Blank init to store name convenience init(name: String) { self.init(name: name, id: "", latitude: 0.0, longitude: 0.0) } /// Init without using the `id` parameter convenience init(name: String, latitude: Double, longitude: Double) { self.init(name: name, id: "", latitude: latitude, longitude: longitude) } /// The coordinates of the location. var coordinates: CLLocationCoordinate2D { return CLLocationCoordinate2D(latitude: self.latitude, longitude: self.longitude) } }
mit
e28d3f84cc5f8903f322be41c88ae6a7
25.368421
89
0.650033
4.343931
false
false
false
false
danfsd/FolioReaderKit
Source/Models/Highlight+Migration.swift
1
1982
// // Highlight+Migration.swift // FolioReaderKit // // Created by Heberti Almeida on 06/07/16. // Copyright (c) 2015 Folio Reader. All rights reserved. // import Foundation import RealmSwift import CoreData extension Highlight { public static func migrateUserDataToRealm() { var highlights: [NSManagedObject]? let coreDataManager = CoreDataManager() do { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Highlight") let sorter: NSSortDescriptor = NSSortDescriptor(key: "date" , ascending: false) fetchRequest.sortDescriptors = [sorter] highlights = try coreDataManager.managedObjectContext.fetch(fetchRequest) as? [NSManagedObject] let realm = try! Realm() realm.beginWrite() realm.deleteAll() for oldHighlight in highlights! { let newHighlight = Highlight() newHighlight.bookId = oldHighlight.value(forKey: "bookId") as! String newHighlight.content = oldHighlight.value(forKey: "content") as! String newHighlight.contentPost = oldHighlight.value(forKey: "contentPost") as! String newHighlight.contentPre = oldHighlight.value(forKey: "contentPre") as! String newHighlight.date = oldHighlight.value(forKey: "date") as! Foundation.Date newHighlight.highlightId = oldHighlight.value(forKey: "highlightId") as! String newHighlight.page = oldHighlight.value(forKey: "page") as! Int newHighlight.type = oldHighlight.value(forKey: "type") as! Int realm.add(newHighlight, update: true) } try! realm.commitWrite() FolioReader.defaults.set(true, forKey: kMigratedToRealm) } catch let error as NSError { print("Error on migrateuserDataToRealm : \(error)") } } }
bsd-3-clause
53990b26664f7f1ec9cfa07d6c2220d1
41.170213
107
0.622603
4.979899
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/ArticleViewController+Media.swift
1
4119
import Foundation extension ArticleViewController { func getMediaList(_ completion: @escaping (Result<MediaList, Error>) -> Void) { assert(Thread.isMainThread) if let mediaList = mediaList { completion(.success(mediaList)) return } let request: URLRequest do { request = try fetcher.mobileHTMLMediaListRequest(articleURL: articleURL) } catch let error { completion(.failure(error)) return } fetcher.fetchMediaList(with: request) { [weak self] (result, _) in DispatchQueue.main.async { switch result { case .success(let mediaList): self?.mediaList = mediaList completion(.success(mediaList)) case .failure(let error): completion(.failure(error)) } } } } func showImage(src: String, href: String, width: Int?, height: Int?) { getMediaList { (result) in switch result { case .failure(let error): self.showError(error) case .success(let mediaList): self.showImage(in: mediaList, src: src, href: href, width: width, height: height) } } } func showLeadImage() { getMediaList { (result) in switch result { case .failure(let error): self.showError(error) case .success(let mediaList): self.showImage(in: mediaList, item: mediaList.items.first(where: { $0.isLeadImage })) } } } func showImage(in mediaList: MediaList, src: String, href: String, width: Int?, height: Int?) { let title = href.replacingOccurrences(of: "./", with: "", options: .anchored) guard let index = mediaList.items.firstIndex(where: { $0.title == title }) else { showImage(in: mediaList, item: nil) return } let item = mediaList.items[index] showImage(in: mediaList, item: item) } func showImage(in mediaList: MediaList, item: MediaListItem?) { let gallery = getGalleryViewController(for: item, in: mediaList) present(gallery, animated: true) } func fetchAndDisplayGalleryViewController() { /// We can't easily change the photos on the VC after it launches, so we create a loading VC screen and then add the proper galleryVC as a child after the data returns. let emptyPhotoViewer = WMFImageGalleryViewController(photos: nil) let activityIndicator = UIActivityIndicatorView(style: .medium) activityIndicator.color = .white emptyPhotoViewer.view.addSubview(activityIndicator) activityIndicator.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ activityIndicator.centerXAnchor.constraint(equalTo: emptyPhotoViewer.view.centerXAnchor), activityIndicator.centerYAnchor.constraint(equalTo: emptyPhotoViewer.view.centerYAnchor) ]) activityIndicator.startAnimating() present(emptyPhotoViewer, animated: true) getMediaList { (result) in switch result { case .failure(let error): let completion = { self.showError(error) } emptyPhotoViewer.dismiss(animated: true, completion: completion) case .success(let mediaList): activityIndicator.stopAnimating() let gallery = self.getGalleryViewController(for: nil, in: mediaList) emptyPhotoViewer.wmf_add(childController: gallery, andConstrainToEdgesOfContainerView: emptyPhotoViewer.view) } } } func getGalleryViewController(for item: MediaListItem?, in mediaList: MediaList) -> MediaListGalleryViewController { return MediaListGalleryViewController(articleURL: articleURL, mediaList: mediaList, dataStore: dataStore, initialItem: item, theme: theme) } }
mit
f0a5daed03a36e80207d0eb449d51b3c
39.382353
176
0.606701
5.253827
false
false
false
false
sabirvirtuoso/Mockit
Mockit/Classes/VerificationData.swift
1
1609
// // Mockit // // Copyright (c) 2016 Syed Sabir Salman-Al-Musawi <[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 /** * A class to hold verification data of a specific method call. */ public class VerificationData { public var functionName = "" public var timesInvoked = 0 public var calledOnly = false public var file = "" public var line: Int = 0 public typealias buildVerificationDataClosure = (VerificationData) -> Void public init(build: buildVerificationDataClosure) { build(self) } }
mit
d7c0bb4547bc48529ba09b773a2260b4
36.418605
81
0.742076
4.212042
false
false
false
false
ps2/rileylink_ios
MinimedKit/Extensions/Int.swift
1
527
// // Int.swift // Naterade // // Created by Nathan Racklyeft on 12/26/15. // Copyright © 2015 Nathan Racklyeft. All rights reserved. // import Foundation extension Int { init<T: Collection>(bigEndianBytes bytes: T) where T.Element == UInt8 { assert(bytes.count <= 4) var result: UInt = 0 for (index, byte) in bytes.enumerated() { let shiftAmount = UInt((bytes.count) - index - 1) * 8 result += UInt(byte) << shiftAmount } self.init(result) } }
mit
3bff923fe4e905bb766a321ff8ea276f
20.916667
75
0.585551
3.678322
false
false
false
false
antitypical/TesseractCore
TesseractCore/FlatMapSequenceView.swift
1
1774
// Copyright (c) 2015 Rob Rix. All rights reserved. public struct FlatMapSequenceView<Base: SequenceType, Each: SequenceType>: SequenceType { public init(_ base: Base, _ transform: Base.Generator.Element -> Each) { self.base = base self.transform = transform } // MARK: SequenceType public func generate() -> GeneratorOf<Each.Generator.Element> { var outer = base.generate() var inner: Each.Generator? return GeneratorOf { next( { () -> Bool in inner = outer.next().map(self.transform)?.generate() return inner != nil }, { inner?.next() } ) } } // MARK: Private private let base: Base private let transform: Base.Generator.Element -> Each } private func next<T>(outer: () -> Bool, inner: () -> T?) -> T? { return inner() ?? (outer() ? next(outer, inner) : nil) } extension LazySequence { func flatMap<Each: SequenceType>(transform: S.Generator.Element -> Each) -> LazySequence<FlatMapSequenceView<LazySequence<S>, Each>> { return lazy(FlatMapSequenceView(self, transform)) } } extension LazyForwardCollection { func flatMap<Each: SequenceType>(transform: S.Generator.Element -> Each) -> LazySequence<FlatMapSequenceView<LazyForwardCollection<S>, Each>> { return lazy(FlatMapSequenceView(self, transform)) } } extension LazyBidirectionalCollection { func flatMap<Each: SequenceType>(transform: S.Generator.Element -> Each) -> LazySequence<FlatMapSequenceView<LazyBidirectionalCollection<S>, Each>> { return lazy(FlatMapSequenceView(self, transform)) } } extension LazyRandomAccessCollection { func flatMap<Each: SequenceType>(transform: S.Generator.Element -> Each) -> LazySequence<FlatMapSequenceView<LazyRandomAccessCollection<S>, Each>> { return lazy(FlatMapSequenceView(self, transform)) } }
mit
1609125461d11fa9cd47c388d41acaed
28.566667
150
0.719278
3.750529
false
false
false
false
mownier/photostream
Photostream/Modules/Follow List/Interactor/FollowListInteractor.swift
1
4485
// // FollowListInteractor.swift // Photostream // // Created by Mounir Ybanez on 17/01/2017. // Copyright © 2017 Mounir Ybanez. All rights reserved. // protocol FollowListInteractorInput: BaseModuleInteractorInput { func fetchNew(userId: String, type: FollowListFetchType, limit: UInt) func fetchNext(userId: String, type: FollowListFetchType, limit: UInt) func follow(userId: String) func unfollow(userId: String) } protocol FollowListInteractorOutput: BaseModuleInteractorOutput { func didFetchNew(with data: [FollowListData]) func didFetchNext(with data: [FollowListData]) func didFetchNew(with error: UserServiceError) func didFetchNext(with error: UserServiceError) func didFollow(with error: UserServiceError?, userId: String) func didUnfollow(with error: UserServiceError?, userId: String) } protocol FollowListInteractorInterface: BaseModuleInteractor { var service: UserService! { set get } var offset: String? { set get } var isFetching: Bool { set get } init(service: UserService) func fetch(userId: String, type: FollowListFetchType, limit: UInt) } class FollowListInteractor: FollowListInteractorInterface { typealias Output = FollowListInteractorOutput weak var output: Output? var service: UserService! var offset: String? var isFetching: Bool = false required init(service: UserService) { self.service = service } func fetch(userId: String, type: FollowListFetchType, limit: UInt) { guard output != nil, offset != nil, !isFetching else { return } isFetching = true switch type { case .followers: service.fetchFollowers(id: userId, offset: offset!, limit: limit, callback: { [weak self] result in self?.didFinishFetching(result: result) }) case .following: service.fetchFollowing(id: userId, offset: offset!, limit: limit, callback: { [weak self] result in self?.didFinishFetching(result: result) }) } } fileprivate func didFinishFetching(result: UserServiceFollowListResult) { isFetching = false guard result.error == nil else { didFetch(with: result.error!) return } guard let users = result.users, users.count > 0 else { didFetch(with: [FollowListData]()) return } var data = [FollowListData]() for user in users { var item = FollowListDataItem() item.avatarUrl = user.avatarUrl item.displayName = user.displayName item.userId = user.id item.isFollowing = result.following != nil && result.following![user.id] != nil if let isMe = result.following?[user.id] { item.isMe = isMe } data.append(item) } didFetch(with: data) } fileprivate func didFetch(with error: UserServiceError) { guard offset != nil else { return } if offset!.isEmpty { output?.didFetchNew(with: error) } else { output?.didFetchNext(with: error) } } fileprivate func didFetch(with data: [FollowListData]) { guard offset != nil else { return } if offset!.isEmpty { output?.didFetchNew(with: data) } else { output?.didFetchNext(with: data) } } } extension FollowListInteractor: FollowListInteractorInput { func fetchNew(userId: String, type: FollowListFetchType, limit: UInt) { offset = "" fetch(userId: userId, type: type, limit: limit) } func fetchNext(userId: String, type: FollowListFetchType, limit: UInt) { fetch(userId: userId, type: type, limit: limit) } func follow(userId: String) { service.follow(id: userId) { [weak self] error in self?.output?.didFollow(with: error, userId: userId) } } func unfollow(userId: String) { service.unfollow(id: userId) { [weak self] error in self?.output?.didUnfollow(with: error, userId: userId) } } }
mit
f01df26e26004f487b142b7d40130147
27.379747
91
0.584523
4.790598
false
false
false
false
zouguangxian/VPNOn
TodayWidget/TodayViewController.swift
1
3717
// // TodayViewController.swift // TodayWidget // // Created by Lex Tang on 12/10/14. // Copyright (c) 2014 LexTang.com. All rights reserved. // import UIKit import NotificationCenter import NetworkExtension import VPNOnKit class TodayViewController: UIViewController, NCWidgetProviding { @IBOutlet weak var VPNSwitch: UISwitch! @IBOutlet weak var VPNLabel: UILabel! var VPNTitle = "" override func viewDidLoad() { super.viewDidLoad() preferredContentSize = CGSizeMake(0, 50) var tapGesture = UITapGestureRecognizer(target: self, action: Selector("didTapLabel:")) tapGesture.numberOfTapsRequired = 1 tapGesture.numberOfTouchesRequired = 1 VPNLabel.userInteractionEnabled = true VPNLabel.addGestureRecognizer(tapGesture) if let vpn = VPNManager.sharedManager().activatedVPNDict as NSDictionary? { VPNTitle = vpn.objectForKey("title") as String VPNSwitch.enabled = true VPNStatusDidChange(nil) } else { VPNLabel.text = "Please add a VPN." VPNSwitch.setOn(false, animated: false) VPNSwitch.enabled = false } NSNotificationCenter.defaultCenter().addObserver( self, selector: Selector("VPNStatusDidChange:"), name: NEVPNStatusDidChangeNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver( self, name: NEVPNStatusDidChangeNotification, object: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.VPNSwitch.setNeedsUpdateConstraints() } func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) -> Void)!) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData completionHandler(NCUpdateResult.NewData) } func widgetMarginInsetsForProposedMarginInsets(defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets { var edgeInsets = defaultMarginInsets edgeInsets.bottom = 0 edgeInsets.right = 0 return edgeInsets } @IBAction func toggleVPN(sender: UISwitch) { if sender.on { VPNManager.sharedManager().connect() } else { VPNManager.sharedManager().disconnect() } } func didTapLabel(label: UILabel) { let appURL = NSURL(string: "vpnon://") extensionContext!.openURL(appURL!, completionHandler: { (complete: Bool) -> Void in }) } func VPNStatusDidChange(notification: NSNotification?) { switch VPNManager.sharedManager().status { case NEVPNStatus.Connecting: VPNLabel.text = "\(VPNTitle) - Connecting..." VPNSwitch.enabled = false break case NEVPNStatus.Connected: VPNLabel.text = "\(VPNTitle) - Connected" VPNSwitch.setOn(true, animated: false) VPNSwitch.enabled = true break case NEVPNStatus.Disconnecting: VPNLabel.text = "\(VPNTitle) - Disconnecting..." VPNSwitch.enabled = false break default: VPNSwitch.setOn(false, animated: false) VPNSwitch.enabled = true VPNLabel.text = "\(VPNTitle) - Not Connected" } } }
mit
70fe486a2a64185080b89801cb2ea611
30.769231
101
0.612053
5.257426
false
false
false
false
paritoshmmmec/IBM-Ready-App-for-Healthcare
iOS/ReadyAppPT/Controllers/ExerciseListViewController.swift
2
9007
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2014, 2015. All Rights Reserved. */ import UIKit /** View controller to display a list of exercise categories. */ class ExerciseListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CustomAlertViewDelegate { var areaTypes = [NSLocalizedString("Assigned", comment: "n/a"), NSLocalizedString("Neck", comment: "n/a"), NSLocalizedString("Back", comment: "n/a") , NSLocalizedString("Torso", comment: "n/a"), NSLocalizedString("Arm", comment: "n/a"), NSLocalizedString("Hand", comment: "n/a"), NSLocalizedString("Leg", comment: "n/a"), NSLocalizedString("Feet", comment: "n/a")] @IBOutlet weak var exerciseTableView: UITableView! var alertViewSimple: CustomAlertView! var tapGestureRecognizer: UITapGestureRecognizer! var dataReturned = (routine: RoutineResultType.Unknown, exercise: ExerciseResultType.Unknown) var alertText = NSLocalizedString("Assets not added yet.", comment: "") var noDataAlertText = NSLocalizedString("Could not retrieve data from the server, try again later.", comment: "") var appDelegate : AppDelegate! // MARK: lifecycle methods override func viewDidLoad() { super.viewDidLoad() Utils.rootViewMenu(self.parentViewController!, disablePanning: true) appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate tapGestureRecognizer = UITapGestureRecognizer(target: self, action:Selector("handleTap:")) tapGestureRecognizer.numberOfTapsRequired = 1 self.view.addGestureRecognizer(tapGestureRecognizer) tapGestureRecognizer.enabled = false // Setup the alert view var alertImageName = "x_blue" alertViewSimple = CustomAlertView.initWithText(alertText, imageName: alertImageName) alertViewSimple.setTranslatesAutoresizingMaskIntoConstraints(false) alertViewSimple.delegate = self alertViewSimple.hidden = true self.view.addSubview(alertViewSimple) self.setupAlertViewConstraints() //send notification to challenge handler let userInfo:Dictionary<String,UIViewController!> = ["ExerciseListViewController" : self] NSNotificationCenter.defaultCenter().postNotificationName("viewController", object: nil, userInfo: userInfo) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) dataReturned = (RoutineResultType.Unknown, ExerciseResultType.Unknown) } /** Notifies the ReadyAppsChallengeHandler that another view controller has been placed on top of the exercise list view controller */ override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) let userInfo:Dictionary<String,Bool!> = ["ExerciseListViewController" : false] NSNotificationCenter.defaultCenter().postNotificationName("disappear", object: nil, userInfo: userInfo) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /** Setups the the custom alert view to fill the entire view */ func setupAlertViewConstraints() { var viewsDict = Dictionary<String, UIView>() viewsDict["alertView"] = self.alertViewSimple viewsDict["view"] = self.view self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[alertView]|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: viewsDict)) self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[alertView]|", options: NSLayoutFormatOptions.DirectionLeadingToTrailing, metrics: nil, views: viewsDict)) } /** Custom alert view delegate method that is triggered when the alert view is tapped. */ func handleAlertTap() { self.alertViewSimple.hidden = true self.alertViewSimple.alertLabel.text = alertText } /** Method to open the side panel */ func openSideMenu() { var container = self.navigationController?.parentViewController as! ContainerViewController container.toggleLeftPanel() self.exerciseTableView.userInteractionEnabled = false tapGestureRecognizer.enabled = true } /** Method to handle taps when the side menu is open :param: recognizer tap gesture used to call method */ func handleTap(recognizer: UITapGestureRecognizer) { var container = self.navigationController?.parentViewController as! ContainerViewController // check if expanded so tapgesture isn't enabled when it shouldn't be if container.currentState == SlideOutState.LeftExpanded { container.toggleLeftPanel() self.exerciseTableView.userInteractionEnabled = true tapGestureRecognizer.enabled = false } else { self.exerciseTableView.userInteractionEnabled = true tapGestureRecognizer.enabled = false } } // MARK: UITableView delegate methods func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return areaTypes.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("exerciseCell") as! ListTableViewCell if indexPath.row == 0 { cell.primaryLabel.textColor = UIColor.readyAppBlue() } cell.primaryLabel.text = areaTypes[indexPath.row] return cell } /** Handles a selection of the table view. If "Assigned" is selected, segue to the next view controller. Otherwise show an alert notifying the user that those assets are not available. */ func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.row == 0 { SVProgressHUD.showWithMaskType(SVProgressHUDMaskType.Gradient) var routineDataManager = RoutineDataManager.routineDataManager routineDataManager.getRoutines(DataManager.dataManager.currentPatient.userID, callback: routineDataGathered) //check if routines has been populated since they could be invoked when the user has timedout //if rountines is nil, make sure it has been populated before moving on var routineID : [String] = DataManager.dataManager.currentPatient.routineId var exerciseDataManager = ExerciseDataManager.exerciseDataManager exerciseDataManager.getExercisesForRoutine(routineID[0], callback: exerciseDataGathered) } else { self.alertViewSimple.hidden = false } } /** Callback method that gets called when data is returned from the server :param: result the result stating if the database call was successful */ func routineDataGathered(result: RoutineResultType) { dataReturned.routine = result if result == RoutineResultType.Success { if dataReturned.routine == RoutineResultType.Success && dataReturned.exercise == ExerciseResultType.Success { SVProgressHUD.dismiss() self.performSegueWithIdentifier("routineSegue", sender: nil) } } else { if dataReturned.routine == RoutineResultType.Failure && dataReturned.exercise == ExerciseResultType.Failure { SVProgressHUD.dismiss() self.alertViewSimple.alertLabel.text = noDataAlertText self.alertViewSimple.hidden = false } } } /** Callback method that gets called when data is returned from the server (in the case that user is logged in and there was no timeout. In the case of a user timeout, the ReadyAppsChallengeHandler:customResponse is called. :param: result the result stating if the database call was successful */ func exerciseDataGathered(result: ExerciseResultType) { dataReturned.exercise = result if result == ExerciseResultType.Success { if dataReturned.routine == RoutineResultType.Success && dataReturned.exercise == ExerciseResultType.Success { SVProgressHUD.dismiss() self.performSegueWithIdentifier("routineSegue", sender: nil) } } else { if dataReturned.routine == RoutineResultType.Failure && dataReturned.exercise == ExerciseResultType.Failure { SVProgressHUD.dismiss() self.alertViewSimple.alertLabel.text = noDataAlertText self.alertViewSimple.hidden = false } } } }
epl-1.0
63519a3cf6fe8401a8d1ca113f52dcc3
41.885714
368
0.681324
5.70361
false
false
false
false
taqun/TodoEver
TodoEver/Classes/Operation/TDEListNotesOperation.swift
1
2472
// // TDEListNotesOperation.swift // TodoEver // // Created by taqun on 2015/05/30. // Copyright (c) 2015年 envoixapp. All rights reserved. // import UIKit class TDEListNotesOperation: TDEConcurrentOperation { override func start() { super.start() let semaphore = dispatch_semaphore_create(0) var noteFilter = EDAMNoteFilter() noteFilter.tagGuids = [TDEModelManager.sharedInstance.todoEverTagGuid] var resultSpec = EDAMNotesMetadataResultSpec() resultSpec.includeTitle = true resultSpec.includeUpdateSequenceNum = true let noteStore = ENSession.sharedSession().primaryNoteStore() noteStore.findNotesMetadataWithFilter(noteFilter, maxResults: 100, resultSpec: resultSpec, success: { (response) -> Void in if let noteMetas = response as? [EDAMNoteMetadata] { for noteMeta in noteMetas { if let localNote = TDEModelManager.sharedInstance.getNoteByGuid(noteMeta.guid) { if let usn = noteMeta.updateSequenceNum { println(" note: " + localNote.title) println(" Remote USN: \(usn)") println(" Local USN: \(localNote.usn)") if usn.intValue > localNote.usn.intValue { println(" => \(localNote.title) should be update.") localNote.needsToSync = true localNote.remoteUsn = usn } } } else { var note = TDEMNote.MR_createEntity() as! TDEMNote note.parseMetaData(noteMeta) note.needsToSync = true note.remoteUsn = 0 } } } NSNotificationCenter.defaultCenter().postNotificationName(TDENotification.UPDATE_NOTES, object: nil) dispatch_semaphore_signal(semaphore) }) { (error) -> Void in println(error) dispatch_semaphore_signal(semaphore) } dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) self.complete() } }
mit
1a47f2ed855e004813a1c4f971513b18
34.797101
131
0.505263
5.266525
false
false
false
false
aronse/Hero
Sources/Debug Plugin/HeroDebugPlugin.swift
2
6354
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit #if os(iOS) public class HeroDebugPlugin: HeroPlugin { public static var showOnTop: Bool = false var debugView: HeroDebugView? var zPositionMap = [UIView: CGFloat]() var addedLayers: [CALayer] = [] var updating = false override public func animate(fromViews: [UIView], toViews: [UIView]) -> TimeInterval { if hero.forceNotInteractive { return 0 } var hasArc = false for v in context.fromViews + context.toViews where context[v]?.arc != nil && context[v]?.position != nil { hasArc = true break } let debugView = HeroDebugView(initialProcess: hero.isPresenting ? 0.0 : 1.0, showCurveButton: hasArc, showOnTop: HeroDebugPlugin.showOnTop) debugView.frame = hero.container.bounds debugView.delegate = self hero.container.window?.addSubview(debugView) debugView.layoutSubviews() self.debugView = debugView UIView.animate(withDuration: 0.4) { debugView.showControls = true } return .infinity } public override func resume(timePassed: TimeInterval, reverse: Bool) -> TimeInterval { guard let debugView = debugView else { return 0.4 } debugView.delegate = nil UIView.animate(withDuration: 0.4) { debugView.showControls = false debugView.debugSlider.setValue(roundf(debugView.progress), animated: true) } on3D(wants3D: false) return 0.4 } public override func clean() { debugView?.removeFromSuperview() debugView = nil } } extension HeroDebugPlugin: HeroDebugViewDelegate { public func onDone() { guard let debugView = debugView else { return } let seekValue = hero.isPresenting ? debugView.progress : 1.0 - debugView.progress if seekValue > 0.5 { hero.finish() } else { hero.cancel() } } public func onProcessSliderChanged(progress: Float) { let seekValue = hero.isPresenting ? progress : 1.0 - progress hero.update(CGFloat(seekValue)) } func onPerspectiveChanged(translation: CGPoint, rotation: CGFloat, scale: CGFloat) { var t = CATransform3DIdentity t.m34 = -1 / 4000 t = CATransform3DTranslate(t, translation.x, translation.y, 0) t = CATransform3DScale(t, scale, scale, 1) t = CATransform3DRotate(t, rotation, 0, 1, 0) hero.container.layer.sublayerTransform = t } func animateZPosition(view: UIView, to: CGFloat) { let a = CABasicAnimation(keyPath: "zPosition") a.fromValue = view.layer.value(forKeyPath: "zPosition") a.toValue = NSNumber(value: Double(to)) a.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) a.duration = 0.4 view.layer.add(a, forKey: "zPosition") view.layer.zPosition = to } func onDisplayArcCurve(wantsCurve: Bool) { for layer in addedLayers { layer.removeFromSuperlayer() addedLayers.removeAll() } if wantsCurve { for layer in hero.container.layer.sublayers! { for (_, anim) in layer.animations { if let keyframeAnim = anim as? CAKeyframeAnimation, let path = keyframeAnim.path { let s = CAShapeLayer() s.zPosition = layer.zPosition + 10 s.path = path s.strokeColor = UIColor.blue.cgColor s.fillColor = UIColor.clear.cgColor hero.container.layer.addSublayer(s) addedLayers.append(s) } } } } } func on3D(wants3D: Bool) { var t = CATransform3DIdentity if wants3D { var viewsWithZPosition = Set<UIView>() for view in hero.container.subviews where view.layer.zPosition != 0 { viewsWithZPosition.insert(view) zPositionMap[view] = view.layer.zPosition } let viewsWithoutZPosition = hero.container.subviews.filter { return !viewsWithZPosition.contains($0) } let viewsWithPositiveZPosition = viewsWithZPosition.filter { return $0.layer.zPosition > 0 } for (i, v) in viewsWithoutZPosition.enumerated() { animateZPosition(view: v, to: CGFloat(i * 10)) } var maxZPosition: CGFloat = 0 for v in viewsWithPositiveZPosition { maxZPosition = max(maxZPosition, v.layer.zPosition) animateZPosition(view: v, to: v.layer.zPosition + CGFloat(viewsWithoutZPosition.count * 10)) } t.m34 = -1 / 4000 t = CATransform3DTranslate(t, debugView!.translation.x, debugView!.translation.y, 0) t = CATransform3DScale(t, debugView!.scale, debugView!.scale, 1) t = CATransform3DRotate(t, debugView!.rotation, 0, 1, 0) } else { for v in hero.container.subviews { animateZPosition(view: v, to: self.zPositionMap[v] ?? 0) } self.zPositionMap.removeAll() } let a = CABasicAnimation(keyPath: "sublayerTransform") a.fromValue = hero.container.layer.value(forKeyPath: "sublayerTransform") a.toValue = NSValue(caTransform3D: t) a.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) a.duration = 0.4 UIView.animate(withDuration: 0.4) { self.context.container.backgroundColor = UIColor(white: 0.85, alpha: 1.0) } hero.container.layer.add(a, forKey: "debug") hero.container.layer.sublayerTransform = t } } #endif
mit
47a20f89b74694d305422350db4a3f7d
34.497207
143
0.689487
4.150229
false
false
false
false
hardikdevios/HKKit
Pod/Classes/HKExtensions/UIKit+Extensions/UITextField+Extension.swift
1
4203
// // UITextField+Extension.swift // HKCustomization // // Created by Hardik on 10/18/15. // Copyright © 2015 . All rights reserved. // import UIKit extension UITextField{ public func hk_setDefaultBottomBorder()->Void{ let border = CALayer() let width = CGFloat(1) border.borderColor = UIColor.lightGray.cgColor border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.bounds.size.width, height: self.frame.size.height) border.borderWidth = width self.layer.addSublayer(border) self.layer.masksToBounds = true } public func hk_setSelectedBottomBorder()->Void{ let border = CALayer() let width = CGFloat(1) border.borderColor = HKConstant.sharedInstance.main_color.cgColor border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height) border.borderWidth = width self.layer.addSublayer(border) self.layer.masksToBounds = true } public func hk_setDefaultText(_ defaultText:String!)->Void{ if self.text == "" || self.text == " " || self.text == nil{ self.text = defaultText } } public func hk_setLeftImgView(_ imgName:String!,contentMode:UIView.ContentMode = .center)->Void{ self.layoutIfNeeded() let leftViewForImg = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: self.frame.size.height)) let imgView = UIImageView(image: UIImage(named: imgName)!) imgView.frame = CGRect(x: 0, y: 0, width: leftViewForImg.frame.size.width - 20, height: leftViewForImg.frame.size.height - 20) imgView.center = leftViewForImg.center imgView.contentMode = contentMode leftViewForImg.addSubview(imgView) self.leftView = leftViewForImg self.leftViewMode = .always } public func hk_setPlaceHolderColor(_ color:UIColor){ self.attributedPlaceholder = NSAttributedString(string:self.placeholder ?? "", attributes:[NSAttributedString.Key.foregroundColor:color]) } } extension UITextField { public func hk_getIndexPathForTableView(for tableView:UITableView)->IndexPath?{ return tableView.indexPathForRow(at: (self.superview?.convert(self.frame.origin, to:tableView))!) } } extension UITextField{ public func hk_isEmpty()->Bool{ if self.text!.hk_trimWhiteSpace() != "" { return false } if let textfield = self as? HKTextField{ textfield.hk_setPlaceHolderColor(textfield.validationErrorColor) } self.hk_shake() return true } public func hk_isEmail() -> Bool { let regex = try? NSRegularExpression(pattern: "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2}", options: .caseInsensitive) return regex?.firstMatch(in: self.text!.hk_trimWhiteSpace()!, options: [], range: NSMakeRange(0, self.text!.hk_trimWhiteSpace()!.count)) != nil } public func hk_shake(){ let animation = CABasicAnimation(keyPath: "position") animation.duration = 0.10 animation.autoreverses = true animation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 10, y: self.center.y)) animation.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + 10, y: self.center.y)) self.layer.add(animation, forKey: "position") } public func hk_setLockViewAndDisabled(_ isLeft:Bool = false){ let view:UIView = UIView(frame: CGRect(x: 0, y: 0, width: 30 , height: 30)) let label = UILabel(frame: CGRect(x: 0, y: 0, width: 25 ,height: 25)) label.textAlignment = NSTextAlignment.center label.text = "🔒" view.addSubview(label) self.isEnabled = false if isLeft { self.leftView = view self.leftViewMode = .always }else{ self.rightView = view self.rightViewMode = .always } } }
mit
64d0b1cf98dd64190c67865983f4da05
32.062992
151
0.60443
4.302254
false
false
false
false
Monnoroch/Cuckoo
Generator/Dependencies/SourceKitten/Source/sourcekitten/DocCommand.swift
1
3814
// // DocCommand.swift // SourceKitten // // Created by JP Simard on 2015-01-07. // Copyright (c) 2015 SourceKitten. All rights reserved. // import Commandant import Foundation import Result import SourceKittenFramework struct DocCommand: CommandProtocol { let verb = "doc" let function = "Print Swift docs as JSON or Objective-C docs as XML" struct Options: OptionsProtocol { let spmModule: String let singleFile: Bool let moduleName: String let objc: Bool let arguments: [String] static func create(spmModule: String) -> (_ singleFile: Bool) -> (_ moduleName: String) -> (_ objc: Bool) -> (_ arguments: [String]) -> Options { return { singleFile in { moduleName in { objc in { arguments in self.init(spmModule: spmModule, singleFile: singleFile, moduleName: moduleName, objc: objc, arguments: arguments) }}}} } static func evaluate(_ m: CommandMode) -> Result<Options, CommandantError<SourceKittenError>> { return create <*> m <| Option(key: "spm-module", defaultValue: "", usage: "document a Swift Package Manager module") <*> m <| Option(key: "single-file", defaultValue: false, usage: "only document one file") <*> m <| Option(key: "module-name", defaultValue: "", usage: "name of module to document (can't be used with `--single-file` or `--objc`)") <*> m <| Option(key: "objc", defaultValue: false, usage: "document Objective-C headers") <*> m <| Argument(defaultValue: [], usage: "Arguments list that passed to xcodebuild. If `-` prefixed argument exists, place ` -- ` before that.") } } func run(_ options: Options) -> Result<(), SourceKittenError> { let args = options.arguments if !options.spmModule.isEmpty { return runSPMModule(moduleName: options.spmModule) } else if options.objc { return runObjC(options: options, args: args) } else if options.singleFile { return runSwiftSingleFile(args: args) } let moduleName: String? = options.moduleName.isEmpty ? nil : options.moduleName return runSwiftModule(moduleName: moduleName, args: args) } func runSPMModule(moduleName: String) -> Result<(), SourceKittenError> { if let docs = Module(spmName: moduleName)?.docs { print(docs) return .success() } return .failure(.docFailed) } func runSwiftModule(moduleName: String?, args: [String]) -> Result<(), SourceKittenError> { let module = Module(xcodeBuildArguments: args, name: moduleName) if let docs = module?.docs { print(docs) return .success() } return .failure(.docFailed) } func runSwiftSingleFile(args: [String]) -> Result<(), SourceKittenError> { if args.isEmpty { return .failure(.invalidArgument(description: "at least 5 arguments are required when using `--single-file`")) } let sourcekitdArguments = Array(args.dropFirst(1)) if let file = File(path: args[0]), let docs = SwiftDocs(file: file, arguments: sourcekitdArguments) { print(docs) return .success() } return .failure(.readFailed(path: args[0])) } func runObjC(options: Options, args: [String]) -> Result<(), SourceKittenError> { if args.isEmpty { return .failure(.invalidArgument(description: "at least 5 arguments are required when using `--objc`")) } let translationUnit = ClangTranslationUnit(headerFiles: [args[0]], compilerArguments: Array(args.dropFirst(1))) print(translationUnit) return .success() } }
mit
50777ae1879339df598fdbed83dbff70
40.010753
162
0.613005
4.508274
false
false
false
false
jaredjones/MetalByExample
MetalByExample/MBERenderer.swift
1
9009
// // MBERenderer.swift // MetalByExample // // Created by Jared Jones on 12/23/15. // Copyright © 2015 Jared Jones. All rights reserved. // import Foundation import MetalKit typealias MBEIndex = UInt16 let MBEIndexType:MTLIndexType = MTLIndexType.UInt16 struct MBEVertex { var position:float4 var color:float4 } struct MBEUniforms { var MVP: matrix_float4x4 } class MBERenderer: MBEMetalViewDelegate { let kInFlightCommandBuffers = 3 let inflightSemaphore:dispatch_semaphore_t var bufferIndex = 0 var device: MTLDevice var commandQueue:MTLCommandQueue? var pipeline:MTLRenderPipelineState? var depthStencilState:MTLDepthStencilState? var vertexBuffer:MTLBuffer? var indexBuffer:MTLBuffer? var uniformBuffer:MTLBuffer? init(device: MTLDevice) { self.device = device inflightSemaphore = dispatch_semaphore_create(kInFlightCommandBuffers) makePipeline() makeBuffers() } func makePipeline() { let library = self.device.newDefaultLibrary() let vertexFunc = library?.newFunctionWithName("vertex_main") let fragmentFunc = library?.newFunctionWithName("fragment_main") let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm pipelineDescriptor.depthAttachmentPixelFormat = .Depth32Float pipelineDescriptor.vertexFunction = vertexFunc pipelineDescriptor.fragmentFunction = fragmentFunc let depthStencilDescriptor = MTLDepthStencilDescriptor() depthStencilDescriptor.depthCompareFunction = .Less depthStencilDescriptor.depthWriteEnabled = true self.depthStencilState = self.device.newDepthStencilStateWithDescriptor(depthStencilDescriptor) do { try self.pipeline = self.device.newRenderPipelineStateWithDescriptor(pipelineDescriptor) } catch MTLRenderPipelineError.InvalidInput{ print("The input values are invalid") } catch MTLRenderPipelineError.Internal { print("This action caused an internal error") } catch MTLRenderPipelineError.Unsupported { print("This action is unsupported") } catch { print("Unknown RenderPipelineState Error") } self.commandQueue = self.device.newCommandQueue() } func makeBuffers() { let vertices:[MBEVertex] = [ MBEVertex(position: [-1, 1, 1, 1], color: [0, 1, 1, 1]), MBEVertex(position: [-1, -1, 1, 1], color: [0, 0, 1, 1]), MBEVertex(position: [ 1, -1, 1, 1], color: [1, 0, 1, 1]), MBEVertex(position: [ 1, 1, 1, 1], color: [1, 1, 1, 1]), MBEVertex(position: [-1, 1, -1, 1], color: [0, 1, 0, 1]), MBEVertex(position: [-1, -1, -1, 1], color: [0, 0, 0, 1]), MBEVertex(position: [ 1, -1, -1, 1], color: [1, 0, 0, 1]), MBEVertex(position: [ 1, 1, -1, 1], color: [1, 1, 0, 1]) ] let indicies: [MBEIndex] = [ 3,2,6,6,7,3, 4,5,1,1,0,4, 4,0,3,3,7,4, 1,5,6,6,2,1, 0,1,2,2,3,0, 7,6,5,5,4,7 ] let vertexSize = vertices.count * sizeofValue(vertices[0]) let indexSize = indicies.count * sizeofValue(indicies[0]) self.vertexBuffer = self.device.newBufferWithBytes(vertices, length: vertexSize, options: .CPUCacheModeDefaultCache) self.indexBuffer = self.device.newBufferWithBytes(indicies, length: indexSize, options: .CPUCacheModeDefaultCache) self.uniformBuffer = self.device.newBufferWithLength(sizeof(MBEUniforms) * kInFlightCommandBuffers, options: .CPUCacheModeDefaultCache) } var rotDeg: Double = 0.0 func updateUniforms(view: MBEMetalView, duration:NSTimeInterval) { var viewMatrix:matrix_float4x4 var projMatrix:matrix_float4x4 var modelMatrix:matrix_float4x4 viewMatrix = matrix_float4x4_identity() let cameraTranslation: float3 = [0, 0, -7] viewMatrix = matrix_multiply(viewMatrix, matrix_float4x4_translation(cameraTranslation)) let near:Float = 0.1 let far:Float = 100.0 let aspect:Float = Float(view.metalLayer.drawableSize.width / view.metalLayer.drawableSize.height) let fov:Float = Float((2 * M_PI) / 5) projMatrix = matrix_float4x4_perspective(aspect, fovy: fov, near: near, far: far) modelMatrix = matrix_float4x4_identity() modelMatrix = matrix_multiply(modelMatrix, matrix_float4x4_rotation(float3(0, 1, 0), angle: Float(rotDeg))) rotDeg += duration * (M_PI / 2); let MVP = matrix_multiply(projMatrix, matrix_multiply(viewMatrix, modelMatrix)) var uniforms: MBEUniforms = MBEUniforms(MVP: MVP) let uniformBufferOffset = sizeof(MBEUniforms) * self.bufferIndex memcpy((uniformBuffer?.contents())! + uniformBufferOffset, &uniforms, sizeofValue(uniforms)) } func drawInView(view: MBEMetalView) { dispatch_semaphore_wait(inflightSemaphore, DISPATCH_TIME_FOREVER) updateUniforms(view, duration: view.frameDuration) // MTLTextures are containers for images, where each image is called a slice. // each texture has a particular size and pixel format. 1D/2D/3D // We are using a single 2D texture for our renderbuffer (same resolution as screen) // CAMetalDrawable will give us a nextDrawable from the CALayer that has a texture we // may use as our screen buffer let drawable: CAMetalDrawable = view.currentDrawable let texture:MTLTexture = drawable.texture // A pass descriptor tells Metal which actions to take while a frame is being rendered // The LoadAction tells us whether the previous contents are Cleared or Retained // The StoreAction deals with the effects the rendering has on our texture, to store or discard let passDescriptor = MTLRenderPassDescriptor() passDescriptor.colorAttachments[0].texture = texture passDescriptor.colorAttachments[0].loadAction = .Clear passDescriptor.colorAttachments[0].storeAction = .Store passDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(93.0/255.0, 161.0/255.0, 219.0/255.0, 1.0) passDescriptor.depthAttachment.texture = view.depthTexture passDescriptor.depthAttachment.clearDepth = 1.0 passDescriptor.depthAttachment.loadAction = .Clear passDescriptor.depthAttachment.storeAction = .DontCare // The CommandQueue is given to us by the device and holds a list of CommandBuffers. // Generally the CommandQueue exists for more than one frame // The CommandBuffer is a collection of render commands to be executed together as a single unit // The CommandEncoder tells Metal what drawing we want to do. It translates high level code like // (Set Shaders, Draw Triangles, etc) and converts them to lower level instructions that are written // into the CommandBuffer. After we finish our draw calls, we send endEncoding to the CommandEncoder so // it has a chance to finish its encoding. let commandBuffer = commandQueue?.commandBuffer() let commandEncoder = commandBuffer?.renderCommandEncoderWithDescriptor(passDescriptor) commandEncoder?.setRenderPipelineState(self.pipeline!) commandEncoder?.setDepthStencilState(self.depthStencilState!) commandEncoder?.setFrontFacingWinding(.CounterClockwise) commandEncoder?.setCullMode(.Back) let uniformBufferOffset = sizeof(MBEUniforms) * self.bufferIndex commandEncoder?.setVertexBuffer(self.vertexBuffer, offset: 0, atIndex: 0) //Index 0 matches buffer(0) in Shader commandEncoder?.setVertexBuffer(self.uniformBuffer, offset: uniformBufferOffset, atIndex: 1) //commandEncoder?.drawPrimitives(.Triangle, vertexStart: 0, vertexCount: 3) commandEncoder?.drawIndexedPrimitives(.Triangle, indexCount: (self.indexBuffer?.length)! / sizeof(MBEIndex), indexType: MBEIndexType, indexBuffer: self.indexBuffer!, indexBufferOffset: 0) commandEncoder?.endEncoding() // Presents a drawable object when the command buffer is executed. commandBuffer!.presentDrawable(drawable) commandBuffer!.addCompletedHandler { (buffer:MTLCommandBuffer) -> Void in self.bufferIndex = (self.bufferIndex + 1) % self.kInFlightCommandBuffers dispatch_semaphore_signal(self.inflightSemaphore) } // The CommandBuffer is executed by the GPU. commandBuffer!.commit() } }
mit
01d473fa65b977630f06c7b1f1b5c0be
42.73301
143
0.660857
4.638517
false
false
false
false
fortmarek/Supl
Supl/ClassCell.swift
1
2701
// // Classswift // Supl // // Created by Marek Fořt on 07/08/16. // Copyright © 2016 Marek Fořt. All rights reserved. // import UIKit class ClassCell: UITableViewCell, UITextFieldDelegate { @IBOutlet weak var segmentController: UISegmentedControl! @IBOutlet weak var textField: UITextField! let defaults = UserDefaults.standard override func awakeFromNib() { super.awakeFromNib() // Initialization code textField.delegate = self self.selectionStyle = .none textField.keyboardType = .default textForTextfield() textField.addTarget(self, action: #selector(refreshPlaceholder), for: .editingDidEndOnExit) segmentController.addTarget(self, action: #selector(segmentChanged(_:)), for: .valueChanged) guard let segmentIndex = defaults.value(forKey: "segmentIndex") as? Int else {return} segmentController.selectedSegmentIndex = segmentIndex getPlaceholder() } func segmentChanged(_ segmentController: UISegmentedControl) { getPlaceholder() guard let clas = defaults.value(forKey: "class") as? String, let school = defaults.value(forKey: "schoolUrl") as? String else { defaults.set(segmentController.selectedSegmentIndex, forKey: "segmentIndex") return } let dataController = DataController() //Before setting segmentIndex delete the property and then post it again with the new segmentIndex dataController.deleteProperty(clas, school: school) defaults.set(segmentController.selectedSegmentIndex, forKey: "segmentIndex") dataController.postProperty(clas, school: school) } func refreshPlaceholder() { if let clas = textField.text?.removeExcessiveSpaces , clas == "" { textField.text = "" getPlaceholder() } } func textForTextfield() { //Placeholder if class is not set guard let classString = defaults.value(forKey: "class") as? String else {return} getPlaceholder() textField.text = classString.removeExcessiveSpaces } func getPlaceholder() { if segmentController.selectedSegmentIndex == 0 { textField.autocapitalizationType = .allCharacters textField.attributedPlaceholder = NSAttributedString(string: "R6.A") } else { textField.autocapitalizationType = .words textField.attributedPlaceholder = NSAttributedString(string: "Příjmení Jméno") } } }
mit
6d4c2cb9661f213174415782c478e20c
31.457831
106
0.632146
5.398798
false
false
false
false
HaloWang/WCQuick
WCQuick/UIView+WCQ.swift
1
3514
// // UIView+WCQ.swift // SuperGina // // Created by 王策 on 15/6/17. // Copyright (c) 2015年 Anve. All rights reserved. // import UIKit import WCLayout public extension UIView { /** 设置 view.superView :param: superView 父视图 :returns: self */ public func superView(superView : UIView) -> Self { superView.addSubview(self) return self } public func userInteractionEnabled(userInteractionEnabled : Bool) -> Self { self.userInteractionEnabled = userInteractionEnabled return self } public func backgroundColor(backgroundColor : UIColor) -> Self { self.backgroundColor = backgroundColor return self } public func backgroundColorWhite() -> Self { self.backgroundColor = UIColor.whiteColor() return self } public func cornerRadius(radius : CGFloat) -> Self { layer.cornerRadius = radius layer.masksToBounds = true return self } public func circle() -> Self { return cornerRadius(width/2.f) } /** 设置圆角 :param: radius 圆角半径 :param: borderWidth 描边宽度 :param: borderColor 描边颜色 :returns: self */ public func cornerRadius(radius : CGFloat, borderWidth : CGFloat, borderColor : UIColor) -> Self { layer.cornerRadius = radius layer.masksToBounds = true layer.borderWidth = borderWidth layer.borderColor = borderColor.CGColor return self } public func circleWithBorderWidth(borderWidth : CGFloat, borderColor : UIColor) -> Self { return cornerRadius(width/2.f, borderWidth: borderWidth, borderColor: borderColor) } public func contentMode(contentMode : UIViewContentMode) -> Self { self.contentMode = contentMode return self } public func contentModeCenter() -> Self { return contentMode(.Center) } public func alpha(alpha: CGFloat) -> Self { self.alpha = alpha return self } public func frame(frame : CGRect) -> Self { self.frame = frame return self } /// 返回某个 UIView 相对于当前屏幕的 rect public var relativeFrameToWindow: CGRect { var screen_X: CGFloat = 0 var screen_Y: CGFloat = 0 var tempView = self while !tempView.isKindOfClass(UIWindow) { screen_X += tempView.left screen_Y += tempView.top tempView = tempView.superview! if tempView.isKindOfClass(UIScrollView) { screen_X -= (tempView as! UIScrollView).contentOffset.x screen_Y -= (tempView as! UIScrollView).contentOffset.y } } return CGRect(x: screen_X, y: screen_Y, width: width, height: height) } public var relativeBottomToWindow: CGFloat { return relativeFrameToWindow.chainBottom } public func addTopLine(#height:CGFloat, color:UIColor) -> Self { return addTopLine(width: width, height: height, color: color) } public func addTopLine(#width: CGFloat, height:CGFloat, color:UIColor) -> Self { UIView().superView(self) .frame(CGRect(x: 0, y: height, width: width, height: height)) .backgroundColor(color) return self } public func addTopLine() -> Self{ return addTopLine(height: 0.5, color: WCSystemSeparatorColor) } public func addBottomLine(#height:CGFloat, color:UIColor) -> Self { return addBottomLine(width: width, height: height, color: color) } public func addBottomLine(#width: CGFloat, height:CGFloat, color:UIColor) -> Self { UIView().superView(self) .frame(CGRect(x: 0, y: self.height - height, width: width, height: height)) .backgroundColor(color) return self } public func addBottomLine() -> Self{ return addBottomLine(height: 0.5, color: WCSystemSeparatorColor) } }
mit
909bfd0554895b4bff5707c0db17551f
23.411348
99
0.711505
3.526639
false
false
false
false
ztyjr888/WeChat
WeChat/Plugins/Tools/WeChatContactPhotoView.swift
1
2513
// // WeChatContactPhotoView.swift // WeChat // // Created by Smile on 16/1/13. // Copyright © 2016年 [email protected]. All rights reserved. // import UIKit //自定义联系人图片 class WeChatContactPhotoView: WeChatDrawView { //MARKS: Properties var isLayedOut:Bool = false//是否初始化view var images:[UIImage] = [UIImage]()//图片数组 var imageWidth:CGFloat = 40//默认图片宽度 var imageHeight:CGFloat = 40//默认图片高度 var paddingTopOrBottom:CGFloat = 5 var paddingLeftOrRight:CGFloat = 5 required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } //MARKS:Init Frame init(frame: CGRect,images:[UIImage]) { super.init(frame: frame) //设置一些属性 self.images = images self.backgroundColor = UIColor.clearColor() getPicWidth() } override func layoutSubviews() { super.layoutSubviews() if images.count == 0 { return } if !isLayedOut { addImages() } } //MARKS: 添加图片 func addImages(){ var originX:CGFloat = 0 for(var i = 0;i < images.count;i++){ let y = self.paddingTopOrBottom imageRectForContentRect(originX, y: y, image: images[i]) if i != (images.count - 1) { originX += (paddingLeftOrRight + self.imageWidth) } } } //MARKS: 图片成正比 func getPicWidth(){ let width = self.frame.width let picWidth = width - paddingLeftOrRight * 3 self.imageWidth = picWidth / 4 self.imageHeight = self.frame.height if self.imageHeight > self.imageWidth { self.imageHeight = self.imageWidth } if self.imageWidth > self.imageHeight { self.imageWidth = self.imageHeight } //重新计算上边距或左边距 self.paddingLeftOrRight = (width - self.imageWidth * 4) / 3 self.paddingTopOrBottom = (self.frame.height - self.imageHeight) / 2 } //MARKS: 改变图片位置 func imageRectForContentRect(x:CGFloat,y:CGFloat,image:UIImage){ let imageView = UIImageView(image: image) imageView.userInteractionEnabled = true// 使图片视图支持交互 imageView.frame = CGRectMake(x, y, self.imageWidth, self.imageHeight) self.addSubview(imageView) } }
apache-2.0
008237698c89725bbb4dae47f653e0df
26.241379
77
0.58692
4.136126
false
false
false
false
bingoogolapple/SwiftNote-PartTwo
刷新视图/刷新视图/ViewController.swift
1
1339
// // ViewController.swift // 刷新视图 // // Created by bingoogol on 14/10/11. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit class ViewController: UIViewController,UITextFieldDelegate { var myView:MyView! override func viewDidLoad() { super.viewDidLoad() myView = MyView(frame: CGRectMake(0, 20, 320, 200)) self.view.addSubview(myView) var textField = UITextField(frame: CGRectMake(20, 240, 280, 30)) textField.borderStyle = UITextBorderStyle.Line textField.contentVerticalAlignment = UIControlContentVerticalAlignment.Center textField.delegate = self self.view.addSubview(textField) var slider = UISlider(frame: CGRectMake(20, 300, 280, 20)) slider.minimumValue = 10 slider.maximumValue = 40 slider.value = 20 slider.addTarget(self, action: Selector("sliderValueChanged:"), forControlEvents: UIControlEvents.ValueChanged) self.view.addSubview(slider) } func sliderValueChanged(slider:UISlider) { self.myView.setFontSize(CGFloat(slider.value)) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() self.myView.setText(textField.text) return true } }
apache-2.0
715f9fc66e12b0075a01b12397ef695a
29.227273
119
0.665162
4.815217
false
false
false
false
zsheikh-systango/WordPower
Skeleton/Word Share/Network/Requests/WordRequest.swift
1
1377
// // WordRequest.swift // WordPower // // Created by Best Peers on 16/10/17. // Copyright © 2017 www.BestPeers.Skeleton. All rights reserved. // import UIKit class WordRequest: Request { func initWordRequest(word:String) -> WordRequest{ let searchWord:String = word.components(separatedBy: " ").first! let path:String = "https://wordsapiv1.p.mashape.com/words/"+searchWord urlPath = path.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! return self } func initTranslatorRequest(word:String) -> WordRequest{ let path:String = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20171024T105142Z.903b3e1c791c4cd5.3de81202f9dda907aab4dafbe86006f16141a764&lang=\(Constants.getDefaultLanguageCode())" urlPath = path.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! parameters = ["text":word as AnyObject] return self } func initGetLangsRequest() -> WordRequest{ let path:String = "https://translate.yandex.net/api/v1.5/tr.json/getLangs?key=trnsl.1.1.20171024T105142Z.903b3e1c791c4cd5.3de81202f9dda907aab4dafbe86006f16141a764&ui=\(Constants.getDefaultLanguageCode())" urlPath = path.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)! return self } }
mit
9d39e917ea28bf1b16133477b226f9df
40.69697
215
0.728198
3.659574
false
false
false
false
Draveness/NightNight
NightNight/Classes/UIKit/UITextField+Mixed.swift
1
2037
// // UITextField+Mixed.swift // Pods // // Created by Draveness. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // import Foundation public extension UITextField { fileprivate struct AssociatedKeys { static var mixedKeyboardAppearanceKey = "mixedKeyboardAppearanceKey" } var mixedTextColor: MixedColor? { get { return getMixedColor(&Keys.textColor) } set { textColor = newValue?.unfold() setMixedColor(&Keys.textColor, value: newValue) } } var mixedKeyboardAppearance: MixedKeyboardAppearance? { get { return objc_getAssociatedObject(self, &AssociatedKeys.mixedKeyboardAppearanceKey) as? MixedKeyboardAppearance } set { objc_setAssociatedObject(self, &AssociatedKeys.mixedKeyboardAppearanceKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } override func _updateCurrentStatus() { super._updateCurrentStatus() if let mixedTextColor = mixedTextColor { textColor = mixedTextColor.unfold() } if let mixedKeyboardAppearance = mixedKeyboardAppearance { keyboardAppearance = mixedKeyboardAppearance.unfold() } } }
mit
a432c12f59432109c27d0d5a01eeeeb3
32.95
132
0.682376
5.105263
false
false
false
false
WXYC/wxyc-ios-64
iOS/SpinningAnimation.swift
1
1522
// // SpinningAnimation.swift // WXYC // // Created by Jake Bromberg on 12/24/18. // Copyright © 2018 WXYC. All rights reserved. // import UIKit final class SpinningAnimation: CABasicAnimation { override init() { super.init() self.keyPath = "transform.rotation.z" self.duration = 2 self.repeatCount = 100 self.autoreverses = false self.fromValue = Float.pi / 3.0 self.toValue = -0.0 self.isRemovedOnCompletion = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension UIView { static let AnimationKey = "spinAnimation" func startSpin() { if self.layer.animation(forKey: UIView.AnimationKey) == nil { self.layer.add(SpinningAnimation(), forKey: UIView.AnimationKey) } self.resume(layer: self.layer) } func stopSpin() { self.pause(layer: self.layer) } private func pause(layer: CALayer) { let pausedTime = layer.convertTime(CACurrentMediaTime(), from: nil) layer.speed = 0.0 layer.timeOffset = pausedTime } private func resume(layer: CALayer) { let pausedTime = layer.timeOffset layer.speed = 1.0 layer.timeOffset = 0.0 layer.beginTime = 0.0 let timeSincePause = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime layer.beginTime = timeSincePause } }
mit
5e94411a929b0d4df30f43c42be504a4
24.779661
92
0.604865
4.358166
false
false
false
false
mgsergio/omim
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/ViatorCells/PPViatorCarouselCell.swift
1
2786
@objc(MWMPPViatorCarouselCell) final class PPViatorCarouselCell: MWMTableViewCell { @IBOutlet private weak var title: UILabel! { didSet { title.text = L("place_page_viator_title") title.font = UIFont.bold14() title.textColor = UIColor.blackSecondaryText() } } @IBOutlet private weak var more: UIButton! { didSet { more.setTitle(L("placepage_more_button"), for: .normal) more.titleLabel?.font = UIFont.regular17() more.setTitleColor(UIColor.linkBlue(), for: .normal) } } @IBOutlet private weak var collectionView: UICollectionView! fileprivate var dataSource: [ViatorItemModel] = [] fileprivate let kMaximumNumberOfElements = 5 fileprivate var delegate: MWMPlacePageButtonsProtocol? fileprivate var statisticsParameters: [AnyHashable: Any] { return [kStatProvider: kStatViator] } @objc func config(with ds: [ViatorItemModel], delegate d: MWMPlacePageButtonsProtocol?) { if ds.isEmpty { Statistics.logEvent(kStatPlacepageSponsoredError, withParameters: statisticsParameters) } dataSource = ds delegate = d collectionView.contentOffset = .zero collectionView.delegate = self collectionView.dataSource = self collectionView.register(cellClass: ViatorElement.self) collectionView.reloadData() isSeparatorHidden = true backgroundColor = UIColor.clear } fileprivate func isLastCell(_ indexPath: IndexPath) -> Bool { return indexPath.item == collectionView.numberOfItems(inSection: indexPath.section) - 1 } @IBAction func onMore() { Statistics.logEvent(kStatPlacepageSponsoredLogoSelected, withParameters: statisticsParameters) delegate?.openSponsoredURL(nil) } } extension PPViatorCarouselCell: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withCellClass: ViatorElement.self, indexPath: indexPath) as! ViatorElement cell.model = isLastCell(indexPath) ? nil : dataSource[indexPath.item] cell.onMoreAction = { [weak self] in self?.onMore() } return cell } func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int { return min(dataSource.count, kMaximumNumberOfElements) + 1 } func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) { let isMore = isLastCell(indexPath) let url: URL? = isMore ? nil : dataSource[indexPath.item].pageURL delegate?.openSponsoredURL(url) Statistics.logEvent(isMore ? kStatPlacepageSponsoredMoreSelected : kStatPlacepageSponsoredItemSelected, withParameters: statisticsParameters) } }
apache-2.0
18476a3963c0ac0391bb7394efb92bdb
36.648649
145
0.733668
4.786942
false
false
false
false
tus/TUSKit
Sources/TUSKit/UploadMetada.swift
1
4710
// // File.swift // // // Created by Tjeerd in ‘t Veen on 16/09/2021. // import Foundation /// This type represents data to store on the disk. To allow for persistence between sessions. /// E.g. For background uploading or when an app is killed, we can use this data to continue where we left off. /// The reason this is a class is to preserve reference semantics while the data is being updated. final class UploadMetadata: Codable { let queue = DispatchQueue(label: "com.tuskit.uploadmetadata") enum CodingKeys: String, CodingKey { case id case uploadURL case filePath case remoteDestination case version case context case uploadedRange case mimeType case customHeaders case size case errorCount } var isFinished: Bool { size == uploadedRange?.count } private var _id: UUID var id: UUID { get { queue.sync { _id } } set { queue.async { self._id = newValue } } } let uploadURL: URL private var _filePath: URL var filePath: URL { get { queue.sync { _filePath } } set { queue.async { self._filePath = newValue } } } private var _remoteDestination: URL? var remoteDestination: URL? { get { queue.sync { _remoteDestination } } set { queue.async { self._remoteDestination = newValue } } } private var _uploadedRange: Range<Int>? /// The total range that's uploaded var uploadedRange: Range<Int>? { get { queue.sync { self._uploadedRange } } set { queue.async { self._uploadedRange = newValue } } } let version: Int let context: [String: String]? let mimeType: String? let customHeaders: [String: String]? let size: Int private var _errorCount: Int /// Number of times the upload failed var errorCount: Int { get { queue.sync { _errorCount } } set { queue.sync { _errorCount = newValue } } } init(id: UUID, filePath: URL, uploadURL: URL, size: Int, customHeaders: [String: String]? = nil, mimeType: String? = nil, context: [String: String]? = nil) { self._id = id self._filePath = filePath self.uploadURL = uploadURL self.size = size self.customHeaders = customHeaders self.mimeType = mimeType self.version = 1 // Can't make default property because of Codable self.context = context self._errorCount = 0 } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) _id = try values.decode(UUID.self, forKey: .id) uploadURL = try values.decode(URL.self, forKey: .uploadURL) _filePath = try values.decode(URL.self, forKey: .filePath) _remoteDestination = try values.decode(URL?.self, forKey: .remoteDestination) version = try values.decode(Int.self, forKey: .version) context = try values.decode([String: String]?.self, forKey: .context) _uploadedRange = try values.decode(Range<Int>?.self, forKey: .uploadedRange) mimeType = try values.decode(String?.self, forKey: .mimeType) customHeaders = try values.decode([String: String]?.self, forKey: .customHeaders) size = try values.decode(Int.self, forKey: .size) _errorCount = try values.decode(Int.self, forKey: .errorCount) } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(_id, forKey: .id) try container.encode(uploadURL, forKey: .uploadURL) try container.encode(_remoteDestination, forKey: .remoteDestination) try container.encode(_filePath, forKey: .filePath) try container.encode(version, forKey: .version) try container.encode(context, forKey: .context) try container.encode(uploadedRange, forKey: .uploadedRange) try container.encode(mimeType, forKey: .mimeType) try container.encode(customHeaders, forKey: .customHeaders) try container.encode(size, forKey: .size) try container.encode(_errorCount, forKey: .errorCount) } }
mit
be4ec9260662e48ebe7d6c0b3f98880f
28.987261
161
0.569881
4.540019
false
false
false
false
chengxianghe/MissGe
MissGe/MissGe/Class/Project/UI/Cell/MLTopicCellLayout.swift
1
10282
// // MLTopicCellLayout.swift // MissLi // // Created by chengxianghe on 16/7/20. // Copyright © 2016年 cn. All rights reserved. // import UIKit import YYText class MLTopicCellLayout: NSObject { var height: CGFloat = 0 var joke: MLSquareModel! // 顶部留白 var marginTop: CGFloat = 0 //顶部灰色留白 var textMarginTop: CGFloat = 0 //文字上方留白 // 头像 var iconHeight: CGFloat = 0 var iconWidth: CGFloat = 0 var iconX: CGFloat = 0 var iconY: CGFloat = 0 var menuWidth: CGFloat = 0 var menuHeight: CGFloat = 0 var nameTextHeight: CGFloat = 0 var nameTextLeft: CGFloat = 0 var nameTextLayout: YYTextLayout! //文本 //@property (nonatomic, assign) CGFloat timeTextWidth; var timeTextHeight: CGFloat = 0 var timeTextLayout: YYTextLayout? var textTop: CGFloat = 0 var textHeight: CGFloat = 0 var textLayout: YYTextLayout! // 图片 var picViewHeight: CGFloat = 0 var picSize = CGSize.zero // 工具栏 var toolbarHeight: CGFloat = 0 var toolbarCommentTextWidth: CGFloat = 0 var toolbarCommentTextLayout: YYTextLayout! var toolbarLikeTextWidth: CGFloat = 0 var toolbarLikeTextLayout: YYTextLayout! // 下边留白 var textMarginBottom: CGFloat = 0 var marginBottom: CGFloat = 0 override init() { super.init() } convenience init(model: MLSquareModel) { self.init() self.joke = model self.layout() } func layout() { marginTop = kSquareCellTopMargin; marginBottom = kSquareCellBottomMargin; textMarginTop = kSquareCellTextTopMargin; textMarginBottom = kSquareCellTextBottomMargin; textTop = kSquareCellTextLeftMargin; textHeight = 0; // 文本排版,计算布局 self.layoutIcon() self.layoutLike() self.layoutName() self.layoutTime() self.layoutText() self.layoutPics() self.layoutToolbar() // 计算高度 height = 0; height += marginTop; height += textMarginTop; height += nameTextHeight; height += timeTextHeight; height += textTop; height += textHeight; height += textMarginBottom; height += picViewHeight; height += picViewHeight == 0 ? 0 : kSquareCellPaddingPic height += toolbarHeight; height += kSquareCellBottomImageHeight height += marginBottom; } func layoutIcon() { // 文本排版,计算布局 iconHeight = kSquareCellIconHeight; iconWidth = kSquareCellIconHeight; iconX = kSquareCellIconLeftMargin; iconY = kSquareCellIconTopMargin; } func layoutName() { nameTextHeight = 0; nameTextLayout = nil; var text = NSMutableAttributedString(string: "") if joke.isAnonymous { text = NSMutableAttributedString(string: "匿名") } else { let name = joke.nickname ?? joke.uname; if (name != nil || name!.length > 0) { text = NSMutableAttributedString(string: name!) }; } // 加入事件 text.yy_color = kSquareCellNameColor; text.yy_font = UIFont.systemFont(ofSize: kSquareCellNameFontSize) let container = YYTextContainer(size: CGSize(width: kSquareCellContentWidth - menuWidth, height: kSquareCellNameHeight)) container.maximumNumberOfRows = 1; nameTextLayout = YYTextLayout(container: container, text: text); nameTextHeight = kSquareCellNameHeight; nameTextLeft = iconWidth + iconX * 2; } func layoutTime() { timeTextHeight = kSquareCellTimeHeight; timeTextLayout = nil; let time = joke.showTime; if (time == nil || time?.length == 0) {return}; let text = NSMutableAttributedString(string: time!) text.yy_color = kSquareCellTimeColor; text.yy_font = UIFont.systemFont(ofSize: kSquareCellTimeFontSize) let container = YYTextContainer(size: CGSize(width: kSquareCellContentWidth, height: kSquareCellTimeHeight)) container.maximumNumberOfRows = 1; timeTextLayout = YYTextLayout(container: container, text: text) } func layoutLike() { menuWidth = 30; menuHeight = 10; } func layoutToolbar() { let kJokeCellToolbarHeight:CGFloat = 35 // should be localized let font = UIFont.systemFont(ofSize: 12.0) let container = YYTextContainer.init(size: CGSize(width: kScreenWidth, height: kJokeCellToolbarHeight)) container.maximumNumberOfRows = 1; let commentText = NSMutableAttributedString(string: (joke.replies as NSString).integerValue <= 0 ? "评论" : JokeHelper.shortedNumberDesc(number: (joke.replies as NSString).integerValue)); commentText.yy_font = font; commentText.yy_color = kColorFromHexA(0x929292); toolbarCommentTextLayout = YYTextLayout(container: container, text: commentText); toolbarCommentTextWidth = YYTextCGFloatPixelRound(toolbarCommentTextLayout.textBoundingRect.size.width); let likeText = NSMutableAttributedString(string: (joke.like as NSString).integerValue <= 0 ? "赞" : JokeHelper.shortedNumberDesc(number: (joke.like as NSString).integerValue)); likeText.yy_font = font; likeText.yy_color = joke.isLike ? kColorFromHexA(0xdf422d) : kColorFromHexA(0x929292); toolbarLikeTextLayout = YYTextLayout(container: container, text: likeText); toolbarLikeTextWidth = YYTextCGFloatPixelRound(toolbarLikeTextLayout.textBoundingRect.size.width); toolbarHeight = kJokeCellToolbarHeight; } /// 文本 func layoutText() { textHeight = 0; textLayout = nil; let text = JokeHelper.textWithText(originStr: joke.content, linkKey: kSquareLinkAtName, fontSize: kSquareCellTextFontSize, textColor: kSquareCellTextColor, textHighlighColor: kTopicCommentCellTextHighlightColor, highlightBackgroundColor: kTopicCommentCellTextHighlightBackgroundColor) if (text == nil || text!.length == 0) {return}; text!.yy_lineSpacing = 5.0; // text.yy_kern = @1.0; // WBTextLinePositionModifier *modifier = [WBTextLinePositionModifier new]; // modifier.font = [UIFont fontWithName:@"Heiti SC" size:kWBCellTextFontSize]; // modifier.paddingTop = kWBCellPaddingText; // modifier.paddingBottom = kWBCellPaddingText; let container = YYTextContainer() container.size = CGSize(width: kSquareCellContentWidth, height: CGFloat.greatestFiniteMagnitude); // container.linePositionModifier = modifier; textLayout = YYTextLayout(container: container, text: text!); textHeight = textLayout != nil ? (textLayout.textBoundingRect.maxY) : 0; // _textHeight = [modifier heightForLineCount:_textLayout.rowCount]; } func layoutPics() { picViewHeight = 0; picSize = CGSize.zero var len1_3 = (kSquareCellContentWidth + kSquareCellPaddingPic) / 3 - kSquareCellPaddingPic; len1_3 = YYTextCGFloatPixelRound(len1_3); if joke.imglist != nil && joke.imglist!.count > 0 { switch (joke.imglist!.count) { case 1: let pic = joke.imglist!.first!; let temWidth = CGFloat((pic.width as NSString).floatValue) let temHeight = CGFloat((pic.height as NSString).floatValue) if (temWidth < 1 || temHeight < 1) { var maxLen: CGFloat = kSquareCellContentWidth / 2.0; maxLen = YYTextCGFloatPixelRound(maxLen); picSize = CGSize(width: maxLen, height: maxLen); picViewHeight = maxLen; } else { let maxLen: CGFloat = len1_3 * 2 + kSquareCellPaddingPic; if (temWidth < temHeight) { picSize.width = temWidth / temHeight * maxLen; picSize.height = maxLen; } else { picSize.width = maxLen; picSize.height = temHeight / temWidth * maxLen; } picSize = YYTextCGSizePixelRound(picSize); picViewHeight = picSize.height; } case 2: fallthrough case 3: picSize = CGSize(width: len1_3, height: len1_3); picViewHeight = len1_3; case 4: fallthrough case 5: fallthrough case 6: picSize = CGSize(width: len1_3, height: len1_3); picViewHeight = len1_3 * 2 + kSquareCellPaddingPic; default: // 7, 8, 9 picSize = CGSize(width: len1_3, height: len1_3); picViewHeight = len1_3 * 3 + kSquareCellPaddingPic * 2; } return } if joke.thumb_small == nil || joke.thumb_small!.count == 0 { return } switch (joke.thumb_small!.count) { case 1: picSize = CGSize(width: len1_3, height: len1_3 * 1.5); picViewHeight = len1_3 * 1.5; case 2: fallthrough case 3: picSize = CGSize(width: len1_3, height: len1_3); picViewHeight = len1_3; case 4: fallthrough case 5: fallthrough case 6: picSize = CGSize(width: len1_3, height: len1_3); picViewHeight = len1_3 * 2 + kSquareCellPaddingPic; default: // 7, 8, 9 picSize = CGSize(width: len1_3, height: len1_3); picViewHeight = len1_3 * 3 + kSquareCellPaddingPic * 2; } } }
mit
c4c4aedb468cfb4f0c39b14dd01cd504
33.191919
292
0.582964
4.679724
false
false
false
false
instacrate/Subber-api
Sources/App/Stripe/Models/Invoice/LineItem.swift
2
3015
// // LineItem.swift // Stripe // // Created by Hakon Hanesand on 1/18/17. // // import Foundation import Node public final class Period: NodeConvertible { public let start: Date public let end: Date public init(node: Node, in context: Context = EmptyNode) throws { start = try node.extract("start") end = try node.extract("end") } public func makeNode(context: Context = EmptyNode) throws -> Node { return try Node(node: [ "start" : try start.makeNode(), "end" : try end.makeNode() ] as [String : Node]) } } public enum LineItemType: String, NodeConvertible { case invoiceitem case subscription } public final class LineItem: NodeConvertible { static let type = "line_item" public let id: String public let amount: Int public let currency: Currency public let description: String? public let discountable: Bool public let livemode: Bool public let metadata: Node public let period: Period public let plan: Plan public let proration: Bool public let quantity: Int public let subscription: StripeSubscription public let subscription_item: String public let type: LineItemType public init(node: Node, in context: Context = EmptyNode) throws { guard try node.extract("object") == LineItem.type else { throw NodeError.unableToConvert(node: node, expected: LineItem.type) } id = try node.extract("id") amount = try node.extract("amount") currency = try node.extract("currency") description = try node.extract("description") discountable = try node.extract("discountable") livemode = try node.extract("livemode") metadata = try node.extract("metadata") period = try node.extract("period") plan = try node.extract("plan") proration = try node.extract("proration") quantity = try node.extract("quantity") subscription = try node.extract("subscription") subscription_item = try node.extract("subscription_item") type = try node.extract("type") } public func makeNode(context: Context = EmptyNode) throws -> Node { return try Node(node: [ "id" : .string(id), "amount" : .number(.int(amount)), "currency" : try currency.makeNode(), "discountable" : .bool(discountable), "livemode" : .bool(livemode), "metadata" : metadata, "period" : try period.makeNode(), "plan" : try plan.makeNode(), "proration" : .bool(proration), "quantity" : .number(.int(quantity)), "subscription" : try subscription.makeNode(), "subscription_item" : .string(subscription_item), "type" : try type.makeNode() ] as [String : Node]).add(objects: [ "description" : description ]) } }
mit
11787705bad0c69d026ba0d9cbaf3074
30.736842
80
0.598342
4.407895
false
false
false
false
LockLight/Weibo_Demo
SinaWeibo/SinaWeibo/Tools/UIColor+extension.swift
1
789
// // UIColor+extension.swift // weiboNine // // Created by HM09 on 17/4/2. // Copyright © 2017年 itheima. All rights reserved. // import UIKit extension UIColor { class func rgbColor(r: CGFloat, g: CGFloat, b: CGFloat) -> UIColor { let red = r/255.0 let green = g/255.0 let blue = b/255.0 return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } //随机颜色 class func randomColor () -> UIColor { let r = arc4random() % 255 let g = arc4random() % 255 let b = arc4random() % 255 let red = CGFloat(r)/255.0 let green = CGFloat(g)/255.0 let blue = CGFloat(b)/255.0 return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } }
mit
ba9d54cee52ead71bde99a77e594df27
23.3125
72
0.546272
3.39738
false
false
false
false
etamity/AlienBlast
Source/Blaster.swift
1
4135
// // Blaster.swift // AlientBlast // // Created by Joey etamity on 29/03/2016. // Copyright © 2016 Innovation Apps. All rights reserved. // import Foundation class Blaster: CCSprite { var bornRate :Int = 100; var hurtRate :Int = 0; var healthRate :Int = 1; var type: BlasterType! = nil; var subType: String! = ""; func didLoadFromCCB(){ self.userInteractionEnabled = false; self.physicsBody.collisionType = "shape"; self.physicsBody.sensor = false self.physicsBody.collisionGroup = "blaster"; self.physicsBody.affectedByGravity = true; self.type = BlasterType(rawValue: self.name) } func topUpAnimation(block:()->Void){ self.physicsBody.affectedByGravity = false self.physicsBody.collisionType = "" let moveto = CCActionMoveBy.actionWithDuration(3, position: CGPointMake(-300, 300)) let scaleToHeart = CCActionScaleTo.actionWithDuration(3, scale: 5) let fadeout = CCActionFadeTo.actionWithDuration(3, opacity: 0.0) let callback = CCActionCallBlock.actionWithBlock({ block() }) let spwan = CCActionSpawn.actionWithArray([moveto,scaleToHeart,fadeout]) let sequene = CCActionSequence.actionWithArray([spwan,callback]) self.runAction(sequene as! CCActionSequence) } func blast(){ OALSimpleAudio.sharedInstance().playEffect(StaticData.getSoundFile(GameSoundType.BLAST.rawValue)) var points: Int = StaticData.sharedInstance.points; points += 1 ; StaticData.sharedInstance.points = points if (self.type == BlasterType.Heart){ var lives : Int = StaticData.sharedInstance.lives; lives -= self.hurtRate; StaticData.sharedInstance.lives = lives self.removeFromParentAndCleanup(true); }else if (self.type == BlasterType.Clock) { var touches : Int = StaticData.sharedInstance.touches; touches += 500; StaticData.sharedInstance.touches = touches self.removeFromParentAndCleanup(true); } else { var touches : Int = StaticData.sharedInstance.touches; touches += self.hurtRate; StaticData.sharedInstance.touches = touches if (self.parent != nil){ let pnode:CCParticleSystem = CCBReader.load(StaticData.getEffectFile(EffectType.BLAST.rawValue)) as! CCParticleSystem; pnode.position = self.position; pnode.autoRemoveOnFinish = true; pnode.duration=0.5; self.parent.addChild(pnode); } self.removeFromParentAndCleanup(true); } } override func update(delta: CCTime) { let rect : CGRect = CGRectMake(self.parent.position.x, self.parent.position.y,self.parent.contentSize.width, CCDirector.sharedDirector().viewSize().height + 200); let inRect : Bool = CGRectContainsPoint(rect,self.position); if (!inRect) { if (self.position.y < 0) { if (self.type != BlasterType.Heart){ var lives : Int = StaticData.sharedInstance.lives; lives += self.hurtRate; StaticData.sharedInstance.lives = lives OALSimpleAudio.sharedInstance().playEffect(StaticData.getSoundFile(GameSoundType.HIT.rawValue)) } if (self.parent != nil){ let pnode: CCParticleSystem = CCBReader.load(StaticData.getEffectFile(EffectType.HURT.rawValue)) as! CCParticleSystem; pnode.position = self.position; pnode.autoRemoveOnFinish = true; pnode.duration = 0.5; self.parent.addChild(pnode); } } self.removeFromParentAndCleanup(true); } } }
mit
8b3047d10f5516329627ba3d89839295
37.287037
170
0.581035
4.650169
false
false
false
false
LiulietLee/BilibiliCD
BCD/ViewController/Feedback/EditController.swift
1
4727
// // EditController.swift // BCD // // Created by Liuliet.Lee on 16/7/2019. // Copyright © 2019 Liuliet.Lee. All rights reserved. // import UIKit import LLDialog protocol EditControllerDelegate: class { func editFinished(username: String, content: String) } class EditController: UIViewController { enum EditModel { case comment case reply } @IBOutlet weak var postButton: UIButton! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var textView: UITextView! @IBOutlet weak var bottomConstraint: NSLayoutConstraint! weak var delegate: EditControllerDelegate? = nil var model = EditModel.comment var currentComment: Comment? = nil private var commentProvider = CommentProvider() override func viewDidLoad() { super.viewDidLoad() view.tintColor = UIColor.systemOrange usernameField.text = UserDefaults.standard.string(forKey: "feedbackUsername") textView.text = UserDefaults.standard.string(forKey: "feedbackContent") textView.becomeFirstResponder() NotificationCenter.default.addObserver( self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil ) } @objc private func keyboardWillShow(_ notification: Notification) { if let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue { let keyboardRectangle = keyboardFrame.cgRectValue let height = keyboardRectangle.height bottomConstraint.constant = height view.layoutIfNeeded() } } private func goBack() { UserDefaults.standard.set(usernameField.text!, forKey: "feedbackUsername") usernameField.resignFirstResponder() textView.resignFirstResponder() dismiss(animated: true, completion: nil) } @IBAction func backButtonTapped() { UserDefaults.standard.set(textView.text!, forKey: "feedbackContent") goBack() } private var isUsernameFirst = false @objc private func showKeyboard() { if isUsernameFirst { usernameField.becomeFirstResponder() } else { textView.becomeFirstResponder() } } private func showTip(message str: String) { isUsernameFirst = usernameField.isFirstResponder usernameField.resignFirstResponder() textView.resignFirstResponder() LLDialog() .set(message: str) .setPositiveButton(withTitle: "嗯", target: self, action: #selector(showKeyboard)) .show() } @IBAction func goButtonTapped() { if var username = usernameField.text, var content = textView.text { username = username.trimmingCharacters(in: .whitespacesAndNewlines) content = content.trimmingCharacters(in: .whitespacesAndNewlines) var tempString = content.replacingOccurrences(of: "\n\n\n", with: "\n\n") while tempString != content { content = tempString tempString = content.replacingOccurrences(of: "\n\n\n", with: "\n\n") } if content == "" { showTip(message: "什么都不填是不行的呢") return } else if content.count > 450 { showTip(message: "正文最长可以有 450 个字哦。") return } else if username.hasSpecialCharacters() { showTip(message: "用户名只能由数字和英文字母组成哦。") return } else if username.count > 12 { showTip(message: "用户名最长可以有 12 个字哦。") return } if username == "" { username = "anonymous" } self.delegate?.editFinished(username: username, content: content) UserDefaults.standard.set("", forKey: "feedbackContent") self.goBack() } } } extension String { func hasSpecialCharacters() -> Bool { do { let regex = try NSRegularExpression(pattern: ".*[^A-Za-z0-9].*", options: .caseInsensitive) if regex.firstMatch( in: self, options: .reportCompletion, range: NSMakeRange(0, self.count) ) != nil { return true } } catch { debugPrint(error.localizedDescription) return false } return false } }
gpl-3.0
330d26d720666c4fc5ca35042f65f52c
31.56338
108
0.59667
5.195506
false
false
false
false
motylevm/skstylekit
Sources/SKStyleUIControl.swift
1
2388
// // Copyright (c) 2016 Mikhail Motylev https://twitter.com/mikhail_motylev // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import UIKit public extension SKStyle { // MARK: - UIControl - /** Applies style to a control - parameter control: Control view to apply style to */ func apply(control: UIControl?) { apply(view: control) if !checkFlag(flagControllWasSet) { setControlFlags() } guard checkFlag(flagControllAny) else { return } if let contentVerticalAlignment = contentVerticalAlignment { control?.contentVerticalAlignment = contentVerticalAlignment } if let contentHorizontalAlignment = contentHorizontalAlignment { control?.contentHorizontalAlignment = contentHorizontalAlignment } } // MARK: - Check Style - func checkIfContainsControlStyle() -> Bool { return contentVerticalAlignment != nil || contentHorizontalAlignment != nil } // MARK: - Set flags - private func setControlFlags() { if contentVerticalAlignment != nil || contentHorizontalAlignment != nil { setFlag(flagControllAny) } setFlag(flagControllWasSet) } }
mit
4ef8dfd24c1bdc3714b697b511c70cca
35.738462
86
0.667504
5.157667
false
false
false
false
MegaManX32/CD
CD/CD/View Controllers/SignupCountryViewController.swift
1
8787
// // SignupCountryViewController.swift // CustomDeal // // Created by Vladislav Simovic on 9/28/16. // Copyright © 2016 Vladislav Simovic. All rights reserved. // import UIKit import MBProgressHUD class SignupCountryViewController: UIViewController, GeneralPickerViewControllerDelegate, MutlipleLanguagePickerViewControllerDelegate { // MARK: - Properties @IBOutlet weak var countryButtonView: ButtonView! @IBOutlet weak var cityButtonView: ButtonView! @IBOutlet weak var zipCodeButtonView: ButtonView! @IBOutlet weak var languageButtonView: ButtonView! @IBOutlet weak var genderButtonView: ButtonView! @IBOutlet weak var birthDateButtonView: ButtonView! var userID : String! var country : Country? var city : City? var languages : [Language]? var gender : String? var birthDate : Date? // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // prepare text fields self.prepareButtonViews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func prepareButtonViews() { self.countryButtonView.title = NSLocalizedString("Country", comment: "country") self.countryButtonView.isWhite = true self.countryButtonView.action = { [unowned self] in let controller = self.storyboard?.instantiateViewController(withIdentifier: "GeneralPickerViewController") as! GeneralPickerViewController controller.topTitle = self.countryButtonView.title controller.selectionType = .country controller.delegate = self self.show(controller, sender: self) } self.cityButtonView.title = NSLocalizedString("City", comment: "city") self.cityButtonView.isWhite = true self.cityButtonView.action = { [unowned self] in // first check if country guard let country = self.country else { CustomAlert.presentAlert(message: "You must choose country first", controller: self) return } let controller = self.storyboard?.instantiateViewController(withIdentifier: "GeneralPickerViewController") as! GeneralPickerViewController controller.topTitle = self.cityButtonView.title controller.selectionType = .city controller.country = country controller.delegate = self self.show(controller, sender: self) } self.languageButtonView.title = NSLocalizedString("Language", comment: "language") self.languageButtonView.isWhite = true self.languageButtonView.action = { [unowned self] in let controller = self.storyboard?.instantiateViewController(withIdentifier: "MutlipleLanguagePickerViewController") as! MutlipleLanguagePickerViewController controller.delegate = self self.show(controller, sender: self) } self.genderButtonView.title = NSLocalizedString("Gender", comment: "gender") self.genderButtonView.isWhite = true self.genderButtonView.action = { [unowned self] in let controller = self.storyboard?.instantiateViewController(withIdentifier: "GeneralPickerViewController") as! GeneralPickerViewController controller.topTitle = self.genderButtonView.title controller.selectionType = .gender controller.delegate = self self.show(controller, sender: self) } self.birthDateButtonView.title = NSLocalizedString("Birth Date", comment: "") self.birthDateButtonView.isWhite = true self.birthDateButtonView.action = { [unowned self] in let controller = self.storyboard?.instantiateViewController(withIdentifier: "DatePickerViewController") as! DatePickerViewController controller.datePickedAction = { [unowned self] (pickedDate) in self.birthDateButtonView.title = StandardDateFormatter.presentationStringFrom(date: pickedDate) self.birthDate = pickedDate _ = self.navigationController?.popViewController(animated: true) } controller.dateCancelledAction = { [unowned self] in _ = self.navigationController?.popViewController(animated: true) } self.show(controller, sender: self) } } // MARK: - User actions @IBAction func nextAction(sender: UIButton) { guard let countryName = self.country?.countryName, let cityName = self.city?.cityName, let languages = self.languages, let gender = self.gender, let birthDate = self.birthDate as NSDate? else { CustomAlert.presentAlert(message: "Please select country, city, language, gender and date of birth", controller: self) return; } // add progress hud MBProgressHUD.showAdded(to: self.view, animated: true) // get language IDs var languageIDArray = [String]() for language in languages { languageIDArray.append(language.uid!) } // update user let context = CoreDataManager.sharedInstance.createScratchpadContext(onMainThread: false) context.perform { [unowned self] in // get user and update let user = User.findUserWith(uid: self.userID, context: context) user?.country = countryName user?.city = cityName user?.gender = gender user?.birthDate = birthDate // add languages for languageID in languageIDArray { let language = Language.findLanguageWith(id: languageID, context: context) user?.addToLanguages(language!) } // update user NetworkManager.sharedInstance.createOrUpdate(user: user!, context: context, success: { [unowned self] (userID) in // go to interests let controller = self.storyboard?.instantiateViewController(withIdentifier: "SignupYourInterestsViewController") as! SignupYourInterestsViewController controller.userID = userID self.show(controller, sender: self) MBProgressHUD.hide(for: self.view, animated: true) }, failure: { [unowned self] (errorMessage) in print(errorMessage) MBProgressHUD.hide(for: self.view, animated: true) }) } } // MARK: - SignupChooseFromListViewControllerDelegate methods func generalPickerViewControllerDidSelect(object: Any, selectionType: SelectionType, selectedIndex : Int, controller: UIViewController) { switch selectionType { case .country: self.country = object as? Country self.countryButtonView.title = self.country?.countryName self.city = nil self.cityButtonView.title = "City" case .city: self.city = object as? City self.cityButtonView.title = self.city?.cityName case .profession: break case .gender: self.gender = object as? String self.genderButtonView.title = self.gender default: break // do nothing, should never happen } // pop view controller _ = self.navigationController?.popViewController(animated: true) } func generalPickerViewControllerDidCancel(controller: UIViewController) { // pop view controller _ = self.navigationController?.popViewController(animated: true) } // MARK: - MutlipleLanguagePickerViewControllerDelegate methods func mutlipleLanguagePickerViewControllerDidSelect(languages: [Language], controller: MutlipleLanguagePickerViewController) { self.languages = languages // upate languages label var languagesTitle = "" var index = 0 if let languages = self.languages { for language in languages { languagesTitle += index == 0 ? language.language! : ", \(language.language!)" index += 1 } } self.languageButtonView.title = languagesTitle _ = self.navigationController?.popViewController(animated: true) } func mutlipleLanguagePickerViewControllerDidCancel(controller: MutlipleLanguagePickerViewController) { // pop view controller _ = self.navigationController?.popViewController(animated: true) } }
mit
bff6ebc3d98c6091ecd5ef3c61d71710
40.838095
201
0.638857
5.508464
false
false
false
false
andrea-prearo/LiteJSONConvertible
LiteJSONConvertibleTests/Model/LocationData.swift
1
950
// // LocationData.swift // LiteJSONConvertible // // Created by Andrea Prearo on 4/16/16. // Copyright © 2016 Andrea Prearo // import Foundation import LiteJSONConvertible struct LocationData { let address: String? let city: String? let state: String? let country: String? let zipCode: String? init(address: String?, city: String?, state: String?, country: String?, zipCode: String?) { self.address = address self.city = city self.state = state self.country = country self.zipCode = zipCode } } extension LocationData: JSONDecodable { static func decode(json: JSON) -> LocationData? { return LocationData( address: json <| "address", city: json <| "city", state: json <| "state", country: json <| "country", zipCode: json <| "zipCode") } }
mit
09e049f28762fdda3b7bb2a017339b0b
20.088889
53
0.563751
4.333333
false
false
false
false
mapsme/omim
iphone/Maps/UI/Search/Tabs/HistoryTab/SearchHistoryViewController.swift
5
3755
protocol SearchHistoryViewControllerDelegate: AnyObject { func searchHistoryViewController(_ viewController: SearchHistoryViewController, didSelect query: String) } final class SearchHistoryViewController: MWMViewController { private weak var delegate: SearchHistoryViewControllerDelegate? private var lastQueries: [String] private let frameworkHelper: MWMSearchFrameworkHelper private static let clearCellIdentifier = "SearchHistoryViewController_clearCellIdentifier" @IBOutlet private var tableView: UITableView! @IBOutlet private weak var noResultsViewContainer: UIView! init(frameworkHelper: MWMSearchFrameworkHelper, delegate: SearchHistoryViewControllerDelegate?) { self.delegate = delegate self.lastQueries = frameworkHelper.lastSearchQueries() self.frameworkHelper = frameworkHelper super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() if frameworkHelper.isSearchHistoryEmpty() { showNoResultsView() } else { tableView.registerNib(cellClass: SearchHistoryQueryCell.self) let nib = UINib(nibName: "SearchHistoryClearCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: SearchHistoryViewController.clearCellIdentifier) } tableView.keyboardDismissMode = .onDrag } func showNoResultsView() { guard let noResultsView = MWMSearchNoResults.view(with: UIImage(named: "img_search_history"), title: L("search_history_title"), text: L("search_history_text")) else { assertionFailure() return } noResultsViewContainer.addSubview(noResultsView) tableView.isHidden = true } func clearSearchHistory() { frameworkHelper.clearSearchHistory() lastQueries = [] } } extension SearchHistoryViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return frameworkHelper.isSearchHistoryEmpty() ? 0 : lastQueries.count + 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.row == lastQueries.count { let cell = tableView.dequeueReusableCell(withIdentifier: SearchHistoryViewController.clearCellIdentifier, for: indexPath) return cell } let cell = tableView.dequeueReusableCell(cell: SearchHistoryQueryCell.self, indexPath: indexPath) cell.update(with: lastQueries[indexPath.row]) return cell } } extension SearchHistoryViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.row == lastQueries.count { clearSearchHistory() UIView.animate(withDuration: kDefaultAnimationDuration, animations: { tableView.alpha = 0.0 }) { _ in self.showNoResultsView() } Statistics.logEvent(kStatEventName(kStatSearch, kStatSelectResult), withParameters: [ kStatValue : kStatClear, kStatScreen : kStatHistory ]) } else { let query = lastQueries[indexPath.row] delegate?.searchHistoryViewController(self, didSelect: query) Statistics.logEvent(kStatEventName(kStatSearch, kStatSelectResult), withParameters: [ kStatValue : query, kStatScreen : kStatHistory ]) } } }
apache-2.0
0ed39d0d13cf11df6266d9d3091a274c
38.946809
111
0.674301
5.562963
false
false
false
false
SereivoanYong/Charts
Source/Charts/Components/LimitLine.swift
1
1573
// // LimitLine.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 /// The limit line is an additional feature for all Line, Bar and ScatterCharts. /// It allows the displaying of an additional line in the chart that marks a certain maximum / limit on the specified axis (x- or y-axis). open class LimitLine: Component { public enum TextPosition { case leftTop case leftBottom case rightTop case rightBottom } /// flag that indicates if this component is enabled or not open var isEnabled: Bool = true /// The offset this component has on the x-axis /// **default**: 5.0 open var xOffset: CGFloat = 5.0 /// The offset this component has on the x-axis /// **default**: 5.0 (or 0.0 on ChartYAxis) open var yOffset: CGFloat = 5.0 /// limit / maximum (the y-value or xIndex) open var limit: CGFloat open var lineWidth: CGFloat = 2.0 { willSet { precondition(newValue >= 0.2 && newValue <= 12.0) } } open var lineColor: UIColor = UIColor(red: 237.0/255.0, green: 91.0/255.0, blue: 91.0/255.0, alpha: 1.0) open var lineDash: CGLineDash? open var font: UIFont = .systemFont(ofSize: 13.0) open var text: String? open var textColor: UIColor = .black open var textPosition: TextPosition = .rightTop public init(limit: CGFloat = 0.0, text: String? = nil) { self.limit = limit self.text = text } }
apache-2.0
894f346921447de63cf25d7a418c9bec
25.661017
138
0.663064
3.772182
false
false
false
false
Urinx/Device-9
Device 9/Device 9/WorksTableViewController.swift
1
1820
// // WorksTableViewController.swift // Device 9 // // Created by Eular on 9/21/15. // Copyright © 2015 Eular. All rights reserved. // import UIKit class WorksTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() let headerView = UIView() let back = UIButton() let title = UILabel() headerView.frame = CGRectMake(0, 0, view.bounds.width, 100) back.frame = CGRectMake(20, 35, 30, 30) back.setImage(UIImage(named: "back-100"), forState: .Normal) back.addTarget(self, action: "back", forControlEvents: .TouchUpInside) headerView.addSubview(back) title.frame = CGRectMake(self.view.bounds.width/2 - 60, 30, 120, 40) title.text = "Our Apps" title.font = UIFont(name: title.font.familyName, size: 25) title.textAlignment = .Center headerView.addSubview(title) tableView.tableHeaderView = headerView } func back() { self.navigationController?.popViewControllerAnimated(true) } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) var url = "" switch indexPath.row { case 0: url = "http://urinx.github.io/app/writetyper" case 1: url = "https://github.com/Urinx/Iconista/blob/master/README.md" case 2: url = "http://pre.im/1820" case 3: url = "http://pre.im/40fb" default: break } UIApplication.sharedApplication().openURL(NSURL(string: url)!) } override func prefersStatusBarHidden() -> Bool { return true } }
apache-2.0
7f7fe89ae8b917bf6a96c38553815371
28.819672
101
0.601979
4.415049
false
false
false
false
akoi/healthkit-poc
healthkit-pocTests/Model/HealthItemTest.swift
1
698
// // HealthItemTest.swift // healthkit-poc // import XCTest class HealthItemTest: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testCreate() { let name = "Test" let identifier = "hkTestIdentifier" let healthItem = HealthItem { item in item.name = name item.hkIdentifier = identifier } XCTAssertTrue(healthItem.name == name, "Wrong name. Expected: \(name), Actual: \(healthItem.name)") XCTAssertTrue(healthItem.hkIdentifier == identifier, "Wrong identifier. Expected: \(identifier), Actual: \(healthItem.name)") } }
unlicense
d23392e3c8d356c7befa5a2f37b9c49a
23.068966
133
0.606017
4.230303
false
true
false
false
edwardvalentini/EVContactsPicker
Pod/Classes/EVPickedContactsView.swift
1
15699
// // EVPickedContactsView.swift // Pods // // Created by Edward Valentini on 8/29/15. // // import UIKit class EVPickedContactsView: UIView, EVContactBubbleDelegate, UITextViewDelegate, UIScrollViewDelegate { // MARK: - Private Variables fileprivate var _shouldSelectTextView = false fileprivate var scrollView : UIScrollView? fileprivate var contacts : [AnyHashable: EVContactBubble]? fileprivate var keyContacts : [AnyHashable : EVContactProtocol]? fileprivate var contactKeys : [AnyHashable]? fileprivate var placeholderLabel : UILabel? fileprivate var lineHeight : CGFloat? fileprivate var textView : UITextView? fileprivate var bubbleColor : EVBubbleColor? fileprivate var bubbleSelectedColor : EVBubbleColor? fileprivate let kViewPadding = CGFloat(5.0) fileprivate let kHorizontalPadding = CGFloat(2.0) fileprivate let kVerticalPadding = CGFloat(4.0) fileprivate let kTextViewMinWidth = CGFloat(130.0) // MARK: - Properties var selectedContactBubble : EVContactBubble? var delegate : EVPickedContactsViewDelegate? var limitToOne : Bool = false var viewPadding : CGFloat? var font : UIFont? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override init(frame: CGRect) { super.init(frame: frame) self.setup() } // MARK: - Public Methods func disableDropShadow() -> Void { let layer = self.layer layer.shadowRadius = 0.0 layer.shadowOpacity = 0.0 } func addContact(_ contact : EVContactProtocol, name: String) -> Void { guard let contactKeys = self.contactKeys else { return } let contactKey = contact.identifier if contactKeys.contains(contactKey) { return } self.textView?.text = "" let contactBubble = EVContactBubble(name: name, color: self.bubbleColor, selectedColor: self.bubbleSelectedColor) if let font = self.font { contactBubble.setFont(font) } contactBubble.delegate = self self.contacts?[contactKey] = contactBubble self.contactKeys?.append(contactKey) self.keyContacts?[contactKey] = contact self.layoutView() self.textView?.isHidden = false self.textView?.text = "" self.scrollToBottomWithAnimation(false) } func selectTextView() -> Void { self.textView?.isHidden = false } func removeAllContacts() -> Void { for ( _ , kValue) in self.contacts! { kValue.removeFromSuperview() } self.contacts?.removeAll() self.contactKeys?.removeAll() self.layoutView() self.textView?.isHidden = false self.textView?.text = "" } func removeContact(_ contact : EVContactProtocol) -> Void { // let contactKey = NSValue(nonretainedObject: contact) let contactKey = contact.identifier if let contacts = self.contacts { if let contactBubble = contacts[contactKey] { contactBubble.removeFromSuperview() _ = self.contacts?.removeValue(forKey: contactKey) _ = self.keyContacts?.removeValue(forKey: contactKey) if let foundIndex = self.contactKeys?.index(of: contactKey) { self.contactKeys?.remove(at: foundIndex) } self.layoutView() self.textView?.isHidden = false self.textView?.text = "" self.scrollToBottomWithAnimation(false) } } } func setPlaceHolderString(_ placeHolderString: String) -> Void { self.placeholderLabel?.text = placeHolderString self.layoutView() } func resignKeyboard() -> Void { self.textView?.resignFirstResponder() } func setBubbleColor(_ color: EVBubbleColor, selectedColor:EVBubbleColor) -> Void { self.bubbleColor = color self.bubbleSelectedColor = selectedColor for contactKey in self.contactKeys! { if let contacts = contacts { if let contactBubble = contacts[contactKey] { contactBubble.color = color contactBubble.selectedColor = selectedColor if(contactBubble.isSelected) { contactBubble.select() } else { contactBubble.unSelect() } } } } } // MARK: - Private Methods fileprivate func setup() -> Void { self.viewPadding = kViewPadding self.contacts = [:] self.contactKeys = [] self.keyContacts = [:] let contactBubble = EVContactBubble(name: "Sample") self.lineHeight = contactBubble.frame.size.height + 2 + kVerticalPadding self.scrollView = UIScrollView(frame: self.bounds) self.scrollView?.scrollsToTop = false self.scrollView?.delegate = self self.addSubview(self.scrollView!) self.textView = UITextView() self.textView?.delegate = self self.textView?.font = contactBubble.label?.font self.textView?.backgroundColor = UIColor.clear self.textView?.contentInset = UIEdgeInsetsMake(-4.0, -2.0, 0, 0) self.textView?.isScrollEnabled = false self.textView?.scrollsToTop = false self.textView?.clipsToBounds = false self.textView?.autocorrectionType = UITextAutocorrectionType.no self.backgroundColor = UIColor.white let layer = self.layer layer.shadowColor = UIColor(red: 225.0/255.0, green: 226.0/255.0, blue: 228.0/255.0, alpha: 1.0).cgColor layer.shadowOffset = CGSize(width: 0, height: 2) layer.shadowOpacity = 1.0 layer.shadowRadius = 1.0 self.placeholderLabel = UILabel(frame: CGRect(x: 8, y: self.viewPadding!, width: self.frame.size.width, height: self.lineHeight!)) self.placeholderLabel?.font = contactBubble.label?.font self.placeholderLabel?.backgroundColor = UIColor.clear self.placeholderLabel?.textColor = UIColor.gray self.addSubview(self.placeholderLabel!) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(EVPickedContactsView.handleTapGesture)) tapGesture.numberOfTapsRequired = 1 tapGesture.numberOfTouchesRequired = 1 self.addGestureRecognizer(tapGesture) } func scrollToBottomWithAnimation(_ animated : Bool) -> Void { if(animated) { let size = self.scrollView?.contentSize let frame = CGRect(x: 0, y: size!.height - (self.scrollView?.frame.size.height)!, width: size!.width, height: (self.scrollView?.frame.size.height)!) self.scrollView?.scrollRectToVisible(frame, animated: animated) } else { var offset = self.scrollView?.contentOffset offset?.y = (self.scrollView?.contentSize.height)! - (self.scrollView?.frame.size.height)! self.scrollView?.contentOffset = offset! } } func removeContactBubble(_ contactBubble : EVContactBubble) -> Void { if let contactKey = self.contactForContactBubble(contactBubble), let keyContacts = self.keyContacts, let contact = keyContacts[contactKey] { self.delegate?.contactPickerDidRemoveContact(contact) self.removeContactByKey(contactKey) } } func removeContactByKey(_ contactKey : AnyHashable) -> Void { guard let contacts = self.contacts else { return } if let contactBubble = contacts[contactKey] { contactBubble.removeFromSuperview() let _ = self.contacts?.removeValue(forKey: contactKey) if let foundIndex = self.contactKeys?.index(of: contactKey) { self.contactKeys?.remove(at: foundIndex) } self.layoutView() self.textView?.isHidden = false self.textView?.text = "" self.scrollToBottomWithAnimation(false) } } func contactForContactBubble(_ contactBubble : EVContactBubble) -> AnyHashable? { guard let contacts = self.contacts else { return nil } var returnKey : AnyHashable? = nil contacts.forEach { (key: AnyHashable, value: EVContactBubble) in if let valueForKey = contacts[key], valueForKey.isEqual(contactBubble) { returnKey = key } } return returnKey } func layoutView() -> Void { var frameOfLastBubble = CGRect.null var lineCount = 0 for contactKey in self.contactKeys! { if let contacts = self.contacts, let contactBubble = contacts[contactKey] { // as EVContactBubble { var bubbleFrame = contactBubble.frame if(frameOfLastBubble.isNull) { bubbleFrame.origin.x = kHorizontalPadding bubbleFrame.origin.y = kVerticalPadding + self.viewPadding! } else { let width = bubbleFrame.size.width + 2 * kHorizontalPadding if( self.frame.size.width - frameOfLastBubble.origin.x - frameOfLastBubble.size.width - width >= 0) { bubbleFrame.origin.x = frameOfLastBubble.origin.x + frameOfLastBubble.size.width + kHorizontalPadding * 2 bubbleFrame.origin.y = frameOfLastBubble.origin.y } else { lineCount += 1 bubbleFrame.origin.x = kHorizontalPadding bubbleFrame.origin.y = (CGFloat(lineCount) * self.lineHeight!) + kVerticalPadding + self.viewPadding! } } frameOfLastBubble = bubbleFrame contactBubble.frame = bubbleFrame if (contactBubble.superview == nil){ self.scrollView?.addSubview(contactBubble) } } } let minWidth = kTextViewMinWidth + 2 * kHorizontalPadding var textViewFrame = CGRect(x: 0, y: 0, width: (self.textView?.frame.size.width)!, height: self.lineHeight!) if (self.frame.size.width - frameOfLastBubble.origin.x - frameOfLastBubble.size.width - minWidth >= 0){ // add to the same line textViewFrame.origin.x = frameOfLastBubble.origin.x + frameOfLastBubble.size.width + kHorizontalPadding textViewFrame.size.width = self.frame.size.width - textViewFrame.origin.x } else { // place text view on the next line lineCount += 1 textViewFrame.origin.x = kHorizontalPadding textViewFrame.size.width = self.frame.size.width - 2 * kHorizontalPadding if (self.contacts?.count == 0){ lineCount = 0 textViewFrame.origin.x = kHorizontalPadding } } textViewFrame.origin.y = CGFloat(lineCount) * self.lineHeight! + kVerticalPadding + self.viewPadding! self.textView?.frame = textViewFrame if (self.textView?.superview == nil){ self.scrollView?.addSubview(self.textView!) } if (self.limitToOne && (self.contacts?.count)! >= 1){ self.textView?.isHidden = true; lineCount = 0; } var frame = self.bounds let maxFrameHeight = 2 * self.lineHeight! + 2 * self.viewPadding! var newHeight = (CGFloat(lineCount) + 1.0) * self.lineHeight! + 2 * self.viewPadding! self.scrollView?.contentSize = CGSize(width: (self.scrollView?.frame.size.width)!, height: newHeight) newHeight = (newHeight > maxFrameHeight) ? maxFrameHeight : newHeight; if (self.frame.size.height != newHeight){ // Adjust self height var selfFrame = self.frame selfFrame.size.height = newHeight self.frame = selfFrame // Adjust scroll view height frame.size.height = newHeight self.scrollView?.frame = frame self.delegate?.contactPickerDidResize(self) } // Show placeholder if no there are no contacts if (self.contacts?.count == 0){ self.placeholderLabel?.isHidden = false } else { self.placeholderLabel?.isHidden = true } } // MARK: - UITextViewDelegate func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { self.textView?.isHidden = false if( text == "\n" ) { return false } if( textView.text == "" && text == "" ) { if let contactKey = self.contactKeys?.last { if let contacts = self.contacts { self.selectedContactBubble = (contacts[contactKey]) self.selectedContactBubble?.select() } } } return true } func textViewDidChange(_ textView: UITextView) { self.delegate?.contactPickerTextViewDidChange(textView.text) if( textView.text == "" && self.contacts?.count == 0) { self.placeholderLabel?.isHidden = false } else { self.placeholderLabel?.isHidden = true } } // MARK: - EVContactBubbleDelegate Methods func contactBubbleWasSelected(_ contactBubble: EVContactBubble) -> Void { if( self.selectedContactBubble != nil ) { self.selectedContactBubble?.unSelect() } self.selectedContactBubble = contactBubble self.textView?.resignFirstResponder() self.textView?.text = "" self.textView?.isHidden = true } func contactBubbleWasUnSelected(_ contactBubble: EVContactBubble) -> Void { self.textView?.becomeFirstResponder() self.textView?.text = "" self.textView?.isHidden = false } func contactBubbleShouldBeRemoved(_ contactBubble: EVContactBubble) -> Void { self.removeContactBubble(contactBubble) } // MARK: - Gesture Recognizer @objc func handleTapGesture() -> Void { if(self.limitToOne && self.contactKeys?.count == 1) { return } self.scrollToBottomWithAnimation(true) self.textView?.isHidden = false self.textView?.becomeFirstResponder() self.selectedContactBubble?.unSelect() self.selectedContactBubble = nil } // MARK: - UIScrollViewDelegate func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { if(_shouldSelectTextView) { _shouldSelectTextView = false self.selectTextView() } } }
mit
887febd47c1c639ef174224b3972992c
33.809313
160
0.57526
5.164145
false
false
false
false
asalom/Cocoa-Design-Patterns-in-Swift
DesignPatterns/DesignPatterns/Decoupling/Hierarchies/File.swift
1
1409
// // File.swift // DesignPatterns // // Created by Alex Salom on 10/11/15. // Copyright © 2015 Alex Salom © alexsalom.es. All rights reserved. // import Foundation class File { var name: String var parent: Directory? init(name: String, parent: Directory?) { self.name = name self.parent = parent } func path() -> String { if let mParent = self.parent { return "\(mParent.path())/\(self.name)" } return "" } } func ==(lhs: File, rhs: File) -> Bool { return lhs.name == lhs.name } extension File: Hashable, Equatable { var hashValue : Int { get { return self.name.hash } } } class Directory: File { var files: Set<File> = Set<File>() func addFile(fileName: String) -> File { let file = File(name: fileName, parent: self) files.insert(file) return file } func addDirectory(directoryName: String) -> Directory { let directory = Directory(name: directoryName, parent: self) files.insert(directory) return directory } func fileNames() -> [String] { var fileNames = [String]() for file in self.files { fileNames.append(file.name) } return fileNames } } class Root: Directory { init() { super.init(name: "/", parent: nil) } }
mit
91f580f9cb1fd59f4720f7c0894765b5
19.391304
68
0.55295
3.930168
false
false
false
false
aducret/vj-ios-tp2
Shooter/Shooter/GameScene.swift
1
2927
// // GameScene.swift // Shooter // // Created by Argentino Ducret on 6/7/17. // Copyright © 2017 ITBA. All rights reserved. // import SpriteKit import GameplayKit class GameScene: SKScene { private var label : SKLabelNode? private var spinnyNode : SKShapeNode? override func didMove(to view: SKView) { // Get label node from scene and store it for use later self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode if let label = self.label { label.alpha = 0.0 label.run(SKAction.fadeIn(withDuration: 2.0)) } // Create shape node to use during mouse interaction let w = (self.size.width + self.size.height) * 0.05 self.spinnyNode = SKShapeNode.init(rectOf: CGSize.init(width: w, height: w), cornerRadius: w * 0.3) if let spinnyNode = self.spinnyNode { spinnyNode.lineWidth = 2.5 spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1))) spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5), SKAction.fadeOut(withDuration: 0.5), SKAction.removeFromParent()])) } } func touchDown(atPoint pos : CGPoint) { if let n = self.spinnyNode?.copy() as! SKShapeNode? { n.position = pos n.strokeColor = SKColor.green self.addChild(n) } } func touchMoved(toPoint pos : CGPoint) { if let n = self.spinnyNode?.copy() as! SKShapeNode? { n.position = pos n.strokeColor = SKColor.blue self.addChild(n) } } func touchUp(atPoint pos : CGPoint) { if let n = self.spinnyNode?.copy() as! SKShapeNode? { n.position = pos n.strokeColor = SKColor.red self.addChild(n) } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let label = self.label { label.run(SKAction.init(named: "Pulse")!, withKey: "fadeInOut") } for t in touches { self.touchDown(atPoint: t.location(in: self)) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchMoved(toPoint: t.location(in: self)) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } override func update(_ currentTime: TimeInterval) { // Called before each frame is rendered } }
mit
229f887575e3f897af98ff973fc36961
31.876404
109
0.572454
4.290323
false
false
false
false
klaus01/Centipede
Centipede/PushKit/CE_PKPushRegistry.swift
1
3566
// // CE_PKPushRegistry.swift // Centipede // // Created by kelei on 2016/9/15. // Copyright (c) 2016年 kelei. All rights reserved. // import PushKit extension PKPushRegistry { private struct Static { static var AssociationKey: UInt8 = 0 } private var _delegate: PKPushRegistry_Delegate? { get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? PKPushRegistry_Delegate } set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } private var ce: PKPushRegistry_Delegate { if let obj = _delegate { return obj } if let obj: AnyObject = self.delegate { if obj is PKPushRegistry_Delegate { return obj as! PKPushRegistry_Delegate } } let obj = getDelegateInstance() _delegate = obj return obj } private func rebindingDelegate() { let delegate = ce self.delegate = nil self.delegate = delegate } internal func getDelegateInstance() -> PKPushRegistry_Delegate { return PKPushRegistry_Delegate() } @discardableResult public func ce_pushRegistry_didUpdate(handle: @escaping (PKPushRegistry, PKPushCredentials, PKPushType) -> Void) -> Self { ce._pushRegistry_didUpdate = handle rebindingDelegate() return self } @discardableResult public func ce_pushRegistry_didReceiveIncomingPushWith(handle: @escaping (PKPushRegistry, PKPushPayload, PKPushType) -> Void) -> Self { ce._pushRegistry_didReceiveIncomingPushWith = handle rebindingDelegate() return self } @discardableResult public func ce_pushRegistry_didInvalidatePushTokenForType(handle: @escaping (PKPushRegistry, PKPushType) -> Void) -> Self { ce._pushRegistry_didInvalidatePushTokenForType = handle rebindingDelegate() return self } } internal class PKPushRegistry_Delegate: NSObject, PKPushRegistryDelegate { var _pushRegistry_didUpdate: ((PKPushRegistry, PKPushCredentials, PKPushType) -> Void)? var _pushRegistry_didReceiveIncomingPushWith: ((PKPushRegistry, PKPushPayload, PKPushType) -> Void)? var _pushRegistry_didInvalidatePushTokenForType: ((PKPushRegistry, PKPushType) -> Void)? override func responds(to aSelector: Selector!) -> Bool { let funcDic1: [Selector : Any?] = [ #selector(pushRegistry(_:didUpdate:forType:)) : _pushRegistry_didUpdate, #selector(pushRegistry(_:didReceiveIncomingPushWith:forType:)) : _pushRegistry_didReceiveIncomingPushWith, #selector(pushRegistry(_:didInvalidatePushTokenForType:)) : _pushRegistry_didInvalidatePushTokenForType, ] if let f = funcDic1[aSelector] { return f != nil } return super.responds(to: aSelector) } @objc func pushRegistry(_ registry: PKPushRegistry, didUpdate credentials: PKPushCredentials, forType type: PKPushType) { _pushRegistry_didUpdate!(registry, credentials, type) } @objc func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, forType type: PKPushType) { _pushRegistry_didReceiveIncomingPushWith!(registry, payload, type) } @objc func pushRegistry(_ registry: PKPushRegistry, didInvalidatePushTokenForType type: PKPushType) { _pushRegistry_didInvalidatePushTokenForType!(registry, type) } }
mit
3b2bfee8a19191cddfdc760d2f464a91
36.515789
139
0.675645
4.52859
false
false
false
false
justin999/gitap
gitap/ReposDetailViewController.swift
1
2163
// // ReposDetailViewController.swift // gitap // // Created by Koichi Sato on 12/26/16. // Copyright © 2016 Koichi Sato. All rights reserved. // import UIKit class ReposDetailViewController: MasterViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var addIssueButton: UIButton! var tableViewDelegate: IssuesTableViewDelegate? var tableViewDataSource: IssuesTableViewDataSource? override func viewDidLoad() { super.viewDidLoad() configureView() if let stateController = stateController { tableViewDelegate = IssuesTableViewDelegate(tableView: tableView, stateController: stateController) tableViewDataSource = IssuesTableViewDataSource(tableView: tableView, stateController: stateController) } } override func viewWillAppear(_ animated: Bool) { self.tabBarController?.tabBar.isHidden = true } override func viewDidAppear(_ animated: Bool) { stateController?.viewController = self } override func viewWillDisappear(_ animated: Bool) { self.tabBarController?.tabBar.isHidden = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func configureView() { segmentedControl.selectedSegmentIndex = 0 segmentedControl.addTarget(self, action: #selector(ReposDetailViewController.segmentValueChanged(segCon:)), for: .valueChanged) navigationController?.title = "Repo Name" } func segmentValueChanged(segCon:UISegmentedControl) { switch segCon.selectedSegmentIndex { case 0: print("Issues selected") case 1: print("Pull Requests selected") default: print("came to default") } } @IBAction func addIssueButtonTapped(_ sender: Any) { if let stateController = stateController { Utils.addButtonTapped(stateController: stateController) } } }
mit
228a79f5287c66a4af846cb7bb67f1a7
29.885714
135
0.66975
5.704485
false
false
false
false
weizhangCoder/DYZB_ZW
DYZB_ZW/DYZB_ZW/Classes/Main/Controller/BaseViewController.swift
1
1701
// // BaseViewController.swift // DYZB_ZW // // Created by zhangwei on 17/7/27. // Copyright © 2017年 jyall. All rights reserved. // import UIKit class BaseViewController: UIViewController { // MARK: 定义属性 var contentView : UIView? fileprivate lazy var aninImageView : UIImageView = { let aninImageView = UIImageView(image: UIImage(named: "img_loading_1")) aninImageView.animationImages = [UIImage(named: "img_loading_1")!, UIImage(named: "img_loading_1")!] aninImageView.animationRepeatCount = LONG_MAX aninImageView.animationDuration = 0.5 aninImageView.center = self.view.center aninImageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin] return aninImageView }() override func viewDidLoad() { super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false navigationController?.navigationBar.isTranslucent = false view.backgroundColor = UIColor.hexInt(0xf3f3f3) setupUI() } } extension BaseViewController{ func setupUI(){ // 1.隐藏内容的View contentView?.isHidden = true // 2.添加执行动画的UIImageView view.addSubview(aninImageView) // 3.给animImageView执行动画 aninImageView.startAnimating() // 4.设置view的背景颜色 view.backgroundColor = RGBCOLOR(r: 250, 250, 250) } func loadDataFinished(){ aninImageView.stopAnimating() aninImageView.isHidden = true contentView?.isHidden = false } }
mit
2e0c9d72ffe2b760e9b18f5ea2802ed6
22.797101
108
0.616931
4.815249
false
false
false
false
ivygulch/SwiftPromises
SwiftPromises/source/Promise.swift
1
15939
// // Promise.swift // SwiftPromises // // Created by Douglas Sjoquist on 2/25/15. // Copyright (c) 2015 Ivy Gulch LLC. All rights reserved. // import Foundation // MARK: - Promise /** A Swift version of the Promise pattern popular in the javascript world "A promise represents the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its then method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled." (https://promisesaplus.com) "The point of promises is to give us back functional composition and error bubbling in the async world. They do this by saying that your functions should return a promise, which can do one of two things: * Become fulfilled by a value * Become rejected with an error" (https://gist.github.com/domenic/3889970) */ open class Promise<T> : NSObject { // MARK: - Interface /** This initializer needs to check for Promise<T> or ErrorType values to handle the case where T is Any and those then become valid argument values. - Returns: an immutable, fulfilled promise using the supplied value */ public static func valueAsPromise(_ value: T?) -> Promise<T> { if let existingPromise = value as? Promise<T> { return existingPromise } else if let error = value as? Error { return Promise(error) } else { return Promise(value) } } /** This initializer checks for Promise values that are not type T which requires special handling. Since Swift cannot currently require R to be assignment compatible with T, the only choice is to reject the promise if an incompatible value is returned from the original promise. This initializer is necessary because if T is Any, then Promise<R> where R is not T, will be passed through as a normal value in the primary initializer. This specialized initializer forces it through this path. - Returns: convenience method wrapping a promise of a different subtype than T */ public static func valueAsPromise<R>(_ existingPromise: Promise<R>) -> Promise<T> { let result:Promise<T> = Promise() existingPromise.then( { value in if let t = value as? T { result.fulfill(t) } else { let errorMessage = "original promise was fulfilled with \(String(describing: value)), but it could not be converted to \(T.self) so fulfilling dependent promise with nil" let error = PromiseError.mismatchPromiseValueTypes(errorMessage) result.reject(error) } return .value(value) }, reject: { error in result.reject(error) return .error(error) } ) return result } /** This initializer frees the client code from needing to check if the value being passed in is a promise already or not. This version is necessary for those cases where T is NOT Any, so the first initializer would not be used by the compiler. - Returns: an immutable, fulfilled promise using an existing promise */ public static func valueAsPromise(_ value: Promise<T>) -> Promise<T> { return value } /** - Returns: an immutable, rejected promise using the supplied error */ public class func valueAsPromise(_ value: Error) -> Promise<T> { return Promise(value) } /** - Parameter promises: list of generic promises that act as dependencies - Returns: a dependent promise that is fulfilled when all the supplied promises are fulfilled or rejected when one or more are rejected */ public class func all(_ promises:[Promise]) -> Promise<[Promise]> { let result:Promise<[Promise]> = Promise<[Promise]>() var completedPromiseCount = 0 let synchronizer = Synchronizer() for promise in promises { promise.then( { value in synchronizer.synchronize({ completedPromiseCount += 1 }) if (completedPromiseCount == promises.count) { result.fulfill(promises) } return .value(value) }, reject: { error in result.reject(error) return .error(error) } ) } return result } /** Creates a new pending promise with no chained promises */ public override init() { state = .pending([]) } /** Creates a new immutable fulfilled promise with an optional type-safe value and no chained promises This can be useful when an async user code process needs to return a promise, but already has the result (such as with a completed network request, database query, etc.) */ public init(_ value:T?) { state = .fulfilled(value) } /** Creates a new immutable rejected promise with an error and no chained promises This can be useful when an async user code process needs to return a promise, but already has an error result (such as with a completed network request, database query, etc.) */ public init(_ error:Error) { state = .rejected(error) } /** Read-only property that is true if the promise is still pending */ public var isPending: Bool { get { var result = false stateSynchronizer.synchronize { switch (self.state) { case .pending( _): result = true default: result = false } } return result } } /** Read-only property that is true if the promise has been fulfilled */ public var isFulfilled: Bool { get { var result = false stateSynchronizer.synchronize { switch (self.state) { case .fulfilled( _): result = true default: result = false } } return result } } /** Read-only property that is true if the promise has been rejected */ public var isRejected: Bool { get { var result = false stateSynchronizer.synchronize { switch (self.state) { case .rejected( _): result = true default: result = false } } return result } } /** Read-only property that is the fulfilled value if the promise has been fulfilled, nil otherwise */ public var value: T? { var result:T? stateSynchronizer.synchronize { switch (self.state) { case .fulfilled(let value): result = value default: result = nil } } return result } /** Read-only property that is the rejection error if the promise has been rejected, nil otherwise */ public var error: Error? { var result:Error? stateSynchronizer.synchronize { switch (self.state) { case .rejected(let error): result = error default: result = nil } } return result } /** If the promise is pending, then change its state to fulfilled using the supplied value and notify any chained promises that it has been fulfilled. If the promise is in any other state, no changes are made and any chained promises are ignored. - Parameter value: optional fulfilled value to use for the promise */ public func fulfill(_ value: T?) { var promiseActionsToFulfill:[PromiseAction<T>] = [] stateSynchronizer.synchronize { switch (self.state) { case .pending(let promiseActions): self.state = .fulfilled(value) promiseActionsToFulfill = promiseActions default: print("WARN: cannot fulfill promise, state already set to \(self.state)") } } for promiseAction in promiseActionsToFulfill { promiseAction.fulfill(value) } } /** If the promise is pending, then change its state to rejected using the supplied error and notify any chained promises that it has been rejected. If the promise is in any other state, no changes are made and any chained promises are ignored. - Parameter error: rejection error to use for the promise */ public func reject(_ error: Error) { var promiseActionsToReject:[PromiseAction<T>] = [] stateSynchronizer.synchronize { switch (self.state) { case .pending(let promiseActions): self.state = .rejected(error) promiseActionsToReject = promiseActions default: print("WARN: cannot reject promise, state already set to \(self.state)") } } for promiseAction in promiseActionsToReject { promiseAction.reject(error) } } /** This method lets your code add dependent results to an existing promise. 'fulfill' and 'reject' closures may be added to a promise at any time. If the promise is eventually fulfilled, the fulfill closure will be called one time, and the reject closure will never be called. If the promise is eventually rejected, the reject closure will be called one time, and the fulfill closure will never be called. If the promise remains in a pending state, neither closure will ever be called. This method may be called as many times as needed, and the appropriate closures will be called in the order they were added via the then method. If the promise is pending, then they will be added to the list of closures to be processed once the promise is fulfilled or rejected in the future. If the promise is already fulfilled, then the fulfill closure will be called immediately If the promise is already rejected, then if the reject closure exists, it will be called immediately - Parameter fulfill: closure to call when the promise is fulfilled that returns an instance of PromiseClosureResult - Parameter reject: optional rejection closure to call when the promise is rejected that returns an instance of PromiseClosureResult If the reject closure does not exist, it will simply pass the .Error(errorType) value down the promise chain If it does exist, it returns an instance of PromiseClosureResult, just as the fulfill closure does. (Note that this means that either closure can redirect dependent promises in the chain, which can allow a reject closure to to recover by supplying a valid value so subsequent promises can continue) - Returns: a new instance of a promise to which application code can add dependent promises (e.g. chaining) */ @discardableResult public func then(_ fulfill: @escaping ((T?) -> PromiseClosureResult<T>), reject: ((Error) -> PromiseClosureResult<T>)?) -> Promise<T> { let result:Promise<T> = Promise() let promiseAction = PromiseAction(result, fulfill, reject) stateSynchronizer.synchronize { switch (self.state) { case .pending(var promiseActions): promiseActions.append(promiseAction) self.state = .pending(promiseActions) case .fulfilled(let value): promiseAction.fulfill(value) case .rejected(let error): promiseAction.reject(error) } } return result } /** A convenience method with a nil reject closure. Since Objective-C does not recognize default parameters, this provides a work-around. */ public func then(_ fulfill: @escaping ((T?) -> PromiseClosureResult<T>)) -> Promise<T> { return then(fulfill, reject: nil) } // MARK: - private values private var state: PromiseState<T> = .pending([]) private let stateSynchronizer = Synchronizer() } // MARK: - // MARK: Public error types /** Custom errors generated from within the SwiftPromise framework */ public enum PromiseError: Error { case mismatchPromiseValueTypes(String) } // MARK: Public helper enum PromiseClosureResult /** PromiseClosureResult is returned by promise fulfill and reject closures so they can return a type-safe value, an error, or a promise to be used in the promise chain. This allows either type of closure to pass along a similar value (e.g. type-safe value -> type-safe value) or redirect the dependent, chained promises into an alternative path by returning a type-safe value from a reject closure. <ul> <li>.Value - it will cause any dependent promises to be fulfilled with the associated type-safe value</li> <li>.Error - it will cause any dependent promises to be rejected with the associated error value</li> <li>.Pending - it will chain this instance's resolution to the associated promise's resolution</li> </ul> */ public enum PromiseClosureResult<T> { /** Associated value is required and is the error that will trigger the reject closure for a promise */ case error(Error) /** Associated value is optional and is the type-safe result that will trigger the fulfill closure for a promise */ case value(T?) /** Associated value is required and is a type-safe promise that the owning promise will be dependent on for a result before the owning promise can be fulfilled or rejected */ case pending(Promise<T>) } // MARK: - // MARK: Private helper enum PromiseState private enum PromiseState<T> { case pending([PromiseAction<T>]) case fulfilled(T?) case rejected(Error) } // MARK: Private helper class PromiseAction private class PromiseAction<T> { private let promise: Promise<T> private let fulfillClosure: ((T?) -> PromiseClosureResult<T>) private let rejectClosure: ((Error) -> PromiseClosureResult<T>)? init(_ promise: Promise<T>, _ fulfillClosure: @escaping ((T?) -> PromiseClosureResult<T>), _ rejectClosure: ((Error) -> PromiseClosureResult<T>)?) { self.promise = promise self.fulfillClosure = fulfillClosure self.rejectClosure = rejectClosure } func fulfill(_ value: T?) { let result = fulfillClosure(value) processClosureResult(result) } func reject(_ error: Error) { var rejectResult:PromiseClosureResult<T> = .error(error) if let rejectClosure = rejectClosure { rejectResult = rejectClosure(error) } processClosureResult(rejectResult) } func processClosureResult(_ promiseClosureResult: PromiseClosureResult<T>) { switch promiseClosureResult { case .error(let error): self.promise.reject(error) case .value(let value): self.promise.fulfill(value) case .pending(let pendingPromise): pendingPromise.then( { result in self.promise.fulfill(result) return .value(result) }, reject: { error in self.promise.reject(error) return .error(error) } ) } } }
mit
d6f1c070915644843feba882a47c91f5
33.273118
190
0.616176
4.955535
false
false
false
false
zbamstudio/DonutChart
Source/DonutChart.swift
1
12051
/* MIT License Copyright (c) [2017] [Emrah Ozer / Zbam Studio] */ import Foundation import UIKit enum OutlinePlacement: Double { static var all:[OutlinePlacement] = [.Inside, .Center, .Outside] case Inside = -1.0 case Center = 0.0 case Outside = 1.0 } @IBDesignable class DonutChart: UIView { fileprivate var outlineLayer: CAShapeLayer? fileprivate var progressLayer: CAShapeLayer? fileprivate var percentageText: UILabel? fileprivate var paragraphStyle: NSMutableParagraphStyle? fileprivate var attributedString: NSMutableAttributedString! fileprivate var _outlinePlacementInterfaceAdapter: String = "inside" override class var layerClass: AnyClass { return AnimationLayer.self } fileprivate var _progress: CGFloat = 0.0 @IBInspectable var progress: CGFloat { set { if let layer = layer as? AnimationLayer { layer.progress = newValue } _progress = newValue updateProgress() } get { return _progress } } fileprivate var _progressColor: UIColor = UIColor.black @IBInspectable var progressColor: UIColor { set { if let layer = layer as? AnimationLayer { layer.progressColor = newValue.cgColor } _progressColor = newValue progressLayer?.strokeColor = _progressColor.cgColor self.setNeedsDisplay() } get { return _progressColor } } fileprivate var _outlineColor: UIColor = UIColor.black @IBInspectable var outlineColor: UIColor { set { if let layer = layer as? AnimationLayer { layer.outlineColor = newValue.cgColor } _outlineColor = newValue outlineLayer?.strokeColor = _outlineColor.cgColor self.setNeedsDisplay() } get { return _outlineColor } } fileprivate var _textColor: UIColor = UIColor.black @IBInspectable var textColor: UIColor { set { if let layer = layer as? AnimationLayer { layer.textColor = newValue.cgColor } _textColor = newValue percentageText?.textColor = _textColor self.setNeedsDisplay() } get { return _textColor } } fileprivate var _radius: Double = 100.0 @IBInspectable var radius: Double { set { if let layer = layer as? AnimationLayer { layer.radius = CGFloat(newValue) } _radius = newValue setFrameOfOutlineLayer() setFrameOfProgressLayer() setFrameOfTextField() self.setNeedsDisplay() } get { return _radius } } fileprivate var _thickness : Double = 10 @IBInspectable var thickness: Double{ set { if let layer = layer as? AnimationLayer { layer.thickness = CGFloat(newValue) } _thickness = newValue progressLayer?.lineWidth = CGFloat(_thickness) setFrameOfOutlineLayer() setFrameOfProgressLayer() setFrameOfTextField() self.setNeedsDisplay() } get { return _thickness } } fileprivate var _outlineWidth : Double = 1 @IBInspectable var outlineWidth: Double { set { if let layer = layer as? AnimationLayer { layer.outlineWidth = CGFloat(newValue) } _outlineWidth = newValue self.outlineLayer?.lineWidth = CGFloat(outlineWidth) self.setNeedsDisplay() } get { return _outlineWidth } } @IBInspectable var fontSize: CGFloat = 12 { didSet { updateFontProperty() } } @IBInspectable var fontFamily: String = "Arial" { didSet { updateFontProperty() } } @IBInspectable var percentageSignFontSize: CGFloat = 16 { didSet { updateFontProperty() } } @IBInspectable var percentageSignFontFamily: String = "Arial" { didSet { updateFontProperty() } } @IBInspectable var isPercentageSignVisible : Bool = true { didSet { updateText() self.setNeedsDisplay() } } @IBInspectable var outlinePlacementInterfaceAdapter: String { set { _outlinePlacementInterfaceAdapter = newValue switch _outlinePlacementInterfaceAdapter { case "inside": outlinePlacement = .Inside case "center": outlinePlacement = .Center case "outside": outlinePlacement = .Outside default: outlinePlacement = .Inside } setFrameOfOutlineLayer() setFrameOfProgressLayer() setFrameOfTextField() self.setNeedsDisplay() } get{ return _outlinePlacementInterfaceAdapter } } var outlinePlacement: OutlinePlacement = .Inside { didSet { self.setNeedsDisplay() } } private var font: UIFont! private var percentageSignFont: UIFont! override init(frame: CGRect) { super.init(frame: frame) create() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) create() } override func awakeFromNib() { super.awakeFromNib() updateProgress() } func create() { self.backgroundColor = UIColor.clear self.isOpaque = false createTextField() createParagraphStyle() createLayers() setFrameOfOutlineLayer() setFrameOfProgressLayer() setFrameOfTextField() createFonts() updateText() addSubview(percentageText!) } private func createTextField() { percentageText = UILabel() percentageText?.textAlignment = NSTextAlignment.center percentageText?.lineBreakMode = NSLineBreakMode.byWordWrapping } fileprivate func createParagraphStyle() { paragraphStyle = NSMutableParagraphStyle() paragraphStyle?.lineHeightMultiple = 0.8 paragraphStyle?.alignment = NSTextAlignment.center } fileprivate func createFonts() { font = UIFont(name: fontFamily, size: fontSize) percentageSignFont = UIFont(name: percentageSignFontFamily, size: percentageSignFontSize) } fileprivate func createLayers() { outlineLayer = CAShapeLayer() progressLayer = CAShapeLayer() self.layer.addSublayer(outlineLayer!) self.layer.addSublayer(progressLayer!) outlineLayer?.lineWidth = CGFloat(outlineWidth) outlineLayer?.fillColor = UIColor.clear.cgColor progressLayer?.lineWidth = CGFloat(thickness) progressLayer?.fillColor = UIColor.clear.cgColor } fileprivate func setFrameOfTextField() { var textFrame: CGRect let offset = thickness * outlinePlacement.rawValue let textFieldWidth = _radius * 1.5 - offset textFrame = CGRect(x: Double(self.frame.width) / 2 - textFieldWidth / 2 + offset/2, y: Double(self.frame.height) / 2 - textFieldWidth / 2 + offset/2, width: textFieldWidth, height: textFieldWidth) percentageText?.frame = textFrame } fileprivate func setFrameOfOutlineLayer() { let outlineCirclePositionOffset = thickness * outlinePlacement.rawValue; let rect = CGRect(x: Double(self.frame.width) / 2 - _radius - outlineCirclePositionOffset / 2, y: Double(self.frame.height) / 2 - _radius - outlineCirclePositionOffset / 2, width: _radius * 2 + outlineCirclePositionOffset, height: _radius * 2 + outlineCirclePositionOffset) outlineLayer?.path = UIBezierPath(roundedRect: rect, cornerRadius: CGFloat(radius)).cgPath } fileprivate func setFrameOfProgressLayer() { let rect = CGRect(x: Double(self.frame.width) / 2 - _radius, y: Double(self.frame.height) / 2 - _radius, width: _radius * 2, height: _radius * 2) progressLayer?.path = UIBezierPath(roundedRect: rect, cornerRadius: CGFloat(radius * 2)).cgPath } fileprivate func updateText() { let percentage = Int(ceil(_progress * 100.0)) var percentageString = "\(percentage)" if(isPercentageSignVisible) { percentageText?.numberOfLines = 0 createAttributedStringForVisiblePercentageSign(percentageString: percentageString) }else { percentageText?.numberOfLines = 1 createAttributedStringWithoutPercentageSign(percentageString: percentageString) } self.percentageText?.attributedText = self.attributedString ?? NSAttributedString(string: "") } fileprivate func createAttributedStringWithoutPercentageSign(percentageString: String) { attributedString = NSMutableAttributedString(string: percentageString) attributedString.addAttribute(NSFontAttributeName, value: font, range: NSRange(location: 0, length: percentageString.utf8.count)) attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle!, range: NSRange(location: 0, length: attributedString.string.utf8.count)) } fileprivate func createAttributedStringForVisiblePercentageSign(percentageString: String) { attributedString = NSMutableAttributedString(string: percentageString + "\n%") attributedString.addAttribute(NSFontAttributeName, value: font, range: NSRange(location: 0, length: percentageString.utf8.count)) attributedString.addAttribute(NSFontAttributeName, value: percentageSignFont, range: NSRange(location: percentageString.utf8.count+1, length: 1)) attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle!, range: NSRange(location: 0, length: attributedString.string.utf8.count)) } fileprivate func updateProgress() { progressLayer?.strokeEnd = CGFloat(_progress) updateText() self.setNeedsDisplay() } fileprivate func updateFontProperty() { createFonts() updateText() self.setNeedsDisplay() } override func display(_ layer: CALayer) { if let pLayer = layer.presentation() as? AnimationLayer { progressLayer?.strokeEnd = CGFloat(pLayer.progress) progressLayer?.strokeColor = pLayer.progressColor outlineLayer?.strokeColor = pLayer.outlineColor progressLayer?.lineWidth = pLayer.thickness percentageText?.textColor = UIColor(cgColor: pLayer.textColor) outlineLayer?.lineWidth = pLayer.outlineWidth if(Double(pLayer.radius) != _radius || Double(pLayer.thickness) != _thickness) { _radius = Double(pLayer.radius) _thickness = Double(pLayer.thickness) setFrameOfTextField() setFrameOfOutlineLayer() setFrameOfProgressLayer() } updateText() _progress = pLayer.progress _progressColor = UIColor(cgColor: pLayer.progressColor) _outlineColor = UIColor(cgColor: pLayer.outlineColor) _textColor = UIColor(cgColor: pLayer.textColor) _thickness = Double(pLayer.thickness) _outlineWidth = Double(pLayer.outlineWidth) } } }
mit
f98717c153c93c49839643d505a46ad0
27.222482
165
0.600282
5.389535
false
false
false
false
cotkjaer/Silverback
Silverback/Color.swift
1
4508
// // Color.swift // Silverback // // Created by Christian Otkjær on 14/12/15. // Copyright © 2015 Christian Otkjær. All rights reserved. // import CoreGraphics public struct RGBA { public var r: CGFloat = 0 public var g: CGFloat = 0 public var b: CGFloat = 0 public var a: CGFloat = 0 public init(r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 1) { (self.r, self.g, self.b, self.a) = (r,g,b,a) } public init(tuple: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)) { self.init(r:tuple.r, g:tuple.g, b: tuple.b, a: tuple.a) } public init(tuple: (r: CGFloat, g: CGFloat, b: CGFloat)) { self.init(r:tuple.r, g:tuple.g, b: tuple.b, a: 1) } } extension RGBA: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return "RGBA(\(r), \(g), \(b), \(a))" } public var debugDescription: String { return description } } // MARK: - Equatable extension RGBA: Equatable {} public func ==(lhs: RGBA, rhs: RGBA) -> Bool { return lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b && lhs.a == rhs.a } public extension RGBA { public var cgColor: CGColor { return CGColor.color(red: r, green: g, blue: b, alpha: a) } } // MARK: HSVA public struct HSVA { public let h: CGFloat public let s: CGFloat public let v: CGFloat public let a: CGFloat public init(h: CGFloat = 0, s: CGFloat = 0, v: CGFloat = 0, a: CGFloat = 1) { (self.h, self.s, self.v, self.a) = (h,s,v,a) } public init(tuple: (h: CGFloat, s: CGFloat, v: CGFloat, a: CGFloat)) { self.init(h: tuple.h, s: tuple.s, v: tuple.v, a: tuple.a) } public init(tuple: (h: CGFloat, s: CGFloat, v: CGFloat)) { self.init(h: tuple.h, s: tuple.s, v: tuple.v, a: 1) } } extension HSVA: CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return "HSVA(\(h), \(s), \(v), \(a))" } public var debugDescription: String { return description } } extension HSVA: Equatable { } public func ==(lhs: HSVA, rhs: HSVA) -> Bool { return lhs.h == rhs.h && lhs.s == rhs.s && lhs.v == rhs.v && lhs.a == rhs.a } public extension HSVA { public var cgColor: CGColor { let rgb = convert(self) return rgb.cgColor } } // MARK: Lerping HSVA extension HSVA: Lerpable { public typealias FactorType = CGFloat } public func + (lhs: HSVA, rhs: HSVA) -> HSVA { return HSVA(h: lhs.h + rhs.h, s: lhs.s + rhs.s, v: lhs.v + rhs.v, a: (rhs.a + lhs.a) / 2) } public func * (lhs: HSVA, rhs: CGFloat) -> HSVA { return HSVA(h: lhs.h * rhs, s: lhs.s * rhs, v: lhs.v * rhs, a: lhs.a * rhs) } public func convert(hsv: HSVA) -> RGBA { var (h, s, v, a) = (hsv.h, hsv.s, hsv.v, hsv.a) if (s == 0) { return RGBA(tuple: (v,v,v,a)) } else { h *= 360 if (h == 360) { h = 0 } else { h /= 60 } let i = floor(h) let f = h - i let p = v * (1 - s) let q = v * (1 - (s * f)) let t = v * (1 - (s * (1 - f))) switch Int(i) { case 0: return RGBA(tuple: (v,t,p,a)) case 1: return RGBA(tuple: (q,v,p,a)) case 2: return RGBA(tuple: (p,v,t,a)) case 3: return RGBA(tuple: (p,q,v,a)) case 4: return RGBA(tuple: (t,p,v,a)) case 5: return RGBA(tuple: (v,p,q,a)) default: fatalError("Cannot convert HSVA to RGBA") } } } public func convert(rgba: RGBA) -> HSVA { let maxRGB = max(rgba.r, rgba.g, rgba.b) let minRGB = min(rgba.r, rgba.g, rgba.b) let delta = maxRGB - minRGB var h: CGFloat = 0 let s = maxRGB != 0 ? delta / maxRGB : 0 let v = maxRGB if s == 0 { h = 0 } else { if rgba.r == maxRGB { h = (rgba.g - rgba.b) / delta } else if rgba.g == maxRGB { h = 2 + (rgba.b - rgba.r) / delta } else if rgba.b == maxRGB { h = 4 + (rgba.r - rgba.g) / delta } h *= 60 while h < 0 { h += 360 } } h /= 360 return HSVA(h: h, s: s, v: v, a: rgba.a) }
mit
793fc87fec504e5aeb76b70180dc7d9a
20.555024
93
0.49545
3.085616
false
false
false
false
CherishSmile/ZYBase
ZYBaseDemo/DemoVC.swift
1
4178
// // DemoVC.swift // BaseDemo // // Created by Mzywx on 2016/12/21. // Copyright © 2016年 Mzywx. All rights reserved. // import ZYBase class DemoVC: BaseTabVC,UITableViewDelegate,UITableViewDataSource,LBXResultDelegate{ fileprivate var demoTab : UITableView! fileprivate var demoArr : Array<String> = [] fileprivate var vcArr : Array<String> = [] override func viewDidLoad() { super.viewDidLoad() self.navigationItem.rightBarButtonItem = UIBarButtonItem(image:#imageLiteral(resourceName: "browser").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(itemClick)) self.navigationItem.leftBarButtonItem = UIBarButtonItem(image:#imageLiteral(resourceName: "scan").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(scanClick)) vcArr = ["BadgeNumberVC","CustomAlertVC","ScanVC","AutoCellHightVC","AorKDemoVC","WKWebVC","HMSegmentVC"] demoArr = ["badgeNumber示例","自定义alert示例","扫一扫示例","TableView自动计算行高示例","Alamofire和Kingfisher示例","WKWebview示例","HMSegmentControl示例"] demoTab = creatTabView(self, .grouped, { (make) in make.left.right.top.equalToSuperview() make.bottom.equalTo(-TOOLBAR_HEIGHT) }) setSearch(searchView: demoTab, location: .tabHeader, resultVC: nil) } func scanClick() { let scanVC = QQScanVC() scanVC.title = "扫一扫" scanVC.resultDelegate = self scanVC.scanStyle = scanViewStyle(.qq) scanVC.isOpenInterestRect = true scanVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(scanVC, animated: true) } @objc private func itemClick() { let browserVC = BrowserVC() browserVC.loadURLString("http://m.baidu.com") let browerNav = UINavigationController(rootViewController: browserVC) self.present(browerNav, animated: true, completion: nil) } func LBXResultHandle(result: LBXScanResult) { if let url = result.strScanned { let webVC = ScanResultVC() webVC.isShowProgress = true webVC.isUseWebTitle = true webVC.webloadHtml(urlStr: url) self.navigationController?.pushViewController(webVC, animated: true) } } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return demoArr.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var demoCell = tableView.dequeueReusableCell(withIdentifier: "CellID") if demoCell == nil { demoCell = UITableViewCell.init(style: .default, reuseIdentifier: "CellID") } demoCell?.textLabel?.text = demoArr[indexPath.row]; return demoCell! } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let vc = classFromString(vcArr[indexPath.row]) if let detailVC = vc { detailVC.title = demoArr[indexPath.row] detailVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(detailVC, animated: true) } } override var preferredStatusBarStyle: UIStatusBarStyle{ return .lightContent } 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
6d0766dc605aa7f5a95fcb0ad4a8f389
35.415929
204
0.652005
4.829812
false
false
false
false
KevinZhouRafael/ActiveSQLite
ActiveSQLiteTests/models/ProductM.swift
1
1205
// // ProductM.swift // ActiveSQLite // // Created by Kevin Zhou on 05/06/2017. // Copyright © 2017 [email protected]. All rights reserved. // import Foundation import SQLite @testable import ActiveSQLite class ProductM:ASModel{ var name:String = "" var price:NSNumber = NSNumber(value:0.0) var desc:String? var code:NSNumber? var publish_date:NSDate? var version:NSNumber? static let name = Expression<String>("product_name") static let price = Expression<Double>("product_price") static let desc = Expression<String?>("desc") static let code = Expression<NSNumber>("code") //Tests add column var type:NSNumber? static let type = Expression<NSNumber?>("type") override class var nameOfTable: String{ return "Product" } override func doubleTypes() -> [String]{ return ["price"] } override func mapper() -> [String:String]{ return ["name":"product_name","price":"product_price"]; } override func transientTypes() -> [String]{ return ["version"] } override class var isSaveDefaulttimestamp:Bool{ return true } }
mit
7cccb63efc636d3d7efe6e4ecd463cf4
20.890909
63
0.622924
4.195122
false
false
false
false
pkx0128/UIKit
MTabBarAndNav/MTabBarAndNav/Class/Main/MainViewController.swift
1
3557
// // MainViewController.swift // MTabBarAndNav // // Created by pankx on 2017/9/29. // Copyright © 2017年 pankx. All rights reserved. // import UIKit class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // setupChild() childNav() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension MainViewController { func setupChild() { let home = HomeViewController() home.title = "首页" home.tabBarItem = UITabBarItem(title: "Home", image: UIImage(named: "tabbar_home"), selectedImage: UIImage(named: "tabbar_home_seleted")) let homeNav = NavViewController(rootViewController: home) let message = MessageViewController() message.title = "信息" message.tabBarItem = UITabBarItem(title: "Message", image: UIImage(named: "tabbar_message_center"), selectedImage: UIImage(named: "tabbar_message_center_seleted")) let messageNav = NavViewController(rootViewController: message) let discover = DisCoverViewController() discover.title = "发现" discover.tabBarItem = UITabBarItem(title: "Discover", image: UIImage(named: "tabbar_discover"), selectedImage: UIImage(named: "tabbar_discover_seleted")) let discoverNav = NavViewController(rootViewController: discover) let profile = ProfileViewController() profile.title = "我" profile.tabBarItem = UITabBarItem(title: "Me", image: UIImage(named: "tabbar_profile"), selectedImage: UIImage(named: "tabbar_profile_seleted")) let profileNav = NavViewController(rootViewController: profile) self.viewControllers = [homeNav,messageNav,discoverNav,profileNav] } func getnavview(dit:[String:String]) -> UIViewController { guard let clsstr = dit["className"] ,let title = dit["title"], let image = dit["image"], let selectedImage = dit["selectedImage"] else { return UIViewController() } let ns = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? "" let clsn = ns + "." + clsstr let cls = NSClassFromString(clsn) as! BaseViewController.Type let vc = cls.init() vc.title = title vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor: UIColor.orange], for: .selected) vc.tabBarItem.image = UIImage(named: image) vc.tabBarItem.selectedImage = UIImage(named: selectedImage)?.withRenderingMode(.alwaysOriginal) let nav = NavViewController(rootViewController: vc) return nav } func childNav() { let NavInfo = [["className":"HomeViewController","title": "首页","image": "tabbar_home","selectedImage":"tabbar_home_selected"], ["className":"MessageViewController","title": "信息","image": "tabbar_message_center","selectedImage":"tabbar_message_center_selected"], ["className":"DisCoverViewController","title": "发现","image": "tabbar_discover","selectedImage":"tabbar_discover_selected"], ["className":"ProfileViewController","title": "我","image": "tabbar_profile","selectedImage":"tabbar_profile_selected"]] var NavArr = [UIViewController]() for nav in NavInfo { NavArr.append(getnavview(dit: nav)) } self.viewControllers = NavArr } }
mit
22122a05bbdee74c80e5b0ba5950b241
42.530864
171
0.650312
4.790761
false
false
false
false
brentdax/SQLKit
Sources/SQLKit/Pool.swift
1
7385
// // Pool.swift // LittlinkRouterPerfect // // Created by Brent Royal-Gordon on 10/27/16. // // import Dispatch /// Errors emitted by a Pool. public enum PoolError: Error { /// Attempting to `retrieve()` an unused `Resource` took longer than the /// `timeout`. case timedOut } /// A shared pool of `Resource` which can be added to and removed from in a /// threadsafe fashion. /// /// To use a `Pool`, initialize it with a `maximum` number of `Resources` to /// manage, a `timeout` indicating the maximum time it should wait for a /// `Resource` to be relinquished if all of them are in use, and a `constructor` /// which creates a new `Resource`. /// /// A `Pool` can manage any kind of object, but it's included in this module to /// support `SQLConnection` pools. When managing a pool of `SQLConnection`s, you /// can use a special constructor which creates connections from a provided /// `SQLDatabase`. /// /// Once the `Pool` has been created, you use the `retrieve()` method to get an /// object from the pool, and the `relinquish(_:)` method to return it to the pool. /// Alternatively, use `discard(_:)` to indicate that the object should be destroyed /// and a new one created; this is useful when the object is in an unknown state. /// If you want to wrap up all these calls into one mistake-resistant method, use /// the `withOne(do:)` method. // // FIXME: I actually have little experience with these primitives, particularly // semaphores. Review by someone who knows more about them than I do would be // welcome. public final class Pool<Resource: AnyObject> { private let constructor: () throws -> Resource private let timeout: DispatchTimeInterval private let counter: DispatchSemaphore private var resourceIsAvailable: [ByIdentity<Resource>: Bool] = [:] private let queue = DispatchQueue(label: "ConnectionPool.queue") /// Creates a `Pool`. The pool is initially empty, but it may eventually contain /// up to `maximum` objects. /// /// - Parameter maximum: The maximum number of `Resource` objects in the pool. /// /// - Parameter timeout: Indicates the maximum time to wait when there are /// `maximum` objects in the pool and none of them have been /// relinquished. /// /// - Parameter constructor: A function which can create a new `Resource`. /// Automatically called when someone tries to `retrieve()` an /// existing `Resource` and there aren't any, but the `maximum` /// has not been reached. public init(maximum: Int = 10, timeout: DispatchTimeInterval = .seconds(10), constructor: @escaping () throws -> Resource) { self.constructor = constructor self.counter = DispatchSemaphore(value: maximum) self.timeout = timeout } /// Retrieves a currently unused `Resource` from the `Pool`, marking it as /// used until it's passed to `relinquish(_:)`. /// /// - Throws: `PoolError.timedOut` if there are none available and none are /// relinquished within `timeout`, or any error thrown by `constructor`. /// /// - Note: This call is synchronized so that it is safe to call from any thread /// or queue. public func retrieve() throws -> Resource { func isAvailable(_: ByIdentity<Resource>, available: Bool) -> Bool { return available } guard counter.wait(timeout: .now() + timeout) != .timedOut else { throw PoolError.timedOut } return try queue.sync { if let index = resourceIsAvailable.index(where: isAvailable) { let resource = resourceIsAvailable[index].key.object resourceIsAvailable[resource] = false return resource } let newResource = try constructor() resourceIsAvailable[newResource] = false return newResource } } private func resetAvailability(of resource: Resource, to available: Bool?) { queue.sync { precondition(resourceIsAvailable[resource] == false) resourceIsAvailable[resource] = available counter.signal() } } /// Returns `resource` to the `Pool` to be reused. /// /// - Parameter resource: The resource to relinquish. It may be returned by a /// future call to `retrieve()`. /// /// - Precondition: `resource` was returned by a prior call to `retrieve()`. /// /// - Note: This call is synchronized so that it is safe to call from any thread /// or queue. public func relinquish(_ resource: Resource) { resetAvailability(of: resource, to: true) } /// Frees up `resource`'s slot in the pool. `resource` itself will never be /// reused, but a new instance of `Resource` may be allocated in its place. /// /// This is useful when `resource` may be in an inconsistent state, such as /// when an error occurs. /// /// - Parameter resource: The resource to discard. It will not be returned by /// any future call to `retrieve()`. /// /// - Precondition: `resource` was returned by a prior call to `retrieve()`. /// /// - Note: This call is synchronized so that it is safe to call from any thread /// or queue. public func discard(_ resource: Resource) { resetAvailability(of: resource, to: nil) } /// Calls `fn` with a newly-`retrieve()`d `Resource`, then `relinquish(_:)`es /// or `discard(_:)`s the resource as appropriate. /// /// The resource is `relinquish(_:)`ed if `fn` returns successfully, or /// `discard(_:)`ed if `fn` throws. /// /// - Parameter fn: The function to run with the `Resource`. /// /// - Returns: The return value of `fn`. /// /// - Throws: If `retrieve()` or `fn` throw. public func withOne<R>(do fn: (Resource) throws -> R) throws -> R { let resource = try retrieve() do { let ret = try fn(resource) relinquish(resource) return ret } catch { discard(resource) throw error } } } // WORKAROUND: #2 Swift doesn't support same-type requirements on generics private protocol _ByIdentityProtocol: Hashable { associatedtype Object: AnyObject init(_ object: Object) } private struct ByIdentity<Object: AnyObject> { let object: Object init(_ object: Object) { self.object = object } } // WORKAROUND: #2 Swift doesn't support same-type requirements on generics extension ByIdentity: Hashable, _ByIdentityProtocol { static func == (lhs: ByIdentity, rhs: ByIdentity) -> Bool { return ObjectIdentifier(lhs.object) == ObjectIdentifier(rhs.object) } var hashValue: Int { return ObjectIdentifier(object).hashValue } } // WORKAROUND: #2 Swift doesn't support same-type requirements on generics extension Dictionary where Key: _ByIdentityProtocol { subscript(key: Key.Object) -> Value? { get { return self[Key(key)] } set { self[Key(key)] = newValue } } }
mit
9fc804be7a83d02b821f44126f617435
36.678571
128
0.61476
4.438101
false
false
false
false
brightify/Bond
Bond/Bond+Arrays.swift
1
36517
// // Bond+Arrays.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // 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 private func cast<T, U>(type: T.Type)(_ object: U) -> T? { return object as? T } private func takeFirst<A, B>(a: A, _ b: B) -> A { return a } // MARK: Array Bond public class ArrayBond<T>: Bond<Array<T>> { public var willInsertListener: (([T], Range<Int>) -> Void)? public var didInsertListener: (([T], Range<Int>) -> Void)? public var willRemoveListener: (([T], Range<Int>) -> Void)? public var didRemoveListener: (([T], Range<Int>) -> Void)? public var willUpdateListener: (([T], Range<Int>) -> Void)? public var didUpdateListener: (([T], Range<Int>) -> Void)? public var willResetListener: ([T] -> Void)? public var didResetListener: ([T] -> Void)? public override init(file: String = __FILE__, line: UInt = __LINE__) { super.init(file: file, line: line) } override func fireListenerInternally(observable: Observable<[T]>) { willResetListener?(observable.value) super.fireListenerInternally(observable) didResetListener?(observable.value) } } public struct ObservableArrayGenerator<T>: GeneratorType { private var index = -1 private let array: ObservableArray<T> init(array: ObservableArray<T>) { self.array = array } public typealias Element = T public mutating func next() -> T? { index++ return index < array.count ? array[index] : nil } } // MARK: Observable array public class ObservableArray<T>: Observable<Array<T>>, SequenceType { public var observableCount: Observable<Int> { return map { $0.count } } public override var value: Array<T> { willSet { dispatchWillReset(noEventValue) } didSet { dispatchDidReset(noEventValue, callDispatch: false) } } public var count: Int { return noEventValue.count } public var capacity: Int { return noEventValue.capacity } public var isEmpty: Bool { return noEventValue.isEmpty } public var first: T? { return noEventValue.first } public var last: T? { return noEventValue.last } public convenience override init(file: String = __FILE__, line: UInt = __LINE__) { self.init([], file: file, line: line) } public override init(_ value: Array<T>, file: String = __FILE__, line: UInt = __LINE__) { super.init(value, file: file, line: line) } public subscript(index: Int) -> T { get { return noEventValue[index] } } public func generate() -> ObservableArrayGenerator<T> { return ObservableArrayGenerator<T>(array: self) } private func dispatchWillReset(array: [T]) { bonds.map { $0.bond as? ArrayBond }.forEach { $0?.willResetListener?(array) } } private func dispatchDidReset(array: [T], callDispatch: Bool = true) { if callDispatch { dispatch(array) } bonds.map { $0.bond as? ArrayBond }.forEach { $0?.didResetListener?(array) } } private func dispatchWillInsert(array: [T], _ range: Range<Int>) { bonds.map { $0.bond as? ArrayBond }.forEach { $0?.willInsertListener?(array, range) } } private func dispatchDidInsert(array: [T], _ range: Range<Int>) { if !range.isEmpty { dispatch(array) } bonds.map { $0.bond as? ArrayBond }.forEach { $0?.didInsertListener?(array, range) } } private func dispatchWillRemove(array: [T], _ range: Range<Int>) { bonds.map { $0.bond as? ArrayBond }.forEach { $0?.willRemoveListener?(array, range) } } private func dispatchDidRemove(array: [T], _ range: Range<Int>) { if !range.isEmpty { dispatch(array) } bonds.map { $0.bond as? ArrayBond }.forEach { $0?.didRemoveListener?(array, range) } } private func dispatchWillUpdate(array: [T], _ range: Range<Int>) { bonds.map { $0.bond as? ArrayBond }.forEach { $0?.willUpdateListener?(array, range) } } private func dispatchDidUpdate(array: [T], _ range: Range<Int>) { if !range.isEmpty { dispatch(array) } bonds.map { $0.bond as? ArrayBond }.forEach { $0?.didUpdateListener?(array, range) } } } public class MutableObservableArray<T>: ObservableArray<T> { public convenience init(file: String = __FILE__, line: UInt = __LINE__) { self.init([], file: file, line: line) } public override init(_ value: Array<T>, file: String = __FILE__, line: UInt = __LINE__) { super.init(value, file: file, line: line) } public func append(newElement: T) { let range = noEventValue.endIndex ..< noEventValue.endIndex.successor() dispatchWillInsert(noEventValue, range) noEventValue.append(newElement) dispatchDidInsert(noEventValue, range) } public func append(array: Array<T>) { insertContentsOf(array, at: noEventValue.count) } public func removeLast() -> T { guard count > 0 else { fatalError("Cannot removeLast() as there are no elements in the array!") } return removeAtIndex(noEventValue.endIndex - 1) } public func insert(newElement: T, atIndex i: Int) { let range = i ..< (i + 1) dispatchWillInsert(noEventValue, range) noEventValue.insert(newElement, atIndex: i) dispatchDidInsert(noEventValue, range) } public func insertContentsOf<C : CollectionType where C.Generator.Element == T, C.Index.Distance == Int>(newElements: C, at i: Int) { guard newElements.count > 0 else { return } newElements.count let range = i ..< i.advancedBy(newElements.count) dispatchWillInsert(noEventValue, range) noEventValue.insertContentsOf(newElements, at: i) dispatchDidInsert(noEventValue, range) } public func removeAtIndex(index: Int) -> T { let range = index ..< index.successor() dispatchWillRemove(noEventValue, range) let object = noEventValue.removeAtIndex(index) dispatchDidRemove(noEventValue, range) return object } public func removeRange(subRange: Range<Int>) { dispatchWillRemove(noEventValue, subRange) noEventValue.removeRange(subRange) dispatchDidRemove(noEventValue, subRange) } public func removeAll(keepCapacity: Bool) { let range = 0 ..< noEventValue.count dispatchWillRemove(noEventValue, range) noEventValue.removeAll(keepCapacity: keepCapacity) dispatchDidRemove(noEventValue, range) } public func replaceRange<C: CollectionType where C.Generator.Element == T, C.Index == Int>(subRange: Range<Int>, with newElements: C) { // Check if the backing value contains the subRange if subRange.count == newElements.count { dispatchWillUpdate(noEventValue, subRange) subRange.enumerate().forEach { self.noEventValue[$1] = newElements[$0] } dispatchDidUpdate(noEventValue, subRange) } else { removeRange(subRange) insertContentsOf(newElements, at: subRange.startIndex) } } public override subscript(index: Int) -> T { get { return super[index] } set { if index == noEventValue.count { append(newValue) } else { let range = index ..< index.successor() dispatchWillUpdate(noEventValue, range) noEventValue[index] = newValue dispatchDidUpdate(noEventValue, range) } } } } // MARK: Dynamic array public class DynamicArray<T>: MutableObservableArray<T>, Bondable { public let arrayBond: ArrayBond<T> public var designatedBond: Bond<Array<T>> { return arrayBond } public convenience init(file: String = __FILE__, line: UInt = __LINE__) { self.init([], file: file, line: line) } public override init(_ array: Array<T>, file: String = __FILE__, line: UInt = __LINE__) { arrayBond = ArrayBond(file: file, line: line) super.init(array, file: file, line: line) arrayBond.listener = { [unowned self] in self.noEventValue = $0 self.dispatch($0) } arrayBond.willInsertListener = { [unowned self] array, range in self.dispatchWillInsert(self.noEventValue, range) } arrayBond.didInsertListener = { [unowned self] array, range in self.dispatchDidInsert(self.noEventValue, range) } arrayBond.willRemoveListener = { [unowned self] array, range in self.dispatchWillRemove(self.noEventValue, range) } arrayBond.didRemoveListener = { [unowned self] array, range in self.dispatchDidRemove(self.noEventValue, range) } arrayBond.willUpdateListener = { [unowned self] array, range in self.dispatchWillUpdate(self.noEventValue, range) } arrayBond.didUpdateListener = { [unowned self] array, range in self.dispatchDidUpdate(self.noEventValue, range) } arrayBond.willResetListener = { [unowned self] array in self.dispatchWillReset(self.noEventValue) } arrayBond.didResetListener = { [unowned self] array in self.dispatchDidReset(self.noEventValue) } } } public class LazyObservableArray<T>: ObservableArray<() -> T> { public override init(_ value: [() -> T], file: String = __FILE__, line: UInt = __LINE__) { super.init(value, file: file, line: line) } public func eager() -> ObservableArray<T> { return map { $0() } } public func eager(range: Range<Int>) -> [T] { return noEventValue[range].map { $0() } } public func eager(index: Int) -> T { return noEventValue[index]() } } // MARK: Dynamic Array Map Proxy private class LazyObservableArrayMapProxy<T, U>: LazyObservableArray<U> { private let bond: ArrayBond<T> private init(sourceArray: ObservableArray<T>, file: String = __FILE__, line: UInt = __LINE__, mapf: (Int, T) -> U) { bond = ArrayBond<T>(file: file, line: line) bond.bind(sourceArray, fire: false) let lazyArray = LazyObservableArrayMapProxy.createArray(sourceArray.noEventValue, mapf) super.init(lazyArray, file: file, line: line) bond.listener = { [unowned self] array in self.noEventValue = LazyObservableArrayMapProxy.createArray(array, mapf) self.dispatch(self.noEventValue) } bond.willInsertListener = { [unowned self] array, range in self.dispatchWillInsert(self.noEventValue, range) } bond.didInsertListener = { [unowned self] array, range in self.dispatchDidInsert(self.noEventValue, range) } bond.willRemoveListener = { [unowned self] array, range in self.dispatchWillRemove(self.noEventValue, range) } bond.didRemoveListener = { [unowned self] array, range in self.dispatchDidRemove(self.noEventValue, range) } bond.willUpdateListener = { [unowned self] array, range in self.dispatchWillUpdate(self.noEventValue, range) } bond.didUpdateListener = { [unowned self] array, range in self.dispatchDidUpdate(self.noEventValue, range) } bond.willResetListener = { [unowned self] array in self.dispatchWillReset(self.noEventValue) } bond.didResetListener = { [unowned self] array in self.dispatchDidReset(self.noEventValue) } } private static func createArray(sourceArray: [T], _ mapf: (Int, T) -> U) -> [() -> U] { guard sourceArray.count > 0 else { return [] } return (0..<sourceArray.count).map(createItem(sourceArray, mapf)) } private static func createItem(sourceArray: [T], _ mapf: (Int, T) -> U)(_ index: Int)() -> U { return mapf(index, sourceArray[index]) } } private class FlatMapContainer<T> { private let bond: ArrayBond<T> private let previous: FlatMapContainer<T>? private let target: ObservableArray<T> private var count: Int = 0 private init(previous: FlatMapContainer<T>?, parent: MutableObservableArray<T>, target: ObservableArray<T>, file: String = __FILE__, line: UInt = __LINE__) { bond = ArrayBond(file: file, line: line) self.previous = previous self.target = target self.count = target.count bond.bind(target, fire: false) bond.didInsertListener = { [unowned self, unowned parent] array, range in parent.insertContentsOf(array[range], at: self.absoluteIndex(range.startIndex)) self.count = array.count } bond.didRemoveListener = { [unowned self, unowned parent] array, range in parent.removeRange(self.absoluteRange(range)) self.count = array.count } bond.didUpdateListener = { [unowned self, unowned parent] array, range in parent.replaceRange(self.absoluteRange(range), with: array[range]) } bond.didResetListener = { [unowned self, unowned parent] array in parent.replaceRange(self.range, with: array) self.count = array.count } } private var range: Range<Int> { let startIndex = previous?.range.endIndex ?? 0 return startIndex ..< startIndex + count } private func absoluteIndex(relativeIndex: Int) -> Int { return range.startIndex + relativeIndex } private func absoluteRange(relativeRange: Range<Int>) -> Range<Int> { let startIndex = range.startIndex return (startIndex + relativeRange.startIndex) ..< (startIndex + relativeRange.endIndex) } } private class ObservableArrayFlatMapProxy<T, U>: MutableObservableArray<U> { private let bond: ArrayBond<T> private var lastSubarrayLink: FlatMapContainer<U>? private init(sourceArray: ObservableArray<T>, file: String = __FILE__, line: UInt = __LINE__, mapf: (Int, T) -> ObservableArray<U>) { bond = ArrayBond(file: file, line: line) bond.bind(sourceArray, fire: false) super.init([]) noEventValue = sourceArray.value.enumerate().map(mapf) .reduce([], combine: ObservableArrayFlatMapProxy.bindSubarrays(&lastSubarrayLink, parent: self)) bond.listener = { [unowned self] array in self.lastSubarrayLink = nil self.noEventValue = sourceArray.value.enumerate().map(mapf) .reduce([], combine: ObservableArrayFlatMapProxy.bindSubarrays(&self.lastSubarrayLink, parent: self)) self.dispatch(self.noEventValue) } bond.willInsertListener = { [unowned self] array, range in self.dispatchWillInsert(self.noEventValue, range) } bond.didInsertListener = { [unowned self] array, range in self.dispatchDidInsert(self.noEventValue, range) } bond.willRemoveListener = { [unowned self] array, range in self.dispatchWillRemove(self.noEventValue, range) } bond.didRemoveListener = { [unowned self] array, range in self.dispatchDidRemove(self.noEventValue, range) } bond.willUpdateListener = { [unowned self] array, range in self.dispatchWillUpdate(self.noEventValue, range) } bond.didUpdateListener = { [unowned self] array, range in self.dispatchDidUpdate(self.noEventValue, range) } bond.willResetListener = { [unowned self] array in self.dispatchWillReset(self.noEventValue) } bond.didResetListener = { [unowned self] array in self.dispatchDidReset(self.noEventValue) } } private static func bindSubarrays(inout lastSubarrayLink: FlatMapContainer<U>?, parent: MutableObservableArray<U>)(accumulator: [U], array: ObservableArray<U>) -> [U] { lastSubarrayLink = FlatMapContainer<U>(previous: lastSubarrayLink, parent: parent, target: array) return accumulator + array.value } } private class ObservableArrayValueFlatMapProxy<T, U>: MutableObservableArray<U> { private let bond: ArrayBond<T> private var valueBonds: [Bond<U>] = [] private init(sourceArray: ObservableArray<T>, file: String = __FILE__, line: UInt = __LINE__, mapf: (Int, T) -> Observable<U>) { bond = ArrayBond(file: file, line: line) bond.bind(sourceArray, fire: false) super.init([]) noEventValue = sourceArray.value.enumerate().map(mapf).enumerate() .map(ObservableArrayValueFlatMapProxy.bindValues(&valueBonds, parent: self)) bond.listener = { [unowned self] array in self.valueBonds = [] self.noEventValue = sourceArray.value.enumerate().map(mapf).enumerate() .map(ObservableArrayValueFlatMapProxy.bindValues(&self.valueBonds, parent: self)) self.dispatch(self.noEventValue) } bond.willInsertListener = { [unowned self] array, range in self.dispatchWillInsert(self.noEventValue, range) } bond.didInsertListener = { [unowned self] array, range in self.dispatchDidInsert(self.noEventValue, range) } bond.willRemoveListener = { [unowned self] array, range in self.dispatchWillRemove(self.noEventValue, range) } bond.didRemoveListener = { [unowned self] array, range in self.dispatchDidRemove(self.noEventValue, range) } bond.willUpdateListener = { [unowned self] array, range in self.dispatchWillUpdate(self.noEventValue, range) } bond.didUpdateListener = { [unowned self] array, range in self.dispatchDidUpdate(self.noEventValue, range) } bond.willResetListener = { [unowned self] array in self.dispatchWillReset(self.noEventValue) } bond.didResetListener = { [unowned self] array in self.dispatchDidReset(self.noEventValue) } } private static func bindValues(inout valueBonds: [Bond<U>], parent: MutableObservableArray<U>)(index: Int, value: Observable<U>) -> U { let bond = Bond<U> { [unowned parent] in parent[index] = $0 } bond.bind(value, fire: false) valueBonds.append(bond) return value.value } } private class ObservableArrayMapProxy<T, U>: ObservableArray<U> { private let bond: ArrayBond<T> private init(sourceArray: ObservableArray<T>, mapf: (Int, T) -> U) { self.bond = ArrayBond<T>() self.bond.bind(sourceArray, fire: false) let array = sourceArray.value.enumerate().map(mapf) super.init(array) bond.listener = { [unowned self] array in self.noEventValue = array.enumerate().map(mapf) self.dispatch(self.noEventValue) } bond.willInsertListener = { [unowned self] array, range in self.dispatchWillInsert(self.noEventValue, range) } bond.didInsertListener = { [unowned self] array, range in self.dispatchDidInsert(self.noEventValue, range) } bond.willRemoveListener = { [unowned self] array, range in self.dispatchWillRemove(self.noEventValue, range) } bond.didRemoveListener = { [unowned self] array, range in self.dispatchDidRemove(self.noEventValue, range) } bond.willUpdateListener = { [unowned self] array, range in self.dispatchWillUpdate(self.noEventValue, range) } bond.didUpdateListener = { [unowned self] array, range in self.dispatchDidUpdate(self.noEventValue, range) } bond.willResetListener = { [unowned self] array in self.dispatchWillReset(self.noEventValue) } bond.didResetListener = { [unowned self] array in self.dispatchDidReset(self.noEventValue) } } override var value: [U] { get { return super.value } set { fatalError("Modifying proxy array is not supported!") } } } private extension SequenceType where Generator.Element == Int { func indexOfFirstEqualOrLargerThan(x: Int) -> Int { var idx: Int = -1 for (index, element) in self.enumerate() { if element < x { idx = index } else { break } } return idx + 1 } } // MARK: Dynamic Array Filter Proxy private class ObservableArrayFilterProxy<T>: ObservableArray<T> { private unowned var sourceArray: ObservableArray<T> private var pointers: [Int] private let filterf: T -> Bool private let bond: ArrayBond<T> private init(sourceArray: ObservableArray<T>, filterf: T -> Bool) { self.sourceArray = sourceArray self.filterf = filterf self.bond = ArrayBond<T>() self.bond.bind(sourceArray, fire: false) var pointers: [Int] = [] let array = self.dynamicType.filteredArray(sourceArray.noEventValue, withPointers: &pointers, filterUsing: filterf) self.pointers = pointers super.init(array) bond.didInsertListener = { [unowned self] array, range in var pointers: [Int] = [] let filtered = self.dynamicType.filteredArray(array[range], withPointers: &pointers, filterUsing: filterf) guard let firstPointer = pointers.first else { return } let startIndex = self.pointers.indexOfFirstEqualOrLargerThan(firstPointer) let insertedRange = startIndex ..< startIndex.advancedBy(filtered.count) self.dispatchWillInsert(self.noEventValue, insertedRange) self.noEventValue.insertContentsOf(filtered, at: startIndex) self.pointers.insertContentsOf(pointers, at: startIndex) self.dispatchDidInsert(self.noEventValue, insertedRange) } bond.willRemoveListener = { [unowned self] array, range in var pointers: [Int] = [] let filtered = self.dynamicType.filteredArray(array[range], withPointers: &pointers, filterUsing: filterf) guard let firstPointer = pointers.first, let startIndex = self.pointers.indexOf(firstPointer) else { return } let removedRange = startIndex ..< startIndex.advancedBy(filtered.count) self.dispatchWillRemove(self.noEventValue, removedRange) self.noEventValue.removeRange(removedRange) self.pointers.removeRange(removedRange) self.dispatchDidRemove(self.noEventValue, removedRange) } bond.didUpdateListener = { [unowned self] array, range in //let idx = range.startIndex //let element = array[idx] var insertedIndices: [Int] = [] var removedIndices: [Int] = [] var updatedIndices: [Int] = [] let pointers = self.pointers for i in range { let keep = filterf(array[i]) let exists = pointers.contains(i) if exists && keep { updatedIndices.append(i) } else if exists && !keep { removedIndices.append(i) } else if keep { insertedIndices.append(i) } } insertedIndices.map { (pointers.indexOfFirstEqualOrLargerThan($0 - 1), $0) }.forEach { let insertedRange = $0...$0 self.dispatchWillInsert(self.noEventValue, insertedRange) self.noEventValue.insert(array[$1], atIndex: $0) self.pointers.insert($1, atIndex: $0) self.dispatchDidInsert(self.noEventValue, insertedRange) } removedIndices.map(pointers.indexOf).forEach { guard let localIndex = $0 else { return } let removedRange = localIndex...localIndex self.dispatchWillRemove(self.noEventValue, removedRange) self.noEventValue.removeAtIndex(localIndex) self.pointers.removeAtIndex(localIndex) self.dispatchDidRemove(self.noEventValue, removedRange) } updatedIndices.map { (pointers.indexOf($0), $0) }.forEach { guard let localIndex = $0 else { return } let updatedRange = localIndex...localIndex self.dispatchWillUpdate(self.noEventValue, updatedRange) self.noEventValue[localIndex] = array[$1] self.dispatchDidUpdate(self.noEventValue, updatedRange) } // if let idx = pointers.indexOf(idx) { // if filterf(element) { // // update // updatedIndices.append(idx) // } else { // // remove // pointers.removeAtIndex(idx) // removedIndices.append(idx) // } // } else { // if filterf(element) { // let position = pointers.indexOfFirstEqualOrLargerThan(idx) // pointers.insert(idx, atIndex: position) // insertedIndices.append(position) // } else { // // nothing // } // } // // if insertedIndices.count > 0 { // self.dispatchWillInsert(insertedIndices) // } // // if removedIndices.count > 0 { // self.dispatchWillRemove(removedIndices) // } // // if updatedIndices.count > 0 { // self.dispatchWillUpdate(updatedIndices) // } // // self.pointers = pointers // // if updatedIndices.count > 0 { // self.dispatchDidUpdate(updatedIndices) // } // // if removedIndices.count > 0 { // self.dispatchDidRemove(removedIndices) // } // // if insertedIndices.count > 0 { // self.dispatchDidInsert(insertedIndices) // } } bond.willResetListener = { [unowned self] array in self.dispatchWillReset(self.noEventValue) } bond.didResetListener = { [unowned self] array in self.noEventValue = self.dynamicType.filteredArray(array, withPointers: &self.pointers, filterUsing: filterf) self.dispatchDidReset(self.noEventValue) } } class func filteredArray<C: CollectionType where C.Generator.Element == T, C.Index == Int>(sourceArray: C, inout withPointers pointers: [Int], filterUsing filterf: T -> Bool) -> [T] { let filtered = sourceArray.enumerate().filter { filterf($0.element) } pointers = filtered.map { sourceArray.startIndex + $0.index } return filtered.map { $0.element } } class func rangesFromPointers(pointers: [Int]) -> [Range<Int>] { var insertedRanges: [Range<Int>] = [] var currentRange: Range<Int>? for i in pointers { if let range = currentRange { if i == range.endIndex { currentRange = range.startIndex...range.endIndex continue } else { insertedRanges.append(range) } } currentRange = i...i } if let range = currentRange { insertedRanges.append(range) } return insertedRanges } // // override var value: [T] { // get { // return sourceArray.lazy.filter(filterf) // } // set(newValue) { // fatalError("Modifying proxy array is not supported!") // } // } // // private override var count: Int { // return pointers.count // } // // private override var capacity: Int { // return pointers.capacity // } // // private override var isEmpty: Bool { // return pointers.isEmpty // } // // private override var first: T? { // if let first = pointers.first { // return sourceArray[first] // } else { // return nil // } // } // // private override var last: T? { // if let last = pointers.last { // return sourceArray[last] // } else { // return nil // } // } // // override private subscript(index: Int) -> T { // get { // return sourceArray[pointers[index]] // } // } } // MARK: Dynamic Array DeliverOn Proxy private class ObservableArrayDeliverOnProxy<T>: ObservableArray<T> { private unowned var sourceArray: ObservableArray<T> private var queue: dispatch_queue_t private let bond: ArrayBond<T> private init(sourceArray: ObservableArray<T>, queue: dispatch_queue_t) { self.sourceArray = sourceArray self.queue = queue self.bond = ArrayBond<T>() self.bond.bind(sourceArray, fire: false) super.init([]) bond.willInsertListener = { [unowned self] array, range in dispatch_async(queue) { [weak self] in self?.dispatchWillInsert(array, range) } } bond.didInsertListener = { [unowned self] array, range in dispatch_async(queue) { [weak self] in self?.dispatchDidInsert(array, range) } } bond.willRemoveListener = { [unowned self] array, range in dispatch_async(queue) { [weak self] in self?.dispatchWillRemove(array, range) } } bond.didRemoveListener = { [unowned self] array, range in dispatch_async(queue) { [weak self] in self?.dispatchDidRemove(array, range) } } bond.willUpdateListener = { [unowned self] array, range in dispatch_async(queue) { [weak self] in self?.dispatchWillUpdate(array, range) } } bond.didUpdateListener = { [unowned self] array, range in dispatch_async(queue) { [weak self] in self?.dispatchDidUpdate(array, range) } } bond.willResetListener = { [unowned self] array in dispatch_async(queue) { [weak self] in self?.dispatchWillReset(array) } } bond.didResetListener = { [unowned self] array in dispatch_async(queue) { [weak self] in self?.dispatchDidReset(array) } } } override var value: [T] { get { fatalError("Getting proxy array value is not supported!") } set(newValue) { fatalError("Modifying proxy array is not supported!") } } override var count: Int { return sourceArray.count } override var capacity: Int { return sourceArray.capacity } override var isEmpty: Bool { return sourceArray.isEmpty } override var first: T? { if let first = sourceArray.first { return first } else { return nil } } override var last: T? { if let last = sourceArray.last { return last } else { return nil } } override subscript(index: Int) -> T { get { return sourceArray[index] } } } // MARK: Dynamic Array additions public extension ObservableArray { public func map<U>(f: (Int, T) -> U) -> ObservableArray<U> { return _map(self, f) } public func map<U>(f: T -> U) -> ObservableArray<U> { let mapf = { (i: Int, o: T) -> U in f(o) } return _map(self, mapf) } public func flatMap<U>(f: T -> Observable<U>) -> ObservableArray<U> { return _flatMap(self) { f($1) } } public func flatMap<U>(f: (Int, T) -> Observable<U>) -> ObservableArray<U> { return _flatMap(self, f) } public func flatMap<U>(f: T -> ObservableArray<U>) -> ObservableArray<U> { return _flatMap(self) { f($1) } } public func flatMap<U>(f: (Int, T) -> ObservableArray<U>) -> ObservableArray<U> { return _flatMap(self, f) } public func lazyMap<U>(f: (Int, T) -> U) -> LazyObservableArray<U> { return _lazyMap(self, f) } public func lazyMap<U>(f: T -> U) -> LazyObservableArray<U> { let mapf = { (i: Int, o: T) -> U in f(o) } return _lazyMap(self, mapf) } public func filter(f: T -> Bool) -> ObservableArray<T> { return _filter(self, f) } } // MARK: Map private func _map<T, U>(dynamicArray: ObservableArray<T>, _ f: (Int, T) -> U) -> ObservableArrayMapProxy<T, U> { return ObservableArrayMapProxy(sourceArray: dynamicArray, mapf: f) } internal func _flatMap<T, U>(observable: ObservableArray<T>, _ f: (Int, T) -> Observable<U>) -> ObservableArray<U> { return ObservableArrayValueFlatMapProxy(sourceArray: observable, mapf: f) } internal func _flatMap<T, U>(observable: ObservableArray<T>, _ f: (Int, T) -> ObservableArray<U>) -> ObservableArray<U> { return ObservableArrayFlatMapProxy(sourceArray: observable, mapf: f) } private func _lazyMap<T, U>(dynamicArray: ObservableArray<T>, _ f: (Int, T) -> U) -> LazyObservableArrayMapProxy<T, U> { return LazyObservableArrayMapProxy(sourceArray: dynamicArray, mapf: f) } // MARK: Filter private func _filter<T>(dynamicArray: ObservableArray<T>, _ f: T -> Bool) -> ObservableArray<T> { return ObservableArrayFilterProxy(sourceArray: dynamicArray, filterf: f) } // MARK: DeliverOn public func deliver<T>(dynamicArray: ObservableArray<T>, on queue: dispatch_queue_t) -> ObservableArray<T> { return ObservableArrayDeliverOnProxy(sourceArray: dynamicArray, queue: queue) }
mit
b25ce4749535b7423e3b9d4b3701b419
33.417531
187
0.582852
4.308282
false
false
false
false
Davidde94/StemCode_iOS
StemCode/StemCode/Code/Window/Console.swift
1
2303
// // Console.swift // StemCode // // Created by David Evans on 19/04/2018. // Copyright © 2018 BlackPoint LTD. All rights reserved. // import UIKit @objc protocol ConsoleDelegate { func consoleDidToggleProjectExplorer(_ consoler: Console) -> Bool func consoleDidToggleFileInfoView(_ consoler: Console) -> Bool func consoleDidToggleHide(_ consoler: Console) -> Bool } class Console: DesignableXibView { @IBOutlet weak var delegate: ConsoleDelegate? = nil @IBOutlet private var keyboardButton: UIButton! @IBOutlet var commandBar: UIView! @IBOutlet var hideLeftPaneButton: UIButton! @IBOutlet var hideRightPaneButton: UIButton! // MARK: - init() { super.init(frame: CGRect.zero) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } // MARK: - private func setup() { NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { [weak self] (notification) in self?.keyboardButton.isEnabled = true } NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil) { [weak self] (notification) in self?.keyboardButton.isEnabled = false } } @IBAction func toggleProjectExplorer() { if let hidden = delegate?.consoleDidToggleProjectExplorer(self) { let imageName = hidden ? "close_left" : "close_right" hideLeftPaneButton.setImage(UIImage(named: imageName), for: UIControl.State.normal) } } @IBAction func toggleFileInfoView() { if let hidden = delegate?.consoleDidToggleFileInfoView(self) { let imageName = hidden ? "close_right" : "close_left" hideRightPaneButton.setImage(UIImage(named: imageName), for: UIControl.State.normal) } } @IBAction func toggleHide() { _ = delegate?.consoleDidToggleHide(self) } @IBAction func toggleKeyboard() { NotificationCenter.default.post(name: Notification.Name.HideKeyboard, object: nil) } }
mit
6f59ef446551f120074e9fb8fda44360
29.693333
154
0.647698
4.444015
false
false
false
false
CaiMiao/CGSSGuide
DereGuide/Common/CGSSVersionManager.swift
1
3127
// // CGSSVersionManager.swift // DereGuide // // Created by zzk on 2016/12/24. // Copyright © 2016年 zzk. All rights reserved. // import UIKit class CGSSVersionManager { static let `default` = CGSSVersionManager() var newestDataVersion: (Int, Int) { let major = (Bundle.main.infoDictionary!["Data Version"] as! [String: Int])["Major"]! let minor = (Bundle.main.infoDictionary!["Data Version"] as! [String: Int])["Minor"]! return (major, minor) } var currentDataVersion: (Int, Int) { set { UserDefaults.standard.set(newValue.0, forKey: "data_major") UserDefaults.standard.set(newValue.1, forKey: "data_minor") } get { let major = UserDefaults.standard.object(forKey: "data_major") as? Int ?? 0 let minor = UserDefaults.standard.object(forKey: "data_minor") as? Int ?? 0 return (major, minor) } } var currentDataVersionString: String { return "\(currentDataVersion.0).\(currentDataVersion.1)" } var apiInfo: ApiInfo? var currentApiVersion: (Int, Int) { set { UserDefaults.standard.set(newValue.0, forKey: "api_major") UserDefaults.standard.set(newValue.1, forKey: "api_reversion") } get { let major = UserDefaults.standard.object(forKey: "api_major") as? Int ?? 0 let reversion = UserDefaults.standard.object(forKey: "api_reversion") as? Int ?? 0 return (major, reversion) } } var gameVersion: Version? { set { UserDefaults.standard.set(newValue?.description, forKey: "game_version") } get { if let string = UserDefaults.standard.object(forKey: "game_version") as? String { return Version(string: string) } else { return nil } } } var currentMasterTruthVersion: String { set { UserDefaults.standard.setValue(newValue, forKey: "master_truth_version") } get { return UserDefaults.standard.object(forKey: "master_truth_version") as? String ?? "0" } } var currentManifestTruthVersion: String { set { UserDefaults.standard.setValue(newValue, forKey: "manifest_truth_version") } get { return UserDefaults.standard.object(forKey: "manifest_truth_version") as? String ?? "0" } } // 设置当前版本号为最新版本 func setDataVersionToNewest() { currentDataVersion = newestDataVersion } func setApiVersionToNewest() { if let info = apiInfo { currentApiVersion = info.apiVersion } } func setMasterTruthVersionToNewest() { if let info = apiInfo { currentMasterTruthVersion = info.truthVersion } } func setManifestTruthVersionToNewest() { if let info = apiInfo { currentManifestTruthVersion = info.truthVersion } } }
mit
660aeb746097ac6c8594b071681a52dc
27.703704
99
0.573548
4.341737
false
false
false
false