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
urbn/URBNJSONDecodable
Tests/URBNJSONDecodableTests/TestHelper.swift
1
1668
// // URBNTestHelper.swift // URBNSwiftyModels // // Created by Kevin Taniguchi on 3/27/16. // Copyright © 2016 CocoaPods. All rights reserved. // import XCTest public func nestedObjectJSON() -> Any? { let nestedObjectString = """ { "nestedObject": { "FIRST": { "string": "STRING", "int": 42 }, "SECOND": { "string": "STRING", "int": 42 } } } """ if let d = nestedObjectString.data(using: .utf8) { return try? JSONSerialization.jsonObject(with: d, options: []) } return nil } public func XCTAssertThrowsError<T, E>(_ expression: @autoclosure () throws -> T, _ type: E.Type, _ message: String = "", file: StaticString = #file, line: UInt = #line) where E: Error { do { _ = try expression() XCTFail("No error to catch! - \(message)", file: file, line: line) } catch is E { } catch let err { XCTFail("Expected error of \(E.self) got \(Swift.type(of: err).self) - \(message)", file: file, line: line) } } public func XCTAssertNoThrows<T>(_ expression: @autoclosure () throws -> T, _ message: String = "", file: StaticString = #file, line: UInt = #line) { do { _ = try expression() } catch let err { XCTFail("Expected not to throw error got \(type(of: err).self) - \(message)", file: file, line: line) } } public func ModelDescriptor(_ object: AnyObject, extra: String) -> String { return "<\(type(of: object)): \(Unmanaged.passUnretained(object).toOpaque())> - " + extra }
mit
4d33d85ceafb9ba681c622dc157a5abd
25.460317
186
0.542292
3.913146
false
false
false
false
nikhilsinghmus/csound
iOS/Csound iOS Swift Examples/Csound iOS SwiftExamples/CsoundVirtualKeyboard.swift
3
7883
/* CsoundVirtualKeyboard.swift Nikhil Singh, Dr. Richard Boulanger Adapted from the Csound iOS Examples by Steven Yi and Victor Lazzarini This file is part of Csound iOS SwiftExamples. The Csound for iOS Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. Csound is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Csound; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ import UIKit class CsoundVirtualKeyboard: UIView { // Variable declarations private var keyDown = [Bool].init(repeating: false, count: 25) private var currentTouches = NSMutableSet() private var keyRects = [CGRect](repeatElement(CGRect(), count: 25)) private var lastWidth: CGFloat = 0.0 private let keysNum = 25 @IBOutlet var keyboardDelegate: AnyObject? // keyboardDelegate object will handle key presses and releases override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) isMultipleTouchEnabled = true // Enable multiple touch so we can press multiple keys } // Check if a key is a white key or a black key depending on its index func isWhiteKey(_ key: Int) -> Bool { switch (key % 12) { case 0, 2, 4, 5, 7, 9, 11: return true default: return false } } // MARK: Update key statuses private func updateKeyRects() { if lastWidth == bounds.size.width { return } lastWidth = bounds.size.width let whiteKeyHeight: CGFloat = bounds.size.height let blackKeyHeight: CGFloat = whiteKeyHeight * 0.625 let whiteKeyWidth: CGFloat = bounds.size.width/15.0 let blackKeyWidth: CGFloat = whiteKeyWidth * 0.833333 let leftKeyBound: CGFloat = whiteKeyWidth - (blackKeyWidth / 2.0) var lastWhiteKey: CGFloat = 0 keyRects[0] = CGRect(x: 0, y: 0, width: whiteKeyWidth, height: whiteKeyHeight) for i in 1 ..< keysNum { if !(isWhiteKey(i)) { keyRects[i] = CGRect(x: (lastWhiteKey * whiteKeyWidth) + leftKeyBound, y: 0, width: blackKeyWidth, height: blackKeyHeight) } else { lastWhiteKey += 1 keyRects[i] = CGRect(x: lastWhiteKey * whiteKeyWidth, y: 0, width: whiteKeyWidth, height: whiteKeyHeight) } } } private func getKeyboardKey(_ point: CGPoint) -> Int { var keyNum = -1 for i in 0 ..< keysNum { if keyRects[i].contains(point) { keyNum = i if !(isWhiteKey(i)) { break } } } return keyNum } private func updateKeyStates() { updateKeyRects() var count = 0 let touches = currentTouches.allObjects count = touches.count var currentKeyState = [Bool](repeatElement(true, count: keysNum)) for i in 0 ..< keysNum { currentKeyState[i] = false } for i in 0 ..< count { let touch = touches[i] as! UITouch let point = touch.location(in: self) let index = getKeyboardKey(point) if index != -1 { currentKeyState[index] = true } } var keysUpdated = false for i in 0 ..< keysNum { if keyDown[i] != currentKeyState[i] { keysUpdated = true let keyDownState = currentKeyState[i] keyDown[i] = keyDownState if keyboardDelegate != nil { if keyDownState { keyboardDelegate?.keyDown(self, keyNum: i) } else { keyboardDelegate?.keyUp(self, keyNum: i) } } } } if keysUpdated { DispatchQueue.main.async { [unowned self] in self.setNeedsDisplay() } } } // MARK: Touch Handling Code override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { currentTouches.add(touch) } updateKeyStates() } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { updateKeyStates() } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { currentTouches.remove(touch) } updateKeyStates() } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { currentTouches.remove(touch) } updateKeyStates() } // MARK: Drawing Code override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let whiteKeyHeight = rect.size.height let blackKeyHeight = round(rect.size.height * 0.625) let whiteKeyWidth = rect.size.width/15.0 let blackKeyWidth = whiteKeyWidth * 0.8333333 let blackKeyOffset = blackKeyWidth/2.0 var runningX: CGFloat = 0 let yval = 0 context?.setFillColor(UIColor.white.cgColor) context?.fill(bounds) context?.setStrokeColor(UIColor.black.cgColor) context?.stroke(bounds) let lineHeight = whiteKeyHeight - 1 var newX = 0 for i in 0 ..< keysNum { if isWhiteKey(i) { newX = Int(round(runningX + 0.5)) if keyDown[i] { let newW = Int(round(runningX + whiteKeyWidth + 0.5) - CGFloat(newX)) context?.setFillColor(UIColor.blue.cgColor) context?.fill(CGRect(x: CGFloat(newX), y: CGFloat(yval), width: CGFloat(newW), height: whiteKeyHeight - 1)) } runningX += whiteKeyWidth context?.setStrokeColor(UIColor.black.cgColor) context?.stroke(CGRect(x: CGFloat(newX), y: CGFloat(yval), width: CGFloat(newX), height: lineHeight)) } } runningX = 0 for i in 0 ..< keysNum { if isWhiteKey(i) { runningX += whiteKeyWidth } else { if keyDown[i] { context?.setFillColor(UIColor.blue.cgColor) } else { context?.setFillColor(UIColor.black.cgColor) } context?.fill(CGRect(x: runningX - blackKeyOffset, y: CGFloat(yval), width: blackKeyWidth, height: blackKeyHeight)) context?.setStrokeColor(UIColor.black.cgColor) context?.stroke(CGRect(x: runningX - blackKeyOffset, y: CGFloat(yval), width: blackKeyWidth, height: blackKeyHeight)) } } } } // Protocol for delegate to conform to @objc protocol CsoundVirtualKeyboardDelegate { func keyUp(_ keybd:CsoundVirtualKeyboard, keyNum:Int) func keyDown(_ keybd:CsoundVirtualKeyboard, keyNum:Int) }
lgpl-2.1
972dcf42d82ba932e1ff69219bc6af4f
32.121849
138
0.562603
4.70908
false
false
false
false
strivingboy/CocoaChinaPlus
Code/CocoaChinaPlus/Application/Business/Util/Helper/CCURLHelper.swift
1
900
// // CCPTools.swift // CocoaChinaPlus // // Created by zixun on 15/8/22. // Copyright © 2015年 zixun. All rights reserved. // import Foundation class CCURLHelper: NSObject { class func generateIdentity(url: String) -> String { let target = url.lowercaseString; if (target.rangeOfString("wap") != nil) { //wap return url.componentsSeparatedByString("=").last! }else { //pc return url.componentsSeparatedByString("/").last!.componentsSeparatedByString(".").first! } } class func generateWapURL(identity:String) -> String { return "http://www.cocoachina.com/cms/wap.php?action=article&id=\(identity)" } class func generateWapURLFromURL(url:String) -> String { let identity = self.generateIdentity(url) return self.generateWapURL(identity) } }
mit
f19c6f7188dea1cf0438f36c88c56e0a
26.212121
101
0.61427
4.231132
false
false
false
false
sprint84/CalculatorKeyboard
Example/Example/ViewController.swift
2
1062
// // ViewController.swift // Example // // Created by Guilherme Moura on 8/17/15. // Copyright (c) 2015 Reefactor, Inc. All rights reserved. // import UIKit import CalculatorKeyboard class ViewController: UIViewController, CalculatorDelegate { @IBOutlet weak var inputTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 300) let keyboard = CalculatorKeyboard(frame: frame) keyboard.delegate = self keyboard.showDecimal = true inputTextField.inputView = keyboard } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) inputTextField.becomeFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - RFCalculatorKeyboard delegate func calculator(_ calculator: CalculatorKeyboard, didChangeValue value: String) { inputTextField.text = value } }
mit
89a5147b8d03b5bbab08b4648ab1310c
26.230769
86
0.6742
4.849315
false
false
false
false
KlubJagiellonski/pola-ios
BuyPolish/Pola/UI/ProductSearch/ScanCode/ScannerCodeView.swift
1
1402
import UIKit final class ScannerCodeView: UIView { var videoLayer: CALayer? { didSet { if let oldValue = oldValue { oldValue.removeFromSuperlayer() } guard let videoLayer = videoLayer else { return } videoLayer.frame = layer.bounds layer.insertSublayer(videoLayer, at: 0) } } let rectangleView = UIView() override init(frame: CGRect) { super.init(frame: frame) rectangleView.layer.borderWidth = 1 rectangleView.layer.borderColor = UIColor.white.cgColor rectangleView.accessibilityTraits = .notEnabled rectangleView.isAccessibilityElement = true rectangleView.accessibilityHint = R.string.localizable.accessibilityRectangleHint() addSubview(rectangleView) } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() var rect = rectangleView.frame rect.size.width = bounds.width / 1.4 rect.size.height = rect.size.width / 2.0 rect.origin.x = (bounds.width / 2) - (rect.width / 2) rect.origin.y = (bounds.height / 2) - rect.height rectangleView.frame = rect videoLayer?.frame = layer.bounds } }
gpl-2.0
83e729a2b89d7b48448acf074e1f176e
28.829787
91
0.61127
4.768707
false
false
false
false
KrishMunot/swift
test/SILGen/lifetime.swift
6
24997
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -parse-as-library -emit-silgen -primary-file %s | FileCheck %s struct Buh<T> { var x: Int { get {} set {} } } class Ref { init() { } } struct Val { } // CHECK-LABEL: sil hidden @_TF8lifetime13local_valtypeFT_T_ func local_valtype() { var b: Val // CHECK: [[B:%[0-9]+]] = alloc_box $Val // CHECK: release [[B]] // CHECK: return } // CHECK-LABEL: sil hidden @_TF8lifetime20local_valtype_branch func local_valtype_branch(_ a: Bool) { var a = a // CHECK: [[A:%[0-9]+]] = alloc_box $Bool if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: br [[EPILOG:bb[0-9]+]] var x:Int // CHECK: [[X:%[0-9]+]] = alloc_box $Int if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: release [[X]] // CHECK: br [[EPILOG]] while a { // CHECK: cond_br if a { break } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK-NOT: release [[X]] // CHECK: br if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: release [[X]] // CHECK: br [[EPILOG]] var y:Int // CHECK: [[Y:%[0-9]+]] = alloc_box $Int if a { break } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: release [[Y]] // CHECK-NOT: release [[X]] // CHECK-NOT: release [[A]] // CHECK: br if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: release [[Y]] // CHECK: release [[X]] // CHECK: br [[EPILOG]] if true { var z:Int // CHECK: [[Z:%[0-9]+]] = alloc_box $Int if a { break } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: release [[Z]] // CHECK: release [[Y]] // CHECK-NOT: release [[X]] // CHECK-NOT: release [[A]] // CHECK: br if a { return } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: release [[Z]] // CHECK: release [[Y]] // CHECK: release [[X]] // CHECK: br [[EPILOG]] // CHECK: release [[Z]] } if a { break } // CHECK: cond_br // CHECK: {{bb.*:}} // CHECK: release [[Y]] // CHECK-NOT: release [[X]] // CHECK-NOT: release [[A]] // CHECK: br // CHECK: {{bb.*:}} // CHECK: release [[Y]] // CHECK: br } // CHECK: release [[X]] // CHECK: [[EPILOG]]: // CHECK: return } func reftype_func() -> Ref {} func reftype_func_with_arg(_ x: Ref) -> Ref {} // CHECK-LABEL: sil hidden @_TF8lifetime14reftype_returnFT_CS_3Ref func reftype_return() -> Ref { return reftype_func() // CHECK: [[RF:%[0-9]+]] = function_ref @_TF8lifetime12reftype_funcFT_CS_3Ref : $@convention(thin) () -> @owned Ref // CHECK-NOT: release // CHECK: [[RET:%[0-9]+]] = apply [[RF]]() // CHECK-NOT: release // CHECK: return [[RET]] } // CHECK-LABEL: sil hidden @_TF8lifetime11reftype_arg func reftype_arg(_ a: Ref) { var a = a // CHECK: bb0([[A:%[0-9]+]] : $Ref): // CHECK: [[AADDR:%[0-9]+]] = alloc_box $Ref // CHECK: [[PA:%[0-9]+]] = project_box [[AADDR]] // CHECK: store [[A]] to [[PA]] // CHECK: release [[AADDR]] // CHECK: return } // CHECK-LABEL: sil hidden @_TF8lifetime17reftype_inout_arg func reftype_inout_arg(_ a: inout Ref) { // CHECK: bb0([[A:%[0-9]+]] : $*Ref): // -- initialize local box for inout // CHECK: [[A_LOCAL:%.*]] = alloc_box $Ref // CHECK: [[PB:%.*]] = project_box [[A_LOCAL]] // CHECK: copy_addr [[A]] to [initialization] [[PB]] // -- write back to inout // CHECK: copy_addr [[PB]] to [[A]] // CHECK: strong_release [[A_LOCAL]] // CHECK: return } // CHECK-LABEL: sil hidden @_TF8lifetime26reftype_call_ignore_returnFT_T_ func reftype_call_ignore_return() { reftype_func() // CHECK: = function_ref @_TF8lifetime12reftype_funcFT_CS_3Ref : $@convention(thin) () -> @owned Ref // CHECK-NEXT: [[R:%[0-9]+]] = apply // CHECK: release [[R]] // CHECK: return } // CHECK-LABEL: sil hidden @_TF8lifetime27reftype_call_store_to_localFT_T_ func reftype_call_store_to_local() { var a = reftype_func() // CHECK: [[A:%[0-9]+]] = alloc_box $Ref // CHECK-NEXT: [[PB:%.*]] = project_box [[A]] // CHECK: = function_ref @_TF8lifetime12reftype_funcFT_CS_3Ref : $@convention(thin) () -> @owned Ref // CHECK-NEXT: [[R:%[0-9]+]] = apply // CHECK-NOT: retain [[R]] // CHECK: store [[R]] to [[PB]] // CHECK-NOT: release [[R]] // CHECK: release [[A]] // CHECK-NOT: release [[R]] // CHECK: return } // CHECK-LABEL: sil hidden @_TF8lifetime16reftype_call_argFT_T_ func reftype_call_arg() { reftype_func_with_arg(reftype_func()) // CHECK: [[RFWA:%[0-9]+]] = function_ref @_TF8lifetime21reftype_func_with_arg // CHECK: [[RF:%[0-9]+]] = function_ref @_TF8lifetime12reftype_func // CHECK: [[R1:%[0-9]+]] = apply [[RF]] // CHECK: [[R2:%[0-9]+]] = apply [[RFWA]]([[R1]]) // CHECK: release [[R2]] // CHECK: return } // CHECK-LABEL: sil hidden @_TF8lifetime21reftype_call_with_arg func reftype_call_with_arg(_ a: Ref) { var a = a // CHECK: bb0([[A1:%[0-9]+]] : $Ref): // CHECK: [[AADDR:%[0-9]+]] = alloc_box $Ref // CHECK: [[PB:%.*]] = project_box [[AADDR]] // CHECK: store [[A1]] to [[PB]] reftype_func_with_arg(a) // CHECK: [[RFWA:%[0-9]+]] = function_ref @_TF8lifetime21reftype_func_with_arg // CHECK: [[A2:%[0-9]+]] = load [[PB]] // CHECK: retain [[A2]] // CHECK: = apply [[RFWA]]([[A2]]) // CHECK: return } // CHECK-LABEL: sil hidden @_TF8lifetime16reftype_reassign func reftype_reassign(_ a: inout Ref, b: Ref) { var b = b // CHECK: bb0([[AADDR:%[0-9]+]] : $*Ref, [[B1:%[0-9]+]] : $Ref): // CHECK: [[A_LOCAL:%[0-9]+]] = alloc_box $Ref // CHECK: [[PBA:%.*]] = project_box [[A_LOCAL]] // CHECK: copy_addr [[AADDR]] to [initialization] [[PBA]] // CHECK: [[BADDR:%[0-9]+]] = alloc_box $Ref // CHECK: [[PBB:%.*]] = project_box [[BADDR]] a = b // CHECK: copy_addr [[PBB]] to [[PBA]] // CHECK: release // CHECK: return } func tuple_with_ref_elements() -> (Val, (Ref, Val), Ref) {} // CHECK-LABEL: sil hidden @_TF8lifetime28tuple_with_ref_ignore_returnFT_T_ func tuple_with_ref_ignore_return() { tuple_with_ref_elements() // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF8lifetime23tuple_with_ref_elementsFT_TVS_3ValTCS_3RefS0__S1__ // CHECK: [[TUPLE:%[0-9]+]] = apply [[FUNC]] // CHECK: [[T0:%[0-9]+]] = tuple_extract [[TUPLE]] : {{.*}}, 0 // CHECK: [[T1_0:%[0-9]+]] = tuple_extract [[TUPLE]] : {{.*}}, 1 // CHECK: [[T1_1:%[0-9]+]] = tuple_extract [[TUPLE]] : {{.*}}, 2 // CHECK: [[T2:%[0-9]+]] = tuple_extract [[TUPLE]] : {{.*}}, 3 // CHECK: release [[T2]] // CHECK: release [[T1_0]] // CHECK: return } struct Aleph { var a:Ref var b:Val // -- loadable value constructor: // CHECK-LABEL: sil hidden @_TFV8lifetime5AlephC{{.*}} : $@convention(method) (@owned Ref, Val, @thin Aleph.Type) -> @owned Aleph // CHECK: bb0([[A:%.*]] : $Ref, [[B:%.*]] : $Val, {{%.*}} : $@thin Aleph.Type): // CHECK-NEXT: [[RET:%.*]] = struct $Aleph ([[A]] : {{.*}}, [[B]] : {{.*}}) // CHECK-NEXT: return [[RET]] } struct Beth { var a:Val var b:Aleph var c:Ref func gimel() {} } protocol Unloadable {} struct Daleth { var a:Aleph var b:Beth var c:Unloadable // -- address-only value constructor: // CHECK-LABEL: sil hidden @_TFV8lifetime6DalethC{{.*}} : $@convention(method) (@owned Aleph, @owned Beth, @in Unloadable, @thin Daleth.Type) -> @out Daleth { // CHECK: bb0([[THIS:%.*]] : $*Daleth, [[A:%.*]] : $Aleph, [[B:%.*]] : $Beth, [[C:%.*]] : $*Unloadable, {{%.*}} : $@thin Daleth.Type): // CHECK-NEXT: [[A_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.a // CHECK-NEXT: store [[A]] to [[A_ADDR]] // CHECK-NEXT: [[B_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.b // CHECK-NEXT: store [[B]] to [[B_ADDR]] // CHECK-NEXT: [[C_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.c // CHECK-NEXT: copy_addr [take] [[C]] to [initialization] [[C_ADDR]] // CHECK-NEXT: tuple () // CHECK-NEXT: return } class He { // -- default initializer: // CHECK-LABEL: sil hidden @_TFC8lifetime2Hec{{.*}} : $@convention(method) (@owned He) -> @owned He { // CHECK: bb0([[THIS:%.*]] : $He): // CHECK-NEXT: debug_value // CHECK-NEXT: mark_uninitialized // CHECK-NEXT: return // CHECK: } // -- default allocator: // CHECK-LABEL: sil hidden @_TFC8lifetime2HeC{{.*}} : $@convention(method) (@thick He.Type) -> @owned He { // CHECK: bb0({{%.*}} : $@thick He.Type): // CHECK-NEXT: [[THIS:%.*]] = alloc_ref $He // CHECK-NEXT: // function_ref lifetime.He.init // CHECK-NEXT: [[INIT:%.*]] = function_ref @_TFC8lifetime2Hec{{.*}} : $@convention(method) (@owned He) -> @owned He // CHECK-NEXT: [[THIS1:%.*]] = apply [[INIT]]([[THIS]]) // CHECK-NEXT: return [[THIS1]] // CHECK-NEXT: } init() { } } struct Waw { var a:(Ref, Val) var b:Val // -- loadable value initializer with tuple destructuring: // CHECK-LABEL: sil hidden @_TFV8lifetime3WawC{{.*}} : $@convention(method) (@owned Ref, Val, Val, @thin Waw.Type) -> @owned Waw // CHECK: bb0([[A0:%.*]] : $Ref, [[A1:%.*]] : $Val, [[B:%.*]] : $Val, {{%.*}} : $@thin Waw.Type): // CHECK-NEXT: [[A:%.*]] = tuple ([[A0]] : {{.*}}, [[A1]] : {{.*}}) // CHECK-NEXT: [[RET:%.*]] = struct $Waw ([[A]] : {{.*}}, [[B]] : {{.*}}) // CHECK-NEXT: return [[RET]] } struct Zayin { var a:(Unloadable, Val) var b:Unloadable // -- address-only value initializer with tuple destructuring: // CHECK-LABEL: sil hidden @_TFV8lifetime5ZayinC{{.*}} : $@convention(method) (@in Unloadable, Val, @in Unloadable, @thin Zayin.Type) -> @out Zayin // CHECK: bb0([[THIS:%.*]] : $*Zayin, [[A0:%.*]] : $*Unloadable, [[A1:%.*]] : $Val, [[B:%.*]] : $*Unloadable, {{%.*}} : $@thin Zayin.Type): // CHECK-NEXT: [[THIS_A_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Zayin, #Zayin.a // CHECK-NEXT: [[THIS_A0_ADDR:%.*]] = tuple_element_addr [[THIS_A_ADDR]] : {{.*}}, 0 // CHECK-NEXT: [[THIS_A1_ADDR:%.*]] = tuple_element_addr [[THIS_A_ADDR]] : {{.*}}, 1 // CHECK-NEXT: copy_addr [take] [[A0]] to [initialization] [[THIS_A0_ADDR]] // CHECK-NEXT: store [[A1]] to [[THIS_A1_ADDR]] // CHECK-NEXT: [[THIS_B_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Zayin, #Zayin.b // CHECK-NEXT: copy_addr [take] [[B]] to [initialization] [[THIS_B_ADDR]] // CHECK-NEXT: tuple () // CHECK-NEXT: return } func fragile_struct_with_ref_elements() -> Beth {} // CHECK-LABEL: sil hidden @_TF8lifetime29struct_with_ref_ignore_returnFT_T_ func struct_with_ref_ignore_return() { fragile_struct_with_ref_elements() // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF8lifetime32fragile_struct_with_ref_elementsFT_VS_4Beth // CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]] // CHECK: release_value [[STRUCT]] : $Beth // CHECK: return } // CHECK-LABEL: sil hidden @_TF8lifetime28struct_with_ref_materializedFT_T_ func struct_with_ref_materialized() { fragile_struct_with_ref_elements().gimel() // CHECK: [[METHOD:%[0-9]+]] = function_ref @_TFV8lifetime4Beth5gimel{{.*}} // CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF8lifetime32fragile_struct_with_ref_elementsFT_VS_4Beth // CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]] // CHECK: apply [[METHOD]]([[STRUCT]]) } class RefWithProp { var int_prop: Int { get {} set {} } var aleph_prop: Aleph { get {} set {} } } // CHECK-LABEL: sil hidden @_TF8lifetime23logical_lvalue_lifetimeFTCS_11RefWithPropSiVS_3Val_T_ : $@convention(thin) (@owned RefWithProp, Int, Val) -> () { func logical_lvalue_lifetime(_ r: RefWithProp, _ i: Int, _ v: Val) { var r = r var i = i var v = v // CHECK: [[RADDR:%[0-9]+]] = alloc_box $RefWithProp // CHECK: [[PR:%[0-9]+]] = project_box [[RADDR]] // CHECK: [[IADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[PI:%[0-9]+]] = project_box [[IADDR]] // CHECK: store %1 to [[PI]] // CHECK: [[VADDR:%[0-9]+]] = alloc_box $Val // CHECK: [[PV:%[0-9]+]] = project_box [[VADDR]] // -- Reference types need to be retained as property method args. r.int_prop = i // CHECK: [[R1:%[0-9]+]] = load [[PR]] // CHECK: strong_retain [[R1]] // CHECK: [[SETTER_METHOD:%[0-9]+]] = class_method {{.*}} : $RefWithProp, #RefWithProp.int_prop!setter.1 : (RefWithProp) -> (Int) -> () , $@convention(method) (Int, @guaranteed RefWithProp) -> () // CHECK: apply [[SETTER_METHOD]]({{.*}}, [[R1]]) // CHECK: strong_release [[R1]] r.aleph_prop.b = v // CHECK: [[R2:%[0-9]+]] = load [[PR]] // CHECK: strong_retain [[R2]] // CHECK: [[STORAGE:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[ALEPH_PROP_TEMP:%[0-9]+]] = alloc_stack $Aleph // CHECK: [[T0:%.*]] = address_to_pointer [[ALEPH_PROP_TEMP]] // CHECK: [[MATERIALIZE_METHOD:%[0-9]+]] = class_method {{.*}} : $RefWithProp, #RefWithProp.aleph_prop!materializeForSet.1 : // CHECK: [[MATERIALIZE:%.*]] = apply [[MATERIALIZE_METHOD]]([[T0]], [[STORAGE]], [[R2]]) // CHECK: [[PTR:%.*]] = tuple_extract [[MATERIALIZE]] : {{.*}}, 0 // CHECK: [[OPTCALLBACK:%.*]] = tuple_extract [[MATERIALIZE]] : {{.*}}, 1 // CHECK: [[ADDR:%.*]] = pointer_to_address [[PTR]] // CHECK: [[MARKED_ADDR:%.*]] = mark_dependence [[ADDR]] : $*Aleph on [[R2]] // CHECK: {{.*}}([[CALLBACK_ADDR:%.*]] : // CHECK: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]] : $Builtin.RawPointer to $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout RefWithProp, @thick RefWithProp.Type) -> () // CHECK: [[TEMP:%.*]] = alloc_stack $RefWithProp // CHECK: store [[R2]] to [[TEMP]] // CHECK: apply [[CALLBACK]]({{.*}}, [[STORAGE]], [[TEMP]], {{%.*}}) } func bar() -> Int {} class Foo<T> { var x : Int var y = (Int(), Ref()) var z : T var w = Ref() class func makeT() -> T {} // Class initializer init() { // -- initializing entry point // CHECK-LABEL: sil hidden @_TFC8lifetime3Fooc{{.*}} : // CHECK: bb0([[THISIN:%[0-9]+]] : $Foo<T>): // CHECK: [[THIS:%[0-9]+]] = mark_uninitialized // initialization for y // CHECK: [[INTCTOR:%[0-9]+]] = function_ref @_TFSiC{{.*}} : $@convention(method) (@thin Int.Type) -> Int // CHECK: [[INTMETA:%[0-9]+]] = metatype $@thin Int.Type // CHECK: [[INTVAL:%[0-9]+]] = apply [[INTCTOR]]([[INTMETA]]) x = bar() // CHECK: function_ref @_TF8lifetime3barFT_Si : $@convention(thin) () -> Int // CHECK: [[THIS_X:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.x // CHECK: assign {{.*}} to [[THIS_X]] z = Foo<T>.makeT() // CHECK: [[FOOMETA:%[0-9]+]] = metatype $@thick Foo<T>.Type // CHECK: [[MAKET:%[0-9]+]] = class_method [[FOOMETA]] : {{.*}}, #Foo.makeT!1 // CHECK: ref_element_addr // -- cleanup this lvalue and return this // CHECK: return [[THIS]] // -- allocating entry point // CHECK-LABEL: sil hidden @_TFC8lifetime3FooC{{.*}} : // CHECK: bb0([[METATYPE:%[0-9]+]] : $@thick Foo<T>.Type): // CHECK: [[THIS:%[0-9]+]] = alloc_ref $Foo<T> // CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @_TFC8lifetime3Fooc{{.*}} // CHECK: [[INIT_THIS:%[0-9]+]] = apply [[INIT_METHOD]]<{{.*}}>([[THIS]]) // CHECK: return [[INIT_THIS]] } init(chi:Int) { var chi = chi z = Foo<T>.makeT() // -- initializing entry point // CHECK-LABEL: sil hidden @_TFC8lifetime3FoocfT3chiSi_GS0_x_ // CHECK: bb0([[CHI:%[0-9]+]] : $Int, [[THISIN:%[0-9]+]] : $Foo<T>): // CHECK: [[THIS:%[0-9]+]] = mark_uninitialized // CHECK: [[CHIADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[PCHI:%[0-9]+]] = project_box [[CHIADDR]] // CHECK: store [[CHI]] to [[PCHI]] // CHECK: ref_element_addr {{.*}}, #Foo.z x = chi // CHECK: [[THIS_X:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.x // CHECK: copy_addr [[PCHI]] to [[THIS_X]] // -- cleanup chi // CHECK: release [[CHIADDR]] // CHECK: return [[THIS]] // -- allocating entry point // CHECK-LABEL: sil hidden @_TFC8lifetime3FooC{{.*}} : // CHECK: bb0([[CHI:%[0-9]+]] : $Int, [[METATYPE:%[0-9]+]] : $@thick Foo<T>.Type): // CHECK: [[THIS:%[0-9]+]] = alloc_ref $Foo<T> // CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @_TFC8lifetime3Fooc{{.*}} // CHECK: [[INIT_THIS:%[0-9]+]] = apply [[INIT_METHOD]]<{{.*}}>([[CHI]], [[THIS]]) // CHECK: return [[INIT_THIS]] } // -- initializing entry point // CHECK-LABEL: sil hidden @_TFC8lifetime3Fooc{{.*}} : // -- allocating entry point // CHECK-LABEL: sil hidden @_TFC8lifetime3FooC{{.*}} : // CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @_TFC8lifetime3Fooc{{.*}} init<U:Intifiable>(chi:U) { z = Foo<T>.makeT() x = chi.intify() } // Deallocating destructor for Foo. // CHECK-LABEL: sil hidden @_TFC8lifetime3FooD : $@convention(method) <T> (@owned Foo<T>) -> () // CHECK: bb0([[SELF:%[0-9]+]] : $Foo<T>): // CHECK: [[DESTROYING_REF:%[0-9]+]] = function_ref @_TFC8lifetime3Food : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject // CHECK-NEXT: [[RESULT_SELF:%[0-9]+]] = apply [[DESTROYING_REF]]<T>([[SELF]]) : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject // CHECK-NEXT: [[SELF:%[0-9]+]] = unchecked_ref_cast [[RESULT_SELF]] : $Builtin.NativeObject to $Foo<T> // CHECK-NEXT: dealloc_ref [[SELF]] : $Foo<T> // CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-LABEL: sil hidden @_TFC8lifetime3Food : $@convention(method) <T> (@guaranteed Foo<T>) -> @owned Builtin.NativeObject deinit { // CHECK: bb0([[THIS:%[0-9]+]] : $Foo<T>): bar() // CHECK: function_ref @_TF8lifetime3barFT_Si // CHECK: apply // CHECK: [[PTR:%.*]] = unchecked_ref_cast [[THIS]] : ${{.*}} to $Builtin.NativeObject // -- don't need to release x because it's trivial // CHECK-NOT: ref_element_addr [[THIS]] : {{.*}}, #Foo.x // -- release y // CHECK: [[YADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.y // CHECK: destroy_addr [[YADDR]] // -- release z // CHECK: [[ZADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.z // CHECK: destroy_addr [[ZADDR]] // -- release w // CHECK: [[WADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.w // CHECK: destroy_addr [[WADDR]] // -- return back this // CHECK: return [[PTR]] } } class ImplicitDtor { var x:Int var y:(Int, Ref) var w:Ref init() { } // CHECK-LABEL: sil hidden @_TFC8lifetime12ImplicitDtord // CHECK: bb0([[THIS:%[0-9]+]] : $ImplicitDtor): // -- don't need to release x because it's trivial // CHECK-NOT: ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.x // -- release y // CHECK: [[YADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.y // CHECK: destroy_addr [[YADDR]] // -- release w // CHECK: [[WADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.w // CHECK: destroy_addr [[WADDR]] // CHECK: return } class ImplicitDtorDerived<T> : ImplicitDtor { var z:T init(z : T) { super.init() self.z = z } // CHECK: bb0([[THIS:%[0-9]+]] : $ImplicitDtorDerived<T>): // -- base dtor // CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $ImplicitDtor // CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @_TFC8lifetime12ImplicitDtord // CHECK: apply [[BASE_DTOR]]([[BASE]]) // -- release z // CHECK: [[ZADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtorDerived.z // CHECK: destroy_addr [[ZADDR]] } class ImplicitDtorDerivedFromGeneric<T> : ImplicitDtorDerived<Int> { init() { super.init(z: 5) } // CHECK-LABEL: sil hidden @_TFC8lifetime30ImplicitDtorDerivedFromGenericc{{.*}} // CHECK: bb0([[THIS:%[0-9]+]] : $ImplicitDtorDerivedFromGeneric<T>): // -- base dtor // CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $ImplicitDtorDerived<Int> // CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @_TFC8lifetime19ImplicitDtorDerivedd // CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]<Int>([[BASE]]) // CHECK: return [[PTR]] } protocol Intifiable { func intify() -> Int } struct Bar { var x:Int // Loadable struct initializer // CHECK-LABEL: sil hidden @_TFV8lifetime3BarC{{.*}} init() { // CHECK: bb0([[METATYPE:%[0-9]+]] : $@thin Bar.Type): // CHECK: [[THISADDRBOX:%[0-9]+]] = alloc_box $Bar // CHECK: [[PB:%.*]] = project_box [[THISADDRBOX]] // CHECK: [[THISADDR:%[0-9]+]] = mark_uninitialized [rootself] [[PB]] x = bar() // CHECK: [[THIS_X:%[0-9]+]] = struct_element_addr [[THISADDR]] : $*Bar, #Bar.x // CHECK: assign {{.*}} to [[THIS_X]] // -- load and return this // CHECK: [[THISVAL:%[0-9]+]] = load [[THISADDR]] // CHECK: release [[THISADDRBOX]] // CHECK: return [[THISVAL]] } init<T:Intifiable>(xx:T) { x = xx.intify() } } struct Bas<T> { var x:Int var y:T // Address-only struct initializer // CHECK-LABEL: sil hidden @_TFV8lifetime3BasC{{.*}} init(yy:T) { // CHECK: bb0([[THISADDRPTR:%[0-9]+]] : $*Bas<T>, [[YYADDR:%[0-9]+]] : $*T, [[META:%[0-9]+]] : $@thin Bas<T>.Type): // CHECK: alloc_box // CHECK: [[THISADDRBOX:%[0-9]+]] = alloc_box $Bas // CHECK: [[PB:%.*]] = project_box [[THISADDRBOX]] // CHECK: [[THISADDR:%[0-9]+]] = mark_uninitialized [rootself] [[PB]] x = bar() // CHECK: [[THIS_X:%[0-9]+]] = struct_element_addr [[THISADDR]] : $*Bas<T>, #Bas.x // CHECK: assign {{.*}} to [[THIS_X]] y = yy // CHECK: [[THIS_Y:%[0-9]+]] = struct_element_addr [[THISADDR]] : $*Bas<T>, #Bas.y // CHECK: copy_addr {{.*}} to [[THIS_Y]] // CHECK: release // -- 'self' was emplaced into indirect return slot // CHECK: return } init<U:Intifiable>(xx:U, yy:T) { x = xx.intify() y = yy } } class B { init(y:Int) {} } class D : B { // CHECK-LABEL: sil hidden @_TFC8lifetime1DcfT1xSi1ySi_S0_ // CHECK: bb0([[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Int, [[THIS:%[0-9]+]] : $D): init(x: Int, y: Int) { var x = x var y = y // CHECK: [[THISADDR1:%[0-9]+]] = alloc_box $D // CHECK: [[PTHIS:%[0-9]+]] = project_box [[THISADDR1]] // CHECK: [[THISADDR:%[0-9]+]] = mark_uninitialized [derivedself] [[PTHIS]] // CHECK: store [[THIS]] to [[THISADDR]] // CHECK: [[XADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[PX:%[0-9]+]] = project_box [[XADDR]] // CHECK: store [[X]] to [[PX]] // CHECK: [[YADDR:%[0-9]+]] = alloc_box $Int // CHECK: [[PY:%[0-9]+]] = project_box [[YADDR]] // CHECK: store [[Y]] to [[PY]] super.init(y: y) // CHECK: [[THIS1:%[0-9]+]] = load [[THISADDR]] // CHECK: [[THIS1_SUP:%[0-9]+]] = upcast [[THIS1]] : ${{.*}} to $B // CHECK: [[SUPER_CTOR:%[0-9]+]] = function_ref @_TFC8lifetime1BcfT1ySi_S0_ : $@convention(method) (Int, @owned B) -> @owned B // CHECK: [[Y:%[0-9]+]] = load [[PY]] // CHECK: [[THIS2_SUP:%[0-9]+]] = apply [[SUPER_CTOR]]([[Y]], [[THIS1_SUP]]) // CHECK: [[THIS2:%[0-9]+]] = unchecked_ref_cast [[THIS2_SUP]] : $B to $D // CHECK: [[THIS1:%[0-9]+]] = load [[THISADDR]] // CHECK: release } func foo() {} } // CHECK-LABEL: sil hidden @_TF8lifetime8downcast func downcast(_ b: B) { var b = b // CHECK: [[BADDR:%[0-9]+]] = alloc_box $B // CHECK: [[PB:%[0-9]+]] = project_box [[BADDR]] (b as! D).foo() // CHECK: [[B:%[0-9]+]] = load [[PB]] // CHECK: retain [[B]] // CHECK: [[D:%[0-9]+]] = unconditional_checked_cast [[B]] : {{.*}} to $D // CHECK: apply {{.*}}([[D]]) // CHECK-NOT: release [[B]] // CHECK: release [[D]] // CHECK: release [[BADDR]] // CHECK: return } func int(_ x: Int) {} func ref(_ x: Ref) {} func tuple() -> (Int, Ref) { return (1, Ref()) } func tuple_explosion() { int(tuple().0) // CHECK: [[F:%[0-9]+]] = function_ref @_TF8lifetime5tupleFT_TSiCS_3Ref_ // CHECK: [[TUPLE:%[0-9]+]] = apply [[F]]() // CHECK: [[T1:%[0-9]+]] = tuple_extract [[TUPLE]] : {{.*}}, 1 // CHECK: release [[T1]] // CHECK-NOT: tuple_extract [[TUPLE]] : {{.*}}, 1 // CHECK-NOT: release ref(tuple().1) // CHECK: [[F:%[0-9]+]] = function_ref @_TF8lifetime5tupleFT_TSiCS_3Ref_ // CHECK: [[TUPLE:%[0-9]+]] = apply [[F]]() // CHECK: [[T1:%[0-9]+]] = tuple_extract [[TUPLE]] : {{.*}}, 1 // CHECK-NOT: release [[T1]] // CHECK-NOT: tuple_extract [[TUPLE]] : {{.*}}, 1 // CHECK-NOT: release } class C { var v = "" // CHECK-LABEL: sil hidden @_TFC8lifetime1C18ignored_assignment{{.*}} func ignored_assignment() { // CHECK: [[STRING:%.*]] = alloc_stack $String // CHECK: [[UNINIT:%.*]] = mark_uninitialized [var] [[STRING]] // CHECK: assign {{%.*}} to [[UNINIT]] // CHECK: destroy_addr [[UNINIT]] _ = self.v } }
apache-2.0
e3c43a225e3056f8991870021f586c79
34.350778
223
0.53575
3.077198
false
false
false
false
tkremenek/swift
test/attr/warn_unqualified_access.swift
53
3516
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module-path %t/Other1.swiftmodule -module-name Other1 %S/Inputs/warn_unqualified_access_other.swift // RUN: %target-swift-frontend -emit-module-path %t/Other2.swiftmodule -module-name Other2 %S/Inputs/warn_unqualified_access_other.swift // RUN: %target-swift-frontend -I %t -typecheck %s -verify import Other1 import Other2 @warn_unqualified_access // expected-error {{@warn_unqualified_access may only be used on 'func' declarations}} {{1-26=}} var x: Int { return 0 } @warn_unqualified_access // expected-error {{@warn_unqualified_access may only be used on 'func' declarations}} {{1-26=}} struct X {} @warn_unqualified_access // expected-error {{only methods can be declared @warn_unqualified_access}} {{1-26=}} func topLevel() { } class Base { @warn_unqualified_access func a() {} // expected-note * {{declared here}} @warn_unqualified_access func toBeOverridden() {} // no-warning } extension Base { @warn_unqualified_access func b() {} // expected-note * {{declared here}} } class Sub : Base { @warn_unqualified_access func c() {} // expected-note * {{declared here}} override func toBeOverridden() {} func test() { a() // expected-warning {{use of 'a' treated as a reference to instance method in class 'Base'}} expected-note{{use 'self.' to silence this warning}} {{5-5=self.}} self.a() b() // expected-warning {{use of 'b' treated as a reference to instance method in class 'Base'}} expected-note{{use 'self.' to silence this warning}} {{5-5=self.}} self.b() c() // expected-warning {{use of 'c' treated as a reference to instance method in class 'Sub'}} expected-note{{use 'self.' to silence this warning}} {{5-5=self.}} self.c() toBeOverridden() // no-warning } func testWithoutCalling() { _ = a // expected-warning {{use of 'a' treated as a reference to instance method in class 'Base'}} expected-note{{use 'self.' to silence this warning}} {{9-9=self.}} _ = b // expected-warning {{use of 'b' treated as a reference to instance method in class 'Base'}} expected-note{{use 'self.' to silence this warning}} {{9-9=self.}} _ = c // expected-warning {{use of 'c' treated as a reference to instance method in class 'Sub'}} expected-note{{use 'self.' to silence this warning}} {{9-9=self.}} } } func test(_ sub: Sub) { sub.a() sub.b() sub.c() @warn_unqualified_access // expected-error {{only methods can be declared @warn_unqualified_access}} {{3-28=}} func inner() { } inner() } class Recovery { @warn_unqualified_access func topLevel() {} // expected-note * {{declared here}} @warn_unqualified_access func overloaded(_ x: Float) {} // expected-note * {{declared here}} func test() { topLevel() // expected-warning {{use of 'topLevel' treated as a reference to instance method in class 'Recovery'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'warn_unqualified_access.' to reference the global function}} {{5-5=warn_unqualified_access.}} overloaded(5) // expected-warning {{use of 'overloaded' treated as a reference to instance method in class 'Recovery'}} // expected-note@-1 {{use 'self.' to silence this warning}} {{5-5=self.}} // expected-note@-2 {{use 'Other1.' to reference the global function in module 'Other1'}} {{5-5=Other1.}} // expected-note@-3 {{use 'Other2.' to reference the global function in module 'Other2'}} {{5-5=Other2.}} } }
apache-2.0
435c524b5f008a2df023b53466c23a24
41.361446
169
0.670933
3.565923
false
false
false
false
mcrollin/safecaster
safecaster/SCRMonthlyMeasurementsCount.swift
1
2497
// // SCRMonthlyMeasurementsCount.swift // safecaster // // Created by Marc Rollin on 4/10/15. // Copyright (c) 2015 safecast. All rights reserved. // import Foundation class SCRMonthlyMeasurementsCount: NSObject { private(set) var month:String = "" private(set) var count:Int = 0 override var description: String { return "\(month): \(count)" } convenience required init(month: String, count: Int) { self.init() self.month = month self.count = count } } extension SCRMonthlyMeasurementsCount { private class func monthlyMeasurementsCount(date: NSDate) -> Int { let calendar = NSCalendar.currentCalendar() let startComponents = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: date) startComponents.day = 1 let start: NSDate = calendar.dateFromComponents(startComponents)! let endComponents = calendar.components(NSCalendarUnit.Month, fromDate: date) endComponents.month = 1 let end: NSDate = calendar.dateByAddingComponents(endComponents, toDate: start, options: [])! let predicate = NSPredicate(format: "(createdAt > %@) AND (createdAt <= %@) AND (approved = 1)", start, end) return SCRImport.aggregateOperation("sum:", attribute: "measurementCount", predicate: predicate, context: SCRImport.context()) ?? 0 } class func monthlyMeasurementsCounts() -> [SCRMonthlyMeasurementsCount] { let calendar = NSCalendar.currentCalendar() let startComponents = calendar.components([NSCalendarUnit.Year, NSCalendarUnit.Month], fromDate: NSDate()) startComponents.day = 1 let start: NSDate = calendar.dateFromComponents(startComponents)! let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MMM" var counts: [SCRMonthlyMeasurementsCount] = [] for month in 0..<12 { let date = calendar.dateByAddingUnit(NSCalendarUnit.Month, value: -month, toDate: start, options:[])! let month = dateFormatter.stringFromDate(date) let count = monthlyMeasurementsCount(date) counts.append(SCRMonthlyMeasurementsCount(month: month, count: count)) } return counts.reverse() } }
cc0-1.0
da194f1c58574cff6d60e7d991738ba0
36.283582
139
0.61674
4.984032
false
false
false
false
tkremenek/swift
test/refactoring/ConvertAsync/labeled_closure_params.swift
1
4110
// RUN: %empty-directory(%t) // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MULTIPLE-LABELED-RESULTS %s func mutlipleLabeledResults(completion: (_ first: String, _ second: String) -> Void) { } // MULTIPLE-LABELED-RESULTS: { // MULTIPLE-LABELED-RESULTS-NEXT: Task { // MULTIPLE-LABELED-RESULTS-NEXT: let result = await mutlipleLabeledResults() // MULTIPLE-LABELED-RESULTS-NEXT: completion(result.first, result.second) // MULTIPLE-LABELED-RESULTS-NEXT: } // MULTIPLE-LABELED-RESULTS-NEXT: } // MULTIPLE-LABELED-RESULTS: func mutlipleLabeledResults() async -> (first: String, second: String) { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MIXED-LABELED-RESULTS %s func mixedLabeledResult(completion: (_ first: String, String) -> Void) { } // MIXED-LABELED-RESULTS: { // MIXED-LABELED-RESULTS-NEXT: Task { // MIXED-LABELED-RESULTS-NEXT: let result = await mixedLabeledResult() // MIXED-LABELED-RESULTS-NEXT: completion(result.first, result.1) // MIXED-LABELED-RESULTS-NEXT: } // MIXED-LABELED-RESULTS-NEXT: } // MIXED-LABELED-RESULTS: func mixedLabeledResult() async -> (first: String, String) { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=SINGLE-LABELED-RESULT %s func singleLabeledResult(completion: (_ first: String) -> Void) { } // SINGLE-LABELED-RESULT: { // SINGLE-LABELED-RESULT-NEXT: Task { // SINGLE-LABELED-RESULT-NEXT: let result = await singleLabeledResult() // SINGLE-LABELED-RESULT-NEXT: completion(result) // SINGLE-LABELED-RESULT-NEXT: } // SINGLE-LABELED-RESULT-NEXT: } // SINGLE-LABELED-RESULT: func singleLabeledResult() async -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=SINGLE-LABELED-RESULT-WITH-ERROR %s func singleLabeledResultWithError(completion: (_ first: String?, _ error: Error?) -> Void) { } // SINGLE-LABELED-RESULT-WITH-ERROR: { // SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: Task { // SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: do { // SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: let result = try await singleLabeledResultWithError() // SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: completion(result, nil) // SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: } catch { // SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: completion(nil, error) // SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: } // SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: } // SINGLE-LABELED-RESULT-WITH-ERROR-NEXT: } // SINGLE-LABELED-RESULT-WITH-ERROR: func singleLabeledResultWithError() async throws -> String { } // RUN: %refactor-check-compiles -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MULTIPLE-LABELED-RESULT-WITH-ERROR %s func multipleLabeledResultWithError(completion: (_ first: String?, _ second: String?, _ error: Error?) -> Void) { } // MULTIPLE-LABELED-RESULT-WITH-ERROR: { // MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: Task { // MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: do { // MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: let result = try await multipleLabeledResultWithError() // MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: completion(result.first, result.second, nil) // MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: } catch { // MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: completion(nil, nil, error) // MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: } // MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: } // MULTIPLE-LABELED-RESULT-WITH-ERROR-NEXT: } // MULTIPLE-LABELED-RESULT-WITH-ERROR: func multipleLabeledResultWithError() async throws -> (first: String, second: String) { } func testConvertCall() { // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 | %FileCheck -check-prefix=CONVERT-CALL %s mutlipleLabeledResults() { (a, b) in print(a) print(b) } // CONVERT-CALL: let (a, b) = await mutlipleLabeledResults() // CONVERT-CALL-NEXT: print(a) // CONVERT-CALL-NEXT: print(b) }
apache-2.0
2d40a66eeec69536b2b5a224183f96f3
57.714286
168
0.732603
3.218481
false
false
false
false
programersun/HiChongSwift
HiChongSwift/FindViewController.swift
1
7889
// // FindViewController.swift // HiChongSwift // // Created by eagle on 14/12/16. // Copyright (c) 2014年 Duostec. All rights reserved. // import UIKit class FindViewController: UITableViewController { private let sectionHeaderHeight = CGFloat(24.0) private var remindInfo: TwitterRemindInfoMsg? { didSet { tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic) if let info = remindInfo { if info.headImage != nil { //navigationController?.tabBarItem.badgeValue = "1" navigationController?.tabBarItem.selectedImage = UIImage(named: "0000Red") navigationController?.tabBarItem.image = UIImage(named: "0000DRed") } else { navigationController?.tabBarItem.badgeValue = nil } } else { navigationController?.tabBarItem.badgeValue = nil } } } override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() self.tableView.hideExtraSeprator() let placeHolder = UIView(frame: CGRect(origin: CGPointZero, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 14.0))) self.tableView.tableHeaderView = placeHolder self.tableView.backgroundColor = UIColor.LCYThemeColor() self.title = "发现" NSNotificationCenter.defaultCenter().addObserver(self, selector: "checkUpdate", name: UIApplicationDidBecomeActiveNotification, object: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func clearBadge() { remindInfo = nil tableView.reloadData() navigationController?.tabBarItem.badgeValue = nil navigationController?.tabBarItem.selectedImage = UIImage(named: "find") navigationController?.tabBarItem.image = UIImage(named: "find") } func checkUpdate() { if LCYCommon.sharedInstance.needToUpdateTwitter { // 需要更新信息 LCYCommon.sharedInstance.needToUpdateTwitter = false let parameter = [ "lasttime": LCYCommon.sharedInstance.lastTime, "user_id": LCYCommon.sharedInstance.userName! ] LCYNetworking.sharedInstance.POST(LCYApi.TwitterRemindInfo, parameters: parameter, success: { [weak self](object) -> Void in let base = TwitterRemindInfoBase.modelObjectWithDictionary(object as [NSObject : AnyObject]) if base.result { self?.remindInfo = base.msg // if(self?.remindInfo != nil) // { // self?.navigationController?.tabBarItem.badgeValue = "\(self?.remindInfo!.comment.count + self?.remindInfo!.star.count!)" // } } return }, failure: { (error) -> Void in return }) } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // Return the number of sections. return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. switch section { case 0: return 4 case 1: return 1 default: return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(FindViewCell.identifier, forIndexPath: indexPath) as! FindViewCell // cell.textLabel?.textColor = UIColor.LCYThemeDarkText() cell.icyImagePath = nil cell.badgeNumber = nil switch indexPath.section { case 0: switch indexPath.row { case 0: cell.icyLabel.text = "宠物圈" cell.backgroundColor = UIColor.whiteColor() cell.imageView?.image = UIImage(named: "findCircle") if let remindInfo = remindInfo { if remindInfo.headImage != nil { cell.icyImagePath = remindInfo.headImage.toAbsolutePath() } cell.badgeNumber = remindInfo.comment.count + remindInfo.star.count } case 1: cell.icyLabel.text = "附近" cell.backgroundColor = UIColor.LCYTableLightBlue() cell.imageView?.image = UIImage(named: "findNearby") case 2: cell.icyLabel.text = "宠友动态" cell.backgroundColor = UIColor.whiteColor() cell.imageView?.image = UIImage(named: "findFriends") case 3: cell.icyLabel.text = "搜索" cell.backgroundColor = UIColor.LCYTableLightBlue() cell.imageView?.image = UIImage(named: "findSearch") default: break } case 1: cell.icyLabel.text = "宠友录" cell.backgroundColor = UIColor.LCYTableLightBlue() cell.imageView?.image = UIImage(named: "findContact") break default: break } return cell } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { switch section { case 1: return sectionHeaderHeight default: return 0.0 } } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { switch section { case 1: return UIView(frame: CGRect(origin: CGPointZero, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: sectionHeaderHeight))) default: return nil } } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.section { case 0: switch indexPath.row { case 0: self.performSegueWithIdentifier("showCircle", sender: nil) case 1: self.performSegueWithIdentifier("showSearchResult", sender: nil) case 2: self.performSegueWithIdentifier("showSearchResult", sender: true) case 3: self.performSegueWithIdentifier("showSearch", sender: nil) default: break } case 1: self.performSegueWithIdentifier("showCatalog", sender: nil) default: break } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { switch identifier { case "showSearchResult": let destination = segue.destinationViewController as! FindSearchResultViewController if let sender = sender as? Bool { destination.forFriend = sender } case "showCircle": clearBadge() default: break } } } }
apache-2.0
7f4b4b3e2aec5c1faf0f7e29ac04393a
35.821596
148
0.57733
5.519353
false
false
false
false
DrabWeb/Sudachi
Sudachi/Sudachi/SCMusicBrowserCollectionViewItem.swift
1
1556
// // SCMusicBrowserCollectionViewItem.swift // Sudachi // // Created by Seth on 2016-04-07. // import Cocoa class SCMusicBrowserCollectionViewItem: NSCollectionViewItem { /// The object to perform openAction var openTarget : AnyObject? = nil; /// The selector to call when this item is opened(When called it also passes this item's SCMusicBrowserItem) var openAction : Selector? = nil; override func mouseDown(theEvent: NSEvent) { super.mouseDown(theEvent); // If we double clicked... if(theEvent.clickCount == 2) { // Open this item open(); } } /// Opens this item func open() { // If the target and action are set... if(openTarget != nil && openAction != nil) { // Perform the open action openTarget!.performSelector(openAction!, withObject: self.representedObject as! SCMusicBrowserItem); } } override func viewDidLoad() { super.viewDidLoad() // Do view setup here. // Load the theme loadTheme(); } /// Loads in the theme variables from SCThemingEngine func loadTheme() { // Set the label colors self.textField?.textColor = SCThemingEngine().defaultEngine().musicBrowserItemTextColor; // Set the fonts self.textField?.font = SCThemingEngine().defaultEngine().setFontFamily((self.textField?.font!)!, size: SCThemingEngine().defaultEngine().musicBrowserItemTitleFontSize); } }
gpl-3.0
ee50b0246446b176f4ed3278da6b1afc
28.923077
176
0.617609
4.787692
false
false
false
false
glbuyer/GbKit
GbKit/Models/GBAddress.swift
1
1567
// // Address.swift // glbuyer-ios // // Created by GuYe on 16/10/24. // Copyright © 2016年 glbuyer. All rights reserved. // import Foundation import ObjectMapper class GBAddress:GBBaseModel { //地点编号 var addressId:String = UUID().uuidString //用户ID var userId:String = "" //国家 var country:String = "中国" //省 var stateProvince:String = "" //市 var city:String = "" //区 var district:String = "" //详细地址 var address:String = "" //邮政编码 var zipcode:String = "" //电话 var tel:String = "" //手机 var mobile:String = "" //收货人 var receviverName:String = "" //最佳送货时间 var bestTime:String = "" //收货人身份信息 var idInfo = GBIdInfo() //是否为默认地址 var setAsDefault = false //地址展示 var addressDisplay = "" // Mappable override func mapping(map: Map) { super.mapping(map: map) addressId <- map["address_id"] userId <- map["user_id"] country <- map["country"] stateProvince <- map["state_province"] city <- map["city"] district <- map["district"] address <- map["address"] zipcode <- map["zipcode"] tel <- map["tel"] mobile <- map["mobile"] receviverName <- map["receiver_name"] bestTime <- map["best_time"] idInfo <- map["id_info"] setAsDefault <- map["is_set_as_default"] } }
mit
ea3eb86d7fb944c249a967b31546ae61
18.466667
51
0.529452
3.72449
false
false
false
false
yanyuqingshi/ios-charts
Charts/Classes/Renderers/RadarChartRenderer.swift
1
9604
// // RadarChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics.CGBase import UIKit.UIFont public class RadarChartRenderer: ChartDataRendererBase { internal weak var _chart: RadarChartView!; public init(chart: RadarChartView, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler); _chart = chart; } public override func drawData(#context: CGContext) { if (_chart !== nil) { var radarData = _chart.data; if (radarData != nil) { for set in radarData!.dataSets as! [RadarChartDataSet] { if (set.isVisible) { drawDataSet(context: context, dataSet: set); } } } } } internal func drawDataSet(#context: CGContext, dataSet: RadarChartDataSet) { CGContextSaveGState(context); var sliceangle = _chart.sliceAngle; // calculate the factor that is needed for transforming the value to pixels var factor = _chart.factor; var center = _chart.centerOffsets; var entries = dataSet.yVals; var path = CGPathCreateMutable(); for (var j = 0; j < entries.count; j++) { var e = entries[j]; var p = ChartUtils.getPosition(center: center, dist: CGFloat(e.value - _chart.chartYMin) * factor, angle: sliceangle * CGFloat(j) + _chart.rotationAngle); if (j == 0) { CGPathMoveToPoint(path, nil, p.x, p.y); } else { CGPathAddLineToPoint(path, nil, p.x, p.y); } } CGPathCloseSubpath(path); // draw filled if (dataSet.isDrawFilledEnabled) { CGContextSetFillColorWithColor(context, dataSet.colorAt(0).CGColor); CGContextSetAlpha(context, dataSet.fillAlpha); CGContextBeginPath(context); CGContextAddPath(context, path); CGContextFillPath(context); } // draw the line (only if filled is disabled or alpha is below 255) if (!dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0) { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(0).CGColor) CGContextSetLineWidth(context, dataSet.lineWidth); CGContextSetAlpha(context, 1.0); CGContextBeginPath(context); CGContextAddPath(context, path); CGContextStrokePath(context); } CGContextRestoreGState(context); } public override func drawValues(#context: CGContext) { if (_chart.data === nil) { return; } var data = _chart.data!; var defaultValueFormatter = _chart.valueFormatter; var sliceangle = _chart.sliceAngle; // calculate the factor that is needed for transforming the value to pixels var factor = _chart.factor; var center = _chart.centerOffsets; var yoffset = CGFloat(5.0); for (var i = 0, count = data.dataSetCount; i < count; i++) { var dataSet = data.getDataSetByIndex(i) as! RadarChartDataSet; if (!dataSet.isDrawValuesEnabled) { continue; } var entries = dataSet.yVals; for (var j = 0; j < entries.count; j++) { var e = entries[j]; var p = ChartUtils.getPosition(center: center, dist: CGFloat(e.value) * factor, angle: sliceangle * CGFloat(j) + _chart.rotationAngle); var valueFont = dataSet.valueFont; var valueTextColor = dataSet.valueTextColor; var formatter = dataSet.valueFormatter; if (formatter === nil) { formatter = defaultValueFormatter; } ChartUtils.drawText(context: context, text: formatter!.stringFromNumber(e.value)!, point: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]); } } } public override func drawExtras(#context: CGContext) { drawWeb(context: context); } private var _webLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); internal func drawWeb(#context: CGContext) { var sliceangle = _chart.sliceAngle; CGContextSaveGState(context); // calculate the factor that is needed for transforming the value to // pixels var factor = _chart.factor; var rotationangle = _chart.rotationAngle; var center = _chart.centerOffsets; // draw the web lines that come from the center CGContextSetLineWidth(context, _chart.webLineWidth); CGContextSetStrokeColorWithColor(context, _chart.webColor.CGColor); CGContextSetAlpha(context, _chart.webAlpha); for (var i = 0, xValCount = _chart.data!.xValCount; i < xValCount; i++) { var p = ChartUtils.getPosition(center: center, dist: CGFloat(_chart.yRange) * factor, angle: sliceangle * CGFloat(i) + rotationangle); _webLineSegmentsBuffer[0].x = center.x; _webLineSegmentsBuffer[0].y = center.y; _webLineSegmentsBuffer[1].x = p.x; _webLineSegmentsBuffer[1].y = p.y; CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2); } // draw the inner-web CGContextSetLineWidth(context, _chart.innerWebLineWidth); CGContextSetStrokeColorWithColor(context, _chart.innerWebColor.CGColor); CGContextSetAlpha(context, _chart.webAlpha); var labelCount = _chart.yAxis.entryCount; for (var j = 0; j < labelCount; j++) { for (var i = 0, xValCount = _chart.data!.xValCount; i < xValCount; i++) { var r = CGFloat(_chart.yAxis.entries[j] - _chart.chartYMin) * factor; var p1 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i) + rotationangle); var p2 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i + 1) + rotationangle); _webLineSegmentsBuffer[0].x = p1.x; _webLineSegmentsBuffer[0].y = p1.y; _webLineSegmentsBuffer[1].x = p2.x; _webLineSegmentsBuffer[1].y = p2.y; CGContextStrokeLineSegments(context, _webLineSegmentsBuffer, 2); } } CGContextRestoreGState(context); } private var _lineSegments = [CGPoint](count: 4, repeatedValue: CGPoint()); public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight]) { if (_chart.data === nil) { return; } var data = _chart.data as! RadarChartData; CGContextSaveGState(context); CGContextSetLineWidth(context, data.highlightLineWidth); if (data.highlightLineDashLengths != nil) { CGContextSetLineDash(context, data.highlightLineDashPhase, data.highlightLineDashLengths!, data.highlightLineDashLengths!.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } var sliceangle = _chart.sliceAngle; var factor = _chart.factor; var center = _chart.centerOffsets; for (var i = 0; i < indices.count; i++) { var set = _chart.data?.getDataSetByIndex(indices[i].dataSetIndex) as! RadarChartDataSet!; if (set === nil || !set.highlightEnabled) { continue; } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor); // get the index to highlight var xIndex = indices[i].xIndex; var e = set.entryForXIndex(xIndex); var j = set.entryIndex(entry: e, isEqual: true); var y = (e.value - _chart.chartYMin); var p = ChartUtils.getPosition(center: center, dist: CGFloat(y) * factor, angle: sliceangle * CGFloat(j) + _chart.rotationAngle); _lineSegments[0] = CGPoint(x: p.x, y: 0.0) _lineSegments[1] = CGPoint(x: p.x, y: viewPortHandler.chartHeight) _lineSegments[2] = CGPoint(x: 0.0, y: p.y) _lineSegments[3] = CGPoint(x: viewPortHandler.chartWidth, y: p.y) CGContextStrokeLineSegments(context, _lineSegments, 4); } CGContextRestoreGState(context); } }
apache-2.0
6dafa7c08f1273f26b99fe53e9a3716e
33.303571
274
0.551125
5.213898
false
false
false
false
openhab/openhab.ios
OpenHABCore/Sources/OpenHABCore/Util/ServerCertificateManager.swift
1
10189
// Copyright (c) 2010-2022 Contributors to the openHAB project // // See the NOTICE file(s) distributed with this work for additional // information. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0 // // SPDX-License-Identifier: EPL-2.0 import Alamofire import Foundation import os.log public protocol ServerCertificateManagerDelegate: NSObjectProtocol { // delegate should ask user for a decision on what to do with invalid certificate func evaluateServerTrust(_ policy: ServerCertificateManager?, summary certificateSummary: String?, forDomain domain: String?) // certificate received from openHAB doesn't match our record, ask user for a decision func evaluateCertificateMismatch(_ policy: ServerCertificateManager?, summary certificateSummary: String?, forDomain domain: String?) // notify delegate that the certificagtes that a user is willing to trust has changed func acceptedServerCertificatesChanged(_ policy: ServerCertificateManager?) } public class ServerCertificateManager: ServerTrustManager, ServerTrustEvaluating { // Handle the different responses of the user public enum EvaluateResult { case undecided case deny case permitOnce case permitAlways } public var evaluateResult: EvaluateResult = .undecided { didSet { if evaluateResult != .undecided { evaluateResultSemaphore.signal() } } } private let evaluateResultSemaphore = DispatchSemaphore(value: 0) weak var delegate: ServerCertificateManagerDelegate? // ignoreSSL is a synonym for allowInvalidCertificates, ignoreCertificates public var ignoreSSL = false public var trustedCertificates: [String: Any] = [:] // Init a ServerCertificateManager and set ignore certificates setting public init(ignoreSSL: Bool) { super.init(evaluators: [:]) self.ignoreSSL = ignoreSSL } func initializeCertificatesStore() { os_log("Initializing cert store", log: .remoteAccess, type: .info) loadTrustedCertificates() if trustedCertificates.isEmpty { os_log("No cert store, creating", log: .remoteAccess, type: .info) trustedCertificates = [:] // [trustedCertificates setObject:@"Bulk" forKey:@"Bulk id to make it non-empty"]; saveTrustedCertificates() } else { os_log("Loaded existing cert store", log: .remoteAccess, type: .info) } } func getPersistensePath() -> URL { #if os(watchOS) let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] return URL(fileURLWithPath: documentsDirectory).appendingPathComponent("trustedCertificates") #else FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.es.spaphone.openhab")!.appendingPathComponent("trustedCertificates") #endif } public func saveTrustedCertificates() { do { let data = try NSKeyedArchiver.archivedData(withRootObject: trustedCertificates, requiringSecureCoding: false) try data.write(to: getPersistensePath()) } catch { os_log("Could not save trusted certificates", log: .default) } } func storeCertificateData(_ certificate: CFData?, forDomain domain: String) { let certificateData = certificate as Data? trustedCertificates[domain] = certificateData saveTrustedCertificates() } func certificateData(forDomain domain: String) -> CFData? { guard let certificateData = trustedCertificates[domain] as? Data else { return nil } return certificateData as CFData } func loadTrustedCertificates() { do { let rawdata = try Data(contentsOf: getPersistensePath()) if let unarchive = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(rawdata) as? [String: Any] { trustedCertificates = unarchive } } catch { os_log("Could not load trusted certificates", log: .default) } } func evaluateTrust(with challenge: URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?) { do { let serverTrust = challenge.protectionSpace.serverTrust! try evaluate(serverTrust, forHost: challenge.protectionSpace.host) return (.useCredential, URLCredential(trust: serverTrust)) } catch { return (.cancelAuthenticationChallenge, nil) } } func wrapperSecTrustEvaluate(serverTrust: SecTrust) -> SecTrustResultType { var result: SecTrustResultType = .invalid if #available(iOS 12.0, *) { // SecTrustEvaluate is deprecated. // Wrap new API to have same calling pattern as we had prior to deprecation. var error: CFError? _ = SecTrustEvaluateWithError(serverTrust, &error) SecTrustGetTrustResult(serverTrust, &result) return result } else { SecTrustEvaluate(serverTrust, &result) return result } } public func evaluate(_ serverTrust: SecTrust, forHost domain: String) throws { // Evaluates trust received during SSL negotiation and checks it against known ones, // against policy setting to ignore certificate errors and so on. let evaluateResult = wrapperSecTrustEvaluate(serverTrust: serverTrust) if evaluateResult.isAny(of: .unspecified, .proceed) || ignoreSSL { // This means system thinks this is a legal/usable certificate, just permit the connection return } let certificate = getLeafCertificate(trust: serverTrust) let certificateSummary = SecCertificateCopySubjectSummary(certificate!) let certificateData = SecCertificateCopyData(certificate!) // If we have a certificate for this domain // Obtain certificate we have and compare it with the certificate presented by the server if let previousCertificateData = self.certificateData(forDomain: domain) { if CFEqual(previousCertificateData, certificateData) { // If certificate matched one in our store - permit this connection return } else { // We have a certificate for this domain in our memory of decisions, but the certificate we've got now // differs. We need to warn user about possible MiM attack and wait for users decision. // TODO: notify user and wait for decision if let delegate = delegate { self.evaluateResult = .undecided delegate.evaluateCertificateMismatch(self, summary: certificateSummary as String?, forDomain: domain) evaluateResultSemaphore.wait() switch self.evaluateResult { case .deny: // User decided to abort connection throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) case .permitOnce: // User decided to accept invalid certificate once return case .permitAlways: // User decided to accept invalid certificate and remember decision // Add certificate to storage storeCertificateData(certificateData, forDomain: domain) delegate.acceptedServerCertificatesChanged(self) return case .undecided: // Something went wrong, abort connection throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) } } throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) } } // Warn user about invalid certificate and wait for user's decision if let delegate = delegate { // Delegate should ask user for decision self.evaluateResult = .undecided delegate.evaluateServerTrust(self, summary: certificateSummary as String?, forDomain: domain) // Wait until we get response from delegate with user's decision evaluateResultSemaphore.wait() switch self.evaluateResult { case .deny: // User decided to abort connection throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) case .permitOnce: // User decided to accept invalid certificate once return case .permitAlways: // User decided to accept invalid certificate and remember decision // Add certificate to storage storeCertificateData(certificateData, forDomain: domain) delegate.acceptedServerCertificatesChanged(self) return case .undecided: throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) } } // We have no way of handling it so no access! throw AFError.serverTrustEvaluationFailed(reason: .noCertificatesFound) } func getLeafCertificate(trust: SecTrust?) -> SecCertificate? { // Returns the leaf certificate from a SecTrust object (that is always the // certificate at index 0). var result: SecCertificate? if let trust = trust { if SecTrustGetCertificateCount(trust) > 0 { result = SecTrustGetCertificateAtIndex(trust, 0) return result } else { return nil } } else { return nil } } override public func serverTrustEvaluator(forHost host: String) -> ServerTrustEvaluating? { self as ServerTrustEvaluating } }
epl-1.0
e2a1b264de3cfd68ebf2a7f78f6f38cd
43.108225
155
0.642752
5.660556
false
false
false
false
Raizlabs/ios-template
PRODUCTNAME/app/Pods/BonMot/Sources/Composable.swift
1
12632
// // Composable.swift // BonMot // // Created by Brian King on 9/28/16. // Copyright © 2016 Raizlabs. All rights reserved. // #if os(OSX) import AppKit #else import UIKit #endif /// Describes types which know how to append themselves to an attributed string. /// Used to provide a flexible, extensible chaning API for BonMot. public protocol Composable { /// Append the receiver to a given attributed string. It is up to the /// receiver's type to define what it means to be appended to an attributed /// string. Typically, the receiver will pick up the attributes of the last /// character of the passed attributed string, but the `baseStyle` parameter /// can be used to provide additional attributes for the appended string. /// /// - Parameters: /// - attributedString: The attributed string to which to append the /// receiver. /// - baseStyle: Additional attribues to apply to the receiver before /// appending it to the passed attributed string. func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle) /// Append the receiver to a given attributed string. It is up to the /// receiver's type to define what it means to be appended to an attributed /// string. Typically, the receiver will pick up the attributes of the last /// character of the passed attributed string, but the `baseStyle` parameter /// can be used to provide additional attributes for the appended string. /// /// - Parameters: /// - attributedString: The attributed string to which to append the /// receiver. /// - baseStyle: Additional attribues to apply to the receiver before /// appending it to the passed attributed string. /// - isLastElement: Whether the receiver is the final element that is /// being appended to an attributed string. Used in cases /// where the receiver wants to customize how it is /// appended if it knows it is the last element, chiefly /// regarding NSAttributedStringKey.kern. func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool) } public extension Composable { func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle) { append(to: attributedString, baseStyle: baseStyle, isLastElement: false) } /// Create an attributed string with only this composable content, and no /// base style. /// /// - returns: a new `NSAttributedString` public func attributedString() -> NSAttributedString { return .composed(of: [self]) } /// Create a new `NSAttributedString` with the style specified. /// /// - parameter style: The style to use. /// - parameter overrideParts: The style parts to override on the base style. /// - parameter stripTrailingKerning: whether to strip NSAttributedStringKey.kern /// from the last character of the result. /// - returns: A new `NSAttributedString`. public func styled(with style: StringStyle, _ overrideParts: StringStyle.Part..., stripTrailingKerning: Bool = true) -> NSAttributedString { let string = NSMutableAttributedString() let newStyle = style.byAdding(stringStyle: StringStyle(overrideParts)) append(to: string, baseStyle: newStyle, isLastElement: stripTrailingKerning) return string } /// Create a new `NSAttributedString` with the style parts specified. /// /// - parameter parts: The style parts to use. /// - parameter stripTrailingKerning: whether to strip NSAttributedStringKey.kern /// from the last character of the result. /// - returns: A new `NSAttributedString`. public func styled(with parts: StringStyle.Part..., stripTrailingKerning: Bool = true) -> NSAttributedString { var style = StringStyle() for part in parts { style.update(part: part) } return styled(with: style, stripTrailingKerning: stripTrailingKerning) } } public extension NSAttributedString { /// Compose an `NSAttributedString` by concatenating every item in /// `composables` with `baseStyle` applied. The `separator` is inserted /// between every item. `baseStyle` acts as the default style, and apply to /// the `Composable` item only if the `Composable` does not have a style /// value configured. /// /// - parameter composables: An array of `Composable` to join into an /// `NSAttributedString`. /// - parameter baseStyle: The base style to apply to every `Composable`. /// If no `baseStyle` is supplied, no additional /// styling will be added. /// - parameter separator: The separator to insert between every pair of /// elements in `composables`. /// - returns: A new `NSAttributedString`. @nonobjc public static func composed(of composables: [Composable], baseStyle: StringStyle = StringStyle(), separator: Composable? = nil) -> NSAttributedString { let string = NSMutableAttributedString() string.beginEditing() let lastComposableIndex = composables.endIndex for (index, composable) in composables.enumerated() { composable.append(to: string, baseStyle: baseStyle, isLastElement: index == lastComposableIndex - 1) if let separator = separator { if index != composables.indices.last { separator.append(to: string, baseStyle: baseStyle) } } } string.endEditing() return string } public func styled(with style: StringStyle, _ overrideParts: StringStyle.Part...) -> NSAttributedString { let newStyle = style.byAdding(overrideParts) let newAttributes = newStyle.attributes let mutableSelf = mutableStringCopy() let fullRange = NSRange(location: 0, length: mutableSelf.string.utf16.count) for (key, value) in newAttributes { mutableSelf.addAttribute(key, value: value, range: fullRange) } return mutableSelf.immutableCopy() } } extension NSAttributedString: Composable { /// Append this `NSAttributedString` to `attributedString`, with `baseStyle` /// applied as default values. This method enumerates all attribute ranges /// in the receiver and use `baseStyle` to supply defaults for the attributes. /// This effectively merges `baseStyle` and the embedded attributes, with a /// tie going to the embedded attributes. /// /// See `StringStyle.supplyDefaults(for:)` for more details. /// /// - parameter to: The attributed string to which to append the receiver. /// - parameter baseStyle: The `StringStyle` that is overridden by the /// receiver's attributes @nonobjc public final func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool) { let range = NSRange(location: 0, length: length) enumerateAttributes(in: range, options: []) { (attributes, range, _) in let substring = self.attributedSubstring(from: range) // Add the string with the defaults supplied by the style let newString = baseStyle.attributedString(from: substring.string, existingAttributes: attributes) attributedString.append(newString) } if isLastElement { attributedString.removeKerningFromLastCharacter() } else { attributedString.restoreKerningOnLastCharacter() } } } extension String: Composable { /// Append the receiver to `attributedString`, with `baseStyle` applied as /// default values. Since `String` has no style, `baseStyle` is the only /// style that is used. /// /// - parameter to: The attributed string to which to append the receiver. /// - parameter baseStyle: The style to use for this string. public func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool) { attributedString.append(baseStyle.attributedString(from: self)) if isLastElement { attributedString.removeKerningFromLastCharacter() } else { attributedString.restoreKerningOnLastCharacter() } } } #if os(iOS) || os(tvOS) || os(OSX) extension BONImage: Composable { /// Append the receiver to `attributedString`, with `baseStyle` applied as /// default values. Only a few properties in `baseStyle` are relevant when /// styling images. These include `baselineOffset`, as well as `color` for /// template images. All attributes are stored in the range of the image for /// consistency inside the attributed string. /// /// - note: the `NSBaselineOffsetAttributeName` value is used as the /// `bounds.origin.y` value for the text attachment, and is removed from the /// attributes dictionary to fix an issue with UIKit. /// /// - note: `NSTextAttachment` is not available on watchOS. /// /// - parameter to: The attributed string to which to append the receiver. /// - parameter baseStyle: The style to use. @nonobjc public final func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool) { let baselinesOffsetForAttachment = baseStyle.baselineOffset ?? 0 let attachment = NSTextAttachment() #if os(OSX) let imageIsTemplate = isTemplate #else let imageIsTemplate = (renderingMode != .alwaysOriginal) #endif var imageToUse = self if let color = baseStyle.color { if imageIsTemplate { imageToUse = tintedImage(color: color) } } attachment.image = imageToUse attachment.bounds = CGRect(origin: CGPoint(x: 0, y: baselinesOffsetForAttachment), size: size) let attachmentString = NSAttributedString(attachment: attachment).mutableStringCopy() // Remove the baseline offset from the attributes so it isn't applied twice var attributes = baseStyle.attributes attributes[.baselineOffset] = nil attachmentString.addAttributes(attributes, range: NSRange(location: 0, length: attachmentString.length)) attributedString.append(attachmentString) } } #endif extension Special: Composable { /// Append the receiver's string value to `attributedString`, with `baseStyle` /// applied as default values. /// /// - parameter to: The attributed string to which to append the receiver. /// - parameter baseStyle: The style to use. public func append(to attributedString: NSMutableAttributedString, baseStyle: StringStyle, isLastElement: Bool) { description.append(to: attributedString, baseStyle: baseStyle) } } public extension Sequence where Element: Composable { func joined(separator: Composable = "") -> NSAttributedString { return NSAttributedString.composed(of: Array(self), separator: separator) } } extension NSAttributedString.Key { public static let bonMotRemovedKernAttribute = NSAttributedString.Key("com.raizlabs.bonmot.removedKernAttributeRemoved") } extension NSMutableAttributedString { func removeKerningFromLastCharacter() { guard length != 0 else { return } let lastCharacterRange = NSRange(location: length - 1, length: 1) guard let currentKernValue = attribute(.kern, at: lastCharacterRange.location, effectiveRange: nil) else { return } removeAttribute(.kern, range: lastCharacterRange) addAttribute(.bonMotRemovedKernAttribute, value: currentKernValue, range: lastCharacterRange) } func restoreKerningOnLastCharacter() { guard length != 0 else { return } let lastCharacterRange = NSRange(location: length - 1, length: 1) guard let currentKernValue = attribute(.bonMotRemovedKernAttribute, at: lastCharacterRange.location, effectiveRange: nil) else { return } removeAttribute(.bonMotRemovedKernAttribute, range: lastCharacterRange) addAttribute(.kern, value: currentKernValue, range: lastCharacterRange) } }
mit
0cfe26f477837c55438f36da17edff35
40.686469
164
0.66313
5.060497
false
false
false
false
Interfere/Deque
Source/Deque.swift
1
24454
// MIT License // // Copyright (c) 2016 Alexey Komnin // // 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. /// A double-ended queue. /// /// You use a deque instead of an array when you need to efficiently insert /// or remove elements from start or end of the collection. public struct Deque<Element>: RandomAccessCollection, MutableCollection { private var _buffer: RingBuffer<Element> /// Creates a new, empty deque. /// /// Example: /// /// var emptyDeque = Deque<Int>() /// print(emptyArray.isEmpty) /// // Prints "true" public init() { self._buffer = RingBuffer.create() } private init(minimumCapacity: Int) { self._buffer = RingBuffer.create(minimumCapacity: minimumCapacity) } /// Creates a deque containing the elements of a sequence. /// /// You can use this initializer to create a deque from any other type that /// conforms to the `Sequence` protocol. For example, you might want to /// create a deque with the integers from 1 through 7. Use this initializer /// around a range instead of typing all those numbers in an array literal. /// /// let numbers = Deque(1...7) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7]" /// /// /// - Parameter s: The sequence of elements to turn into deque. public init<S>(_ s: S) where S: Sequence, S.Iterator.Element == Element { self.init(minimumCapacity: s.underestimatedCount) self.append(contentsOf: s) } /// Creates a new deque containing the specified number of a single, repeated /// value. /// /// Here's an example of creating a deque initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Deque(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. public init(repeating repeatedValue: Element, count: Int) { self._buffer = RingBuffer.create(minimumCapacity: count) for _ in 0..<count { self._buffer.append(repeatedValue) } } /// The number of elements in the deque. public var count: Int { return self._buffer.count } /// The total number of elements that the deque can contain using its current /// storage. /// /// If the deque grows larger than its capacity, it discards its current /// storage and allocates a larger one. /// /// The following example creates an deque of integers from an deque literal, /// then appends the elements of another collection. Before appending, the /// deque allocates new storage that is large enough store the resulting /// elements. /// /// var numbers = Deque([10, 20, 30, 40, 50]) /// print("Count: \(numbers.count), capacity: \(numbers.capacity)") /// // Prints "Count: 5, capacity: 5" /// /// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10)) /// print("Count: \(numbers.count), capacity: \(numbers.capacity)") /// // Prints "Count: 10, capacity: 12" public var capacity: Int { return _buffer.capacity } private mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int) -> RingBuffer<Element>? { if _fastPath(isKnownUniquelyReferenced(&self._buffer) && capacity >= minimumCapacity) { return self._buffer } return nil } /// Reserves enough space to store the specified number of elements. /// /// If you are adding a known number of elements to an deque, use this method /// to avoid multiple reallocations. This method ensures that the deque has /// unique, mutable, contiguous storage, with space allocated for at least /// the requested number of elements. /// /// For performance reasons, the newly allocated storage may be larger than /// the requested capacity. Use the deque's `capacity` property to determine /// the size of the new storage. /// /// - Parameter minimumCapacity: The requested number of elements to store. /// /// - Complexity: O(*n*), where *n* is the count of the deque. public mutating func reserveCapacity(_ minimumCapacity: Int){ if requestUniqueMutableBackingBuffer(minimumCapacity: minimumCapacity) == nil { let newBuffer = RingBuffer<Element>.create(minimumCapacity: minimumCapacity) newBuffer.copyContents(self._buffer) self._buffer = newBuffer } assert(capacity >= minimumCapacity) } /// Adds a new element at the end of the deque. /// /// Use this method to append a single element to the end of a mutable deque. /// /// var numbers = Deque([1, 2, 3, 4, 5]) /// numbers.append(100) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// Because deques increase their allocated capacity using an exponential /// strategy, appending a single element to an deque is an O(1) operation /// when averaged over many calls to the `append(_:)` method. When deque /// has additional capacity and is not sharing its storage with another /// instance, appending an element is O(1). When deque needs to /// reallocate storage before appending or its storage is shared with /// another copy, appending is O(*n*), where *n* is the length of the deque. /// /// - Parameter newElement: The element to append to the deque. /// /// - Complexity: Amortized O(1) over many additions. public mutating func append(_ newElement: Element) { reserveCapacity(count + 1) _buffer.append(newElement) } /// Adds the elements of a sequence to the end of the deque. /// /// Use this method to append the elements of a sequence to the end of a /// deque. This example appends the elements of a `Range<Int>` instance /// to a deque of integers. /// /// var numbers = Deque([1, 2, 3, 4, 5]) /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the deque. /// /// - Complexity: O(*n*), where *n* is the length of the resulting deque. public mutating func append<S : Sequence>(contentsOf newElements: S) where S.Iterator.Element == Element { reserveCapacity(count + newElements.underestimatedCount) var stream = _buffer.append(newElements.underestimatedCount, elementsOf: newElements) while let nextElement = stream.next() { append(nextElement) } } /// Adds the elements of a collection to the end of the deque. /// /// Use this method to append the elements of a collection to the end of this /// deque. This example appends the elements of a `Range<Int>` instance /// to an deque of integers. /// /// var numbers = Deque([1, 2, 3, 4, 5]) /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the deque. /// /// - Complexity: O(*n*), where *n* is the length of the resulting deque. public mutating func append<C : Collection>(contentsOf newElements: C) where C.Iterator.Element == Element { replaceSubrange(endIndex..<endIndex, with: newElements) } /// Adds a new element at the start of the deque. /// /// Use this method to prepend a single element at the start of a mutable deque. /// /// var numbers = Deque([1, 2, 3, 4, 5]) /// numbers.prepend(100) /// print(numbers) /// // Prints "[100, 1, 2, 3, 4, 5]" /// /// Because deques increase their allocated capacity using an exponential /// strategy, prepending a single element to deque is an O(1) operation /// when averaged over many calls to the `prepend(_:)` method. When deque /// has additional capacity and is not sharing its storage with another /// instance, prepending an element is O(1). When deque needs to /// reallocate storage before prepending or its storage is shared with /// another copy, prepending is O(*n*), where *n* is the length of the deque. /// /// - Parameter newElement: The element to prepend to the deque. /// /// - Complexity: Amortized O(1) over many additions. public mutating func prepend(_ newElement: Element) { reserveCapacity(count + 1) _buffer.prepend(newElement) } /// Inserts a new element at the specified position. /// /// The new element is inserted before the element currently at the specified /// index. If you pass the deque's `endIndex` property as the `index` /// parameter, the new element is appended to the deque; if you pass `startIndex` /// property, the new element is prepended to the deque. /// /// var numbers = Deque([1, 2, 3, 4, 5]) /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// numbers.insert(300, at: numbers.startIndex) /// /// print(numbers) /// // Prints "[300, 1, 2, 3, 100, 4, 5, 200]" /// /// - Parameter newElement: The new element to insert into the deque. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index of the deque or equal to its `endIndex` /// property. /// /// - Complexity: O(*n*), where *n* is the length of the deque. public mutating func insert(_ newElement: Element, at i: Int) { precondition(i >= startIndex && i <= endIndex, "Deque insert: index out of bounds") replaceSubrange(i..<i, with: CollectionOfOne(newElement)) } /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved up to /// close the gap. /// /// var measurements: Deque<Double> = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]" /// /// - Parameter index: The position of the element to remove. `index` must /// be a valid index of the deque. /// - Returns: The element at the specified index. /// /// - Complexity: O(*n*), where *n* is the length of the deque. public mutating func remove(at index: Int) -> Element { precondition(index >= startIndex && index < endIndex, "Deque remove: index out of bounds") let result = self[index] replaceSubrange(index..<(index + 1), with: EmptyCollection()) return result } /// Removes all elements from the deque. /// /// - Parameter keepCapacity: Pass `true` to keep the existing capacity of /// the deque after removing its elements. The default value is /// `false`. /// /// - Complexity: O(*n*), where *n* is the length of the deque. public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if !keepCapacity { _buffer = RingBuffer.create() } else { replaceSubrange(Range(self.indices), with: EmptyCollection()) } } /// Replaces a range of elements with the elements in the specified /// collection. /// /// This method has the effect of removing the specified range of elements /// from the deque and inserting the new elements at the same location. The /// number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of deque of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = Deque([10, 20, 30, 40, 50]) /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// - Parameters: /// - subrange: The subrange of the deque to replace. The start and end of /// a subrange must be valid indices of the deque. /// - newElements: The new elements to add to the deque. /// /// - Complexity: O(`subrange.count`) if you are replacing a suffix or a prefix /// of the deque with an empty collection; otherwise, O(*n*), where *n* is the /// length of the deque. public mutating func replaceSubrange<C>(_ subrange: Range<Int>, with newElements: C) where C : Collection, C.Iterator.Element == Element { precondition(subrange.lowerBound >= _buffer.startIndex, "Deque replace: subrange start is negative") precondition(subrange.upperBound <= _buffer.endIndex, "Deque replace: subrange extends past the end") let oldCount = _buffer.count let eraseCount = subrange.count let insertCount = numericCast(newElements.count) as Int let growth = insertCount - eraseCount if requestUniqueMutableBackingBuffer(minimumCapacity: oldCount + growth) != nil { _buffer.replaceSubrange(subrange, with: insertCount, elementsOf: newElements) } else { _buffer = _buffer.copyReplacingSubrange(subrange, with: insertCount, elementsOf: newElements) } } /// A type that represents a position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript /// argument. /// /// - SeeAlso: endIndex public typealias Index = Int /// The position of the first element in a nonempty deque. /// /// For an instance of `Deque`, `startIndex` is always zero. If the deque /// is empty, `startIndex` is equal to `endIndex`. public var startIndex: Int { return 0 } /// The deque's "past the end" position---that is, the position one greater /// than the last valid subscript argument. /// /// When you need a range that includes the last element of an deque, use the /// half-open range operator (`..<`) with `endIndex`. The `..<` operator /// creates a range that doesn't include the upper bound, so it's always /// safe to use with `endIndex`. For example: /// /// let numbers = Deque([10, 20, 30, 40, 50]) /// if let i = numbers.index(of: 30) { /// print(numbers[i ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" /// /// If the deque is empty, `endIndex` is equal to `startIndex`. public var endIndex: Int { return _buffer.count } /// A type that can represent the indices that are valid for subscripting the /// collection, in ascending order. public typealias Indices = CountableRange<Int> /// The indices that are valid for subscripting the collection, in ascending /// order. /// /// A collection's `indices` property can hold a strong reference to the /// collection itself, causing the collection to be non-uniquely referenced. /// If you mutate the collection while iterating over its indices, a strong /// reference can cause an unexpected copy of the collection. To avoid the /// unexpected copy, use the `index(after:)` method starting with /// `startIndex` to produce indices instead. /// /// var c = MyFancyCollection([10, 20, 30, 40, 50]) /// var i = c.startIndex /// while i != c.endIndex { /// c[i] /= 5 /// i = c.index(after: i) /// } /// // c == MyFancyCollection([2, 4, 6, 8, 10]) public var indices: CountableRange<Int> { return startIndex..<endIndex } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. public func index(after i: Int) -> Int { return i + 1 } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index value immediately before `i`. public func index(before i: Int) -> Int { return i - 1 } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. /// /// let numbers: Deque = [10, 20, 30, 40, 50] /// let i = numbers.index(numbers.startIndex, offsetBy: 4) /// print(numbers[i]) /// // Prints "50" /// /// The value passed as `n` must not offset `i` beyond the bounds of the /// collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - n: The distance to offset `i`. /// - Returns: An index offset by `n` from the index `i`. If `n` is positive, /// this is the same value as the result of `n` calls to `index(after:)`. /// If `n` is negative, this is the same value as the result of `-n` calls /// to `index(before:)`. /// /// - Complexity: O(1) public func index(_ i: Int, offsetBy n: Int) -> Int { return i + n } /// Returns the distance between two indices. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. /// /// - Complexity: O(1) public func distance(from start: Int, to end: Int) -> Int { return end - start } /// Accesses the element at the specified position. /// /// The following example uses indexed subscripting to update an deque's /// second element. After assigning the new value (`"Butler"`) at a specific /// position, that value is immediately available at that same position. /// /// var streets = Deque(["Adams", "Bryant", "Channing", "Douglas", "Evarts"]) /// streets[1] = "Butler" /// print(streets[1]) /// // Prints "Butler" /// /// - Parameter index: The position of the element to access. `index` must be /// greater than or equal to `startIndex` and less than `endIndex`. /// /// - Complexity: Reading an element from an deque is O(1). Writing is O(1) /// unless the deque's storage is shared with another deque, in which case /// writing is O(*n*), where *n* is the length of the deque. public subscript(index: Int) -> Element { get { precondition(index >= _buffer.startIndex && index < _buffer.endIndex, "Deque subscript: index {\(index)} out of bounds (\(_buffer.startIndex)..<\(_buffer.endIndex))") return _buffer.at(index: index) } set { precondition(index >= _buffer.startIndex && index < _buffer.endIndex, "Deque subscript: index out of bounds") replaceSubrange(index..<(index + 1), with: CollectionOfOne(newValue)) } } /// Accesses a contiguous subrange of the deque's elements. /// /// The returned `RandomAccessSlice` instance uses the same indices for the /// same elements as the original deque. In particular, that slice, unlike an /// deque, may have a nonzero `startIndex` and an `endIndex` that is not /// equal to `count`. Always use the slice's `startIndex` and `endIndex` /// properties instead of assuming that its indices start or end at a /// particular value. /// /// This example demonstrates getting a slice of a deque of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original deque. /// /// let streets: Deque<String> = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let i = streetsSlice.index(of: "Evarts") // 4 /// print(streets[i!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of integers. The bounds of the range must be /// valid indices of the deque. /// /// - SeeAlso: `RandomAccessSlice` public subscript(bounds: Range<Int>) -> RandomAccessSlice<Deque> { get { precondition(bounds.lowerBound >= _buffer.startIndex, "Deque subscript: subrange start is negative") precondition(bounds.upperBound <= _buffer.endIndex, "Deque subscript: subrange extends past the end") return RandomAccessSlice(base: self, bounds: bounds) } set { precondition(bounds.lowerBound >= _buffer.startIndex, "Deque subscript: subrange start is negative") precondition(bounds.upperBound <= _buffer.endIndex, "Deque subscript: subrange extends past the end") if self._buffer.identity != newValue.base._buffer.identity { replaceSubrange(bounds, with: newValue) } } } } extension Deque: ExpressibleByArrayLiteral { /// Creates a deque from the given array literal. /// /// Do not call this initializer directly. It is used by the compiler /// when you use an array literal. Instead, create a new deque by using an /// array literal as its value. To do this, enclose a comma-separated list of /// values in square brackets. /// /// Here, a deque of strings is created from an array literal holding /// only strings. /// /// let ingredients: Deque = ["cocoa beans", "sugar", "cocoa butter", "salt"] /// /// - Parameter elements: A variadic list of elements of the new array. public init(arrayLiteral elements: Element...) { self.init(elements) } } extension Deque: CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of the array and its elements. public var description: String { return "[" + map(String.init(describing:)).joined(separator: ", ") + "]" } /// A textual representation of the array and its elements, suitable for /// debugging. public var debugDescription: String { return "Deque(" + description + ")" } }
mit
6092c5be08971b8fec2cd0cd10ce1fc2
42.204947
178
0.619326
4.414876
false
false
false
false
bangslosan/CVCalendar
CVCalendar/CVCalendarManager.swift
5
8775
// // CVCalendarManager.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit private let sharedInstance = CVCalendarManager() class CVCalendarManager: NSObject { // MARK: - Private properties private var components: NSDateComponents? var calendar: NSCalendar? // MARK: - Public properties var currentDate: NSDate? class var sharedManager: CVCalendarManager { return sharedInstance } // MARK: - Private initialization var starterWeekday: Int? private override init() { self.calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian) self.currentDate = NSDate() self.components = self.calendar?.components(NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.DayCalendarUnit, fromDate: self.currentDate!) let propertyName = "CVCalendarStarterWeekday" let firstWeekday = NSBundle.mainBundle().objectForInfoDictionaryKey(propertyName) as? Int if firstWeekday != nil { self.starterWeekday = firstWeekday self.calendar!.firstWeekday = starterWeekday! } else { let currentCalendar = NSCalendar.currentCalendar() let firstWeekday = currentCalendar.firstWeekday self.starterWeekday = firstWeekday self.calendar!.firstWeekday = starterWeekday! } } // MARK: - Common date analysis func monthDateRange(date: NSDate) -> (countOfWeeks: NSInteger, monthStartDate: NSDate, monthEndDate: NSDate) { let units = (NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.WeekCalendarUnit) var components = self.calendar!.components(units, fromDate: date) // Start of the month. components.day = 1 let monthStartDate = self.calendar?.dateFromComponents(components) // End of the month. components.month += 1 components.day -= 1 let monthEndDate = self.calendar?.dateFromComponents(components) // Range of the month. let range = self.calendar?.rangeOfUnit(NSCalendarUnit.WeekCalendarUnit, inUnit: NSCalendarUnit.MonthCalendarUnit, forDate: date) let countOfWeeks = range?.length return (countOfWeeks!, monthStartDate!, monthEndDate!) } func dateRange(date: NSDate) -> (year: Int, month: Int, day: Int) { let units = NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.WeekCalendarUnit | NSCalendarUnit.DayCalendarUnit let components = self.calendar?.components(units, fromDate: date) let year = components?.year let month = components?.month let day = components?.day return (year!, month!, day!) } func weekdayForDate(date: NSDate) -> Int { let units = NSCalendarUnit.WeekdayCalendarUnit let components = self.calendar!.components(units, fromDate: date) //println("NSDate: \(date), Weekday: \(components.weekday)") let weekday = self.calendar!.ordinalityOfUnit(.WeekdayCalendarUnit, inUnit: .WeekCalendarUnit, forDate: date) return Int(components.weekday) } // MARK: - Analysis sorting func weeksWithWeekdaysForMonthDate(date: NSDate) -> (weeksIn: [[Int : [Int]]], weeksOut: [[Int : [Int]]]) { let countOfWeeks = self.monthDateRange(date).countOfWeeks let totalCountOfDays = countOfWeeks * 7 let firstMonthDateIn = self.monthDateRange(date).monthStartDate let lastMonthDateIn = self.monthDateRange(date).monthEndDate let countOfDaysIn = self.dateRange(lastMonthDateIn).day let countOfDaysOut = totalCountOfDays - countOfDaysIn // Find all dates in. var datesIn = [NSDate]() for day in 1...countOfDaysIn { let components = self.componentsForDate(firstMonthDateIn) components.day = day let date = self.calendar!.dateFromComponents(components)! datesIn.append(date) } // Find all dates out. let firstMonthDateOut: NSDate? = { let firstMonthDateInWeekday = self.weekdayForDate(firstMonthDateIn) if firstMonthDateInWeekday == self.starterWeekday { println("here") return firstMonthDateIn } let components = self.componentsForDate(firstMonthDateIn) for _ in 1...7 { components.day -= 1 let updatedDate = self.calendar!.dateFromComponents(components)! updatedDate let updatedDateWeekday = self.weekdayForDate(updatedDate) if updatedDateWeekday == self.starterWeekday { updatedDate return updatedDate } } let diff = 7 - firstMonthDateInWeekday for _ in diff..<7 { components.day += 1 let updatedDate = self.calendar!.dateFromComponents(components)! let updatedDateWeekday = self.weekdayForDate(updatedDate) if updatedDateWeekday == self.starterWeekday { updatedDate return updatedDate } } return nil }() // Constructing weeks. var firstWeekDates = [NSDate]() var lastWeekDates = [NSDate]() var firstWeekDate = (firstMonthDateOut != nil) ? firstMonthDateOut! : firstMonthDateIn let components = self.componentsForDate(firstWeekDate) components.day += 6 var lastWeekDate = self.calendar!.dateFromComponents(components)! func nextWeekDateFromDate(date: NSDate) -> NSDate { let components = self.componentsForDate(date) components.day += 7 let nextWeekDate = self.calendar!.dateFromComponents(components)! return nextWeekDate } for weekIndex in 1...countOfWeeks { firstWeekDates.append(firstWeekDate) lastWeekDates.append(lastWeekDate) firstWeekDate = nextWeekDateFromDate(firstWeekDate) lastWeekDate = nextWeekDateFromDate(lastWeekDate) } // Dictionaries. var weeksIn = [[Int : [Int]]]() var weeksOut = [[Int : [Int]]]() let count = firstWeekDates.count for i in 0..<count { var weekdaysIn = [Int : [Int]]() var weekdaysOut = [Int : [Int]]() let firstWeekDate = firstWeekDates[i] let lastWeekDate = lastWeekDates[i] let components = self.componentsForDate(firstWeekDate) for weekday in 1...7 { let weekdate = self.calendar!.dateFromComponents(components)! components.day += 1 let day = self.dateRange(weekdate).day func addDay(inout weekdays: [Int : [Int]]) { var days = weekdays[weekday] if days == nil { days = [Int]() } days!.append(day) weekdays.updateValue(days!, forKey: weekday) } if i == 0 && day > 20 { addDay(&weekdaysOut) } else if i == countOfWeeks - 1 && day < 10 { addDay(&weekdaysOut) } else { addDay(&weekdaysIn) } } if weekdaysIn.count > 0 { weeksIn.append(weekdaysIn) } if weekdaysOut.count > 0 { weeksOut.append(weekdaysOut) } } return (weeksIn, weeksOut) } // MARK: - Util methods func componentsForDate(date: NSDate) -> NSDateComponents { let units = NSCalendarUnit.YearCalendarUnit | NSCalendarUnit.MonthCalendarUnit | NSCalendarUnit.WeekOfMonthCalendarUnit | NSCalendarUnit.DayCalendarUnit let components = self.calendar!.components(units, fromDate: date) return components } func monthSymbols() -> [AnyObject] { return self.calendar!.monthSymbols } func shortWeekdaySymbols() -> [AnyObject] { return self.calendar!.shortWeekdaySymbols } }
mit
3ae806cb4b50ee0cab9682d43b25eb9c
35.115226
160
0.575385
5.635838
false
false
false
false
davidozhang/spycodes
Spycodes/Core/SCStates.swift
1
6796
enum StateType: Int { case actionButton = 0 case readyButton = 1 case timer = 2 case pregameMenu = 3 case customCategory = 4 } enum ActionButtonState: Int { case confirm = 0 case endRound = 1 case gameOver = 2 case gameAborted = 3 case showAnswer = 4 case hideAnswer = 5 } enum CustomCategoryState: Int { case nonEditing = 0 case addingNewWord = 1 case editingExistingWord = 2 case editingCategoryName = 3 case editingEmoji = 4 } enum PregameMenuState: Int { case gameSettings = 0 case categories = 1 } enum ReadyButtonState: Int { case notReady = 0 case ready = 1 } enum TimerState: Int { case stopped = 0 case willStart = 1 case started = 2 } class SCStates { static fileprivate var actionButtonState: ActionButtonState = .endRound static fileprivate var readyButtonState: ReadyButtonState = .notReady static fileprivate var pregameMenuState: PregameMenuState = .gameSettings static fileprivate var customCategoryState: CustomCategoryState = .nonEditing static fileprivate var timerState: TimerState = .stopped static func changeActionButtonState(to state: ActionButtonState) { self.actionButtonState = state self.logState(type: .actionButton) } static func changeCustomCategoryState(to state: CustomCategoryState) { self.customCategoryState = state self.logState(type: .customCategory) } static func changePregameMenuState(to state: PregameMenuState) { self.pregameMenuState = state self.logState(type: .pregameMenu) } static func changeReadyButtonState(to state: ReadyButtonState) { self.readyButtonState = state self.logState(type: .readyButton) } static func changeTimerState(to state: TimerState) { self.timerState = state self.logState(type: .timer) } static func getActionButtonState() -> ActionButtonState { return self.actionButtonState } static func getCustomCategoryState() -> CustomCategoryState { return self.customCategoryState } static func getPregameMenuState() -> PregameMenuState { return self.pregameMenuState } static func getReadyButtonState() -> ReadyButtonState { return self.readyButtonState } static func getTimerState() -> TimerState { return self.timerState } static func resetAll() { SCStates.resetState(type: .actionButton) SCStates.resetState(type: .customCategory) SCStates.resetState(type: .pregameMenu) SCStates.resetState(type: .readyButton) SCStates.resetState(type: .timer) } static func resetState(type: StateType) { switch type { case .actionButton: SCStates.changeActionButtonState(to: .endRound) case .customCategory: SCStates.changeCustomCategoryState(to: .nonEditing) case .pregameMenu: SCStates.changePregameMenuState(to: .gameSettings) case .readyButton: SCStates.changeReadyButtonState(to: .notReady) case .timer: SCStates.changeTimerState(to: .stopped) } } } // MARK: Logging extension SCStates { static func logState(type: StateType) { var output = "" switch type { case .actionButton: output += String( format: SCStrings.state.log.rawValue, SCStrings.state.actionButton.rawValue, SCStates.getActionButtonStateString(state: self.actionButtonState) ) case .customCategory: output += String( format: SCStrings.state.log.rawValue, SCStrings.state.customCategory.rawValue, SCStates.getCustomCategoryStateString(state: self.customCategoryState) ) case .pregameMenu: output += String( format: SCStrings.state.log.rawValue, SCStrings.state.pregameMenu.rawValue, SCStates.getPregameMenuStateString(state: self.pregameMenuState) ) case .readyButton: output += String( format: SCStrings.state.log.rawValue, SCStrings.state.readyButton.rawValue, SCStates.getReadyButtonStateString(state: self.readyButtonState) ) case .timer: output += String( format: SCStrings.state.log.rawValue, SCStrings.state.timer.rawValue, SCStates.getTimerStateString(state: self.timerState) ) } SCLogger.log(identifier: SCConstants.loggingIdentifier.states.rawValue, output) } static func getActionButtonStateString(state: ActionButtonState) -> String { switch state { case .confirm: return SCStrings.state.confirm.rawValue case .endRound: return SCStrings.state.endRound.rawValue case .gameAborted: return SCStrings.state.gameAborted.rawValue case .gameOver: return SCStrings.state.gameOver.rawValue case .hideAnswer: return SCStrings.state.hideAnswer.rawValue case .showAnswer: return SCStrings.state.showAnswer.rawValue } } static func getCustomCategoryStateString(state: CustomCategoryState) -> String { switch state { case .addingNewWord: return SCStrings.state.addingNewWord.rawValue case .editingCategoryName: return SCStrings.state.editingCategoryName.rawValue case .editingEmoji: return SCStrings.state.editingEmoji.rawValue case .editingExistingWord: return SCStrings.state.editingExistingWord.rawValue case .nonEditing: return SCStrings.state.nonEditing.rawValue } } static func getPregameMenuStateString(state: PregameMenuState) -> String { switch state { case .gameSettings: return SCStrings.state.gameSettings.rawValue case .categories: return SCStrings.state.categories.rawValue } } static func getReadyButtonStateString(state: ReadyButtonState) -> String { switch state { case .notReady: return SCStrings.state.notReady.rawValue case .ready: return SCStrings.state.ready.rawValue } } static func getTimerStateString(state: TimerState) -> String { switch state { case .stopped: return SCStrings.state.stopped.rawValue case .willStart: return SCStrings.state.willStart.rawValue case .started: return SCStrings.state.started.rawValue } } }
mit
a96095daeebcf4de0423383e54d137dc
30.174312
87
0.641995
4.648427
false
false
false
false
iStig/Uther_Swift
Pods/KeyboardMan/KeyboardMan/KeyboardMan.swift
1
5628
// // KeyboardMan.swift // Messages // // Created by NIX on 15/7/25. // Copyright (c) 2015年 nixWork. All rights reserved. // import UIKit public class KeyboardMan: NSObject { var keyboardObserver: NSNotificationCenter? { didSet { oldValue?.removeObserver(self) keyboardObserver?.addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) keyboardObserver?.addObserver(self, selector: "keyboardWillChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil) keyboardObserver?.addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) keyboardObserver?.addObserver(self, selector: "keyboardDidHide:", name: UIKeyboardDidHideNotification, object: nil) } } public var keyboardObserveEnabled = false { willSet { if newValue != keyboardObserveEnabled { keyboardObserver = newValue ? NSNotificationCenter.defaultCenter() : nil } } } deinit { // willSet and didSet are not called when deinit, so... NSNotificationCenter.defaultCenter().removeObserver(self) } public struct KeyboardInfo { public let animationDuration: NSTimeInterval public let animationCurve: UInt public let frameBegin: CGRect public let frameEnd: CGRect public var height: CGFloat { return frameEnd.height } public let heightIncrement: CGFloat public enum Action { case Show case Hide } public let action: Action let isSameAction: Bool } public var appearPostIndex = 0 var keyboardInfo: KeyboardInfo? { willSet { if UIApplication.sharedApplication().applicationState != .Active { return } if let info = newValue { if !info.isSameAction || info.heightIncrement != 0 { // do convenient animation let duration = info.animationDuration let curve = info.animationCurve let options = UIViewAnimationOptions(curve << 16 | UIViewAnimationOptions.BeginFromCurrentState.rawValue) UIView.animateWithDuration(duration, delay: 0, options: options, animations: { switch info.action { case .Show: self.animateWhenKeyboardAppear?(appearPostIndex: self.appearPostIndex, keyboardHeight: info.height, keyboardHeightIncrement: info.heightIncrement) self.appearPostIndex++ case .Hide: self.animateWhenKeyboardDisappear?(keyboardHeight: info.height) self.appearPostIndex = 0 } }, completion: nil) // post full info postKeyboardInfo?(keyboardMan: self, keyboardInfo: info) } } } } public var animateWhenKeyboardAppear: ((appearPostIndex: Int, keyboardHeight: CGFloat, keyboardHeightIncrement: CGFloat) -> Void)? { didSet { keyboardObserveEnabled = true } } public var animateWhenKeyboardDisappear: ((keyboardHeight: CGFloat) -> Void)? { didSet { keyboardObserveEnabled = true } } public var postKeyboardInfo: ((keyboardMan: KeyboardMan, keyboardInfo: KeyboardInfo) -> Void)? { didSet { keyboardObserveEnabled = true } } // MARK: - Actions private func handleKeyboard(notification: NSNotification, _ action: KeyboardInfo.Action) { if let userInfo = notification.userInfo { let animationDuration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue let animationCurve = (userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).unsignedLongValue let frameBegin = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue() let frameEnd = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let currentHeight = frameEnd.height let previousHeight = keyboardInfo?.height ?? 0 let heightIncrement = currentHeight - previousHeight let isSameAction: Bool if let previousAction = keyboardInfo?.action { isSameAction = action == previousAction } else { isSameAction = false } keyboardInfo = KeyboardInfo( animationDuration: animationDuration, animationCurve: animationCurve, frameBegin: frameBegin, frameEnd: frameEnd, heightIncrement: heightIncrement, action: action, isSameAction: isSameAction ) } } func keyboardWillShow(notification: NSNotification) { handleKeyboard(notification, .Show) } func keyboardWillChangeFrame(notification: NSNotification) { if let keyboardInfo = keyboardInfo { if keyboardInfo.action == .Show { handleKeyboard(notification, .Show) } } } func keyboardWillHide(notification: NSNotification) { handleKeyboard(notification, .Hide) } func keyboardDidHide(notification: NSNotification) { keyboardInfo = nil } }
mit
77d4f6cc149e9f0876ed14f87dd3e407
30.965909
174
0.602737
6.023555
false
false
false
false
redlock/SwiftyDeepstream
SwiftyDeepstream/Classes/deepstream/enums/Actions.swift
1
3671
// // Actions.swift // deepstreamSwiftTest // // Created by Redlock on 4/5/17. // Copyright © 2017 JiblaTech. All rights reserved. // import Foundation public enum Actions: String { case ERROR = "E" /** * A heartbeat ping from server */ case PING = "PI" /** * An heartbeat pong to server */ case PONG = "PO" /** * An acknowledgement from server */ case ACK = "A" /** * A connection redirect to allow client to connect to other deepstream * for load balancing */ case REDIRECT = "RED" /** * A connection challenge */ case CHALLENGE = "CH" /** * Connection challenge response */ case CHALLENGE_RESPONSE = "CHR" /** * A request or response containing record data for a snapshot or subscription */ case READ = "R" /** * A create to indicate record can be created if it doesn't exist */ case CREATE = "C" /** * A combination of both the create and read actions */ case CREATEORREAD = "CR" /** * An update, meaning all data in record has been updated */ case UPDATE = "U" /** * A path, meaning a specific part of data under a path has been * updated */ case PATCH = "P" /** * Delete a record / be informed a record has been deleted */ case DELETE = "D" /** * Used to subscribe to most things, including events, records * ( although records use CR ) and providing rpcs */ case SUBSCRIBE = "S" /** * Used to unsubscribe to anything that was previously subscribed to */ case UNSUBSCRIBE = "US" /** * Action to enquire if record actually exists on deepstream */ case HAS = "H" /** * Ask for the current state of a record */ case SNAPSHOT = "SN" /** * Used to inform the client listener that it has the opportunity to provide the data * for a event or record subscription */ case SUBSCRIPTION_FOR_PATTERN_FOUND = "SP" /** * Used to inform listener that it it is no longer required to provide the data for a * event or record subscription */ case SUBSCRIPTION_FOR_PATTERN_REMOVED = "SR" /** * Used to indicate if a record has a provider currently providing it data */ case SUBSCRIPTION_HAS_PROVIDER = "SH" /** * Inform the server that it the client is willing to provide any subscription matching * a pattern */ case LISTEN = "L" /** * Inform the server that it the client is no longer willing to provide any subscription * matching a pattern */ case UNLISTEN = "UL" /** * Inform the server the provider is willing to provide the subscription */ case LISTEN_ACCEPT = "LA" /** * Inform the server the provider is not willing to provide the subscription */ case LISTEN_REJECT = "LR" /** * Inform the client a remote event has occured */ case EVENT = "EVT" /** * A request to the server, used for RPC, authentication and connection */ case REQUEST = "REQ" /** * A response from the server for a request */ case RESPONSE = "RES" /** * Used to reject RPC requests */ case REJECTION = "REJ" /** * Called when a user logs in */ case PRESENCE_JOIN = "PNJ" /** * Called when a user logs out */ case PRESENCE_LEAVE = "PNL" /** * Used to query for clients */ case QUERY = "Q" /** * Used when requiring write acknowledgements when setting records */ case WRITE_ACKNOWLEDGEMENT = "WA" }
mit
4a8f6aa65752e8d5dced480672a078f7
24.310345
92
0.586376
4.146893
false
false
false
false
DigitalRogues/DisneyWatch
DisneyWatchApp Extension/ComplicationController.swift
1
5809
// // ComplicationController.swift // DisneyWatcher WatchKit Extension // // Created by punk on 9/19/15. // Copyright © 2015 Digital Rogues. All rights reserved. // import ClockKit class ComplicationController: NSObject, CLKComplicationDataSource { // MARK: - Timeline Configuration var lastUpdated = "" func getSupportedTimeTravelDirectionsForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTimeTravelDirections) -> Void) { handler([.None]) } func getTimelineStartDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) { let now = NSDate() handler(now) } func getTimelineEndDateForComplication(complication: CLKComplication, withHandler handler: (NSDate?) -> Void) { let now = NSDate() handler(now) } func getPrivacyBehaviorForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationPrivacyBehavior) -> Void) { handler(.ShowOnLockScreen) } // MARK: - Timeline Population func getCurrentTimelineEntryForComplication(complication: CLKComplication, withHandler handler: ((CLKComplicationTimelineEntry?) -> Void)) { // Call the handler with the current timeline entry let api = IndexGet() api.drGET(NSURL(string: "https://disney.digitalrecall.net/json")!) { (magicObj, error) -> Void in self.lastUpdated = magicObj!.lastUpdated let entry = self.createTimeLineEntry(magicObj!, compFamily: complication) handler(entry) } } func getTimelineEntriesForComplication(complication: CLKComplication, beforeDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) { // Call the handler with the timeline entries prior to the given date handler(nil) } func getTimelineEntriesForComplication(complication: CLKComplication, afterDate date: NSDate, limit: Int, withHandler handler: (([CLKComplicationTimelineEntry]?) -> Void)) { // Call the handler with the timeline entries after to the given date handler(nil) } // MARK: - Update Scheduling func getNextRequestedUpdateDateWithHandler(handler: (NSDate?) -> Void) { // Call the handler with the date when you would next like to be given the opportunity to update your complication content //runs 30 minutes after the time of the update so if update was at 10, it'll run at 10:30 then 11 then 11:30 etc let lastDate = NSDate(timeIntervalSince1970: Double(self.lastUpdated)!) let updateTime = lastDate + 30.minutes print(updateTime) handler(updateTime); } func requestedUpdateDidBegin() { print("requestedUpdated") let complicationServer = CLKComplicationServer.sharedInstance() for complication in complicationServer.activeComplications { complicationServer.reloadTimelineForComplication(complication) } } // MARK: - Placeholder Templates func getPlaceholderTemplateForComplication(complication: CLKComplication, withHandler handler: (CLKComplicationTemplate?) -> Void) { let dlrText = CLKSimpleTextProvider(text: "DLR:Loading...", shortText: "0") let dcaText = CLKSimpleTextProvider(text: "DCA:Loading...", shortText: "0") let temp = createTemplate(dlrText, dcaText: dcaText, compFamily: complication) handler(temp) } func createTimeLineEntry(magicObj:MagicIndexObject, compFamily:CLKComplication)->CLKComplicationTimelineEntry { let dlrText = CLKSimpleTextProvider(text: "DLR:\(magicObj.dlrIndex)", shortText: magicObj.dlrIndex) let dcaText = CLKSimpleTextProvider(text: "DCA:\(magicObj.dcaIndex)", shortText: magicObj.dcaIndex) print(dlrText) print(dcaText) let entTemplate = createTemplate(dlrText, dcaText:dcaText, compFamily: compFamily) // Create the entry. let entryDate = NSDate(timeIntervalSince1970: Double(magicObj.lastUpdated)!) let entry = CLKComplicationTimelineEntry(date: entryDate, complicationTemplate: entTemplate) return entry } func createTemplate(dlrText:CLKSimpleTextProvider, dcaText:CLKSimpleTextProvider, compFamily:CLKComplication) -> CLKComplicationTemplate{ var entTemplate = CLKComplicationTemplate() switch (compFamily.family) { case (.ModularLarge): let textTemplate = CLKComplicationTemplateModularLargeStandardBody() textTemplate.headerTextProvider = CLKSimpleTextProvider(text:"DisneyWatch") textTemplate.body1TextProvider = dlrText textTemplate.body2TextProvider = dcaText entTemplate = textTemplate case (.CircularSmall): let textTemplate = CLKComplicationTemplateCircularSmallStackText() textTemplate.line1TextProvider = dlrText textTemplate.line2TextProvider = dcaText entTemplate = textTemplate case (.UtilitarianSmall): let textTemplate = CLKComplicationTemplateUtilitarianSmallFlat() let string = "D:\(dlrText.shortText!) • C:\(dcaText.shortText!)" textTemplate.textProvider = CLKSimpleTextProvider(text: string) entTemplate = textTemplate default: print("somethings broke") } return entTemplate } func returnTopOfHour() -> NSDate{ let now = NSDate() let beginHour = now.beginningOfHour return beginHour } }
mit
ced1c8a7eaf7e566a9dcc41f9138a6de
38.496599
178
0.669997
5.370953
false
false
false
false
bermudadigitalstudio/Redshot
Sources/RedShot/ResponseParser.swift
1
3437
// // This source file is part of the RedShot open source project // // Copyright (c) 2017 Bermuda Digital Studio // Licensed under MIT // // See https://github.com/bermudadigitalstudio/Redshot/blob/master/LICENSE for license information // // Created by Laurent Gaches on 13/06/2017. // import Foundation class Parser { let bytes: [UInt8] var index = 0 init(bytes: [UInt8]) { self.bytes = bytes } func parse() throws -> RedisType { guard !bytes.isEmpty else { throw RedisError.emptyResponse } guard let typeIdentifier = TypeIdentifier(rawValue: bytes[index]) else { throw RedisError.typeUnknown } index += 1 switch typeIdentifier { case .error: var buffer = [UInt8]() while index < bytes.count, bytes[index] != Redis.cr { buffer.append(bytes[index]) index += 1 } let errorMessage = String(bytes: buffer, encoding: .utf8) print(errorMessage ?? "no error message") throw RedisError.response(errorMessage ?? "Unknown error") case .bulkString: var buffer = [UInt8]() while index < bytes.count, bytes[index] != Redis.cr { buffer.append(bytes[index]) index += 1 } guard let str = String(bytes: buffer, encoding: .utf8), let bulkSize = Int(str) else { throw RedisError.parseResponse } guard bulkSize > 0 else { index += 2 return NSNull() } index += 2 buffer.removeAll(keepingCapacity: true) while index < bytes.count, bytes[index] != Redis.cr { buffer.append(bytes[index]) index += 1 } guard let value = String(bytes: buffer, encoding: .utf8) else { throw RedisError.parseResponse } index += 2 return value case .simpleString: var buffer = [UInt8]() while index < bytes.count, bytes[index] != Redis.cr { buffer.append(bytes[index]) index += 1 } guard let value = String(bytes: buffer, encoding: .utf8) else { throw RedisError.parseResponse } return value case .integer: var buffer = [UInt8]() while index < bytes.count, bytes[index] != Redis.cr { buffer.append(bytes[index]) index += 1 } guard let strRepresentation = String(bytes: buffer, encoding: .utf8), let value = Int(strRepresentation) else { throw RedisError.parseResponse } return value case .array: var buffer = [UInt8]() while index < bytes.count, bytes[index] != Redis.cr { buffer.append(bytes[index]) index += 1 } guard let str = String(bytes: buffer, encoding: .utf8), let elementsCount = Int(str) else { throw RedisError.parseResponse } index += 2 var values = [RedisType]() for _ in 0..<elementsCount { values.append(try parse()) } return values } } }
mit
f1f89ecc66bf3596b808ae788595bfa1
28.886957
103
0.508874
4.747238
false
false
false
false
jtsmrd/Intrview
TableviewCells/InterviewTemplateDetailsCell.swift
1
1741
// // InterviewTemplateDetailsCell.swift // SnapInterview // // Created by JT Smrdel on 1/18/17. // Copyright © 2017 SmrdelJT. All rights reserved. // import UIKit protocol InterviewTemplateDetailsCellDelegate { func editInterviewtemplateDetails(interviewTemplate: InterviewTemplate) } class InterviewTemplateDetailsCell: UITableViewCell { @IBOutlet weak var interviewTitleLabel: UILabel! @IBOutlet weak var interviewDescriptionLabel: UILabel! @IBOutlet weak var editButton: UIButton! var interviewTemplate: InterviewTemplate! var delegate: InterviewTemplateDetailsCellDelegate! override func awakeFromNib() { super.awakeFromNib() backgroundColor = UIColor.clear } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func configureCell(interviewTemplate: InterviewTemplate, viewOnly: Bool) { self.interviewTemplate = interviewTemplate editButton.isHidden = viewOnly if let jobTitle = interviewTemplate.jobTitle { self.interviewTitleLabel.text = jobTitle } else { self.interviewTitleLabel.text = "Interview Title" } if let jobDescription = interviewTemplate.jobDescription { self.interviewDescriptionLabel.text = jobDescription } else { self.interviewDescriptionLabel.text = "Interview Description" } } @IBAction func editButtonAction(_ sender: Any) { delegate.editInterviewtemplateDetails(interviewTemplate: self.interviewTemplate) } }
mit
07fbfeb7e92206b0b337b170ebfc7fac
28
88
0.67931
4.860335
false
false
false
false
nathawes/swift
test/IRGen/big_types_generic.swift
8
2887
// RUN: %empty-directory(%t) // RUN: %swift -c -primary-file %s -enable-large-loadable-types -Xllvm -sil-print-after=loadable-address -sil-verify-all -o %t/big_types_generic.o 2>&1 | %FileCheck %s struct Big<T> { var a0 : T var a1 : T var a2 : T var a3 : T var a4 : T var a5 : T var a6 : T var a7 : T var a8 : T init(_ t: T) { a0 = t a1 = t a2 = t a3 = t a4 = t a5 = t a6 = t a7 = t a8 = t } } // CHECK-LABEL: sil hidden @$s17big_types_generic10nonGenericAA3BigVys5Int32VG_AGt_AGyctSgyF : $@convention(thin) () -> @out Optional<((Big<Int32>, Big<Int32>), @callee_guaranteed () -> @out Big<Int32>)> // CHECK: bb0(%0 : $*Optional<((Big<Int32>, Big<Int32>), @callee_guaranteed () -> @out Big<Int32>)>): // CHECK: [[ENUMCONSTRUCT:%.*]] = enum $Optional<((Big<Int32>, Big<Int32>), @callee_guaranteed () -> @out Big<Int32>)>, #Optional.none!enumelt // CHECK: store [[ENUMCONSTRUCT]] to %0 : $*Optional<((Big<Int32>, Big<Int32>), @callee_guaranteed () -> @out Big<Int32>)> // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '$s17big_types_generic10nonGenericAA3BigVys5Int32VG_AGt_AGyctSgyF' func nonGeneric() -> ((Big<Int32>, Big<Int32>), () -> Big<Int32>)? { return nil } // CHECK-LABEL: sil hidden @$s17big_types_generic11nonGeneric2AA3BigVys5Int32VG_AGt_AGyctyF : $@convention(thin) () -> (Big<Int32>, Big<Int32>, @owned @callee_guaranteed () -> @out Big<Int32>) // CHECK: bb0: // CHECK: [[TUPLECONSTRUCT:%.*]] = tuple (%{{.*}} : $Big<Int32>, %{{.*}} : $Big<Int32>, %{{.*}} : $@callee_guaranteed () -> @out Big<Int32>) // CHECK: return [[TUPLECONSTRUCT]] // CHECK-LABEL: } // end sil function '$s17big_types_generic11nonGeneric2AA3BigVys5Int32VG_AGt_AGyctyF' func nonGeneric2() -> ((Big<Int32>, Big<Int32>), () -> Big<Int32>) { return ((Big(1), Big(2)), { return Big(1) }) } func generic<T>(_ t: T) -> ((Big<T>, Big<T>), () -> Big<T>)? { return nil } func generic2<T>(_ t: T) -> ((Big<T>, Big<T>), () -> Big<T>) { return ((Big(t), Big(t)), { return Big(t) }) } // CHECK-LABEL: sil hidden @$s17big_types_generic8useStuffyyF : $@convention(thin) () -> () // CHECK: switch_enum_addr %{{.*}} : $*Optional<((Big<Int32>, Big<Int32>), @callee_guaranteed () -> @out Big<Int32>)>, case #Optional.some!enumelt // CHECK: switch_enum_addr %{{.*}} : $*Optional<((Big<Int32>, Big<Int32>), @callee_guaranteed () -> @out Big<Int32>)>, case #Optional.some!enumelt // CHECK: switch_enum %{{.*}} : $Optional<((Big<Int>, Big<Int>), @callee_guaranteed () -> @out Big<Int>)>, case #Optional.some!enumelt // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '$s17big_types_generic8useStuffyyF' func useStuff() { print(nonGeneric()!.0) print(nonGeneric()!.1) print(nonGeneric2().0) print(nonGeneric2().1) print(generic(1)!.0.0) print(generic(1)!.1) print(generic2(1).0) print(generic2(1).1) }
apache-2.0
c0aff3eacca5d9ceca14c5b2600036e4
40.84058
203
0.607897
2.78131
false
false
false
false
jopamer/swift
test/PrintAsObjC/enums.swift
1
5234
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -enable-source-import -emit-module -emit-module-doc -o %t %s -import-objc-header %S/Inputs/enums.h -disable-objc-attr-requires-foundation-module // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %t/enums.swiftmodule -typecheck -emit-objc-header-path %t/enums.h -import-objc-header %S/Inputs/enums.h -disable-objc-attr-requires-foundation-module // RUN: %FileCheck %s < %t/enums.h // RUN: %FileCheck -check-prefix=NEGATIVE %s < %t/enums.h // RUN: %check-in-clang %t/enums.h // RUN: %check-in-clang -fno-modules -Qunused-arguments %t/enums.h -include ctypes.h -include CoreFoundation.h // REQUIRES: objc_interop import Foundation // NEGATIVE-NOT: NSMalformedEnumMissingTypedef : // NEGATIVE-NOT: enum EnumNamed // CHECK-LABEL: enum FooComments : NSInteger; // CHECK-LABEL: enum NegativeValues : int16_t; // CHECK-LABEL: enum ObjcEnumNamed : NSInteger; // CHECK-LABEL: @interface AnEnumMethod // CHECK-NEXT: - (enum NegativeValues)takeAndReturnEnum:(enum FooComments)foo SWIFT_WARN_UNUSED_RESULT; // CHECK-NEXT: - (void)acceptPlainEnum:(enum NSMalformedEnumMissingTypedef)_; // CHECK-NEXT: - (enum ObjcEnumNamed)takeAndReturnRenamedEnum:(enum ObjcEnumNamed)foo SWIFT_WARN_UNUSED_RESULT; // CHECK-NEXT: - (void)acceptTopLevelImportedWithA:(enum TopLevelRaw)a b:(TopLevelEnum)b c:(TopLevelOptions)c d:(TopLevelTypedef)d e:(TopLevelAnon)e; // CHECK-NEXT: - (void)acceptMemberImportedWithA:(enum MemberRaw)a b:(enum MemberEnum)b c:(MemberOptions)c d:(enum MemberTypedef)d e:(MemberAnon)e ee:(MemberAnon2)ee; // CHECK: @end @objc class AnEnumMethod { @objc func takeAndReturnEnum(_ foo: FooComments) -> NegativeValues { return .Zung } @objc func acceptPlainEnum(_: NSMalformedEnumMissingTypedef) {} @objc func takeAndReturnRenamedEnum(_ foo: EnumNamed) -> EnumNamed { return .A } @objc func acceptTopLevelImported(a: TopLevelRaw, b: TopLevelEnum, c: TopLevelOptions, d: TopLevelTypedef, e: TopLevelAnon) {} @objc func acceptMemberImported(a: Wrapper.Raw, b: Wrapper.Enum, c: Wrapper.Options, d: Wrapper.Typedef, e: Wrapper.Anon, ee: Wrapper.Anon2) {} } // CHECK-LABEL: typedef SWIFT_ENUM_NAMED(NSInteger, ObjcEnumNamed, "EnumNamed", closed) { // CHECK-NEXT: ObjcEnumNamedA = 0, // CHECK-NEXT: ObjcEnumNamedB = 1, // CHECK-NEXT: ObjcEnumNamedC = 2, // CHECK-NEXT: ObjcEnumNamedD = 3, // CHECK-NEXT: ObjcEnumNamedHelloDolly = 4, // CHECK-NEXT: }; @objc(ObjcEnumNamed) enum EnumNamed: Int { case A, B, C, d, helloDolly } // CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, EnumWithNamedConstants, closed) { // CHECK-NEXT: kEnumA SWIFT_COMPILE_NAME("A") = 0, // CHECK-NEXT: kEnumB SWIFT_COMPILE_NAME("B") = 1, // CHECK-NEXT: kEnumC SWIFT_COMPILE_NAME("C") = 2, // CHECK-NEXT: }; @objc enum EnumWithNamedConstants: Int { @objc(kEnumA) case A @objc(kEnumB) case B @objc(kEnumC) case C } // CHECK-LABEL: typedef SWIFT_ENUM(unsigned int, ExplicitValues, closed) { // CHECK-NEXT: ExplicitValuesZim = 0, // CHECK-NEXT: ExplicitValuesZang = 219, // CHECK-NEXT: ExplicitValuesZung = 220, // CHECK-NEXT: }; // NEGATIVE-NOT: ExplicitValuesDomain @objc enum ExplicitValues: CUnsignedInt { case Zim, Zang = 219, Zung func methodNotExportedToObjC() {} } // CHECK: /// Foo: A feer, a female feer. // CHECK-NEXT: typedef SWIFT_ENUM(NSInteger, FooComments, closed) { // CHECK: /// Zim: A zeer, a female zeer. // CHECK-NEXT: FooCommentsZim = 0, // CHECK-NEXT: FooCommentsZang = 1, // CHECK-NEXT: FooCommentsZung = 2, // CHECK-NEXT: }; /// Foo: A feer, a female feer. @objc public enum FooComments: Int { /// Zim: A zeer, a female zeer. case Zim case Zang, Zung } // CHECK-LABEL: typedef SWIFT_ENUM(int16_t, NegativeValues, closed) { // CHECK-NEXT: Zang = -219, // CHECK-NEXT: Zung = -218, // CHECK-NEXT: }; @objc enum NegativeValues: Int16 { case Zang = -219, Zung func methodNotExportedToObjC() {} } // CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, SomeError, closed) { // CHECK-NEXT: SomeErrorBadness = 9001, // CHECK-NEXT: SomeErrorWorseness = 9002, // CHECK-NEXT: }; // CHECK-NEXT: static NSString * _Nonnull const SomeErrorDomain = @"enums.SomeError"; @objc enum SomeError: Int, Error { case Badness = 9001 case Worseness } // CHECK-LABEL: typedef SWIFT_ENUM(NSInteger, SomeOtherError, closed) { // CHECK-NEXT: SomeOtherErrorDomain = 0, // CHECK-NEXT: }; // NEGATIVE-NOT: NSString * _Nonnull const SomeOtherErrorDomain @objc enum SomeOtherError: Int, Error { case Domain // collision! } // CHECK-LABEL: typedef SWIFT_ENUM_NAMED(NSInteger, ObjcErrorType, "SomeRenamedErrorType", closed) { // CHECK-NEXT: ObjcErrorTypeBadStuff = 0, // CHECK-NEXT: }; // CHECK-NEXT: static NSString * _Nonnull const ObjcErrorTypeDomain = @"enums.SomeRenamedErrorType"; @objc(ObjcErrorType) enum SomeRenamedErrorType: Int, Error { case BadStuff } // CHECK-NOT: enum {{[A-Z]+}} // CHECK-LABEL: @interface ZEnumMethod // CHECK-NEXT: - (enum NegativeValues)takeAndReturnEnum:(enum FooComments)foo SWIFT_WARN_UNUSED_RESULT; // CHECK: @end @objc class ZEnumMethod { @objc func takeAndReturnEnum(_ foo: FooComments) -> NegativeValues { return .Zung } }
apache-2.0
b6d57e6993e06990cb4478e1388b1991
37.77037
229
0.716469
3.228871
false
false
false
false
networkextension/SFSocket
SFSocket/HTTPProxyServer/AdapterSocket.swift
1
4668
import Foundation open class AdapterSocket: NSObject, SocketProtocol, RawTCPSocketDelegate { open var request: ConnectRequest! open var response: ConnectResponse = ConnectResponse() open var observer: Observer<AdapterSocketEvent>? open let type: String open override var description: String { return "<\(type) host:\(request.host) port:\(request.port))>" } /** Connect to remote according to the `ConnectRequest`. - parameter request: The connect request. */ func openSocketWithRequest(_ request: ConnectRequest) { self.request = request observer?.signal(.socketOpened(self, withRequest: request)) socket?.delegate = self socket?.queue = queue state = .connecting } // MARK: SocketProtocol Implemention /// The underlying TCP socket transmitting data. open var socket: RawTCPSocketProtocol! /// The delegate instance. weak open var delegate: SocketDelegate? /// Every delegate method should be called on this dispatch queue. And every method call and variable access will be called on this queue. open var queue: DispatchQueue! { didSet { socket?.queue = queue } } /// The current connection status of the socket. open var state: SocketStatus = .invalid /// If the socket is disconnected. open var isDisconnected: Bool { return state == .closed || state == .invalid } override public init() { type = "\(type(of: self))" super.init() observer = ObserverFactory.currentFactory?.getObserverForAdapterSocket(self) } /** Read data from the socket. - parameter tag: The tag identifying the data in the callback delegate method. - warning: This should only be called after the last read is finished, i.e., `delegate?.didReadData()` is called. */ open func readDataWithTag(_ tag: Int) { socket?.readDataWithTag(tag) } /** Send data to remote. - parameter data: Data to send. - parameter tag: The tag identifying the data in the callback delegate method. - warning: This should only be called after the last write is finished, i.e., `delegate?.didWriteData()` is called. */ open func writeData(_ data: Data, withTag tag: Int) { socket?.writeData(data, withTag: tag) } // func readDataToLength(length: Int, withTag tag: Int) { // socket.readDataToLength(length, withTag: tag) // } // // func readDataToData(data: NSData, withTag tag: Int) { // socket.readDataToData(data, withTag: tag) // } /** Disconnect the socket elegantly. */ open func disconnect() { state = .disconnecting observer?.signal(.disconnectCalled(self)) socket?.disconnect() } /** Disconnect the socket immediately. */ open func forceDisconnect() { state = .disconnecting observer?.signal(.forceDisconnectCalled(self)) socket?.forceDisconnect() } // MARK: RawTCPSocketDelegate Protocol Implemention /** The socket did disconnect. - parameter socket: The socket which did disconnect. */ open func didDisconnect(_ socket: RawTCPSocketProtocol) { state = .closed observer?.signal(.disconnected(self)) delegate?.didDisconnect(self) } /** The socket did read some data. - parameter data: The data read from the socket. - parameter withTag: The tag given when calling the `readData` method. - parameter from: The socket where the data is read from. */ open func didReadData(_ data: Data, withTag tag: Int, from: RawTCPSocketProtocol) { observer?.signal(.readData(data, tag: tag, on: self)) } /** The socket did send some data. - parameter data: The data which have been sent to remote (acknowledged). Note this may not be available since the data may be released to save memory. - parameter withTag: The tag given when calling the `writeData` method. - parameter from: The socket where the data is sent out. */ open func didWriteData(_ data: Data?, withTag tag: Int, from: RawTCPSocketProtocol) { observer?.signal(.wroteData(data, tag: tag, on: self)) } /** The socket did connect to remote. - parameter socket: The connected socket. */ open func didConnect(_ socket: RawTCPSocketProtocol) { state = .established observer?.signal(.connected(self, withResponse: response)) delegate?.didConnect(self, withResponse: response) } }
bsd-3-clause
9855846b9510e4317e78182d25a951aa
29.913907
159
0.642674
4.630952
false
false
false
false
kysonyangs/ysbilibili
Pods/SwiftDate/Sources/SwiftDate/Region.swift
6
5207
// // SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones. // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - Region /// Region encapsulate information about the TimeZone, Calendar and Locale of an absolute time public struct Region: CustomStringConvertible { public fileprivate(set) var timeZone: TimeZone public fileprivate(set) var calendar: Calendar public fileprivate(set) var locale: Locale public var description: String { return "Region with timezone: \(self.timeZone), calendar: \(self.calendar), locale: \(self.locale)" } /// Initialize a new Region by passing `TimeZone`, `Calendar` and `Locale` objects /// /// - parameter tz: timezone to use /// - parameter cal: calendar to use /// - parameter loc: locale to use /// /// - returns: a new `Region` public init(tz: TimeZone, cal: Calendar, loc: Locale) { self.timeZone = tz self.calendar = cal self.calendar.timeZone = tz self.locale = loc } /// Initialize a new region by passing names for TimeZone, Calendar and Locale /// /// - parameter tz: timezone name to use (see `TimeZoneName`) /// - parameter cal: calendar name to use (see `CalendarName`) /// - parameter loc: locale name to use (see `LocaleName`) /// /// - returns: a new `Region` public init(tz: TimeZoneName, cal: CalendarName, loc: LocaleName) { self.timeZone = tz.timeZone self.calendar = cal.calendar self.calendar.timeZone = tz.timeZone self.locale = loc.locale } /// Initialize a new region by passing a `DateComponents` instance /// Region is created by reading object's `.timezone`, `.calendar` and `.calendar.locale` /// /// - parameter components: components to use /// /// - returns: a new `Region` public init?(components: DateComponents) { let tz = components.timeZone ?? TimeZoneName.current.timeZone let cal = components.calendar ?? CalendarName.gregorian.calendar let loc = cal.locale ?? LocaleName.current.locale self.init(tz: tz, cal: cal, loc: loc) } /// Generate a new region which uses `GMT` timezone and current's device `Calendar` and `Locale` /// /// - returns: a new `Region` public static func GMT() -> Region { let tz = TimeZoneName.gmt.timeZone let cal = CalendarName.current.calendar let loc = LocaleName.current.locale return Region(tz: tz, cal: cal, loc: loc) } /// Generate a new regione which uses current device's local settings (`Calendar`,`TimeZone` and `Locale`) /// /// - parameter auto: `true` to get automatically new settings when device's timezone/calendar/locale changes /// /// - returns: a new `Region` public static func Local(autoUpdate auto: Bool = true) -> Region { let tz = (auto ? TimeZoneName.currentAutoUpdating : TimeZoneName.current).timeZone let cal = (auto ? CalendarName.currentAutoUpdating : CalendarName.current).calendar let loc = (auto ? Locale.autoupdatingCurrent : Locale.current) return Region(tz: tz, cal: cal, loc: loc) } /// Identify the first weekday of the calendar. /// By default is `sunday`. public var firstWeekday: WeekDay { set { self.calendar.firstWeekday = newValue.rawValue } get { return WeekDay(rawValue: self.calendar.firstWeekday)! } } } // MARK: - Region Equatable Protocol extension Region: Equatable {} /// See if two regions are equal by comparing timezone, calendar and locale /// /// - parameter left: first region for comparision /// - parameter right: second region for comparision /// /// - returns: `true` if both region represent the same geographic/cultural location public func == (left: Region, right: Region) -> Bool { if left.calendar.identifier != right.calendar.identifier { return false } if left.timeZone.identifier != right.timeZone.identifier { return false } if left.locale.identifier != right.locale.identifier { return false } return true } // MARK: - Region Hashable Protocol extension Region: Hashable { public var hashValue: Int { return self.calendar.hashValue ^ self.timeZone.hashValue ^ self.locale.hashValue } }
mit
7edfaca8cf01a912f58980d02056c4df
33.483444
121
0.721913
3.834315
false
false
false
false
tellowkrinkle/Sword
Sources/Sword/Gateway/Payload.swift
1
1558
// // Payload.swift // Sword // // Created by Alejandro Alonso // Copyright © 2017 Alejandro Alonso. All rights reserved. // /// Payload Type struct Payload { // MARK: Properties /// OP Code for payload var op: Int /// Data for payload var d: Any /// Sequence number from payload let s: Int? /// Event name from payload let t: String? // MARK: Initializers /** Creates a payload from JSON String - parameter text: JSON String */ init(with text: String) { let data = text.decode() as! [String: Any] self.op = data["op"] as! Int self.d = data["d"]! self.s = data["s"] as? Int self.t = data["t"] as? String } /** Creates a payload from either an Array | Dictionary - parameter op: OP code to dispatch - parameter data: Either an Array | Dictionary to dispatch under the payload.d */ init(op: OP, data: Any) { self.op = op.rawValue self.d = data self.s = nil self.t = nil } /** Creates a payload from either an Array | Dictionary - parameter voiceOP: VoiceOP code to dispatch - parameter data: Either an Array | Dictionary to dispatch under the payload.d */ init(voiceOP: VoiceOP, data: Any) { self.op = voiceOP.rawValue self.d = data self.s = nil self.t = nil } // MARK: Functions /// Returns self as a String func encode() -> String { var payload = ["op": self.op, "d": self.d] if self.t != nil { payload["s"] = self.s! payload["t"] = self.t! } return payload.encode() } }
mit
b3641aa3840d230c55ef7a27d39d2fac
18.222222
81
0.598587
3.604167
false
false
false
false
BitBaum/Swift-Big-Integer
Benchmarks/Benchmarks.swift
1
6040
/* * ———————————————————————————————————————————————————————————————————————————— * Benchmarks.swift * ———————————————————————————————————————————————————————————————————————————— * Created by Marcel Kröker on 05.09.17. * Copyright © 2017 Marcel Kröker. All rights reserved. */ import Foundation public class Benchmarks { static func Matrix1() { let A = Matrix<BDouble>( [[2,5,-2], [3,5,6], [-55,4,3]] ) let G12 = Matrix<BDouble>([ [0.8, -0.6, 0.0], [0.6, 0.8, 0.0], [0.0, 0.0, 1.0] ]) let al = Matrix<BDouble>([4, -3, 1]) print(G12 * al) let (L, R, P, D) = LRDecompPivEquil(A) print(solveGauss(A, [2.0, -4.0, 15.0])) print(solveLR(A, [2.0, -4.0, 15.0])) print(solveLRPD(A, [2.0, -4.0, 15.0])) print("P L R") print(P) print(L) print(R) print("LR == PDA") print(L * R) print(P * D * A) benchmarkPrint(title: "Matix ^ 100") { var R = A for _ in 0...100 { R = R * A } } } static func BDoubleConverging() { benchmarkPrint(title: "BDouble converging to 2") { // BDouble converging to 2 Debug Mode // 06.02.16: 3351ms var res: BDouble = 0 var den: BInt = 1 for _ in 0..<1000 { res = res + BDouble(BInt(1), over: den) den *= 2 } } } static func factorial() { let n = 25_000 benchmarkPrint(title: "Factorial of 25000") { // Fkt 1000 Debug Mode // 27.01.16: 2548ms // 30.01.16: 1707ms // 01.02.16: 398ms // Fkt 2000 Debug Mode // 01.02.16: 2452ms // 04.02.16: 2708ms // 06.02.16: 328ms // Factorial 4000 Debug Mode // 06.02.16: 2669ms // 10.02.16: 571ms // 28.02.16: 550ms // 01.03.16: 56ms // Factorial 25000 Debug Mode // 01.03.16: 2871ms // 07.03.16: 2221ms // 16.08.16: 1759ms // 20.08.16: 1367ms _ = BInt(n).factorial() } } static func exponentiation() { let n = 10 let pow = 120_000 benchmarkPrint(title: "10^120_000") { // 10^14000 Debug Mode // 06.02.16: 2668ms // 10.02.16: 372ms // 20.02.16: 320ms // 28.02.16: 209ms // 01.03.16: 39ms // 10^120_000 Debug Mode // 01.03.16: 2417ms // 07.03.16: 1626ms // 16.08.16: 1154ms // 20.08.16: 922ms _ = BInt(n) ** pow } } static func fibonacci() { let n = 100_000 benchmarkPrint(title: "Fib \(n)") { // Fib 35.000 Debug Mode // 27.01.16: 2488ms // 30.01.16: 1458ms // 01.02.16: 357ms // Fib 100.000 Debug Mode // 01.02.16: 2733ms // 04.02.16: 2949ms // 10.02.16: 1919ms // 28.02.16: 1786ms // 07.03.16: 1716ms _ = BIntMath.fib(n) } } static func mersennes() { let n = 256 benchmarkPrint(title: "\nMersennes to 2^\(n)") { // Mersenne to exp 256 Debug Mode // 02.10.16: 1814ms for i in 1...n { if math.isPrime(i) && BIntMath.isMersenne(i) { print(i, terminator: ",") } } } } static func BIntToString() { let factorialBase = 15_000 let n = BInt(factorialBase).factorial() benchmarkPrint(title: "Get \(factorialBase)! as String") { // Get 300! (615 decimal digits) as String Debug Mode // 30.01.16: 2635ms // 01.02.16: 3723ms // 04.02.16: 2492m // 06.02.16: 2326ms // 07.02.16: 53ms // Get 1000! (2568 decimal digits) as String Debug Mode // 07.02.16: 2386ms // 10.02.16: 343ms // 20.02.16: 338ms // 22.02.16: 159ms // Get 3000! (9131 decimal digits) as String Debug Mode // 22.02.16: 2061ms // 28.02.16: 1891ms // 01.03.16: 343ms // Get 7500! (25809 decimal digits) as String Debug Mode // 01.03.16: 2558ms // 07.03.16: 1604ms // 07.03.16: 1562ms // 16.08.16: 455ms // Get 15000! (56130 decimal digits) as String Debug Mode // 07.09.17: 2701ms _ = n.description } } static func StringToBInt() { let factorialBase = 16_000 let asStr = BInt(factorialBase).factorial().description var res: BInt = 0 benchmarkPrint(title: "BInt from String, \(asStr.count) digits (\(factorialBase)!)") { // BInt from String, 3026 digits (1151!) Debug Mode // 07.02.16: 2780ms // 10.02.16: 1135ms // 28.02.16: 1078ms // 01.03.16: 430ms // BInt from String, 9131 digits (3000!) Debug Mode // 01.03.16: 3469ms // 07.03.16: 2305ms // 07.03.16: 1972ms // 26.06.16: 644ms // BInt from String, 20066 digits (6000!) Debug Mode // 26.06.16: 3040ms // 16.08.16: 2684ms // 20.08.16: 2338ms // BInt from String, 60320 digits (16000!) Debug Mode // 07.09.17: 2857ms // 26.04.18: 1081ms res = BInt(asStr)! } assert(asStr == res.description) } static func permutationsAndCombinations() { benchmarkPrint(title: "Perm and Comb") { // Perm and Comb (2000, 1000) Debug Mode // 04.02.16: 2561ms // 06.02.16: 2098ms // 07.02.16: 1083ms // 10.02.16: 350ms // 28.02.16: 337ms // 01.03.16: 138ms // Perm and Comb (8000, 4000) Debug Mode // 07.03.16: 905ms // 07.03.16: 483ms _ = BIntMath.permutations(8000, 4000) _ = BIntMath.combinations(8000, 4000) } } static func multiplicationBalanced() { benchmarkPrint(title: "Multiply two random BInts with size of 270_000 and 270_000 bits") { // Multiply two random BInts with size of 270_000 and 270_000 bits // 26.04.18: 2427ms let b1 = BIntMath.randomBInt(bits: 270_000) let b2 = BIntMath.randomBInt(bits: 270_000) _ = b1 * b2 } } static func multiplicationUnbalanced() { benchmarkPrint(title: "Multiply two random BInts with size of 70_000_000 and 1_000 bits") { // Multiply two random BInts with size of 70_000_000 and 1_000 bits // 26.04.18: 2467ms let b1 = BIntMath.randomBInt(bits: 70_000_000) let b2 = BIntMath.randomBInt(bits: 1_000) _ = b1 * b2 } } }
mit
db86663e5e95f04405755a6c4bd9f70d
18.5
91
0.565149
2.495864
false
false
false
false
renyufei8023/WeiBo
Pods/BSImagePicker/Pod/Classes/Extension/UIViewController+BSImagePicker.swift
1
2791
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import Photos /** Extension on UIViewController to simply presentation of BSImagePicker */ public extension UIViewController { /** Present a given image picker with closures, any of the closures can be nil. - parameter imagePicker: a BSImagePickerViewController to present - parameter animated: To animate the presentation or not - parameter select: Closure to call when user selects an asset or nil - parameter deselect: Closure to call when user deselects an asset or nil - parameter cancel: Closure to call when user cancels or nil - parameter finish: Closure to call when user finishes or nil - parameter completion: presentation completed closure or nil */ func bs_presentImagePickerController(imagePicker: BSImagePickerViewController, animated: Bool, select: ((asset: PHAsset) -> Void)?, deselect: ((asset: PHAsset) -> Void)?, cancel: (([PHAsset]) -> Void)?, finish: (([PHAsset]) -> Void)?, completion: (() -> Void)?) { BSImagePickerViewController.authorize(fromViewController: self) { (authorized) -> Void in // Make sure we are authorized before proceding guard authorized == true else { return } // Set blocks imagePicker.selectionClosure = select imagePicker.deselectionClosure = deselect imagePicker.cancelClosure = cancel imagePicker.finishClosure = finish // Present self.presentViewController(imagePicker, animated: animated, completion: completion) } } }
mit
c9d9710d16e77f26802d3ac00062ad2a
47.103448
267
0.698925
5.157116
false
false
false
false
smartmobilefactory/SMF-iOS-CommonProjectSetupFiles
HockeyApp/HockeySDK+SMFLogger.swift
1
5034
// // HockeySDK.swift // SMF-iOS-CommonProjectSetupFiles // // Created by Hanas Seiffert on 29/08/16. // Copyright (c) 2016 Smart Mobile Factory. All rights reserved. // import Foundation import HockeySDK import SMFLogger class HockeySDK: NSObject { // MARK: - Private static properties fileprivate static var shared : HockeySDK? fileprivate static let plistHockeyIDKey = "HockeyAppId" static let uiTestModeArgument = "SMF.UITestMode" fileprivate static let isDebugBuild : Bool = { #if DEBUG return true #else return false #endif }() // MARK: - Private properties fileprivate var isInitialized = false fileprivate var configuration : HockeySDK.Configuration? // MARK: - Public properties static var wasInitialized : Bool { return (HockeySDK.shared?.isInitialized ?? false) } // MARK: - Initialization init(configuration: HockeySDK.Configuration) { self.configuration = configuration super.init() HockeySDK.shared = self } // MARK: - Methods /// This will setup the HockeySDK with the common base configuration. Crashes will be detected if the app is build with the release build type and the `HockeyAppId` token taken from the info plists. /// /// - Parameters: /// - configuration: HockeySDK Configuration static func setup(_ configuration: HockeySDK.Configuration) { // Get the HockeyApp identifier let idFromConfiguration = configuration.hockeyAppID let idFromPlist = Bundle.main.object(forInfoDictionaryKey: HockeySDK.plistHockeyIDKey) as? String guard let _identifierKey = (idFromConfiguration ?? idFromPlist) else { assertionFailure("Error: You have to set the `\(HockeySDK.plistHockeyIDKey)` key in the info plist.") return } // Make sure HockeySDK is not setup in a debug build guard (self.isDebugBuild == false) else { // Configure HockeyApp only for non debug builds or if the exception flag is set to true return } let instance = (self.shared ?? HockeySDK(configuration: configuration)) BITHockeyManager.shared().configure(withIdentifier: _identifierKey, delegate: instance) if (CommandLine.arguments.contains(uiTestModeArgument)) { BITHockeyManager.shared().isUpdateManagerDisabled = true } BITHockeyManager.shared().start() BITHockeyManager.shared().authenticator.authenticateInstallation() BITHockeyManager.shared().crashManager.crashManagerStatus = configuration.crashManagerStatus instance.isInitialized = true } /// Modifies the crash mananger status. This method should be used to enable or disable crash reports during the app usage. /// /// - Parameters: /// - status: The `BITCrashManagerStatus` which determines whether crashes should be send to HockeyApp and whether it should be done automatically or manually by the user. The default value is `autoSend`. static func updateCrashManagerStatus(to status: BITCrashManagerStatus) { guard (self.shared?.isInitialized == true) else { assertionFailure("Error: You have to setup `HockeySDK` before updating the crash manager status. The update won't be performed.") return } BITHockeyManager.shared().crashManager.crashManagerStatus = status } /// This will create a `fatalError` to crash the app. static func performTestCrash() { guard (self.shared?.isInitialized == true) else { assertionFailure("Error: You have to setup `HockeySDK` before performing a test crash. The test crash won't be performed otherwise.") return } fatalError("This is a test crash to trigger a crash report in the HockeyApp") } } // MARK: - HockeySDK.Configuration extension HockeySDK { struct Configuration { fileprivate var hockeyAppID : String? fileprivate var crashManagerStatus : BITCrashManagerStatus fileprivate var enableSMFLogUpload : Bool fileprivate let smfLogUploadMaxSize : Int /// Initialized a HockeySDK Configuration /// /// - Parameters: /// - hockeyAppID: The app's hockeyAppID /// - crashManagerStatus: initial crash manager status /// - enableSMFLogUpload: true if you want the SMFLogger logs to be submitted with a crash /// - smfLogUploadMaxSize: The max count of characters which should be uploaded init(hockeyAppID: String? = nil, crashManagerStatus: BITCrashManagerStatus = .autoSend, enableSMFLogUpload: Bool = true, smfLogUploadMaxSize: Int = 5000) { self.hockeyAppID = hockeyAppID self.enableSMFLogUpload = enableSMFLogUpload self.smfLogUploadMaxSize = smfLogUploadMaxSize self.crashManagerStatus = crashManagerStatus } static var `default`: HockeySDK.Configuration { return Configuration() } } } // MARK: - BITHockeyManagerDelegate extension HockeySDK: BITHockeyManagerDelegate { func applicationLog(for crashManager: BITCrashManager!) -> String! { guard let configuration = self.configuration, (configuration.enableSMFLogUpload == true), let description = Logger.logFilesContent(maxSize: configuration.smfLogUploadMaxSize), (description.isEmpty == false) else { return nil } return description } }
mit
e800fbfc544dad229160dbbe1bcc879a
31.063694
207
0.748709
3.988906
false
true
false
false
iphone4peru/ejercicios_videos_youtube
SpotLightSearch/SpotLightSearch/SpotlightSearchManager.swift
1
1046
// // SpotlightSearchManager.swift // SpotLightSearch // // Created by Christian Quicano on 12/6/15. // Copyright © 2015 iphone4peru. All rights reserved. // import Foundation import UIKit import CoreSpotlight import MobileCoreServices class SpotlightSearchManager { class func addUserToSearch(identifier:String, user:User){ let atributos = CSSearchableItemAttributeSet(itemContentType: (kUTTypeData as String)) atributos.title = user.nombre atributos.thumbnailData = UIImagePNGRepresentation(UIImage(named: user.nombreFoto)!) atributos.phoneNumbers = [user.numeroTelefono] atributos.supportsPhoneCall = 1 let item = CSSearchableItem(uniqueIdentifier: identifier, domainIdentifier: "com.iphone4peru", attributeSet: atributos) CSSearchableIndex.defaultSearchableIndex().indexSearchableItems([item], completionHandler: nil) } } struct User { var nombre = "" var profesion = "" var nombreFoto = "" var numeroTelefono = "" }
gpl-2.0
154a426e919fcc585dd17d61605f2f3f
27.27027
127
0.708134
4.3361
false
false
false
false
Adorkable/APIBaseiOS
Sources/NSError+Utility.swift
1
2367
// // NSError+Utility.swift // APIBase // // Created by Ian Grossberg on 7/26/15. // Copyright © 2015 Adorkable. All rights reserved. // import Foundation public let NSFunctionErrorKey = "FunctionError" public let NSLineErrorKey = "LineError" extension NSError { // TODO: support NSLocalizedString // TODO: support Recovery Attempter static func userInfo(_ description : String, underlyingError : NSError? = nil, failureReason : String? = nil, recoverySuggestion : String? = nil, recoveryOptions : [String]? = nil, fileName : String = #file, functionName : String = #function, line : Int = #line) -> [String : AnyObject] { var userInfo = [ NSFilePathErrorKey : fileName, NSFunctionErrorKey : functionName, NSLineErrorKey : NSNumber(value: line as Int), NSLocalizedDescriptionKey : description ] as [String : Any] if let underlyingError = underlyingError { userInfo[NSUnderlyingErrorKey] = underlyingError } if let failureReason = failureReason { userInfo[NSLocalizedFailureReasonErrorKey] = failureReason } if let recoverySuggestion = recoverySuggestion { userInfo[NSLocalizedRecoverySuggestionErrorKey] = recoverySuggestion } if let recoveryOptions = recoveryOptions { userInfo[NSLocalizedRecoveryOptionsErrorKey] = recoveryOptions } return userInfo as [String : AnyObject] } convenience init(domain : String? = nil, code : Int = 0, description : String, underlyingError : NSError? = nil, failureReason : String? = nil, recoverySuggestion : String? = nil, recoveryOptions : [String]? = nil, fileName : String = #file, functionName : String = #function, line : Int = #line) { let useDomain : String if let domain = domain { useDomain = domain } else { useDomain = description } let userInfo = NSError.userInfo(description, underlyingError: underlyingError, failureReason: failureReason, recoverySuggestion: recoverySuggestion, recoveryOptions: recoveryOptions, fileName: fileName, functionName: functionName, line: line) self.init(domain: useDomain, code: 0, userInfo: userInfo) } }
mit
a35bea1238993be60d91878b03b4bc57
38.433333
302
0.645816
5.304933
false
false
false
false
pengwei1024/swiftSamples
swiftstudy/swiftstudy/main.swift
1
3090
// // main.swift // swiftstudy // // Created by baidu on 15/8/26. // Copyright (c) 2015年 apkfuns. All rights reserved. // import Foundation println("Hello, World!") // let来声明常量,var来声明变量 let a = "abc" var b = 123 // 指定变量类型 var c :Double = 20 // 显式转换 let lable = "hello world!" let width = 12 let string = lable + String(width) println(string) // 变量输出\() var height = 20.5 var a1 = "the price= \(height)" println(a1) // 字典和数组 var array1 = ["aa","bb","cc"] println("array1[1]= \(array1[1])") // 数组赋值 array1[2] = "dd"; println("array1[2]= \(array1[2])") // 字典 var array2 = ["a":"aaa","b":"bbb"] println(array2["b"]) // ??? 输出这个Optional("bbb") // 空数组 var array3 = [] var array4 = [String]() var array5 = [String:Float]() // ???这是什么情况 // 控制流 let intArray = [1,2,3,4,5,6,7,8,9] for num in intArray { if num % 2 == 0 { //println("双数") }else{ //println("单数") } } var optionString: String? = "hello" println(optionString == nil) // optionString: String? 默认赋值为nil if let name = optionString { println("\(name) pw") }else{ println("it's nil") } // switch语句,必须包含default,不需要break let abc = "a" switch(abc){ case "a": println("a") case "b": println("b") default: println("c") } //遍历字典 let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25], ] for (key, value) in interestingNumbers{ print("key=\(key)=>") for num in value{ print(num) } println() } // for循环 ,不能用i++,只能++i for var i = 0;i<10;++i{ print(i) } // 第二种写法 for i in 0..<10{ print(i) } // 拓展写法,包含10 for i in 0...10{ print(i) } //////////////////函数定义/////////////// // 函数定义 func getUser(name:String , age:Int) -> String{ return "name=\(name);age=\(age)" } println(getUser("pengwei", 18)) // 函数返回多个值 func calculateStatistics(scores:[Int])->(min:Int,max:Int,sum:Int){ var max = scores[0] var min = scores[0] var sum = 0 for score in scores{ if score > max { max = score }else if score < min{ min = score } sum += score } return (min, max, sum) } var scores = calculateStatistics([5, 3, 100, 3, 9]) println("max=\(scores.max);sum=\(scores.2)") // 函数可变参数 func numSum(sums:Int...)->Int{ var sum = 0 for num in sums { sum += num } return sum } println(numSum(1,2,3,4,5)) // 练习:计算平均数 func average(nums:Int...)->Float{ var num = nums.count var sum = nums.reduce(0, combine: +) // 可变参数函数调用求解决方案!!!! // var sum = numSum(nums) return Float(sum/num) } println(average(1,2,3,4,5)) // 格式化,参考:http://blog.csdn.net/remote_roamer/article/details/7166043 var string1 = NSString(format:"name=%@,age=%d", "pw", 123) println(string1)
apache-2.0
970e5b72537f3cba9ce8999c6e525a86
16.935897
68
0.560758
2.743137
false
false
false
false
srn214/Floral
Floral/Floral/Classes/Expand/ThirdParty/ZCycleView/ZCycleView.swift
1
22621
// // ZCycleView.swift // ZCycleView // // Created by mengqingzheng on 2017/11/17. // Copyright © 2017年 MQZHot. All rights reserved. // import UIKit // modify by LeeYZ @objc public protocol ZCycleViewProtocol { /// scrollToIndex /// /// - Parameter index: index @objc func cycleViewDidScrollToIndex(_ index: Int) /// selectedIndex /// /// - Parameter index: index @objc func cycleViewDidSelectedIndex(_ index: Int) // ----------------------------------- custom cell ------------------------------ /// cell identifier /// add by LeeYZ /// get custom cell reuse identifier , default is 'ZCycleViewCell' @objc optional func customCollectionViewCellIdentifier() -> String /// customCell register with class /// add by LeeYZ /// custom collectionViewCell with class @objc optional func customCollectionViewCellClassForCycleScrollView() -> AnyClass /// customCell register with nib /// add by LeeYZ /// custom collectionViewCell with nib @objc optional func customCollectionViewCellNibForCycleScrollView() -> UINib /// setup data for customCell /// add by LeeYZ /// setup customCell @objc optional func setupCustomCell(_ cell: UICollectionViewCell, for index: NSInteger, cycleView: ZCycleView) } public class ZCycleView: UIView { /// cell identifier /// add by LeeYZ private var reuseIdentifier: String = "ZCycleViewCell" /// isAutomatic public var isAutomatic: Bool = true /// isInfinite public var isInfinite: Bool = true { didSet { if isInfinite == false { itemsCount = realDataCount <= 1 || !isInfinite ? realDataCount : realDataCount*200 collectionView.reloadData() collectionView.setContentOffset(.zero, animated: false) dealFirstPage() } } } /// scroll timeInterval public var timeInterval: Int = 2 /// scrollDirection public var scrollDirection: UICollectionView.ScrollDirection = .horizontal { didSet { flowLayout.scrollDirection = scrollDirection } } /// placeholderImage public var placeholderImage: UIImage? = nil { didSet { placeholderImgView.image = placeholderImage } } // MARK: - set image or image url or text // you can also set the desc `titlesGroup` or `attributedTitlesGroup`, pick one of two, `attributedTitlesGroup` first /// set local image public func setImagesGroup(_ imagesGroup: Array<UIImage?>, titlesGroup: [String?]? = nil, attributedTitlesGroup: [NSAttributedString?]? = nil) { if imagesGroup.count == 0 { return } resourceType = .image realDataCount = imagesGroup.count self.imagesGroup = imagesGroup setResource(titlesGroup, attributedTitlesGroup: attributedTitlesGroup) } /// set image url public func setUrlsGroup(_ urlsGroup: Array<String>, titlesGroup: [String?]? = nil, attributedTitlesGroup: [NSAttributedString?]? = nil) { if urlsGroup.count == 0 { return } resourceType = .imageURL realDataCount = urlsGroup.count self.imageUrlsGroup = urlsGroup setResource(titlesGroup, attributedTitlesGroup: attributedTitlesGroup) } /// set text public func setTitlesGroup(_ titlesGroup: Array<String?>?, attributedTitlesGroup: [NSAttributedString?]? = nil) { if attributedTitlesGroup == nil && titlesGroup == nil { return } resourceType = .text if attributedTitlesGroup != nil { if attributedTitlesGroup!.count == 0 { return } realDataCount = attributedTitlesGroup!.count } else { if titlesGroup!.count == 0 { return } realDataCount = titlesGroup!.count } setResource(titlesGroup, attributedTitlesGroup: attributedTitlesGroup) } // MARK: - If you want the effect in the picture below, use the following method // Special reminder, be sure to set the size, otherwise the picture does not display /// set image on title's left public func setTitleImagesGroup(_ titleImagesGroup: [UIImage?], sizeGroup:[CGSize?]) { self.titleImagesGroup = titleImagesGroup self.titleImageSizeGroup = sizeGroup collectionView.reloadData() } /// set image url on title's left public func setTitleImageUrlsGroup(_ titleImageUrlsGroup: [String?], sizeGroup:[CGSize?]) { self.titleImageUrlsGroup = titleImageUrlsGroup self.titleImageSizeGroup = sizeGroup collectionView.reloadData() } // MARK: - item setting /// The size of the item, the default cycleView size public var itemSize: CGSize? { didSet { if resourceType == .text { return } if let itemSize = itemSize { let width = min(bounds.size.width, itemSize.width) let height = min(bounds.size.height, itemSize.height) flowLayout.itemSize = CGSize(width: width, height: height) } } } /// The scale of the center item 中间item的放大比例 public var itemZoomScale: CGFloat = 1 { didSet { collectionView.isPagingEnabled = itemZoomScale == 1 if resourceType == .text { return } flowLayout.scale = itemZoomScale } } /// The space of items -- item 间距 public var itemSpacing: CGFloat = 0 { didSet { if resourceType == .text { itemSpacing = 0; return } flowLayout.minimumLineSpacing = itemSpacing } } /// item CornerRadius public var itemCornerRadius: CGFloat = 0 /// item BorderColor public var itemBorderColor: UIColor = UIColor.clear /// item BorderWidth public var itemBorderWidth: CGFloat = 0 // MARK: - imageView Setting /// content Mode of item's image public var imageContentMode: UIView.ContentMode = .scaleToFill // MARK: - titleLabel setting /// The height of the desc containerView, if you set the left image, is also included public var titleViewHeight: CGFloat = 25 /// titleAlignment public var titleAlignment: NSTextAlignment = .left /// desc font public var titleFont: UIFont = UIFont.systemFont(ofSize: 13) /// The backgroundColor of the desc containerView public var titleBackgroundColor: UIColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5) /// titleColor public var titleColor: UIColor = UIColor.white /// The number of lines of text displayed public var titleNumberOfLines = 1 /// The breakMode of lines of text displayed public var titleLineBreakMode: NSLineBreakMode = .byWordWrapping // MARK: - PageControl setting /// Whether to hide pageControl, the default `false` public var pageControlIsHidden = false { didSet { pageControl.isHidden = pageControlIsHidden } } /// Dot color, the default `gray` public var pageControlIndictirColor = UIColor.gray { didSet { pageControl.pageIndicatorTintColor = pageControlIndictirColor } } /// Current dot color, the default `white` public var pageControlCurrentIndictirColor = UIColor.white { didSet { pageControl.currentPageIndicatorTintColor = pageControlCurrentIndictirColor } } /// The current dot image public var pageControlCurrentIndictorImage: UIImage? { didSet { pageControl.currentDotImage = pageControlCurrentIndictorImage } } /// The dot image public var pageControlIndictorImage: UIImage? { didSet { pageControl.dotImage = pageControlIndictorImage } } /// The height of pageControl, default `25` public var pageControlHeight: CGFloat = 25 { didSet { pageControl.frame = CGRect(x: 0, y: frame.size.height-pageControlHeight, width: frame.size.width, height: pageControlHeight) // pageControl.updateFrame() } } /// PageControl's backgroundColor public var pageControlBackgroundColor = UIColor.clear { didSet { pageControl.backgroundColor = pageControlBackgroundColor } } /// The size of all dots public var pageControlItemSize = CGSize(width: 8, height: 8) { didSet { pageControl.dotSize = pageControlItemSize } } /// The size of current dot public var pageControlCurrentItemSize: CGSize? { didSet { pageControl.currentDotSize = pageControlCurrentItemSize } } /// The space of dot public var pageControlSpacing: CGFloat = 8 { didSet { pageControl.spacing = pageControlSpacing } } /// pageControl Alignment, left/right/center , default `center` public var pageControlAlignment: ZPageControlAlignment = .center { didSet { pageControl.alignment = pageControlAlignment } } /// the radius of dot public var pageControlItemRadius: CGFloat? { didSet { pageControl.dotRadius = pageControlItemRadius } } /// the radius of current dot public var pageControlCurrentItemRadius: CGFloat? { didSet { pageControl.currentDotRadius = pageControlCurrentItemRadius } } // MARK: - closure // Click and scroll events are in the form of closures /// delegate public var delegate: ZCycleViewProtocol? { didSet { /// add by LeeYZ if delegate != nil { registerCell() } } } /// 点击了item public var didSelectedItem: ((Int)->())? /// 滚动到某一位置 public var didScrollToIndex: ((Int)->())? // --- end --------- //============================================= fileprivate var flowLayout: ZCycleLayout! fileprivate var collectionView: UICollectionView! fileprivate var placeholderImgView: UIImageView! fileprivate var pageControl: ZPageControl! fileprivate var imagesGroup: Array<UIImage?> = [] fileprivate var imageUrlsGroup: Array<String> = [] fileprivate var titlesGroup: [NSAttributedString?] = [] fileprivate var titleImagesGroup: Array<UIImage?> = [] fileprivate var titleImageUrlsGroup: Array<String?> = [] fileprivate var titleImageSizeGroup: Array<CGSize?> = [] fileprivate var timer: Timer? fileprivate var itemsCount: Int = 0 fileprivate var realDataCount: Int = 0 fileprivate var resourceType: ResourceType = .image override public init(frame: CGRect) { super.init(frame: frame) addPlaceholderImgView() addCollectionView() addPageControl() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addPlaceholderImgView() addCollectionView() addPageControl() } private func addPlaceholderImgView() { placeholderImgView = UIImageView(frame: CGRect.zero) placeholderImgView.image = placeholderImage addSubview(placeholderImgView) placeholderImgView.translatesAutoresizingMaskIntoConstraints = false let hCons = NSLayoutConstraint.constraints(withVisualFormat: "H:|[placeholderImgView]|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["placeholderImgView": placeholderImgView]) let vCons = NSLayoutConstraint.constraints(withVisualFormat: "V:|[placeholderImgView]|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["placeholderImgView": placeholderImgView]) addConstraints(hCons) addConstraints(vCons) } private func addCollectionView() { flowLayout = ZCycleLayout() flowLayout.itemSize = itemSize != nil ? itemSize! : bounds.size flowLayout.minimumInteritemSpacing = 10000 flowLayout.minimumLineSpacing = itemSpacing flowLayout.scrollDirection = scrollDirection collectionView = UICollectionView(frame: bounds, collectionViewLayout: flowLayout) collectionView.backgroundColor = UIColor.clear collectionView.bounces = false collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false collectionView.delegate = self collectionView.dataSource = self collectionView.scrollsToTop = false collectionView.decelerationRate = UIScrollView.DecelerationRate(rawValue: 0.0) // collectionView.isPagingEnabled = true registerCell() addSubview(collectionView) } /// add by LeeYZ private func registerCell() { if let customReuseIdentifier = delegate?.customCollectionViewCellIdentifier?() { self.reuseIdentifier = customReuseIdentifier } if let customClass = delegate?.customCollectionViewCellClassForCycleScrollView?() { collectionView.register(customClass, forCellWithReuseIdentifier: reuseIdentifier) } else if let customNib = delegate?.customCollectionViewCellNibForCycleScrollView?() { collectionView.register(customNib, forCellWithReuseIdentifier: reuseIdentifier) } else { collectionView.register(ZCycleViewCell.self, forCellWithReuseIdentifier: reuseIdentifier) } } private func addPageControl() { pageControl = ZPageControl(frame: CGRect(x: 0, y: bounds.size.height - pageControlHeight, width: bounds.size.width, height: pageControlHeight)) addSubview(pageControl) } override public func willMove(toWindow newWindow: UIWindow?) { super.willMove(toWindow: newWindow) if newWindow != nil { self.startTimer() } else { self.cancelTimer() } } public override func layoutSubviews() { super.layoutSubviews() flowLayout.itemSize = itemSize != nil ? itemSize! : bounds.size collectionView.frame = bounds pageControl.frame = CGRect(x: 0, y: frame.size.height-pageControlHeight, width: frame.size.width, height: pageControlHeight) collectionView.setContentOffset(.zero, animated: false) dealFirstPage() } private func setResource(_ titlesGroup: Array<String?>?, attributedTitlesGroup: [NSAttributedString?]?) { placeholderImgView.isHidden = true itemsCount = realDataCount <= 1 || !isInfinite ? realDataCount : realDataCount*200 if attributedTitlesGroup != nil { self.titlesGroup = attributedTitlesGroup ?? [] } else { let titles = titlesGroup?.map { return NSAttributedString(string: $0 ?? "") } self.titlesGroup = titles ?? [] } collectionView.reloadData() collectionView.setContentOffset(.zero, animated: false) dealFirstPage() pageControl.numberOfPages = realDataCount pageControl.isHidden = realDataCount == 1 pageControl.currentPage = currentIndex() % realDataCount if resourceType == .text {pageControl.isHidden = true} if isAutomatic { startTimer() } } } // MARK: - UICollectionViewDataSource / UICollectionViewDelegate extension ZCycleView: UICollectionViewDelegate, UICollectionViewDataSource { public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return itemsCount } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { /// modify by LeeYZ let cycleCell = collectionView.dequeueReusableCell(withReuseIdentifier: self.reuseIdentifier, for: indexPath) let index = indexPath.item % realDataCount /// add by LeeYZ if self.delegate?.setupCustomCell?(cycleCell, for: index, cycleView: self) != nil { // 在代码方法中配置自定义cell return cycleCell } /// modify by LeeYZ guard let cell = cycleCell as? ZCycleViewCell else { return cycleCell } switch resourceType { case .image: cell.imageView.image = imagesGroup[index] case .imageURL: cell.imageUrl(imageUrlsGroup[index], placeholder: placeholderImage) case .text: break } if resourceType != .text { cell.layer.borderWidth = itemBorderWidth cell.layer.borderColor = itemBorderColor.cgColor cell.layer.cornerRadius = itemCornerRadius cell.layer.masksToBounds = true } /// --------------------title setting----------------------- /// cell.titleContainerViewH = resourceType == .text ? collectionView.bounds.size.height : titleViewHeight cell.titleLabel.textAlignment = titleAlignment cell.titleContainerView.backgroundColor = titleBackgroundColor cell.titleLabel.font = titleFont cell.titleLabel.numberOfLines = titleNumberOfLines cell.titleLabel.textColor = titleColor let title = index < titlesGroup.count ? titlesGroup[index] : nil let titleImage = index < titleImagesGroup.count ? titleImagesGroup[index] : nil let titleImageUrl = index < titleImageUrlsGroup.count ? titleImageUrlsGroup[index] : nil let titleImageSize = index < titleImageSizeGroup.count ? titleImageSizeGroup[index] : nil cell.attributeString(title, titleImgURL: titleImageUrl, titleImage: titleImage, titleImageSize: titleImageSize) /// --------------imgView setting---------------------------- /// cell.imageView.contentMode = imageContentMode return cell } public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let centerViewPoint = convert(collectionView.center, to: collectionView) if let centerIndex = collectionView.indexPathForItem(at: centerViewPoint) { if indexPath.item == centerIndex.item { let index = indexPath.item % realDataCount if delegate != nil { delegate?.cycleViewDidSelectedIndex(index) } else { if didSelectedItem != nil { didSelectedItem!(index) } } } else { collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true) } } } } // MARK: - UIScrollViewDelegate extension ZCycleView { public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { if isAutomatic { cancelTimer() } dealLastPage() dealFirstPage() } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if isAutomatic { startTimer() } } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { scrollViewDidEndScrollingAnimation(scrollView) } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { let index = currentIndex() % realDataCount pageControl?.currentPage = index if delegate != nil { delegate?.cycleViewDidScrollToIndex(index) } else { if didScrollToIndex != nil { didScrollToIndex!(index) } } } public func scrollViewDidScroll(_ scrollView: UIScrollView) { pageControl?.currentPage = currentIndex() % realDataCount } } // MARK: - deal the first page and last page extension ZCycleView { fileprivate func dealFirstPage() { if currentIndex() == 0 && itemsCount > 1 && isInfinite { let targetIndex = itemsCount / 2 let scrollPosition: UICollectionView.ScrollPosition = scrollDirection == .horizontal ? .centeredHorizontally : .centeredVertically collectionView.scrollToItem(at: IndexPath(item: targetIndex, section: 0), at: scrollPosition, animated: false) if didScrollToIndex != nil { didScrollToIndex!(0) } } } fileprivate func dealLastPage() { if currentIndex() == itemsCount-1 && itemsCount > 1 && isInfinite { let targetIndex = itemsCount / 2 - 1 let scrollPosition: UICollectionView.ScrollPosition = scrollDirection == .horizontal ? .centeredHorizontally : .centeredVertically collectionView.scrollToItem(at: IndexPath(item: targetIndex, section: 0), at: scrollPosition, animated: false) } } } // MARK: - timer extension ZCycleView { fileprivate func startTimer() { if !isAutomatic { return } if itemsCount <= 1 { return } cancelTimer() timer = Timer.init(timeInterval: Double(timeInterval), target: self, selector: #selector(timeRepeat), userInfo: nil, repeats: true) RunLoop.main.add(timer!, forMode: .common) } fileprivate func cancelTimer() { if timer != nil { timer?.invalidate() timer = nil } } @objc func timeRepeat() { let current = currentIndex() var targetIndex = current + 1 if (current == itemsCount - 1) { if isInfinite == false {return} dealLastPage() targetIndex = itemsCount / 2 } let scrollPosition: UICollectionView.ScrollPosition = scrollDirection == .horizontal ? .centeredHorizontally : .centeredVertically collectionView.scrollToItem(at: IndexPath(item: targetIndex, section: 0), at: scrollPosition, animated: true) } fileprivate func currentIndex() -> Int { let itemWH = scrollDirection == .horizontal ? flowLayout.itemSize.width+itemSpacing : flowLayout.itemSize.height+itemSpacing let offsetXY = scrollDirection == .horizontal ? collectionView.contentOffset.x : collectionView.contentOffset.y // contentOffset changes /(ㄒoㄒ)/~~ ?????????? if itemWH == 0 { return 0 } let index = round(offsetXY / itemWH) return Int(index) } }
mit
a6f20f4cc3a7dd2ad79c4461c73458f2
40.007273
151
0.632881
5.445196
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Read/View/CoverView.swift
1
17781
// // CoverView.swift // WePeiYang // // Created by Allen X on 10/27/16. // Copyright © 2016 Qin Yubo. All rights reserved. // let readRed = UIColor(red: 237.0/255.0, green: 84.0/255.0, blue: 80.0/255.0, alpha: 1.0) let computedBGViewHeight = UIScreen.mainScreen().bounds.height * 0.52 let computedBGViewWidth = UIScreen.mainScreen().bounds.width class CoverView: UIView { var book: Book! var coverView: UIImageView! var computedBGView: UIView! var titleLabel: UILabel! var authorLabel: UILabel! var publisherLabel: UILabel! var yearLabel: UILabel! var scoreLabel: UILabel! var favBtn: UIButton! var reviewBtn: UIButton! var starReviewLabel: UILabel! var summaryLabel: UILabel! var summaryTitleLabel: UILabel! var tapToSeeMoreBtn: UIButton! convenience init(book: Book) { self.init() self.backgroundColor = UIColor(red: 250.0/255.0, green: 250.0/255.0, blue: 250.0/255.0, alpha: 1) self.book = book coverView = { $0.contentMode = UIViewContentMode.ScaleAspectFit $0.sizeToFit() $0.layer.masksToBounds = false; $0.layer.shadowOffset = CGSizeMake(-15, 15); $0.layer.shadowRadius = 10; $0.layer.shadowOpacity = 0.5; return $0 }(UIImageView()) computedBGView = UIView() //coverView.setImageWithURL(NSURL(string: book.coverURL)) titleLabel = { $0.font = UIFont.boldSystemFontOfSize(24) $0.numberOfLines = 1 return $0 }(UILabel(text: book.title, color: .blackColor())) authorLabel = { //$0.font = UIFont.boldSystemFontOfSize(14) $0.font = UIFont.systemFontOfSize(14) return $0 }(UILabel(text: "作者:"+book.author, color: .grayColor())) publisherLabel = { //$0.font = UIFont.boldSystemFontOfSize(14) $0.font = UIFont.systemFontOfSize(14) return $0 }(UILabel(text: "出版社:"+book.publisher, color: .grayColor())) yearLabel = { //$0.font = UIFont.boldSystemFontOfSize(14) $0.font = UIFont.systemFontOfSize(14) return $0 }(UILabel(text: "出版时间:"+book.year, color: .grayColor())) //Gotta refine it scoreLabel = { $0.font = UIFont(name: "Menlo-BoldItalic", size: 60) return $0 }(UILabel(text: "\(book.rating)", color: readRed)) favBtn = UIButton(title: "收藏", borderWidth: 1.5, borderColor: readRed) favBtn.addTarget(self, action: #selector(self.favourite), forControlEvents: .TouchUpInside) reviewBtn = UIButton(title: "写书评", borderWidth: 1.5, borderColor: readRed) //reviewBtn.addTarget(self, action: #selector(self.presentReviewWritingView), forControlEvents: .TouchUpInside) reviewBtn.addTarget(self, action: #selector(self.presentRateView), forControlEvents: .TouchUpInside) starReviewLabel = { //TODO: DO OTHER UI MODIFICATIONS $0.font = UIFont.boldSystemFontOfSize(20) return $0 }(UILabel(text: "This is a very great book", color: .grayColor())) summaryTitleLabel = { $0.font = UIFont.systemFontOfSize(12) return $0 }(UILabel(text: "图书简介", color: .grayColor())) summaryLabel = { //TODO: DO OTHER UI MODIFICATIONS & Click to read more $0.numberOfLines = 7 $0.font = UIFont.systemFontOfSize(15) return $0 }(UILabel(text: book.summary, color: .grayColor())) tapToSeeMoreBtn = { $0.addTarget(self, action: #selector(self.tapToSeeMore), forControlEvents: .TouchUpInside) $0.setTitleColor(readRed, forState: .Normal) $0.titleLabel!.font = UIFont.systemFontOfSize(15) return $0 }(UIButton(title: "点击查看更多")) //let img = UIImage(named: "cover4") // let imageURL = NSURL(string: book.coverURL) // let fuckStr = book.coverURL.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! let fuckStr = book.coverURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! let fuckURL = NSURL(string: fuckStr) let imageRequest = NSURLRequest(URL: fuckURL!) coverView.setImageWithURLRequest(imageRequest, placeholderImage: nil, success: { (_, _, img) in if img.size.height > img.size.width { self.coverView.image = UIImage.resizedImageKeepingRatio(img, scaledToWidth: UIScreen.mainScreen().bounds.width / 2) } else { self.coverView.image = UIImage.resizedImageKeepingRatio(img, scaledToHeight: UIScreen.mainScreen().bounds.height * 0.52 * 0.6) } let fooRGB = self.coverView.image?.smartAvgRGB() self.computedBGView.backgroundColor = UIColor(red: (fooRGB?.red)!, green: (fooRGB?.green)!, blue: (fooRGB?.blue)!, alpha: (fooRGB?.alpha)!) // //NavigationBar 的背景,使用了View // UIViewController.currentViewController().navigationController!.jz_navigationBarBackgroundAlpha = 0; // let bgView = UIView(frame: CGRect(x: 0, y: 0, width: UIViewController.currentViewController().view.frame.size.width, height: UIViewController.currentViewController().navigationController!.navigationBar.frame.size.height+UIApplication.sharedApplication().statusBarFrame.size.height)) // UIViewController.currentViewController().navigationController?.navigationBar.tintColor = .whiteColor() // bgView.backgroundColor = self.computedBGView.backgroundColor //// log.any(self.computedBGView.backgroundColor)/ //// log.any(bgView.backgroundColor)/ // UIViewController.currentViewController().view.addSubview(bgView) }) { (_, _, _) in guard let img = UIImage(named: "placeHolderImageForBookCover") else { self.coverView.backgroundColor = .grayColor() self.computedBGView.backgroundColor = .grayColor() //NavigationBar 的背景,使用了View UIViewController.currentViewController().navigationController!.jz_navigationBarBackgroundAlpha = 0; let bgView = UIView(frame: CGRect(x: 0, y: 0, width: UIViewController.currentViewController().view.frame.size.width, height: UIViewController.currentViewController().navigationController!.navigationBar.frame.size.height+UIApplication.sharedApplication().statusBarFrame.size.height)) UIViewController.currentViewController().navigationController?.navigationBar.tintColor = .whiteColor() bgView.backgroundColor = self.computedBGView.backgroundColor // log.any(self.computedBGView.backgroundColor)/ // log.any(bgView.backgroundColor)/ UIViewController.currentViewController().view.addSubview(bgView) return } self.coverView.image = img let fooRGB = self.coverView.image?.smartAvgRGB() self.computedBGView.backgroundColor = UIColor(red: (fooRGB?.red)!, green: (fooRGB?.green)!, blue: (fooRGB?.blue)!, alpha: (fooRGB?.alpha)!) //NavigationBar 的背景,使用了View UIViewController.currentViewController().navigationController!.jz_navigationBarBackgroundAlpha = 0; let bgView = UIView(frame: CGRect(x: 0, y: 0, width: UIViewController.currentViewController().view.frame.size.width, height: UIViewController.currentViewController().navigationController!.navigationBar.frame.size.height+UIApplication.sharedApplication().statusBarFrame.size.height)) UIViewController.currentViewController().navigationController?.navigationBar.tintColor = .whiteColor() bgView.backgroundColor = self.computedBGView.backgroundColor // log.any(self.computedBGView.backgroundColor)/ // log.any(bgView.backgroundColor)/ UIViewController.currentViewController().view.addSubview(bgView) } //Can't do it outside the Asynchronous Closure // let fooRGB = coverView.image?.smartAvgRGB() // computedBGView.backgroundColor = UIColor(red: (fooRGB?.red)!, green: (fooRGB?.green)!, blue: (fooRGB?.blue)!, alpha: (fooRGB?.alpha)!) computedBGView.addSubview(coverView) coverView.snp_makeConstraints { make in make.center.equalTo(computedBGView.center) } self.addSubview(computedBGView) computedBGView.snp_makeConstraints { make in make.top.equalTo(self) make.left.equalTo(self) make.right.equalTo(self) make.height.equalTo(computedBGViewHeight) } self.addSubview(titleLabel) titleLabel.snp_makeConstraints { make in make.left.equalTo(self).offset(20) make.width.lessThanOrEqualTo(248) make.top.equalTo(computedBGView.snp_bottom).offset(20) } self.addSubview(authorLabel) authorLabel.snp_makeConstraints { make in make.left.equalTo(titleLabel) make.top.equalTo(titleLabel.snp_bottom).offset(14) } self.addSubview(scoreLabel) scoreLabel.snp_makeConstraints { make in make.centerY.equalTo(authorLabel) make.right.equalTo(self).offset(-20) } self.addSubview(publisherLabel) publisherLabel.snp_makeConstraints { make in make.left.equalTo(titleLabel) make.top.equalTo(authorLabel.snp_bottom).offset(4) make.right.lessThanOrEqualTo(scoreLabel.snp_left).offset(-10) } self.addSubview(yearLabel) yearLabel.snp_makeConstraints { make in make.left.equalTo(titleLabel) make.top.equalTo(publisherLabel.snp_bottom).offset(4) } self.addSubview(favBtn) favBtn.snp_makeConstraints { make in make.left.equalTo(yearLabel) make.top.equalTo(yearLabel).offset(38) make.width.equalTo(100) make.height.equalTo(36) } self.addSubview(reviewBtn) reviewBtn.snp_makeConstraints { make in make.top.equalTo(favBtn) make.right.equalTo(self.snp_right).offset(-20) make.width.equalTo(100) make.height.equalTo(36) } self.addSubview(summaryTitleLabel) summaryTitleLabel.snp_makeConstraints { make in make.top.equalTo(favBtn.snp_bottom).offset(28) make.left.equalTo(favBtn) } self.addSubview(summaryLabel) summaryLabel.snp_makeConstraints { make in make.top.equalTo(summaryTitleLabel.snp_bottom).offset(20) make.left.equalTo(summaryTitleLabel) make.right.equalTo(reviewBtn) } self.addSubview(tapToSeeMoreBtn) tapToSeeMoreBtn.snp_makeConstraints { make in make.top.equalTo(summaryLabel.snp_bottom).offset(4) make.left.equalTo(summaryLabel) } self.snp_makeConstraints { make in make.width.equalTo(UIScreen.mainScreen().bounds.width) //make.height.equalTo(UIScreen.mainScreen().bounds.height + 100) make.bottom.equalTo(tapToSeeMoreBtn.snp_bottom).offset(18) } } } private extension UIButton { convenience init(title: String, borderWidth: CGFloat, borderColor: UIColor) { self.init() setTitle(title, forState: .Normal) setTitleColor(borderColor, forState: .Normal) titleLabel?.font = UIFont.boldSystemFontOfSize(18) //titleLabel?.sizeToFit() tintColor = borderColor //TODO: self-sizing UIButton with Snapkit // frame.size = CGSize(width: ((titleLabel?.frame.width)! + 60), height: ((titleLabel?.frame.height)! + 20)) // print((titleLabel?.frame.width)! + 50) //let titleSize = NSString(string: title).sizeWithAttributes(<#T##attrs: [String : AnyObject]?##[String : AnyObject]?#>) //sizeThatFits(CGSize(width: ((titleLabel?.frame.width)! + 50), height: ((titleLabel?.frame.height)! + 20))) self.layer.cornerRadius = 3 self.layer.borderWidth = borderWidth self.layer.borderColor = borderColor.CGColor } } extension CoverView: UIWebViewDelegate { func presentRateView() { let rateView = RateView(rating: 3.0, id: "\(book.id)") //self.addSubview(rateView) // UIViewController.currentViewController().view.addSubview(rateView) // rateView.snp_makeConstraints { // make in // make.height.equalTo(UIScreen.mainScreen().bounds.height) // make.width.equalTo(UIScreen.mainScreen().bounds.width) // make.top.equalTo(UIViewController.currentViewController().view) // make.left.equalTo(UIViewController.currentViewController().view) // } // UIViewController.currentViewController().navigationview.addSubview(rateView) //UIViewController.currentViewController().navigationController?.view.addSubview(rateView) UIViewController.currentViewController().view.addSubview(rateView) //rateView.superview!.bringSubviewToFront(rateView) UIViewController.currentViewController().navigationItem.setHidesBackButton(true, animated: true) rateView.frame = CGRect(x: 0, y: self.frame.height, width: 0, height: self.frame.height/4) UIView.beginAnimations("ratingViewPopUp", context: nil) UIView.setAnimationDuration(0.6) rateView.frame = self.frame UIView.commitAnimations() } override func willRemoveSubview(subview: UIView) { UIViewController.currentViewController().navigationItem.setHidesBackButton(false, animated: true) } func favourite() { User.sharedInstance.addToFavourite(with: "\(self.book.id)") { MsgDisplay.showSuccessMsg("添加成功") } //Call `favourite` method of a user } func tapToSeeMore() { let blurEffect = UIBlurEffect(style: .Light) let frostView = UIVisualEffectView(effect: blurEffect) let doneBtn: UIButton = { $0.addTarget(self, action: #selector(self.tapAgainToDismiss), forControlEvents: .TouchUpInside) $0.setTitleColor(readRed, forState: .Normal) return $0 }(UIButton(title: "完成")) UIViewController.currentViewController().navigationItem.setHidesBackButton(true, animated: true) frostView.frame = self.frame frostView.addSubview(doneBtn) doneBtn.snp_makeConstraints { make in make.left.equalTo(frostView).offset(20) make.top.equalTo(frostView).offset(100) } UIViewController.currentViewController().view.addSubview(frostView) // frostView.snp_makeConstraints { // make in // make.left.equalTo(UIViewController.currentViewController().view) // make.right.equalTo(UIViewController.currentViewController().view) // make.top.equalTo(UIViewController.currentViewController().view) // make.bottom.equalTo(UIViewController.currentViewController().view) // } let summaryDetailView = UIWebView(htmlString: book.summary) frostView.addSubview(summaryDetailView) //summaryDetailView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height) summaryDetailView.snp_makeConstraints { make in make.top.equalTo(doneBtn.snp_bottom).offset(20) make.left.equalTo(frostView).offset(20) make.right.equalTo(frostView).offset(-20) make.bottom.equalTo(frostView) } summaryDetailView.alpha = 0 UIView.beginAnimations("summaryDetailViewFadeIn", context: nil) UIView.setAnimationDuration(0.6) summaryDetailView.alpha = 1 UIView.commitAnimations() // let tap = UITapGestureRecognizer(target: self, action: #selector(self.tapAgainToDismiss)) // summaryDetailView.addGestureRecognizer(tap) } func tapAgainToDismiss() { for fooView in (UIViewController.currentViewController().view.subviews) { if fooView.isKindOfClass(UIVisualEffectView) { UIView.animateWithDuration(0.7, animations: { fooView.alpha = 0 }, completion: { (_) in UIViewController.currentViewController().navigationItem.setHidesBackButton(false, animated: true) fooView.removeFromSuperview() }) } } } } private extension UIWebView { convenience init(htmlString: String) { self.init() backgroundColor = .clearColor() opaque = false userInteractionEnabled = true scrollView.scrollEnabled = true loadHTMLString(htmlString, baseURL: nil) } }
mit
8acd2cd4a6003494c47017e612650aee
42.527094
298
0.619964
4.762059
false
false
false
false
lieonCX/Live
Live/View/Home/SearchViewController.swift
1
17374
// // SearchViewController.swift // Live // // Created by fanfans on 2017/7/12. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // import UIKit import RxSwift import RxCocoa import CoreData class SearchViewController: BaseViewController { fileprivate var searchVM: SearchViewModel = SearchViewModel() fileprivate var inputTF: UITextField = UITextField() fileprivate lazy var searchBtn: UIButton = { let searchBtn = UIButton() searchBtn.frame = CGRect(x: 0, y: 20, width: 44, height: 44) searchBtn.setImage(UIImage(named: "home_nav_search_white"), for: .normal) searchBtn.addTarget(self, action: #selector(self.searchTapAction), for: .touchUpInside) return searchBtn }() fileprivate lazy var cancelBtn: UIButton = { let cancelBtn = UIButton() cancelBtn.frame = CGRect(x:UIScreen.width - 44, y: 20, width: 44, height: 44) cancelBtn.setTitle("取消", for: .normal) cancelBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14) cancelBtn.setTitleColor(UIColor.white, for: .normal) cancelBtn.addTarget(self, action: #selector(self.cancelTapAction), for: .touchUpInside) return cancelBtn }() fileprivate lazy var inputNavView: UIView = {[unowned self] in let inputNavView = UIView(frame: CGRect(x: 0, y: 64, width: UIScreen.main.bounds.width - 88, height: 44)) let inputbgView: UIView = UIView(frame: CGRect(x: 0, y: 7, width: UIScreen.main.bounds.width - 150, height: 30)) inputbgView.backgroundColor = UIColor(hex: 0x333333) inputbgView.layer.cornerRadius = 30 * 0.5 inputbgView.layer.masksToBounds = true inputNavView.addSubview(inputbgView) self.inputTF = UITextField(frame: CGRect(x: 23, y: 0, width: 140, height: 30)) self.inputTF.font = UIFont.systemFont(ofSize: 14) self.inputTF.placeholder = "输入昵称/ID" self.inputTF.returnKeyType = .search self.inputTF.delegate = self self.inputTF.textColor = .white self.inputTF.setValue(UIColor(hex: 0x999999), forKeyPath: "_placeholderLabel.textColor") inputbgView.addSubview(self.inputTF) return inputNavView }() fileprivate lazy var tableView: UITableView = { let taleView = UITableView() taleView.separatorStyle = .none taleView.backgroundColor = UIColor(hex: 0xfafafa) taleView.register(AttentionAndFansListCell.self, forCellReuseIdentifier: "AttentionAndFansListCell") taleView.register(SearchHistoryCell.self, forCellReuseIdentifier: "SearchHistoryCell") taleView.register(ClearAllHistoryCell.self, forCellReuseIdentifier: "ClearAllHistoryCell") return taleView }() fileprivate lazy var userListTableView: UITableView = { let userListTableView = UITableView() userListTableView.separatorStyle = .none userListTableView.backgroundColor = UIColor(hex: 0xfafafa) userListTableView.register(AttentionAndFansListCell.self, forCellReuseIdentifier: "AttentionAndFansListCell") return userListTableView }() fileprivate lazy var coverBtn: UIButton = { let btn = UIButton() btn.backgroundColor = UIColor.black.withAlphaComponent(0.3) btn.isHidden = true return btn }() fileprivate var isFirstLoad: Bool = true override func viewDidLoad() { super.viewDidLoad() configUI() loadRecomandList() getSearchHistoryArr() isFirstLoad = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if isFirstLoad { isFirstLoad = false inputTF.becomeFirstResponder() } } } extension SearchViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { inputTF.resignFirstResponder() coverBtn.isHidden = true search(text: textField.text) return true } } extension SearchViewController { fileprivate func configUI() { tableView.dataSource = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell") tableView.register(AttentionAndFansListCell.self, forCellReuseIdentifier: "AttentionAndFansListCell") view.backgroundColor = UIColor.white navigationItem.titleView = inputNavView self.inputTF.addTarget(self, action: #selector(self.textfieldEditing(textfield:)), for: .editingChanged) let leftBtnItem = UIBarButtonItem(customView: searchBtn) navigationItem.leftBarButtonItem = leftBtnItem let rightBtnItem = UIBarButtonItem(customView: cancelBtn) navigationItem.rightBarButtonItem = rightBtnItem tableView.delegate = self view.addSubview(tableView) userListTableView.dataSource = self userListTableView.delegate = self view.addSubview(userListTableView) view.addSubview(coverBtn) tableView.allowsSelection = true tableView.snp.makeConstraints { (maker) in maker.top.equalTo(0) maker.left.equalTo(0) maker.right.equalTo(0) maker.bottom.equalTo(0) } userListTableView.snp.makeConstraints { (maker) in maker.top.equalTo(0) maker.left.equalTo(0) maker.right.equalTo(0) maker.bottom.equalTo(0) } userListTableView.isHidden = true coverBtn.snp.makeConstraints { (maker) in maker.top.equalTo(0) maker.left.equalTo(0) maker.right.equalTo(0) maker.bottom.equalTo(0) } coverBtn.rx.tap .subscribe(onNext: { [weak self] in self?.inputTF.resignFirstResponder() self?.coverBtn.isHidden = true }) .disposed(by: disposeBag) inputTF.rx.text .orEmpty .map { $0.characters.isEmpty } .bind(to: coverBtn.rx.isHidden) .disposed(by: disposeBag) } @objc fileprivate func textfieldEditing(textfield: UITextField) { if let text = textfield.text { if text.characters.isEmpty { self.userListTableView.isHidden = true self.tableView.isHidden = false } } } @objc fileprivate func searchTapAction() { coverBtn.isHidden = true search(text: inputTF.text) } @objc fileprivate func cancelTapAction() { inputTF.resignFirstResponder() navigationController?.popViewController(animated: true) } fileprivate func loadRecomandList() { HUD.show(true, show: "", enableUserActions: true, with: self) searchVM.requestRecommendList() .then { [unowned self] (usermodels) -> Void in self.searchVM.recommendUses = usermodels self.tableView.reloadData() } .always { HUD.show(false, show: "", enableUserActions: true, with: self) } .catch { _ in } } fileprivate func getSearchHistoryArr() { searchVM.getSearchHistory() .then { (historys) -> Void in self.searchVM.history = historys print(self.searchVM.history) self.tableView.reloadData() }.catch { (_) in } } fileprivate func search(text: String?) { let param = LiveListRequstParam() param.keywords = text HUD.show(true, show: "", enableUserActions: true, with: self) searchVM.requestSearchuUser(param: param) .then { [unowned self] (usermodels) -> Void in if !usermodels.isEmpty { } self.searchVM.searchedUses = usermodels if let name = param.keywords { self.searchVM.saveSearchHistory(name) } self.userListTableView.reloadData() self.userListTableView.isHidden = false self.tableView.isHidden = true } .always { HUD.show(false, show: "", enableUserActions: true, with: self) } .catch { [unowned self] (error) in if let error = error as? AppError { self.view.makeToast(error.message) } } } } extension SearchViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if tableView == self.userListTableView { let vc = UserInfoDetailsController() guard let model = searchVM.searchedUses?[indexPath.row] else {return} vc.anchorID = model.userId navigationController?.pushViewController(vc, animated: true) return } if searchVM.history.isEmpty || indexPath.section == 1 { let vc = UserInfoDetailsController() guard let model = searchVM.recommendUses?[indexPath.row] else {return} vc.anchorID = model.userId navigationController?.pushViewController(vc, animated: true) } else { if indexPath.row == searchVM.history.count {//清除历史搜索记录 searchVM.clearHistory() self.getSearchHistoryArr() } else { self.inputTF.text = searchVM.history[indexPath.row] self.search(text: searchVM.history[indexPath.row]) } } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 32 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let sectionView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 32)) sectionView.backgroundColor = UIColor(hex: 0xfafafa) let tipsLable: UILabel = UILabel(frame: CGRect(x: 10, y: 0, width: UIScreen.width - 10, height: 32)) if searchVM.history.isEmpty || section == 1 { tipsLable.text = "您可能感兴趣的用户" } else { tipsLable.text = "近期搜索" } if tableView == self.userListTableView { tipsLable.text = "共搜索到\(self.searchVM.searchedUsersCount)个人" } tipsLable.font = UIFont.systemFont(ofSize: 12) tipsLable.textColor = UIColor(hex:0x999999) sectionView.addSubview(tipsLable) return sectionView } } extension SearchViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { if tableView == self.userListTableView { return 1 } return searchVM.history.isEmpty ? 1 : 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == self.userListTableView { return searchVM.searchedUses?.count ?? 0 } if section == 0 { if searchVM.history.isEmpty { return searchVM.recommendUses?.count ?? 0 } return searchVM.history.count + 1 } else { return searchVM.recommendUses?.count ?? 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView == self.userListTableView { let cell: AttentionAndFansListCell = tableView.dequeueReusableCell(forIndexPath: indexPath) cell.selectionStyle = .none guard let element = searchVM.searchedUses?[indexPath.row] else {return UITableViewCell()} cell.config(element) cell.attentAction = { weak var weaSelf = self guard let weakSelf = weaSelf else { return } let attentVM = RoomViewModel() let param = CollectionRequstParam() param.userId = element.userId if element.isFollowed { /// 取消关注 attentVM.cancleCollectionLiver(with: param) .then(execute: { _ -> Void in self.view.makeToast("取消关注成功") if let inputText = weakSelf.inputTF.text, inputText.isEmpty { weakSelf.loadRecomandList() } else { weakSelf.search(text: weakSelf.inputTF.text) } }).catch(execute: { (error) in if let error = error as? AppError { weakSelf.view.makeToast(error.message) } }) } else { /// 关注 attentVM.collectionLiver(with: param) .then(execute: { _ -> Void in self.view.makeToast("关注成功") if let inputText = weakSelf.inputTF.text, inputText.isEmpty { weakSelf.loadRecomandList() } else { weakSelf.search(text: weakSelf.inputTF.text) } }).catch(execute: { (error) in if let error = error as? AppError { weakSelf.view.makeToast(error.message) } }) } } return cell } if searchVM.history.isEmpty || indexPath.section == 1 { let cell: AttentionAndFansListCell = tableView.dequeueReusableCell(forIndexPath: indexPath) cell.selectionStyle = .none guard let element = searchVM.recommendUses?[indexPath.row] else {return UITableViewCell()} cell.config(element) cell.attentAction = { weak var weaSelf = self guard let weakSelf = weaSelf else { return } let attentVM = RoomViewModel() let param = CollectionRequstParam() param.userId = element.userId if element.isFollowed { /// 取消关注 attentVM.cancleCollectionLiver(with: param) .then(execute: { _ -> Void in self.view.makeToast("取消关注成功") if let inputText = weakSelf.inputTF.text, inputText.isEmpty { weakSelf.loadRecomandList() } else { weakSelf.search(text: weakSelf.inputTF.text) } }).catch(execute: { (error) in if let error = error as? AppError { weakSelf.view.makeToast(error.message) } }) } else { /// 关注 attentVM.collectionLiver(with: param) .then(execute: { _ -> Void in self.view.makeToast("关注成功") if let inputText = weakSelf.inputTF.text, inputText.isEmpty { weakSelf.loadRecomandList() } else { weakSelf.search(text: weakSelf.inputTF.text) } }).catch(execute: { (error) in if let error = error as? AppError { weakSelf.view.makeToast(error.message) } }) } } return cell } if indexPath.section == 0 { if indexPath.row == searchVM.history.count { let cell: ClearAllHistoryCell = tableView.dequeueReusableCell(forIndexPath: indexPath) cell.selectionStyle = .none return cell } else { let cell: SearchHistoryCell = tableView.dequeueReusableCell(forIndexPath: indexPath) cell.nameLable.text = searchVM.history[indexPath.row] cell.selectionStyle = .none return cell } } return UITableViewCell() } } extension SearchViewController: UIScrollViewDelegate { func scrollViewDidScroll(_ scrollView: UIScrollView) { self.inputTF.resignFirstResponder() } }
mit
d8e5cac719958687ed4a3e20e27cfa0e
40.147971
120
0.555478
5.158887
false
false
false
false
danielrhodes/Swift-ActionCableClient
Source/Classes/Error.swift
3
3025
// // Copyright (c) 2016 Daniel Rhodes <[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 enum SerializationError : Swift.Error { case json case encoding case protocolViolation } public enum ReceiveError : Swift.Error { case invalidIdentifier case unknownChannel case decoding case invalidFormat case unknownMessageType } public enum TransmitError : Swift.Error { case notConnected case notSubscribed } public enum ConnectionError : Swift.Error { case notFound(Error) case goingAway(Error) case refused(Error) case sslHandshake(Error) case unknownDomain(Error) case closed(Error) case protocolViolation(Error) case unknown(Error) case none var recoverable : Bool { switch self { case .notFound: return false case .goingAway: return false case .refused: return true case .sslHandshake: return false case .unknownDomain: return false case .protocolViolation: return false case .closed: return false case .unknown: return true case .none: return false } } init(from error: Swift.Error) { switch error._code { case 2: self = ConnectionError.unknownDomain(error) case 61: self = ConnectionError.refused(error) case 404: self = ConnectionError.notFound(error) case 1000: self = ConnectionError.closed(error) case 1002: self = ConnectionError.protocolViolation(error) case 1003: self = ConnectionError.protocolViolation(error) case 1005: self = ConnectionError.unknown(error) case 1007: self = ConnectionError.protocolViolation(error) case 1008: self = ConnectionError.protocolViolation(error) case 1009: self = ConnectionError.protocolViolation(error) case 9847: self = ConnectionError.sslHandshake(error) default: self = ConnectionError.unknown(error) } } }
mit
f14dd49edef9f590441a9cb5d70e3a12
34.174419
79
0.709752
4.528443
false
false
false
false
leftdal/youslow
iOS/YouSlow/Controllers/VideoTableDataSource.swift
1
2163
// // VideoTableDataSource.swift // Demo // // Created by to0 on 2/12/15. // Copyright (c) 2015 to0. All rights reserved. // import UIKit class VideoTableDataSource: NSObject, UITableViewDataSource, UITableViewDelegate { var videoList = VideoList() func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return videoList.numberOfVideos() } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 120; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("VideoListCell", forIndexPath: indexPath) as! VideoItemViewCell let row = indexPath.row cell.titleLabel?.text = videoList.videoTitleOfIndex(row) cell.detailLabel?.text = videoList.videoDescriptionOfIndex(row) cell.thumbnailView?.contentMode = UIViewContentMode.ScaleAspectFill // cell.thumbnailView?.image = UIImage(named: "grey") let url = NSURL(string: videoList.videoThumbnailOfIndex(row)) let request: NSURLRequest = NSURLRequest(URL: url!) let urlConnection: NSURLConnection = NSURLConnection(request: request, delegate: self)! NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in if error == nil { let img: UIImage? = UIImage(data: data!) if img != nil { dispatch_async(dispatch_get_main_queue(), { cell.thumbnailView?.image = img! }) } } }) return cell } }
gpl-3.0
d478e980a8aff8c5e5dfa664d8e5e045
38.345455
183
0.649098
5.25
false
false
false
false
openHPI/xikolo-ios
Binge/Media Selection/BingeMediaSelectionViewController.swift
1
10129
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import AVFoundation import UIKit class BingeMediaSelectionViewController: UITableViewController { private let mediaCharacteristics: [AVMediaCharacteristic] = [.audible, .legible] private weak var delegate: (BingeMediaSelectionDataSource & BingeMediaSelectionDelegate & BingePlaybackRateDelegate)? init(delegate: BingeMediaSelectionDataSource & BingeMediaSelectionDelegate & BingePlaybackRateDelegate) { self.delegate = delegate if #available(iOS 13, *) { super.init(style: .insetGrouped) } else { super.init(style: .grouped) } self.view.backgroundColor = UIColor(white: 0.2, alpha: 1.0) self.tableView.separatorColor = UIColor(white: 0.2, alpha: 1.0) self.tableView.allowsMultipleSelection = true } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = BingeLocalizedString("media-option-selection.navigation-bar.title", comment: "navigation bar title for the media option selection") self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(close)) self.tableView.register(BingePlaybackRateCell.self, forCellReuseIdentifier: BingePlaybackRateCell.identifier) self.tableView.register(BingeMediaOptionCell.self, forCellReuseIdentifier: BingeMediaOptionCell.identifier) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.selectCurrentOptions(animated: animated) } @objc private func close() { self.navigationController?.dismiss(animated: trueUnlessReduceMotionEnabled) { self.delegate?.didCloseMediaSelection() } } private func selectCurrentOptions(animated: Bool) { for section in 0..<self.numberOfSections(in: self.tableView) { guard let mediaSelectionGroup = self.mediaSelectionGroup(forSection: section) else { continue } if let selectedMediaOption = self.delegate?.currentMediaSelection?.selectedMediaOption(in: mediaSelectionGroup) { if let index = mediaSelectionGroup.options.firstIndex(of: selectedMediaOption) { let row = self.allowsEmptySelection(inSection: section) ? index + 1 : index let indexPath = IndexPath(row: row, section: section) self.tableView.selectRow(at: indexPath, animated: animated, scrollPosition: .none) } } else { if self.allowsEmptySelection(inSection: section) { let indexPath = IndexPath(row: 0, section: section) self.tableView.selectRow(at: indexPath, animated: animated, scrollPosition: .none) } } } } } // UITableViewDataSource extension BingeMediaSelectionViewController { override func numberOfSections(in tableView: UITableView) -> Int { return self.mediaCharacteristics.filter { self.multipleOptionAvailable(forMediaCharacteristic: $0) }.count + 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let mediaSelectionGroup = self.mediaSelectionGroup(forSection: section) else { return 1 } return self.allowsEmptySelection(inSection: section) ? mediaSelectionGroup.options.count + 1 : mediaSelectionGroup.options.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = indexPath.section == 0 ? BingePlaybackRateCell.identifier : BingeMediaOptionCell.identifier let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) if let playbackRateCell = cell as? BingePlaybackRateCell { playbackRateCell.delegate = self.delegate } else { let (nativeDisplayName, localizedDisplayName) = self.languageDisplayNamesForOption(at: indexPath) cell.textLabel?.text = nativeDisplayName cell.detailTextLabel?.text = localizedDisplayName } return cell } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return BingeLocalizedString("media-option-selection.section.title.playback-rate", comment: "section title for playback rate in the media option selection") } switch self.mediaCharacteristic(forSection: section) { case .audible?: return BingeLocalizedString("media-option-selection.section.title.audio", comment: "section title for audio in the media option selection") case .legible?: return BingeLocalizedString("media-option-selection.section.title.subtitles", comment: "section title for subtitles and closed captions in the media option selection") default: return nil } } override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let headerView = view as? UITableViewHeaderFooterView { headerView.textLabel?.textColor = UIColor(white: 0.9, alpha: 1) } } private func mediaCharacteristic(forSection section: Int) -> AVMediaCharacteristic? { if section == 0 { return nil } return self.mediaCharacteristics.filter { self.multipleOptionAvailable(forMediaCharacteristic: $0) }[section - 1] } private func mediaSelectionGroup(forSection section: Int) -> AVMediaSelectionGroup? { guard let mediaCharacteristic = self.mediaCharacteristic(forSection: section) else { return nil } return self.mediaSelectionGroup(forMediaCharacteristic: mediaCharacteristic) } private func mediaSelectionGroup(forMediaCharacteristic mediaCharacteristic: AVMediaCharacteristic) -> AVMediaSelectionGroup? { return self.delegate?.currentMediaSelection?.asset?.mediaSelectionGroup(forMediaCharacteristic: mediaCharacteristic) } private func multipleOptionAvailable(forMediaCharacteristic mediaCharacteristic: AVMediaCharacteristic) -> Bool { guard let mediaSelectionGroup = self.mediaSelectionGroup(forMediaCharacteristic: mediaCharacteristic) else { return false } return self.allowsEmptySelection(forMediaCharacteristic: mediaCharacteristic) || mediaSelectionGroup.options.count > 1 } private func allowsEmptySelection(inSection section: Int) -> Bool { guard let mediaCharacteristic = self.mediaCharacteristic(forSection: section) else { return false } return self.allowsEmptySelection(forMediaCharacteristic: mediaCharacteristic) } private func allowsEmptySelection(forMediaCharacteristic mediaCharacteristic: AVMediaCharacteristic) -> Bool { guard let mediaSelectionGroup = self.mediaSelectionGroup(forMediaCharacteristic: mediaCharacteristic) else { return false } return mediaSelectionGroup.allowsEmptySelection && mediaCharacteristic == .legible } private func languageDisplayNamesForOption(at indexPath: IndexPath) -> (String, String?) { guard let mediaSelectionGroup = self.mediaSelectionGroup(forSection: indexPath.section) else { let title = BingeLocalizedString("media-option-selection.cell.title.unknown", comment: "cell title for an unknown option in the media option selection") return (title, nil) } let allowsEmptySelection = self.allowsEmptySelection(inSection: indexPath.section) if allowsEmptySelection, indexPath.row == 0 { let title = BingeLocalizedString("media-option-selection.cell.title.off", comment: "cell title for the off option in the media option selection") return (title, nil) } let row = allowsEmptySelection ? indexPath.row - 1 : indexPath.row let mediaSelectionOption = mediaSelectionGroup.options[row] let locale = mediaSelectionOption.extendedLanguageTag.flatMap(Locale.init(identifier:)) let nativeDisplayName = mediaSelectionOption.displayName(with: locale ?? Locale.current).capitalized let localizedDisplayName = mediaSelectionOption.displayName(with: Locale.current).capitalized return (nativeDisplayName, localizedDisplayName) } } // UITableViewDelegate extension BingeMediaSelectionViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let mediaSelectionGroup = self.mediaSelectionGroup(forSection: indexPath.section) else { return } let currentlySelectedIndexPath = self.tableView.indexPathsForSelectedRows?.first { $0.section == indexPath.section } if indexPath == currentlySelectedIndexPath { return } if let indexPathToDeselect = currentlySelectedIndexPath { self.tableView.deselectRow(at: indexPathToDeselect, animated: trueUnlessReduceMotionEnabled) } let allowsEmptySelection = self.allowsEmptySelection(inSection: indexPath.section) if allowsEmptySelection, indexPath.row == 0 { self.delegate?.select(nil, in: mediaSelectionGroup) self.tableView.selectRow(at: indexPath, animated: trueUnlessReduceMotionEnabled, scrollPosition: .none) } else { let row = allowsEmptySelection ? indexPath.row - 1 : indexPath.row self.delegate?.select(mediaSelectionGroup.options[row], in: mediaSelectionGroup) self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none) } } }
gpl-3.0
943c4960247e15f5670c694bf9c89e20
47.927536
136
0.694708
5.193846
false
false
false
false
Ben21hao/edx-app-ios-new
Source/CourseCardView.swift
1
8980
// // CourseCardView.swift // edX // // Created by Jianfeng Qiu on 13/05/2015. // Copyright (c) 2015 edX. All rights reserved. // import UIKit @IBDesignable class CourseCardView: UIView, UIGestureRecognizerDelegate { private let arrowHeight = 15.0 private let verticalMargin = 10 var course: OEXCourse? let container = UIView() private let coverImageView = UIImageView() private let titleLabel = UILabel() private let detailLabel = UILabel() private let bottomLine = UIView() private let bottomTrailingLabel = UILabel() private let overlayContainer = UIView() var tapAction : (CourseCardView -> ())? private var titleTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .Large, color: OEXStyles.sharedStyles().neutralBlack()) } private var detailTextStyle : OEXTextStyle { return OEXTextStyle(weight : .Normal, size: .XXXSmall, color: OEXStyles.sharedStyles().neutralXDark()) } private func setup() { configureViews() accessibilityTraits = UIAccessibilityTraitStaticText accessibilityHint = Strings.accessibilityShowsCourseContent } override init(frame : CGRect) { super.init(frame : frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } @available(iOS 8.0, *) override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() let bundle = NSBundle(forClass: self.dynamicType) coverImageView.image = UIImage(named:"", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection) titleLabel.attributedText = titleTextStyle.attributedStringWithText("Demo Course") detailLabel.attributedText = detailTextStyle.attributedStringWithText("edx | DemoX") bottomTrailingLabel.attributedText = detailTextStyle.attributedStringWithText("X Videos, 1.23 MB") } func configureViews() { self.backgroundColor = OEXStyles.sharedStyles().neutralXLight() self.clipsToBounds = true self.bottomLine.backgroundColor = OEXStyles.sharedStyles().neutralXLight() self.container.backgroundColor = OEXStyles.sharedStyles().neutralWhite().colorWithAlphaComponent(0.85) self.coverImageView.backgroundColor = OEXStyles.sharedStyles().neutralWhiteT() self.coverImageView.contentMode = UIViewContentMode.ScaleAspectFill self.coverImageView.clipsToBounds = true self.coverImageView.hidesLoadingSpinner = true self.container.accessibilityIdentifier = "Title Bar" self.container.addSubview(titleLabel) self.container.addSubview(detailLabel) self.container.addSubview(bottomTrailingLabel) self.addSubview(coverImageView) self.addSubview(container) self.insertSubview(bottomLine, aboveSubview: coverImageView) self.addSubview(overlayContainer) coverImageView.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, forAxis: .Horizontal) coverImageView.setContentCompressionResistancePriority(UILayoutPriorityDefaultLow, forAxis: .Vertical) detailLabel.setContentHuggingPriority(UILayoutPriorityDefaultLow, forAxis: UILayoutConstraintAxis.Horizontal) detailLabel.setContentCompressionResistancePriority(UILayoutPriorityDefaultHigh, forAxis: UILayoutConstraintAxis.Horizontal) self.container.snp_makeConstraints { make -> Void in make.leading.equalTo(self) make.trailing.equalTo(self).priorityRequired() make.bottom.equalTo(self).offset(-OEXStyles.dividerSize()) } self.coverImageView.snp_makeConstraints { (make) -> Void in make.top.equalTo(self) make.leading.equalTo(self) make.trailing.equalTo(self) make.height.equalTo(self.coverImageView.snp_width).multipliedBy(0.533).priorityLow() make.bottom.equalTo(self) } self.detailLabel.snp_makeConstraints { (make) -> Void in make.leading.equalTo(self.container).offset(StandardHorizontalMargin) make.top.equalTo(self.titleLabel.snp_bottom) make.bottom.equalTo(self.container).offset(-verticalMargin) make.trailing.equalTo(self.titleLabel) } self.bottomLine.snp_makeConstraints { (make) -> Void in make.leading.equalTo(self) make.trailing.equalTo(self) make.bottom.equalTo(self) make.top.equalTo(self.container.snp_bottom) } self.bottomTrailingLabel.snp_makeConstraints { (make) -> Void in make.centerY.equalTo(detailLabel) make.trailing.equalTo(self.container).offset(-StandardHorizontalMargin) } self.overlayContainer.snp_makeConstraints {make in make.leading.equalTo(self) make.trailing.equalTo(self) make.top.equalTo(self) make.bottom.equalTo(container.snp_top) } let tapGesture = UITapGestureRecognizer {[weak self] _ in self?.cardTapped() } tapGesture.delegate = self self.addGestureRecognizer(tapGesture) } override func updateConstraints() { if let accessory = titleAccessoryView { accessory.snp_remakeConstraints { make in make.trailing.equalTo(container).offset(-StandardHorizontalMargin) make.centerY.equalTo(container) } } self.titleLabel.snp_remakeConstraints { (make) -> Void in make.leading.equalTo(container).offset(StandardHorizontalMargin) if let accessory = titleAccessoryView { make.trailing.lessThanOrEqualTo(accessory).offset(-StandardHorizontalMargin) } else { make.trailing.equalTo(container).offset(-StandardHorizontalMargin) } make.top.equalTo(container).offset(verticalMargin) } super.updateConstraints() } var titleAccessoryView : UIView? = nil { willSet { titleAccessoryView?.removeFromSuperview() } didSet { if let accessory = titleAccessoryView { container.addSubview(accessory) } updateConstraints() } } override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { return tapAction != nil } var titleText : String? { get { return self.titleLabel.text } set { self.titleLabel.attributedText = titleTextStyle.attributedStringWithText(newValue) updateAcessibilityLabel() } } var detailText : String? { get { return self.detailLabel.text } set { self.detailLabel.attributedText = detailTextStyle.attributedStringWithText(newValue) updateAcessibilityLabel() } } var bottomTrailingText : String? { get { return self.bottomTrailingLabel.text } set { self.bottomTrailingLabel.attributedText = detailTextStyle.attributedStringWithText(newValue) self.bottomTrailingLabel.hidden = !(newValue != nil && !newValue!.isEmpty) updateAcessibilityLabel() } } var coverImage : RemoteImage? { get { return self.coverImageView.remoteImage } set { self.coverImageView.remoteImage = newValue } } private func cardTapped() { self.tapAction?(self) } func wrapTitleLabel() { self.titleLabel.numberOfLines = 3 self.titleLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping self.titleLabel.minimumScaleFactor = 0.5 self.titleLabel.adjustsFontSizeToFitWidth = true self.layoutIfNeeded() } func updateAcessibilityLabel()-> String { var accessibilityString = "" if let title = titleText { accessibilityString = title } if let text = detailText { let formatedDetailText = text.stringByReplacingOccurrencesOfString("|", withString: "") accessibilityString = "\(accessibilityString),\(Strings.accessibilityBy) \(formatedDetailText)" } if let bottomText = bottomTrailingText { accessibilityString = "\(accessibilityString), \(bottomText)" } accessibilityLabel = accessibilityString return accessibilityString } func addCenteredOverlay(view : UIView) { addSubview(view) view.snp_makeConstraints {make in // make.center.equalTo(overlayContainer) make.center.equalTo(self) } } }
apache-2.0
d31f43f8643dab9754139ac00b0f8c80
35.064257
132
0.644098
5.626566
false
false
false
false
KevinShawn/HackingWithSwift
project1/Project1/DetailViewController.swift
24
1260
// // DetailViewController.swift // Project1 // // Created by Hudzilla on 13/09/2015. // Copyright © 2015 Paul Hudson. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var detailImageView: UIImageView! var detailItem: String? { didSet { // Update the view. self.configureView() } } func configureView() { // Update the user interface for the detail item. if let detail = self.detailItem { if let imageView = self.detailImageView { imageView.image = UIImage(named: detail) } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: "shareTapped") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.hidesBarsOnTap = true } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) navigationController?.hidesBarsOnTap = false } }
unlicense
12465dd75dc2cd132d24ab677e4b9320
21.482143
120
0.729944
4.127869
false
true
false
false
Rapid-SDK/ios
Examples/RapiDO - ToDo list/RapiDO iOS/TagsTableView.swift
1
5851
// // TagsTableViewController.swift // ExampleApp // // Created by Jan on 08/05/2017. // Copyright © 2017 Rapid. All rights reserved. // import UIKit class TagsTableView: UITableView { fileprivate var selectedRows = Set<Int>() override init(frame: CGRect, style: UITableViewStyle) { super.init(frame: frame, style: style) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } var selectedTags: [Tag] { var rows = [Tag]() for (row, tag) in Tag.allValues.enumerated() { if selectedRows.contains(row) { rows.append(tag) } } return rows } func selectTags(_ tags: [Tag]) { for (row, tag) in Tag.allValues.enumerated() { setCellSelected(tags.contains(tag), atIndexPath: IndexPath(row: row, section: 0)) } } func selectAll() { for row in 0..<Tag.allValues.count { setCellSelected(true, atIndexPath: IndexPath(row: row, section: 0)) } } } extension TagsTableView: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Tag.allValues.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TagsTableViewCell let tag = Tag.allValues[indexPath.row] cell.configure(withTag: tag, selected: selectedRows.contains(indexPath.row)) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { toggleCell(atIndexPath: indexPath) } } fileprivate extension TagsTableView { func setupUI() { register(TagsTableViewCell.self, forCellReuseIdentifier: "Cell") delegate = self dataSource = self separatorColor = .appSeparator rowHeight = 60 isScrollEnabled = false separatorInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20) } func toggleCell(atIndexPath indexPath: IndexPath) { guard let cell = cellForRow(at: indexPath) as? TagsTableViewCell else { return } setCellSelected(!cell.checkBox.on, atIndexPath: indexPath) } func setCellSelected(_ selected: Bool, atIndexPath indexPath: IndexPath) { if selected { selectedRows.insert(indexPath.row) } else { selectedRows.remove(indexPath.row) } if let cell = cellForRow(at: indexPath) as? TagsTableViewCell { cell.checkBoxSelected(selected) } } } class TagsTableViewCell: UITableViewCell { var checkBox: BEMCheckBox! { didSet { checkBox.isUserInteractionEnabled = false } } var titleLabel: UILabel! { didSet { titleLabel.textColor = .appText titleLabel.font = UIFont.systemFont(ofSize: 15) } } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } func configure(withTag tag: Tag, selected: Bool) { titleLabel.text = tag.title checkBox.setOn(selected, animated: false) checkBox.tintColor = tag.color.withAlphaComponent(0.5) checkBox.onFillColor = tag.color checkBox.onTintColor = tag.color checkBox.onCheckColor = .white } func checkBoxSelected(_ selected: Bool) { checkBox.setOn(selected, animated: true) } fileprivate func setupUI() { selectionStyle = .none titleLabel = UILabel() titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(titleLabel) checkBox = BEMCheckBox() checkBox.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(checkBox) let titleLeading = NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: contentView, attribute: .left, multiplier: 1, constant: 20) let titleTrailing = NSLayoutConstraint(item: titleLabel, attribute: .right, relatedBy: .greaterThanOrEqual, toItem: checkBox, attribute: .left, multiplier: 1, constant: 10) let titleCenter = NSLayoutConstraint(item: titleLabel, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0) let checkBoxTrailing = NSLayoutConstraint(item: contentView, attribute: .right, relatedBy: .equal, toItem: checkBox, attribute: .right, multiplier: 1, constant: 20) let checkBoxCenter = NSLayoutConstraint(item: checkBox, attribute: .centerY, relatedBy: .equal, toItem: contentView, attribute: .centerY, multiplier: 1, constant: 0) let checkBoxWidth = NSLayoutConstraint(item: checkBox, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30) let checkBoxHeight = NSLayoutConstraint(item: checkBox, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30) contentView.addConstraints([titleLeading, titleTrailing, titleCenter, checkBoxWidth, checkBoxHeight, checkBoxCenter, checkBoxTrailing]) } }
mit
b1d7f4600b9c4c1a0bd7ae8d806b7698
32.238636
180
0.633846
4.970263
false
false
false
false
jimmya/CryptoTick
CryptoTick/Classes/Application/CurrencyManager.swift
1
3379
// // CurrencyManager.swift // CryptoTick // // Created by Jimmy Arts on 31/05/2017. // Copyright © 2017 Jimmy Arts. All rights reserved. // import Foundation import RxSwift import SWXMLHash import SocketIO import JASON final class CurrencyManager { static let shared = CurrencyManager() var currencies: Variable = Variable<[Currency]>([]) var coins: Variable = Variable<[Coin]>([]) var priceGraph: Variable = Variable<[DataPoint]>([]) var selectedCoin: String { set { UserDefaults.standard.set(newValue, forKey: "selectedCoin") loadCurrencies() } get { return UserDefaults.standard.value(forKey: "selectedCoin") as? String ?? "BTC" } } var selectedCurrency: String { set { UserDefaults.standard.set(newValue, forKey: "selectedCurrency") loadCurrencies() } get { return UserDefaults.standard.value(forKey: "selectedCurrency") as? String ?? "EUR" } } var selectedCurrencyRate: Double? { for currency in currencies.value { if currency.cleanSymbol == selectedCurrency { return currency.price } } return nil } private let disposeBag = DisposeBag() private let socket = SocketIOClient(socketURL: URL(string: "http://socket.coincap.io")!) init() { } func scheduleCurrencyLoading() { loadCurrencies() Timer.scheduledTimer(timeInterval: 300, target: self, selector: #selector(loadCurrencies), userInfo: nil, repeats: true) CoinCap.getFront .request() .map(to: [Coin.self]) .subscribe(onNext: { [weak self] (coins) in self?.coins.value = coins }, onError: { (error) in }).addDisposableTo(disposeBag) socket.on("trades") { [weak self] (data, ack) in data.flatMap({ (currentItem) -> Trade? in if let current = currentItem as? [String: Any], let message = current["message"] as? [String: Any] { return Trade(dictionary: message) } return nil }).forEach({ (trade) in if let shortName = trade.coin?.shortName, let newPrice = trade.coin?.price { self?.coins.value.updatePriceForCoin(withShortName: shortName, newPrice: newPrice) } }) } socket.connect() } @objc func loadCurrencies() { CoinCap.getHistory(coin: selectedCoin) .request() .map(to: History.self) .subscribe(onNext: { [weak self] (history) in self?.priceGraph.value = history.price ?? [] }, onError: { (error) in }).addDisposableTo(disposeBag) Yahoo.getCurrencies.request().subscribe(onNext: { [weak self] (response) in let xml = SWXMLHash.parse(response.data) self?.currencies.value = xml["list"]["resources"]["resource"].all.flatMap({ (resource) -> Currency? in return Currency(xml: resource) }) }, onError: { (error) in print(error) }).addDisposableTo(disposeBag) } }
mit
c550fe586c59cc1d4984c1602812ab6a
31.796117
128
0.548845
4.784703
false
false
false
false
iOS-Connect/HackathonFeb2017
PinVid/PinVid/CreateClips/SearchView.swift
1
1918
// // SearchView.swift // PinVid // // Created by Stanley Chiang on 2/26/17. // Copyright © 2017 SantaClaraiOSConnect. All rights reserved. // import UIKit class SearchView: UIView { var searchView:UIView! var urlTextField: UITextField! var loadURL:UIButton! override init(frame: CGRect) { super.init(frame: frame) urlTextField = UITextField() urlTextField.translatesAutoresizingMaskIntoConstraints = false urlTextField.backgroundColor = UIColor.white urlTextField.text = "https://www.youtube.com/watch?v=kXzGyrbjWGY" addSubview(urlTextField) loadURL = UIButton() loadURL.translatesAutoresizingMaskIntoConstraints = false loadURL.backgroundColor = UIColor.yellow loadURL.setTitle("Load Video", for: .normal) loadURL.setTitleColor(UIColor.black, for: .normal) addSubview(loadURL) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { urlTextField.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true urlTextField.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true urlTextField.trailingAnchor.constraint(equalTo: loadURL.leadingAnchor).isActive = true urlTextField.heightAnchor.constraint(equalToConstant: self.frame.height / 2).isActive = true loadURL.leadingAnchor.constraint(equalTo: urlTextField.trailingAnchor).isActive = true loadURL.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true loadURL.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true loadURL.heightAnchor.constraint(equalToConstant: self.frame.height / 2).isActive = true loadURL.widthAnchor.constraint(equalToConstant: self.frame.width * 2 / 5).isActive = true } }
mit
276ad533ced2549df74e84ca4fe027a2
36.588235
100
0.703182
4.979221
false
false
false
false
KrishMunot/swift
benchmark/single-source/ArrayAppend.swift
9
1034
//===--- ArrayAppend.swift ------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // This test checks the performance of appending to an array. import TestsUtils @inline(never) public func run_ArrayAppend(_ N: Int) { for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() for _ in 0..<40000 { nums.append(1) } } } } @inline(never) public func run_ArrayAppendReserved(_ N: Int) { for _ in 0..<N { for _ in 0..<10 { var nums = [Int]() nums.reserveCapacity(40000) for _ in 0..<40000 { nums.append(1) } } } }
apache-2.0
494ec720a86f2ca32e88ddb19a70fdb3
24.85
80
0.529981
4.086957
false
false
false
false
liuxianghong/GreenBaby
工程/greenbaby/greenbaby/View/Home/KChartView.swift
1
8437
// // KChartView.swift // greenbaby // // Created by 刘向宏 on 16/1/8. // Copyright © 2016年 刘向宏. All rights reserved. // import UIKit struct KChartModel { let value : CGFloat let x : String } class KChartViewModel : NSObject { init(type : Int , time : Int ,dic : [[String : AnyObject]]?){ if dic != nil{ dataDicArray = dic! } else{ dataDicArray = [[String : AnyObject]]() } chartType = type timeType = time if chartType == 1{ maxValue = 40 minValue = 25 maxBestValue = 35 minBestValue = 30 } else if chartType == 2{ // maxValue = 60 // minValue = 0 // maxBestValue = 45 // minBestValue = 30 maxValue = 90 minValue = 0 maxBestValue = 60 minBestValue = 30 } else if chartType == 3{ maxValue = 60 minValue = -10 maxBestValue = 45 minBestValue = 0 } } var maxValue = 35 var minValue = 20 var maxBestValue = 30 var minBestValue = 25 var chartType = 0 var timeType = 0 var subType = 0 var dataDicArray = [[String : AnyObject]]() func getDataArray() -> [String : KChartModel]{ var valueKey = "distance" if chartType == 2{ valueKey = "time" } else if chartType == 3{ if subType == 1{ valueKey = "pitch" } else if subType == 2{ valueKey = "yaw" } else if subType == 3{ valueKey = "roll" } } print(subType) print(valueKey) var chartModels = [String : KChartModel]() chartModels = [String : KChartModel]() var tt = 0 var ystring = "" for dic in dataDicArray{ let calendar = NSCalendar.currentCalendar() if timeType == 2{ let formote = "yyyy-w" let form = NSDateFormatter() form.dateFormat = formote let dd = form.dateFromString(dic["y"] as! String) let week = calendar.components(.WeekOfYear, fromDate: dd!, toDate: NSDate(), options: .WrapComponents).weekOfYear tt = 12 - week } else if timeType == 1{ let formote = "yyyy-MM-dd" let form = NSDateFormatter() form.dateFormat = formote let dd = form.dateFromString(dic["y"] as! String) let week = calendar.components(.Day, fromDate: dd!, toDate: NSDate(), options: .WrapComponents).day print(week) tt = 12 - week } else if timeType == 3{ let formote = "yyyy-MM" let form = NSDateFormatter() form.dateFormat = formote let dd = form.dateFromString(dic["y"] as! String) let week = calendar.components(.Month, fromDate: dd!, toDate: NSDate(), options: .WrapComponents).month print(week) tt = 12 - week } else if timeType == 4{ let formote = dic["y"] as! String tt = 2015 - Int(formote)! } if tt < 0 || tt > 11{ continue } if timeType != 4{ ystring = "\(tt)" } chartModels["\(tt++)"] = KChartModel(value: dic[valueKey] as! CGFloat, x: ystring) print(dic[valueKey]) } return chartModels } } class KChartView: UIView { // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. var viewModel = KChartViewModel(type: 0, time: 0, dic: nil) override func drawRect(rect: CGRect) { // Drawing code let topBegin:CGFloat = 15 let bottomBegin:CGFloat = 15 let leftBegin:CGFloat = 20 let rectHeght = rect.size.height let rectCHeght = rectHeght - topBegin - bottomBegin let rectWidth = rect.size.width let rectCWidth = rectWidth - leftBegin - 8 let maxBestTop = rectCHeght - rectCHeght / CGFloat(viewModel.maxValue - viewModel.minValue) * CGFloat(viewModel.maxBestValue - viewModel.minValue) let minBestTop = rectCHeght - rectCHeght / CGFloat(viewModel.maxValue - viewModel.minValue) * CGFloat(viewModel.minBestValue - viewModel.minValue) - maxBestTop let context = UIGraphicsGetCurrentContext() CGContextSetRGBFillColor(context, 1, 70/255.0, 70/255.0, 1) CGContextFillRect(context, CGRectMake(0, topBegin, rect.size.width, maxBestTop)) CGContextSetRGBFillColor(context, 1, 199/255.0, 99/255.0, 1) CGContextFillRect(context, CGRectMake(0, topBegin + maxBestTop, rect.size.width, minBestTop)) CGContextSetRGBFillColor(context, 55/255.0, 108/255.0, 214/255.0, 1) CGContextFillRect(context, CGRectMake(0, topBegin + maxBestTop + minBestTop, rect.size.width, rectHeght - (topBegin + maxBestTop + minBestTop))) CGContextStrokePath(context) CGContextBeginTransparencyLayer(context, nil) CGContextSetRGBFillColor(context, 1, 1, 1, 1) CGContextFillRect(context, rect) CGContextSetRGBStrokeColor(context, 0.95, 0.95, 0.95, 1) CGContextSetLineWidth(context, 1) CGContextMoveToPoint(context, leftBegin, topBegin) CGContextAddLineToPoint(context, rect.size.width , topBegin) CGContextMoveToPoint(context, leftBegin, topBegin + maxBestTop) CGContextAddLineToPoint(context, rect.size.width, topBegin + maxBestTop) CGContextMoveToPoint(context, leftBegin, topBegin + maxBestTop + minBestTop) CGContextAddLineToPoint(context, rect.size.width, topBegin + maxBestTop + minBestTop) CGContextMoveToPoint(context, leftBegin, topBegin + rectCHeght) CGContextAddLineToPoint(context, rect.size.width, topBegin + rectCHeght) CGContextStrokePath(context) let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .Center; let dic = [NSFontAttributeName : UIFont.systemFontOfSize(10), NSParagraphStyleAttributeName : paragraphStyle,NSForegroundColorAttributeName : UIColor.darkGrayColor()] let s60:NSString = String(viewModel.maxValue) s60.drawInRect(CGRectMake(0, topBegin + 0-8, leftBegin, 16), withAttributes: dic) let s45:NSString = String(viewModel.maxBestValue) s45.drawInRect(CGRectMake(0, topBegin + maxBestTop-8, leftBegin, 16), withAttributes: dic) let s30:NSString = String(viewModel.minBestValue) s30.drawInRect(CGRectMake(0, topBegin + maxBestTop + minBestTop-8, leftBegin, 16), withAttributes: dic) let s15:NSString = String(viewModel.minValue) s15.drawInRect(CGRectMake(0, topBegin + rectCHeght-8, leftBegin, 16), withAttributes: dic) let dic2 = [NSFontAttributeName : UIFont.systemFontOfSize(7), NSParagraphStyleAttributeName : paragraphStyle,NSForegroundColorAttributeName : UIColor.darkGrayColor()] var array = [NSValue]() let arr = self.viewModel.getDataArray() for index in 0...12{ if let model = arr["\(index)"]{ let point = CGPointMake(leftBegin + CGFloat(index)*rectCWidth/12, topBegin + rectCHeght - (model.value - CGFloat(viewModel.minValue)) / CGFloat(viewModel.maxValue - viewModel.minValue) * rectCHeght); array.append(NSValue(CGPoint: point)) } var s:NSString = "\(index)" if viewModel.timeType == 4{ s = "\(2015+index)" } s.drawInRect(CGRectMake(leftBegin + CGFloat(index)*rectCWidth/12 - 10, topBegin + rectCHeght, 20, 16), withAttributes: dic2) } CGContextSetBlendMode(context, .Clear) if arr.count > 0{ let path = UIBezierPath.quadCurvedPathWithPoints(array) path.stroke() CGContextAddPath(context, path.CGPath); } CGContextStrokePath(context); CGContextEndTransparencyLayer(context); } }
lgpl-3.0
3c311fb93148ca49f1cbc2b26596ab1b
38.35514
215
0.582641
4.552432
false
false
false
false
adrfer/swift
test/Inputs/forward_extension_reference.swift
90
356
extension Foo : Bar { var count: Int { get { var x = Int(_countAndFlags >> 1) var y = Int(_countAndFlags >> 1) var z = _countAndFlags >> 1 return x } set { let growth = newValue - count if growth == 0 { return } _countAndFlags = (UInt(newValue) << 1) | (_countAndFlags & 1) } } }
apache-2.0
33354bb669d2a39200f3edf33d5c8368
19.941176
67
0.494382
3.869565
false
false
false
false
harenbrs/swix
swixUseCases/swix-OSX/swix/ndarray/operators.swift
2
7495
// // oneD-functions.swift // swix // // Created by Scott Sievert on 7/9/14. // Copyright (c) 2014 com.scott. All rights reserved. // import Foundation import Accelerate func make_operator(lhs:ndarray, operation:String, rhs:ndarray) -> ndarray{ assert(lhs.n == rhs.n, "Sizes must match!") var array = zeros(lhs.n) // lhs[i], rhs[i] var arg_b = zeros(lhs.n) var arg_c = zeros(lhs.n) // see [1] on how to integrate Swift and accelerate // [1]:https://github.com/haginile/SwiftAccelerate var result = lhs.copy() var N = lhs.n if operation=="+" {cblas_daxpy(N.cint, 1.0.cdouble, !rhs, 1.cint, !result, 1.cint);} else if operation=="-" {cblas_daxpy(N.cint, -1.0.cdouble, !rhs, 1.cint, !result, 1.cint);} else if operation=="*" {vDSP_vmulD(!lhs, 1, !rhs, 1, !result, 1, vDSP_Length(lhs.grid.count))} else if operation=="/" {vDSP_vdivD(!rhs, 1, !lhs, 1, !result, 1, vDSP_Length(lhs.grid.count))} else if operation=="<" || operation==">" || operation==">=" || operation=="<=" { result = zeros(lhs.n) CVWrapper.compare(!lhs, with: !rhs, using: operation.nsstring, into: !result, ofLength: lhs.n.cint) // since opencv uses images which use 8-bit values result /= 255 } else if operation == "=="{ return abs(lhs-rhs) < 1e-9 } else if operation == "!=="{ return abs(lhs-rhs) > 1e-9 } else {assert(false, "operation not recongized!")} return result } func make_operator(lhs:ndarray, operation:String, rhs:Double) -> ndarray{ var array = zeros(lhs.n) var right = [rhs] if operation == "%" // unoptimized. for loop in c {mod_objc(!lhs, rhs, !array, lhs.n.cint); } else if operation == "*"{ var C:CDouble = 0 var mul = CDouble(rhs) vDSP_vsmsaD(!lhs, 1.cint, &mul, &C, !array, 1.cint, vDSP_Length(lhs.n.cint)) } else if operation == "+" {vDSP_vsaddD(!lhs, 1, &right, !array, 1, vDSP_Length(lhs.grid.count))} else if operation=="/" {vDSP_vsdivD(!lhs, 1, &right, !array, 1, vDSP_Length(lhs.grid.count))} else if operation=="-" {array = make_operator(lhs, "-", ones(lhs.n)*rhs)} else if operation=="<" || operation==">" || operation=="<=" || operation==">="{ CVWrapper.compare(!lhs, withDouble:rhs.cdouble, using:operation.nsstring, into:!array, ofLength:lhs.n.cint) array /= 255 } else {assert(false, "operation not recongnized! Error with the speedup?")} return array } func make_operator(lhs:Double, operation:String, rhs:ndarray) -> ndarray{ var array = zeros(rhs.n) // lhs[i], rhs[i] var l = ones(rhs.n) * lhs if operation == "*" {array = make_operator(rhs, "*", lhs)} else if operation == "+"{ array = make_operator(rhs, "+", lhs)} else if operation=="-" {array = -1 * make_operator(rhs, "-", lhs)} else if operation=="/"{ array = make_operator(l, "/", rhs)} else if operation=="<"{ array = make_operator(rhs, ">", lhs)} else if operation==">"{ array = make_operator(rhs, "<", lhs)} else if operation=="<="{ array = make_operator(rhs, ">=", lhs)} else if operation==">="{ array = make_operator(rhs, "<=", lhs)} else {assert(false, "Operator not reconginzed")} return array } // EQUALITY infix operator ~== {associativity none precedence 140} func ~== (lhs: ndarray, rhs: ndarray) -> Bool{ assert(lhs.n == rhs.n, "`~==` only works on arrays of equal size") return max(abs(lhs - rhs)) > 1e-6 ? false : true; } func == (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "==", rhs)} func !== (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "!==", rhs)} // NICE ARITHMETIC func += (inout x: ndarray, right: Double){ x = x + right} func *= (inout x: ndarray, right: Double){ x = x * right} func -= (inout x: ndarray, right: Double){ x = x - right} func /= (inout x: ndarray, right: Double){ x = x / right} // MOD infix operator % {associativity none precedence 140} func % (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "%", rhs)} // POW infix operator ^ {associativity none precedence 140} func ^ (lhs: ndarray, rhs: Double) -> ndarray{ return pow(lhs, rhs)} func ^ (lhs: ndarray, rhs: ndarray) -> ndarray{ return pow(lhs, rhs)} func ^ (lhs: Double, rhs: ndarray) -> ndarray{ return pow(lhs, rhs)} // PLUS infix operator + {associativity none precedence 140} func + (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "+", rhs)} func + (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, "+", rhs)} func + (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "+", rhs)} // MINUS infix operator - {associativity none precedence 140} func - (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "-", rhs)} func - (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, "-", rhs)} func - (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "-", rhs)} // TIMES infix operator * {associativity none precedence 140} func * (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "*", rhs)} func * (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, "*", rhs)} func * (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "*", rhs)} // DIVIDE infix operator / {associativity none precedence 140} func / (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "/", rhs) } func / (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, "/", rhs)} func / (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "/", rhs)} // LESS THAN infix operator < {associativity none precedence 140} func < (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "<", rhs)} func < (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "<", rhs)} func < (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, "<", rhs)} // GREATER THAN infix operator > {associativity none precedence 140} func > (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, ">", rhs)} func > (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, ">", rhs)} func > (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, ">", rhs)} // GREATER THAN OR EQUAL infix operator >= {associativity none precedence 140} func >= (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, ">=", rhs)} func >= (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, ">=", rhs)} func >= (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, ">=", rhs)} // LESS THAN OR EQUAL infix operator <= {associativity none precedence 140} func <= (lhs: ndarray, rhs: Double) -> ndarray{ return make_operator(lhs, "<=", rhs)} func <= (lhs: ndarray, rhs: ndarray) -> ndarray{ return make_operator(lhs, "<=", rhs)} func <= (lhs: Double, rhs: ndarray) -> ndarray{ return make_operator(lhs, "<=", rhs)} // LOGICAL AND infix operator && {associativity none precedence 140} func && (lhs: ndarray, rhs: ndarray) -> ndarray{ return lhs * rhs} // LOGICAL OR func || (lhs: ndarray, rhs: ndarray) -> ndarray { var i = lhs + rhs var j = argwhere(i>1.double) i[j] = ones(j.n) return i}
mit
a44f227fd5f3781a48368e32adf65201
31.586957
115
0.606137
3.380695
false
false
false
false
esttorhe/RxSwift
RxSwift/RxSwift/Observables/Implementations/Timer.swift
1
2659
// // Timer.swift // RxSwift // // Created by Krunoslav Zaher on 6/7/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation class TimerSink<S: Scheduler, O: ObserverType where O.Element == Int64> : Sink<O> { typealias Parent = Timer<S> let parent: Parent init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let result = self.parent.schedulePeriodic(state: 0, startAfter: self.parent.dueTime, period: self.parent.period!) { state in trySendNext(self.observer, state) return state &+ 1 } return result } } class TimerOneOffSink<S: Scheduler, O: ObserverType where O.Element == Int64> : Sink<O> { typealias Parent = Timer<S> let parent: Parent init(parent: Parent, observer: O, cancel: Disposable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { let result = self.parent.scheduler.scheduleRelative((), dueTime: self.parent.dueTime) { (_) -> RxResult<Disposable> in trySendNext(self.observer, 0) trySendCompleted(self.observer) return NopDisposableResult } ensureScheduledSuccessfully(result.map { _ in () }) return result.get() } } class Timer<S: Scheduler>: Producer<Int64> { typealias TimeInterval = S.TimeInterval typealias SchedulePeriodic = ( state: Int64, startAfter: S.TimeInterval, period: S.TimeInterval, action: (state: Int64) -> Int64 ) -> Disposable let scheduler: S let dueTime: TimeInterval let period: TimeInterval? let schedulePeriodic: SchedulePeriodic init(dueTime: TimeInterval, period: TimeInterval?, scheduler: S, schedulePeriodic: SchedulePeriodic) { self.scheduler = scheduler self.dueTime = dueTime self.period = period self.schedulePeriodic = schedulePeriodic } override func run<O : ObserverType where O.Element == Int64>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable { if let _ = period { let sink = TimerSink(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } else { let sink = TimerOneOffSink(parent: self, observer: observer, cancel: cancel) setSink(sink) return sink.run() } } }
mit
e0d9b9015b487a10b0e2da20b3234117
28.88764
144
0.606995
4.446488
false
false
false
false
Eonil/HomeworkApp1
Driver/Workbench1/AppDelegate.swift
1
2693
// // AppDelegate.swift // Workbench1 // // Created by Hoon H. on 2015/02/26. // // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window = UIWindow(frame: UIScreen.mainScreen().bounds) as UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let u1 = NSBundle.mainBundle().URLForResource("a", withExtension: "jpg")! let u2 = NSBundle.mainBundle().URLForResource("b", withExtension: "jpg")! let u3 = NSBundle.mainBundle().URLForResource("c", withExtension: "jpg")! let u4 = NSBundle.mainBundle().URLForResource("d", withExtension: "png")! let u5 = NSBundle.mainBundle().URLForResource("e", withExtension: "gif")! let us = [u1, u2, u3, u4, u5] let ms = us.map({ u in Client.ImageItem(title: "Test1", URL:u) }) let nc = UINavigationController() let vc = SlideViewController3() nc.pushViewController(vc, animated: false) vc.queueImageItems(ms) window!.makeKeyAndVisible() window!.rootViewController = nc return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
3e9c43537a13094af9e578265f1cf01d
43.883333
279
0.759005
4.254344
false
false
false
false
mcarter6061/FetchedResultsCoordinator
Example/FetchedResultsCoordinator/DataViewController.swift
1
5068
// Copyright © 2015 Mark Carter. All rights reserved. import UIKit import CoreData @objc protocol ExampleViewControllersWithFetchedResultController { var fetchedResultsController: NSFetchedResultsController! {get set} } class DataViewController: UIViewController { var managedObjectContext: NSManagedObjectContext? var dataManager: DemoDataManager? var childTabBarController: UITabBarController? override func viewDidLoad() { super.viewDidLoad() } @IBOutlet weak var itemCountSlider: UISlider! @IBOutlet weak var itemCountLabel: UILabel! @IBOutlet weak var sectionCountSlider: UISlider! @IBOutlet weak var sectionCountLabel: UILabel! var sectionCount:Int { return Int( sectionCountSlider.value ) } var itemCount:Int { return Int( itemCountSlider.value ) } @IBAction func sectionCountSliderChanged(sender: UISlider) { sectionCountLabel.text = "across \(sectionCount) section\(sectionCount > 1 ? "s":"")" } @IBAction func itemCountSliderChanged(sender: UISlider) { itemCountLabel.text = "\(itemCount) items" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation @IBAction func unwindToDemoViewController(sender: UIStoryboardSegue) { childTabBarController = nil } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { managedObjectContext = ManagedObjectContextFactory.managedObjectContextOfInMemoryStoreTypeWithModel("Example") guard let managedObjectContext = managedObjectContext else { fatalError("Core Data stack not setup") } // Creates the data and then modifies it dataManager = DemoDataManager( managedObjectContext: managedObjectContext, numberOfItems: itemCount, numberOfSections: sectionCount ) // Set fetch results controller on all the ExampleViewControllersWithFetchedResultController ( search vc heirarchy ) setupChildControllers(segue.destinationViewController, managedObjectContext: managedObjectContext) childTabBarController = segue.destinationViewController as? UITabBarController } func fetchedResultsController( managedObjectContext: NSManagedObjectContext ) -> NSFetchedResultsController { let sectionKeyPath:String? = (sectionCountSlider.value > 1) ? "section" : nil return NSFetchedResultsController(fetchRequest: fetchRequest(managedObjectContext), managedObjectContext: managedObjectContext, sectionNameKeyPath: sectionKeyPath, cacheName: nil) } func fetchRequest( managedObjectContext: NSManagedObjectContext ) -> NSFetchRequest { guard let fetchRequest = managedObjectContext.persistentStoreCoordinator?.managedObjectModel.fetchRequestFromTemplateWithName( "VisibleItems", substitutionVariables: [:]) else { fatalError() } fetchRequest.sortDescriptors = [NSSortDescriptor(key: "section", ascending: true),NSSortDescriptor(key: "ordinal", ascending: true)] return fetchRequest } func setupChildControllers( viewController: UIViewController, managedObjectContext: NSManagedObjectContext) { if let viewController = viewController as? ExampleViewControllersWithFetchedResultController { viewController.fetchedResultsController = fetchedResultsController( managedObjectContext ) } else { viewController.childViewControllers.forEach{setupChildControllers($0, managedObjectContext: managedObjectContext)} } } } // Keyboard shortcuts for switching between tabs extension DataViewController { override var keyCommands: [UIKeyCommand] { if #available(iOS 9.0, *) { return [UIKeyCommand(input: "1", modifierFlags: UIKeyModifierFlags(), action: #selector(DataViewController.switchTab1), discoverabilityTitle: "Table VC"), UIKeyCommand(input: "2", modifierFlags: UIKeyModifierFlags(), action: #selector(DataViewController.switchTab2), discoverabilityTitle: "Table View"), UIKeyCommand(input: "3", modifierFlags: UIKeyModifierFlags(), action: #selector(DataViewController.switchTab3), discoverabilityTitle: "Collection VC"), UIKeyCommand(input: "4", modifierFlags: UIKeyModifierFlags(), action: #selector(DataViewController.switchTab4), discoverabilityTitle: "Collection View")] } else { return [] } } func switchTab1() { childTabBarController?.selectedIndex = 0 } func switchTab2() { childTabBarController?.selectedIndex = 1 } func switchTab3() { childTabBarController?.selectedIndex = 2 } func switchTab4() { childTabBarController?.selectedIndex = 3 } }
mit
215e29ae414e28963820510f9bec3764
38.905512
187
0.71344
6.171742
false
false
false
false
pkrawat1/TravelApp-ios
TravelApp/View/TripCell.swift
1
12217
// // VideoCell.swift // YoutubeClone // // Created by Pankaj Rawat on 20/01/17. // Copyright © 2017 Pankaj Rawat. All rights reserved. // import UIKit class TripCell: BaseCell { var user: User! var trip: Trip! { didSet { user = trip.user titleLabel.text = user.name setupThumbnailImage() setupProfileImage() if let numberOfLikes = trip.trip_likes_count { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal tripStatusLabel.text = "\(numberFormatter.string(from: numberOfLikes)!) Likes" } subTitleLabel.text = trip.created_at?.relativeDate() // measure Title text if let title = trip.name { let size = CGSize(width: frame.width - 16 - 44 - 8 - 16 , height: 1000) let options = NSStringDrawingOptions.usesFontLeading.union(.usesLineFragmentOrigin) let estimatedRect = NSString(string: title).boundingRect(with: size, options: options, attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 14)], context: nil) if estimatedRect.size.height > 20 { titleLabelHeightConstraint?.constant = 44 } else { titleLabelHeightConstraint?.constant = 20 } } followButton.addTarget(self, action: #selector(handleFollow), for: .touchUpInside) if user.is_followed_by_current_user { self.followButton.backgroundColor = UIColor.appCallToActionColor() self.followButton.setTitle("Following", for: .normal) self.followButton.setTitleColor(UIColor.white, for: .normal) } else { self.followButton.backgroundColor = UIColor.white self.followButton.setTitle("Follow", for: .normal) self.followButton.setTitleColor(UIColor.appCallToActionColor(), for: .normal) } likeButton.addTarget(self, action: #selector(handleLike), for: .touchUpInside) if trip.is_liked_by_current_user { likeButton.setImage(UIImage(named: "like-filled"), for: .normal) likeButton.tintColor = UIColor.appCallToActionColor() } else { likeButton.setImage(UIImage(named: "like"), for: .normal) likeButton.tintColor = UIColor.gray } } } func setupThumbnailImage() { if let thumbnailImageUrl = trip.thumbnail_image_url { thumbnailImageView.loadImageUsingUrlString(urlString: thumbnailImageUrl, width: Float(frame.width)) } let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(showTripDetail)) thumbnailImageView.isUserInteractionEnabled = true thumbnailImageView.addGestureRecognizer(tapGestureRecognizer) } func showTripDetail() { let tripDetailViewCtrl = TripDetailViewController() store.dispatch(SelectTrip(tripId: trip.id!)) SharedData.sharedInstance.homeController?.present(tripDetailViewCtrl, animated: true, completion: nil) } func setupProfileImage() { if let profileImageURL = user.profile_pic?.url { userProfileImageView.loadImageUsingUrlString(urlString: profileImageURL, width: 44) } } let thumbnailImageView: CustomImageView = { let imageView = CustomImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.image = UIImage(named: "") imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() let userProfileImageView: CustomImageView = { let imageView = CustomImageView() imageView.image = UIImage(named: "") imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.layer.cornerRadius = 22 imageView.layer.masksToBounds = true imageView.translatesAutoresizingMaskIntoConstraints = false return imageView }() let titleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "" label.numberOfLines = 1 label.font = label.font.withSize(14) return label }() let subTitleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "" label.numberOfLines = 1 label.font = label.font.withSize(12) return label }() let tripStatusLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "" label.numberOfLines = 1 label.font = label.font.withSize(12) return label }() let separatorView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = UIColor.appMainBGColor() return view }() let likeButton: UIButton = { let ub = UIButton(type: .system) ub.setImage(UIImage(named: "like"), for: .normal) ub.tintColor = UIColor.gray ub.translatesAutoresizingMaskIntoConstraints = false return ub }() let followButton: UIButton = { let button = UIButton(type: .system) button.backgroundColor = UIColor.white button.layer.borderColor = UIColor.appCallToActionColor().cgColor button.layer.borderWidth = 1 button.setTitle("Follow", for: .normal) button.translatesAutoresizingMaskIntoConstraints = false button.layer.cornerRadius = 5 button.layer.masksToBounds = true button.setTitleColor(UIColor.appCallToActionColor(), for: .normal) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 10) return button }() func handleFollow() { user.is_followed_by_current_user = !user.is_followed_by_current_user toggleFollow() UserService.sharedInstance.followUser(followedId: (trip.user_id)!) { (user: User) in guard user.is_followed_by_current_user != self.user.is_followed_by_current_user else { return } self.toggleFollow() } } func toggleFollow() { UIView.animate(withDuration: 0.5) { if self.user.is_followed_by_current_user { self.followButton.backgroundColor = UIColor.appCallToActionColor() self.followButton.setTitle("Following", for: .normal) self.followButton.setTitleColor(UIColor.white, for: .normal) } else { self.followButton.backgroundColor = UIColor.white self.followButton.setTitle("Follow", for: .normal) self.followButton.setTitleColor(UIColor.appCallToActionColor(), for: .normal) } } } func handleLike(firstChange: Bool) { trip.is_liked_by_current_user = !trip.is_liked_by_current_user self.likeButton.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) toggleLike() TripService.sharedInstance.likeTrip(tripId: (trip.id)!) { (trip: Trip) in guard trip.is_liked_by_current_user != self.trip.is_liked_by_current_user else { return } self.toggleLike() } } func toggleLike() { UIView.animate(withDuration: 0.5, animations: { self.likeButton.transform = CGAffineTransform.identity if self.trip.is_liked_by_current_user { self.likeButton.setImage(UIImage(named: "like-filled"), for: .normal) self.likeButton.tintColor = UIColor.appCallToActionColor() } else { self.likeButton.setImage(UIImage(named: "like"), for: .normal) self.likeButton.tintColor = UIColor.gray } }) } var titleLabelHeightConstraint: NSLayoutConstraint? override func setupViews() { addSubview(userProfileImageView) addSubview(titleLabel) addSubview(subTitleLabel) addSubview(thumbnailImageView) addSubview(tripStatusLabel) addSubview(separatorView) addSubview(likeButton) addSubview(followButton) setupThumbnailImageViews() userProfileImageView.topAnchor.constraint(equalTo: topAnchor, constant: 16).isActive = true userProfileImageView.leftAnchor.constraint(equalTo: leftAnchor, constant: 16).isActive = true userProfileImageView.widthAnchor.constraint(equalToConstant: 44).isActive = true userProfileImageView.heightAnchor.constraint(equalToConstant: 44).isActive = true thumbnailImageView.topAnchor.constraint(equalTo: userProfileImageView.bottomAnchor, constant: 16).isActive = true thumbnailImageView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true thumbnailImageView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true thumbnailImageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -80).isActive = true followButton.rightAnchor.constraint(equalTo: thumbnailImageView.rightAnchor, constant: -16).isActive = true followButton.heightAnchor.constraint(equalToConstant: 30).isActive = true followButton.topAnchor.constraint(equalTo: userProfileImageView.topAnchor, constant: 7).isActive = true followButton.widthAnchor.constraint(equalToConstant: 60).isActive = true //top constraint titleLabel.topAnchor.constraint(equalTo: userProfileImageView.topAnchor).isActive = true // left constraint titleLabel.leftAnchor.constraint(equalTo: userProfileImageView.rightAnchor, constant: 8).isActive = true //right constraint titleLabel.rightAnchor.constraint(equalTo: followButton.leftAnchor, constant: -5).isActive = true // hight Constraint titleLabel.heightAnchor.constraint(equalToConstant: 22).isActive = true //top constraint subTitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor).isActive = true // left constraint subTitleLabel.leftAnchor.constraint(equalTo: userProfileImageView.rightAnchor, constant: 8).isActive = true //right constraint subTitleLabel.rightAnchor.constraint(equalTo: titleLabel.rightAnchor).isActive = true // hight Constraint subTitleLabel.heightAnchor.constraint(equalToConstant: 30).isActive = true likeButton.topAnchor.constraint(equalTo: thumbnailImageView.bottomAnchor, constant: 2).isActive = true likeButton.leftAnchor.constraint(equalTo: thumbnailImageView.leftAnchor, constant: 16).isActive = true likeButton.widthAnchor.constraint(equalToConstant: 35).isActive = true likeButton.heightAnchor.constraint(equalToConstant: 35).isActive = true separatorView.topAnchor.constraint(equalTo: likeButton.bottomAnchor, constant: 2).isActive = true separatorView.widthAnchor.constraint(equalTo: thumbnailImageView.widthAnchor).isActive = true separatorView.heightAnchor.constraint(equalToConstant: 1).isActive = true tripStatusLabel.topAnchor.constraint(equalTo: separatorView.bottomAnchor, constant: 10).isActive = true tripStatusLabel.leftAnchor.constraint(equalTo: likeButton.leftAnchor).isActive = true tripStatusLabel.widthAnchor.constraint(equalTo: thumbnailImageView.widthAnchor, constant: -32).isActive = true tripStatusLabel.heightAnchor.constraint(equalToConstant: 15).isActive = true } func setupThumbnailImageViews() { } }
mit
92a9d6b8910709c828c4dc2f7b3d2fa3
40.692833
182
0.638998
5.398144
false
false
false
false
ReactiveKit/ReactiveKit
Sources/SignalProtocol+Transforming.swift
1
6077
// // The MIT License (MIT) // // Copyright (c) 2016-2019 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 extension SignalProtocol { /// Batch signal elements into arrays of the given size. /// /// Check out interactive example at [https://rxmarbles.com/#bufferCount](https://rxmarbles.com/#bufferCount) public func buffer(ofSize 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() } } } } /// Collect all elements into an array and emit the array as a single element. public func collect() -> Signal<[Element], Error> { return reduce([], { memo, new in memo + [new] }) } /// Emit default element if the signal completes without emitting any element. /// /// Check out interactive example at [https://rxmarbles.com/#defaultIfEmpty](https://rxmarbles.com/#defaultIfEmpty) 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() } } } } /// Map all elements to instances of Void. public func eraseType() -> Signal<Void, Error> { return replaceElements(with: ()) } /// Par each element with its predecessor, starting from the second element. /// Similar to `zipPrevious`, but starts from the second element. /// /// Check out interactive example at [https://rxmarbles.com/#pairwise](https://rxmarbles.com/#pairwise) public func pairwise() -> Signal<(Element, Element), Error> { return zipPrevious().compactMap { a, b in a.flatMap { ($0, b) } } } /// Replace all emitted elements with the given element. public func replaceElements<ReplacementElement>(with element: ReplacementElement) -> Signal<ReplacementElement, Error> { return map { _ in element } } /// Reduce all elements to a single element. Similar to `scan`, but emits only the final element. /// /// Check out interactive example at [https://rxmarbles.com/#reduce](https://rxmarbles.com/#reduce) public func reduce<U>(_ initial: U, _ combine: @escaping (U, Element) -> U) -> Signal<U, Error> { return scan(initial, combine).last() } /// Apply `combine` to each element starting with `initial` and emit each /// intermediate result. This differs from `reduce` which only emits the final result. /// /// Check out interactive example at [https://rxmarbles.com/#scan](https://rxmarbles.com/#scan) 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() } } } } /// Prepend the given element to the signal element sequence. /// /// Check out interactive example at [https://rxmarbles.com/#startWith](https://rxmarbles.com/#startWith) public func start(with element: Element) -> Signal<Element, Error> { return scan(element, { _, next in next }) } /// Batch each `size` elements into another signal. public func window(ofSize size: Int) -> Signal<Signal<Element, Error>, Error> { return buffer(ofSize: size).map { Signal(sequence: $0) } } /// Par each element with its predecessor. /// Similar to `parwise`, but starts from the first element which is paird with `nil`. public func zipPrevious() -> Signal<(Element?, Element), Error> { return scan(nil) { (pair, next) in (pair?.1, next) }.ignoreNils() } }
mit
48f15cc5ee806ee5c89d99bd1dd9cc5c
41.201389
124
0.605727
4.586415
false
false
false
false
cherish-delicate/Swift-Tour
Ch 0. Playgrounds.playground/section-1.swift
1
1541
// Playground - noun: a place where people can play import Cocoa var str = "Hello, playground" println("Hello, world") /// 變數與常數 var firstVariable = 42 //宣告變數,設定為42 firstVariable = 50 //更改變數值為 50 let firstConstant = 42 // 設定一個常數值為42; let firstDouble = 60.0 // 宣告一個 Double let explicitDouble : Double = 70 // 宣告一個常數為 Double // 以上兩種做法都可以宣告 Double. 但後者較容易明白。 let explicitFloat : Float = 4 /// 形態的轉換 // 變數的形態是固定的,無法直接轉為其他形態。必須透過轉換 let label = "This width is" let width = 94 let widthLabel = label + String(width) // 假如去掉 String 會發生什麼錯誤呢? // let noWidthLabel = label + width // 不同形態是無法直接相加的,必須透過轉換。 /// 字串中傳入參數 let apples = 3 var oranges = 5 let appleSummary = "I have \(apples) apples." let fruitSummary = "I have \(apples + oranges) pieces of fruit." // 整數與浮點數相加 var cherry: Float = 3.5 // 整數無法直接相加 // let fruit = "I have \(oranges + cherry) pieces of fruit." /// 陣列與詞典 var shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList[1] = "bottle of water" var occupations = [ "Malcolm" : "Captain", "Kaylee" : "Mechanic", ] occupations ["Jayne"] = "Public Relations" println(occupations) let emptyArray = String[]() let emptyDictionary = Dictionary<String, Float>() /// 流程控制
mit
ef2a2a96f1f0f0a923410edc8a886ba5
14.807692
64
0.676399
2.335227
false
false
false
false
natecook1000/ExSwift
ExSwift/NSArray.swift
1
1353
// // NSArray.swift // ExSwift // // Created by pNre on 10/06/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation extension NSArray { /** * Converts an NSArray object to an OutType[] array containing * the items in the NSArray that can be bridged from their ObjC type to OutType. * @return Swift Array */ func cast <OutType> () -> OutType[] { var result = OutType[]() for item : AnyObject in self { // Keep only objC objects compatible with OutType if let converted = bridgeFromObjectiveC(item, OutType.self) { result.append(converted) } } return result } /** * Flattens a multidimensional NSArray to an OutType[] array containing * the items in the NSArray that can be bridged from their ObjC type to OutType. * @return Flattened array */ func flatten <OutType> () -> OutType[] { var result = OutType[]() for item: AnyObject in self { if let converted = bridgeFromObjectiveC(item, OutType.self) { result.append(converted) } else if item is NSArray { result += (item as NSArray).flatten() as OutType[] } } return result } }
bsd-2-clause
f1042c1c2a28fd567679a0051ff45f14
25.019231
84
0.558019
4.450658
false
false
false
false
SuPair/VPNOn
VPNOnData/VPN+URLScheme.swift
1
2204
// // VPN+URLScheme.swift // VPNOn // // Created by Lex on 1/23/15. // Copyright (c) 2015 LexTang.com. All rights reserved. // import Foundation extension VPN { public class func parseURL(url: NSURL) -> VPNInfo? { var title = "" let server = url.host ?? "" let account = url.user ?? "" let password = url.password ?? "" var group = "" var secret = "" var alwaysOn = true var ikev2 = false var certificateURL = "" // The server is required, otherwise we just open the container app. if server.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0 { return .None } // Parse the query string. if let params = url.query { for paramString in params.componentsSeparatedByString("&") { let param = paramString.componentsSeparatedByString("=") if param.count != 2 { continue } let value = param[1] ?? "" switch param[0] { case "title": title = value break case "group": group = value break case "secret": secret = value break case "alwayson": alwaysOn = Bool(value == "1" || value == "true" || value == "yes") break case "ikev2": ikev2 = Bool(value == "1" || value == "true" || value == "yes") break case "certificate": certificateURL = value break default: () } } } let info = VPNInfo() info.title = title info.server = server info.account = account info.password = password info.group = group info.secret = secret info.alwaysOn = alwaysOn info.ikev2 = ikev2 info.certificateURL = certificateURL return info } }
mit
2928922408d62b495d8bb27a4701ab9e
28
86
0.443285
5.210402
false
false
false
false
lelandjansen/fatigue
ios/fatigue/OccupationCell.swift
1
3435
import UIKit class RoleCell: UICollectionViewCell { override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } weak var delegate: OnboardingDelegate? let titleLabel: UILabel = { let label = UILabel() label.text = "What is your role?" label.font = .systemFont(ofSize: 22) label.textAlignment = .center label.lineBreakMode = .byWordWrapping label.numberOfLines = 0 label.textColor = .dark return label }() lazy var pilotButton: UIButton = { let button = UIButton.createStyledSelectButton(withColor: .violet) button.setTitle(Role.pilot.rawValue.capitalized, for: .normal) button.addTarget(self, action: #selector(handlePilotButton), for: .touchUpInside) return button }() lazy var engineerButton: UIButton = { let button = UIButton.createStyledSelectButton(withColor: .violet) button.setTitle(Role.engineer.rawValue.capitalized, for: .normal) button.addTarget(self, action: #selector(handleEngineerButton), for: .touchUpInside) return button }() var selection: Role = .none { didSet { switch selection { case .pilot: pilotButton.isSelected = true engineerButton.isSelected = false case .engineer: pilotButton.isSelected = false engineerButton.isSelected = true default: pilotButton.isSelected = false engineerButton.isSelected = false } UserDefaults.standard.role = selection } } func handlePilotButton() { selection = .pilot delegate?.addNextPage() delegate?.moveToNextPage() } func handleEngineerButton() { selection = .engineer delegate?.addNextPage() delegate?.moveToNextPage() } func setupViews() { addSubview(titleLabel) addSubview(pilotButton) addSubview(engineerButton) let padding: CGFloat = 16 titleLabel.anchorWithConstantsToTop( topAnchor, left: leftAnchor, right: rightAnchor, topConstant: 3 * padding, leftConstant: padding, rightConstant: padding ) pilotButton.anchorWithConstantsToTop( topAnchor, left: leftAnchor, bottom: centerYAnchor, right: rightAnchor, topConstant: (frame.height - UIConstants.buttonSpacing) / 2 - UIConstants.buttonHeight, leftConstant: (frame.width - UIConstants.buttonWidth) / 2, bottomConstant: UIConstants.buttonSpacing / 2, rightConstant: (frame.width - UIConstants.buttonWidth) / 2 ) engineerButton.anchorWithConstantsToTop( centerYAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: UIConstants.buttonSpacing / 2, leftConstant: (frame.width - UIConstants.buttonWidth) / 2, bottomConstant: (frame.height - UIConstants.buttonSpacing) / 2 - UIConstants.buttonHeight, rightConstant: (frame.width - UIConstants.buttonWidth) / 2 ) } }
apache-2.0
56c8754475458feb178df39ff64ccacb
32.349515
102
0.595924
5.188822
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCILERemoteConnectionParameterRequestReply.swift
1
5277
// // HCILERemoteConnectionParameterRequestReply.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// LE Remote Connection Parameter Request Reply Command /// /// Both the master Host and the slave Host use this command to reply to the HCI /// LE Remote Connection Parameter Request event. This indicates that the Host /// has accepted the remote device’s request to change connection parameters. func lowEnergyRemoteConnectionParameterRequestReply(connectionHandle: UInt16, interval: LowEnergyConnectionIntervalRange, latency: LowEnergyConnectionLatency, timeOut: LowEnergySupervisionTimeout, length: LowEnergyConnectionLength, timeout: HCICommandTimeout = .default) async throws -> UInt16 { let parameters = HCILERemoteConnectionParameterRequestReply(connectionHandle: connectionHandle, interval: interval, latency: latency, timeOut: timeOut, length: length) let returnParameters = try await deviceRequest(parameters, HCILERemoteConnectionParameterRequestReplyReturn.self, timeout: timeout) return returnParameters.connectionHandle } } // MARK: - Command /// LE Remote Connection Parameter Request Reply Command /// /// Both the master Host and the slave Host use this command to reply to the HCI /// LE Remote Connection Parameter Request event. This indicates that the Host /// has accepted the remote device’s request to change connection parameters. @frozen public struct HCILERemoteConnectionParameterRequestReply: HCICommandParameter { public static let command = HCILowEnergyCommand.remoteConnectionParameterRequestReply //0x0020 public var connectionHandle: UInt16 public var interval: LowEnergyConnectionIntervalRange public var latency: LowEnergyConnectionLatency public var timeOut: LowEnergySupervisionTimeout public var length: LowEnergyConnectionLength public init(connectionHandle: UInt16, interval: LowEnergyConnectionIntervalRange, latency: LowEnergyConnectionLatency, timeOut: LowEnergySupervisionTimeout, length: LowEnergyConnectionLength) { self.connectionHandle = connectionHandle self.interval = interval self.latency = latency self.timeOut = timeOut self.length = length } public var data: Data { let connectionHandleBytes = connectionHandle.littleEndian.bytes let connectionIntervalMinBytes = interval.rawValue.lowerBound.littleEndian.bytes let connectionIntervalMaxBytes = interval.rawValue.upperBound.littleEndian.bytes let connectionLatencyBytes = latency.rawValue.littleEndian.bytes let supervisionTimeoutBytes = timeOut.rawValue.littleEndian.bytes let connectionLengthMinBytes = length.rawValue.lowerBound.littleEndian.bytes let connectionLengthMaxBytes = length.rawValue.upperBound.littleEndian.bytes return Data([ connectionHandleBytes.0, connectionHandleBytes.1, connectionIntervalMinBytes.0, connectionIntervalMinBytes.1, connectionIntervalMaxBytes.0, connectionIntervalMaxBytes.1, connectionLatencyBytes.0, connectionLatencyBytes.1, supervisionTimeoutBytes.0, supervisionTimeoutBytes.1, connectionLengthMinBytes.0, connectionLengthMinBytes.1, connectionLengthMaxBytes.0, connectionLengthMaxBytes.1 ]) } } // MARK: - Return parameter /// LE Remote Connection Parameter Request Reply Command /// /// Both the master Host and the slave Host use this command to reply to the HCI /// LE Remote Connection Parameter Request event. This indicates that the Host /// has accepted the remote device’s request to change connection parameters. @frozen public struct HCILERemoteConnectionParameterRequestReplyReturn: HCICommandReturnParameter { public static let command = HCILowEnergyCommand.remoteConnectionParameterRequestReply //0x0020 public static let length: Int = 2 /// Connection_Handle /// Range 0x0000-0x0EFF (all other values reserved for future use) public let connectionHandle: UInt16 // Connection_Handle public init?(data: Data) { guard data.count == type(of: self).length else { return nil } connectionHandle = UInt16(littleEndian: UInt16(bytes: (data[0], data[1]))) } }
mit
bd47b3006151940e6875005aa71e38ed
40.171875
139
0.642125
5.79758
false
false
false
false
yanagiba/swift-lint
Tests/RuleTests/DeadCodeRuleTests.swift
2
10177
/* Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import XCTest @testable import Lint class DeadCodeRuleTests : XCTestCase { func testProperties() { let rule = DeadCodeRule() XCTAssertEqual(rule.identifier, "dead_code") XCTAssertEqual(rule.name, "Dead Code") XCTAssertEqual(rule.fileName, "DeadCodeRule.swift") XCTAssertEqual(rule.description, """ Control transfer statements (`break`, `continue`, `fallthrough`, `return`, and `throw`) can change the order of program execution. In the same scope of code block, the code after control transfer statements is unreachable and will never be executed. So they are considered as dead, and suggested to be removed. """) XCTAssertEqual(rule.examples?.count, 4) XCTAssertEqual(rule.examples?[0], """ for _ in 0..<10 { if foo { break print("foo") // dead code, never print } } """) XCTAssertEqual(rule.examples?[1], """ while foo { if bar { continue print("bar") // dead code, never print } } """) XCTAssertEqual(rule.examples?[2], """ func foo() { if isJobDone { return startNewJob() // dead code, new job won't start } } """) XCTAssertEqual(rule.examples?[3], """ func foo() throws { if isJobFailed { throw JobError.failed restartJob() // dead code, job won't restart } } """) XCTAssertNil(rule.thresholds) XCTAssertNil(rule.additionalDocument) XCTAssertEqual(rule.severity, .major) XCTAssertEqual(rule.category, .badPractice) } func testNoControlTransferStatement() { let issues = """ func foo() { print("foo") } """.inspect(withRule: DeadCodeRule()) XCTAssertTrue(issues.isEmpty) } func testBreak() { let issues = """ switch foo { default: break print("1") } """.inspect(withRule: DeadCodeRule()) XCTAssertEqual(issues.count, 1) let issue = issues[0] XCTAssertEqual(issue.ruleIdentifier, "dead_code") XCTAssertEqual(issue.description, "") XCTAssertEqual(issue.category, .badPractice) XCTAssertEqual(issue.severity, .major) let range = issue.location XCTAssertEqual(range.start.identifier, "test/test") XCTAssertEqual(range.start.line, 4) XCTAssertEqual(range.start.column, 3) XCTAssertEqual(range.end.identifier, "test/test") XCTAssertEqual(range.end.line, 4) XCTAssertEqual(range.end.column, 13) } func testContinue() { let issues = """ func foo() { continue print("foo") } """.inspect(withRule: DeadCodeRule()) XCTAssertEqual(issues.count, 1) let issue = issues[0] XCTAssertEqual(issue.ruleIdentifier, "dead_code") XCTAssertEqual(issue.description, "") XCTAssertEqual(issue.category, .badPractice) XCTAssertEqual(issue.severity, .major) let range = issue.location XCTAssertEqual(range.start.identifier, "test/test") XCTAssertEqual(range.start.line, 3) XCTAssertEqual(range.start.column, 3) XCTAssertEqual(range.end.identifier, "test/test") XCTAssertEqual(range.end.line, 3) XCTAssertEqual(range.end.column, 15) } func testFallthrough() { let issues = """ switch foo { case 1: fallthrough print("1") } """.inspect(withRule: DeadCodeRule()) XCTAssertEqual(issues.count, 1) let issue = issues[0] XCTAssertEqual(issue.ruleIdentifier, "dead_code") XCTAssertEqual(issue.description, "") XCTAssertEqual(issue.category, .badPractice) XCTAssertEqual(issue.severity, .major) let range = issue.location XCTAssertEqual(range.start.identifier, "test/test") XCTAssertEqual(range.start.line, 4) XCTAssertEqual(range.start.column, 3) XCTAssertEqual(range.end.identifier, "test/test") XCTAssertEqual(range.end.line, 4) XCTAssertEqual(range.end.column, 13) } func testReturn() { let issues = """ foo() { return print("bar") } """.inspect(withRule: DeadCodeRule()) XCTAssertEqual(issues.count, 1) let issue = issues[0] XCTAssertEqual(issue.ruleIdentifier, "dead_code") XCTAssertEqual(issue.description, "") XCTAssertEqual(issue.category, .badPractice) XCTAssertEqual(issue.severity, .major) let range = issue.location XCTAssertEqual(range.start.identifier, "test/test") XCTAssertEqual(range.start.line, 3) XCTAssertEqual(range.start.column, 3) XCTAssertEqual(range.end.identifier, "test/test") XCTAssertEqual(range.end.line, 3) XCTAssertEqual(range.end.column, 15) } func testThrow() { let issues = """ func foo() throws { throw .failed print("foo") } """.inspect(withRule: DeadCodeRule()) XCTAssertEqual(issues.count, 1) let issue = issues[0] XCTAssertEqual(issue.ruleIdentifier, "dead_code") XCTAssertEqual(issue.description, "") XCTAssertEqual(issue.category, .badPractice) XCTAssertEqual(issue.severity, .major) let range = issue.location XCTAssertEqual(range.start.identifier, "test/test") XCTAssertEqual(range.start.line, 3) XCTAssertEqual(range.start.column, 3) XCTAssertEqual(range.end.identifier, "test/test") XCTAssertEqual(range.end.line, 3) XCTAssertEqual(range.end.column, 15) } func testIfStmtsNotAllBranchesExit() { let issues = """ func foo() { if foo { // no else return } if foo { print("foo") } else { return } if foo { break } else { return } if foo { return } else if bar { throw .failed } else { print("bar") } } """.inspect(withRule: DeadCodeRule()) XCTAssertTrue(issues.isEmpty) } func testIfExitFromThenElse() { let issues = """ func foo() throws { if foo { throw .failed } else { return } print("foo") } """.inspect(withRule: DeadCodeRule()) XCTAssertEqual(issues.count, 1) let issue = issues[0] XCTAssertEqual(issue.ruleIdentifier, "dead_code") XCTAssertEqual(issue.description, "") XCTAssertEqual(issue.category, .badPractice) XCTAssertEqual(issue.severity, .major) let range = issue.location XCTAssertEqual(range.start.identifier, "test/test") XCTAssertEqual(range.start.line, 7) XCTAssertEqual(range.start.column, 3) XCTAssertEqual(range.end.identifier, "test/test") XCTAssertEqual(range.end.line, 7) XCTAssertEqual(range.end.column, 15) } func testIfExitFromThenElseIfElse() { let issues = """ func foo() throws { if foo { throw .failed } else if bar { return } else { throw .again } print("foo") } """.inspect(withRule: DeadCodeRule()) XCTAssertEqual(issues.count, 1) let issue = issues[0] XCTAssertEqual(issue.ruleIdentifier, "dead_code") XCTAssertEqual(issue.description, "") XCTAssertEqual(issue.category, .badPractice) XCTAssertEqual(issue.severity, .major) let range = issue.location XCTAssertEqual(range.start.identifier, "test/test") XCTAssertEqual(range.start.line, 9) XCTAssertEqual(range.start.column, 3) XCTAssertEqual(range.end.identifier, "test/test") XCTAssertEqual(range.end.line, 9) XCTAssertEqual(range.end.column, 15) } func testDeadCodeInBothInnerAndOuterIfs() { let issues = """ func foo() throws { if foo { throw .failed } else { return print("bar") } print("foo") } """.inspect(withRule: DeadCodeRule()) XCTAssertEqual(issues.count, 2) let issue0 = issues[0] XCTAssertEqual(issue0.ruleIdentifier, "dead_code") XCTAssertEqual(issue0.description, "") XCTAssertEqual(issue0.category, .badPractice) XCTAssertEqual(issue0.severity, .major) let range0 = issue0.location XCTAssertEqual(range0.start.identifier, "test/test") XCTAssertEqual(range0.start.line, 8) XCTAssertEqual(range0.start.column, 3) XCTAssertEqual(range0.end.identifier, "test/test") XCTAssertEqual(range0.end.line, 8) XCTAssertEqual(range0.end.column, 15) let issue1 = issues[1] XCTAssertEqual(issue1.ruleIdentifier, "dead_code") XCTAssertEqual(issue1.description, "") XCTAssertEqual(issue1.category, .badPractice) XCTAssertEqual(issue1.severity, .major) let range1 = issue1.location XCTAssertEqual(range1.start.identifier, "test/test") XCTAssertEqual(range1.start.line, 6) XCTAssertEqual(range1.start.column, 5) XCTAssertEqual(range1.end.identifier, "test/test") XCTAssertEqual(range1.end.line, 6) XCTAssertEqual(range1.end.column, 17) } static var allTests = [ ("testProperties", testProperties), ("testNoControlTransferStatement", testNoControlTransferStatement), ("testBreak", testBreak), ("testContinue", testContinue), ("testFallthrough", testFallthrough), ("testReturn", testReturn), ("testThrow", testThrow), ("testIfStmtsNotAllBranchesExit", testIfStmtsNotAllBranchesExit), ("testIfExitFromThenElse", testIfExitFromThenElse), ("testIfExitFromThenElseIfElse", testIfExitFromThenElseIfElse), ("testDeadCodeInBothInnerAndOuterIfs", testDeadCodeInBothInnerAndOuterIfs), ] }
apache-2.0
a14ca569c87db7dce396658f7a01f3b1
29.653614
93
0.647244
4.184622
false
true
false
false
dataich/TypetalkSwift
Carthage/Checkouts/OAuth2/Sources/Base/OAuth2ClientConfig.swift
1
9082
// // OAuth2ClientConfig.swift // OAuth2 // // Created by Pascal Pfiffner on 16/11/15. // Copyright © 2015 Pascal Pfiffner. All rights reserved. // import Foundation /** Client configuration object that holds on to client-server specific configurations such as client id, -secret and server URLs. */ open class OAuth2ClientConfig { /// The client id. public final var clientId: String? /// The client secret, usually only needed for code grant. public final var clientSecret: String? /// The name of the client, e.g. for use during dynamic client registration. public final var clientName: String? /// The URL to authorize against. public final let authorizeURL: URL /// The URL where we can exchange a code for a token. public final var tokenURL: URL? /// Where a logo/icon for the app can be found. public final var logoURL: URL? /// The scope currently in use. open var scope: String? /// The redirect URL string currently in use. open var redirect: String? /// All redirect URLs passed to the initializer. open var redirectURLs: [String]? /// The receiver's access token. open var accessToken: String? /// The receiver's id token. Used by Google + and AWS Cognito open var idToken: String? /// The access token's expiry date. open var accessTokenExpiry: Date? /// If set to true (the default), uses a keychain-supplied access token even if no "expires_in" parameter was supplied. open var accessTokenAssumeUnexpired = true /// The receiver's long-time refresh token. open var refreshToken: String? /// The URL to register a client against. public final var registrationURL: URL? /// Whether the receiver should use the request body instead of the Authorization header for the client secret; defaults to `false`. public var secretInBody = false /// How the client communicates the client secret with the server. Defaults to ".None" if there is no secret, ".clientSecretPost" if /// "secret_in_body" is `true` and ".clientSecretBasic" otherwise. Interacts with the `secretInBody` setting. public final var endpointAuthMethod = OAuth2EndpointAuthMethod.none /// Contains special authorization request headers, can be used to override defaults. open var authHeaders: OAuth2Headers? /// Add custom parameters to the authorization request. public var customParameters: [String: String]? = nil /// Most servers use UTF-8 encoding for Authorization headers, but that's not 100% true: make it configurable (see https://github.com/p2/OAuth2/issues/165). open var authStringEncoding = String.Encoding.utf8 /// There's an issue with authenticating through 'system browser', where safari says: /// "Safari cannot open the page because the address is invalid." if you first selects 'Cancel' when asked to switch back to "your" app, /// and then you try authenticating again. To get rid of it you must restart Safari. /// /// Read more about it here: /// http://stackoverflow.com/questions/27739442/ios-safari-does-not-recognize-url-schemes-after-user-cancels /// https://community.fitbit.com/t5/Web-API/oAuth2-authentication-page-gives-me-a-quot-Cannot-Open-Page-quot-error/td-p/1150391 /// /// Toggling `safariCancelWorkaround` to true will send an extra get-parameter to make the url unique, thus it will ask again for the new /// url. open var safariCancelWorkaround = false /** Initializer to initialize properties from a settings dictionary. */ public init(settings: OAuth2JSON) { clientId = settings["client_id"] as? String clientSecret = settings["client_secret"] as? String clientName = settings["client_name"] as? String // authorize URL var aURL: URL? if let auth = settings["authorize_uri"] as? String { aURL = URL(string: auth) } authorizeURL = aURL ?? URL(string: "https://localhost/p2.OAuth2.defaultAuthorizeURI")! // token, registration and logo URLs if let token = settings["token_uri"] as? String { tokenURL = URL(string: token) } if let registration = settings["registration_uri"] as? String { registrationURL = URL(string: registration) } if let logo = settings["logo_uri"] as? String { logoURL = URL(string: logo) } // client authorization options scope = settings["scope"] as? String if let redirs = settings["redirect_uris"] as? [String] { redirectURLs = redirs redirect = redirs.first } if let inBody = settings["secret_in_body"] as? Bool { secretInBody = inBody } if secretInBody { endpointAuthMethod = .clientSecretPost } else if nil != clientSecret { endpointAuthMethod = .clientSecretBasic } if let headers = settings["headers"] as? OAuth2Headers { authHeaders = headers } if let params = settings["parameters"] as? OAuth2StringDict { customParameters = params } // access token options if let assume = settings["token_assume_unexpired"] as? Bool { accessTokenAssumeUnexpired = assume } } /** Update properties from response data. This method assumes values are present with the standard names, such as `access_token`, and assigns them to its properties. - parameter json: JSON data returned from a request */ func updateFromResponse(_ json: OAuth2JSON) { if let access = json["access_token"] as? String { accessToken = access } if let idtoken = json["id_token"] as? String { idToken = idtoken } accessTokenExpiry = nil if let expires = json["expires_in"] as? TimeInterval { accessTokenExpiry = Date(timeIntervalSinceNow: expires) } else if let expires = json["expires_in"] as? Int { accessTokenExpiry = Date(timeIntervalSinceNow: Double(expires)) } else if let expires = json["expires_in"] as? String { // when parsing implicit grant from URL fragment accessTokenExpiry = Date(timeIntervalSinceNow: Double(expires) ?? 0.0) } if let refresh = json["refresh_token"] as? String { refreshToken = refresh } } /** Creates a dictionary of credential items that can be stored to the keychain. - returns: A storable dictionary with credentials */ func storableCredentialItems() -> [String: Any]? { guard let clientId = clientId, !clientId.isEmpty else { return nil } var items: [String: Any] = ["id": clientId] if let secret = clientSecret { items["secret"] = secret } items["endpointAuthMethod"] = endpointAuthMethod.rawValue return items } /** Creates a dictionary of token items that can be stored to the keychain. - returns: A storable dictionary with token data */ func storableTokenItems() -> [String: Any]? { guard let access = accessToken, !access.isEmpty else { return nil } var items: [String: Any] = ["accessToken": access] if let date = accessTokenExpiry, date == (date as NSDate).laterDate(Date()) { items["accessTokenDate"] = date } if let refresh = refreshToken, !refresh.isEmpty { items["refreshToken"] = refresh } if let idtoken = idToken, !idtoken.isEmpty { items["idToken"] = idtoken } return items } /** Updates receiver's instance variables with values found in the dictionary. Returns a list of messages that can be logged on debug. - parameter items: The dictionary representation of the data to store to keychain - returns: An array of strings containing log messages */ func updateFromStorableItems(_ items: [String: Any]) -> [String] { var messages = [String]() if let id = items["id"] as? String { clientId = id messages.append("Found client id") } if let secret = items["secret"] as? String { clientSecret = secret messages.append("Found client secret") } if let methodName = items["endpointAuthMethod"] as? String, let method = OAuth2EndpointAuthMethod(rawValue: methodName) { endpointAuthMethod = method } if let token = items["accessToken"] as? String, !token.isEmpty { if let date = items["accessTokenDate"] as? Date { if date == (date as NSDate).laterDate(Date()) { messages.append("Found access token, valid until \(date)") accessTokenExpiry = date accessToken = token } else { messages.append("Found access token but it seems to have expired") } } else if accessTokenAssumeUnexpired { messages.append("Found access token but no expiration date, assuming unexpired (set `accessTokenAssumeUnexpired` to false to discard)") accessToken = token } else { messages.append("Found access token but no expiration date, discarding (set `accessTokenAssumeUnexpired` to true to still use it)") } } if let token = items["refreshToken"] as? String, !token.isEmpty { messages.append("Found refresh token") refreshToken = token } if let idtoken = items["idToken"] as? String, !idtoken.isEmpty { messages.append("Found id token") idToken = idtoken } return messages } /** Forgets the configuration's client id and secret. */ open func forgetCredentials() { clientId = nil clientSecret = nil } /** Forgets the configuration's current tokens. */ open func forgetTokens() { accessToken = nil accessTokenExpiry = nil refreshToken = nil idToken = nil } }
mit
48792198a194f56e700518a15a4983cf
32.142336
157
0.710054
3.838123
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/00199-swift-optional-swift-diagnostic-operator.swift
11
903
// 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 // RUN: not %target-swift-frontend %s -parse protocol b { class func e() } struct c { var d: b.Type func e() { d.e() } } func e<k>() -> (k, k -> k) -> k { f j f.i = { } { k) { n } } m e { class func i() } class f: e{ class 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 = 0) { } l -> Any) return $0 } let succeeds: Int = 1, f1) class A<T : A> { } class c { func b((Any, c))(a: (Any, AnyObj c() -> Str rn func e<T where Tj d. h }b }
apache-2.0
f78edc28de45d3853516c0b7bbabc1ae
19.066667
78
0.570321
2.753049
false
false
false
false
jonasman/TeslaSwift
TeslaSwiftDemo/AppDelegate.swift
1
2579
// // AppDelegate.swift // TeslaSwift // // Created by Joao Nunes on 04/03/16. // Copyright © 2016 Joao Nunes. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var api = TeslaSwift() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. api.debuggingEnabled = true if let jsonString = UserDefaults.standard.object(forKey: "tesla.token") as? String, let token: AuthToken = jsonString.decodeJSON(), let email = UserDefaults.standard.object(forKey: "tesla.email") as? String { api.reuse(token: token, email: email) } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. UserDefaults.standard.set(api.token?.jsonString, forKey: "tesla.token") UserDefaults.standard.set(api.email, forKey: "tesla.email") UserDefaults.standard.synchronize() } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
e543b0b5cb1ba47f710c73ce20a51809
41.966667
279
0.772692
4.661844
false
false
false
false
gouyz/GYZBaking
baking/Classes/Mine/Controller/GYZModifyPassWordVC.swift
1
6148
// // GYZModifyPassWordVC.swift // baking // 修改账户密码 二 // Created by gouyz on 2017/3/31. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit import MBProgressHUD class GYZModifyPassWordVC: GYZBaseVC { /// 手机号 var phone: String = "" /// 验证码 var codeStr: String = "" override func viewDidLoad() { super.viewDidLoad() self.title = "修改账户密码" self.view.backgroundColor = kWhiteColor view.addSubview(codeFiled) view.addSubview(codeBtn) view.addSubview(pwdFiled) view.addSubview(okBtn) codeFiled.snp.makeConstraints { (make) in make.left.equalTo(view).offset(kMargin) make.top.equalTo(kMargin) make.right.equalTo(codeBtn.snp.left).offset(-5) make.height.equalTo(kTitleHeight) } codeBtn.snp.makeConstraints { (make) in make.right.equalTo(view).offset(-kMargin) make.top.height.equalTo(codeFiled) make.width.equalTo(80) } pwdFiled.snp.makeConstraints { (make) in make.left.height.equalTo(codeFiled) make.top.equalTo(codeFiled.snp.bottom).offset(kMargin) make.right.equalTo(view).offset(-kMargin) } okBtn.snp.makeConstraints { (make) in make.left.right.height.equalTo(pwdFiled) make.top.equalTo(pwdFiled.snp.bottom).offset(kMargin) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /// 输入框 lazy var codeFiled : UITextField = { let textFiled = UITextField() textFiled.font = k15Font textFiled.textColor = kBlackFontColor textFiled.clearButtonMode = .whileEditing textFiled.placeholder = "输入收到的短信验证码" textFiled.keyboardType = .namePhonePad textFiled.backgroundColor = kBackgroundColor textFiled.cornerRadius = kCornerRadius return textFiled }() /// 输入框 lazy var pwdFiled : UITextField = { let textFiled = UITextField() textFiled.font = k15Font textFiled.textColor = kBlackFontColor textFiled.clearButtonMode = .whileEditing textFiled.placeholder = "输入新密码" textFiled.backgroundColor = kBackgroundColor textFiled.cornerRadius = kCornerRadius textFiled.isSecureTextEntry = true return textFiled }() /// 获取验证码按钮 fileprivate lazy var codeBtn : UIButton = { let btn = UIButton.init(type: .custom) btn.backgroundColor = kWhiteColor btn.setTitle("发送验证码", for: .normal) btn.setTitleColor(kBlackFontColor, for: .normal) btn.titleLabel?.font = k15Font btn.titleLabel?.textAlignment = .center btn.borderColor = kBlackFontColor btn.borderWidth = klineWidth btn.cornerRadius = kCornerRadius btn.addTarget(self, action: #selector(clickedCodeBtn(btn:)), for: .touchUpInside) return btn }() /// 确定按钮 fileprivate lazy var okBtn : UIButton = { let btn = UIButton.init(type: .custom) btn.backgroundColor = kBtnClickBGColor btn.setTitle("确 定", for: .normal) btn.setTitleColor(kWhiteColor, for: .normal) btn.titleLabel?.font = k15Font btn.addTarget(self, action: #selector(clickedOkBtn(btn:)), for: .touchUpInside) btn.cornerRadius = kCornerRadius return btn }() /// 确定 func clickedOkBtn(btn: UIButton){ if codeFiled.text!.isEmpty { MBProgressHUD.showAutoDismissHUD(message: "请输入验证码") return }else if codeFiled.text! != codeStr{ MBProgressHUD.showAutoDismissHUD(message: "验证码错误") return } if pwdFiled.text!.isEmpty { MBProgressHUD.showAutoDismissHUD(message: "请输入密码") return } requestUpdatePwd() } /// 获取验证码 func clickedCodeBtn(btn: UIButton){ requestCode() } ///获取二维码 func requestCode(){ weak var weakSelf = self createHUD(message: "获取中...") GYZNetWork.requestNetwork("User/get_code", parameters: ["phone":phone], success: { (response) in weakSelf?.codeBtn.startSMSWithDuration(duration: 60) weakSelf?.hud?.hide(animated: true) // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 let data = response["result"] let info = data["info"] weakSelf?.codeStr = info["code"].stringValue }else{ MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) } }, failture: { (error) in weakSelf?.hud?.hide(animated: true) GYZLog(error) }) } /// 修改密码 func requestUpdatePwd(){ weak var weakSelf = self createHUD(message: "加载中...") GYZNetWork.requestNetwork("User/updatePassword", parameters: ["phone":phone,"password": pwdFiled.text!.md5()], success: { (response) in weakSelf?.hud?.hide(animated: true) // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 GYZTool.removeUserInfo() KeyWindow.rootViewController = GYZBaseNavigationVC(rootViewController: GYZLoginVC()) }else{ MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) } }, failture: { (error) in weakSelf?.hud?.hide(animated: true) GYZLog(error) }) } }
mit
4a125f9ae29edbdc924299c6db9c6d46
30.919355
144
0.578407
4.799515
false
false
false
false
Draveness/DKChainableAnimationKit
DKChainableAnimationKit/Classes/DKChainableAnimationKit+Effects.swift
3
7110
// // DKChainableAnimationKit+Effects.swift // DKChainableAnimationKit // // Created by Draveness on 15/6/12. // Copyright (c) 2015年 Draveness. All rights reserved. // import UIKit public extension DKChainableAnimationKit { // MARK: - Animation Effects public var easeIn: DKChainableAnimationKit { get { _ = self.easeInQuad return self } } public var easeOut: DKChainableAnimationKit { get { _ = self.easeOutQuad return self } } public var easeInOut: DKChainableAnimationKit { get { _ = self.easeInOutQuad return self } } public var easeBack: DKChainableAnimationKit { get { _ = self.easeOutBack return self } } public var spring: DKChainableAnimationKit { get { _ = self.easeOutElastic return self } } public var bounce: DKChainableAnimationKit { get { _ = self.easeOutBounce return self } } public var easeInQuad: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInQuad) return self } } public var easeOutQuad: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseOutQuad) return self } } public var easeInOutQuad: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInOutQuad) return self } } public var easeInCubic: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInCubic) return self } } public var easeOutCubic: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseOutCubic) return self } } public var easeInOutCubic: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInOutCubic) return self } } public var easeInQuart: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInQuart) return self } } public var easeOutQuart: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseOutQuart) return self } } public var easeInOutQuart: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInOutQuart) return self } } public var easeInQuint: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInQuint) return self } } public var easeOutQuint: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseOutQuint) return self } } public var easeInOutQuint: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInOutQuint) return self } } public var easeInSine: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInSine) return self } } public var easeOutSine: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseOutSine) return self } } public var easeInOutSine: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInOutSine) return self } } public var easeInExpo: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInExpo) return self } } public var easeOutExpo: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseOutExpo) return self } } public var easeInOutExpo: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInOutExpo) return self } } public var easeInCirc: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInCirc) return self } } public var easeOutCirc: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseOutCirc) return self } } public var easeInOutCirc: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInOutCirc) return self } } public var easeInElastic: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInElastic) return self } } public var easeOutElastic: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseOutElastic) return self } } public var easeInOutElastic: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInOutElastic) return self } } public var easeInBack: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInBack) return self } } public var easeOutBack: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseOutBack) return self } } public var easeInOutBack: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInOutBack) return self } } public var easeInBounce: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInBounce) return self } } public var easeOutBounce: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseOutBounce) return self } } public var easeInOutBounce: DKChainableAnimationKit { get { self.addAnimationKeyframeCalculation(DKKeyframeAnimationFunctionEaseInOutBounce) return self } } }
mit
3d65a57fe4c0eef4ba72131cd4e79db2
25.721805
93
0.638576
5.654733
false
false
false
false
tuyenbq/Moya
Demo/DemoTests/MoyaProviderSpec.swift
1
12105
import Quick import Nimble import Alamofire import Moya class MoyaProviderSpec: QuickSpec { override func spec() { var provider: MoyaProvider<GitHub>! beforeEach { provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour) } it("returns stubbed data for zen request") { var message: String? let target: GitHub = .Zen provider.request(target) { (data, statusCode, response, error) in if let data = data { message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String } } let sampleData = target.sampleData as NSData expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding))) } it("returns stubbed data for user profile request") { var message: String? let target: GitHub = .UserProfile("ashfurrow") provider.request(target) { (data, statusCode, response, error) in if let data = data { message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String } } let sampleData = target.sampleData as NSData expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding))) } it("returns equivalent Endpoint instances for the same target") { let target: GitHub = .Zen let endpoint1 = provider.endpoint(target) let endpoint2 = provider.endpoint(target) expect(endpoint1.urlRequest).to(equal(endpoint2.urlRequest)) } it("returns a cancellable object when a request is made") { let target: GitHub = .UserProfile("ashfurrow") let cancellable: Cancellable = provider.request(target) { (_, _, _, _) in } expect(cancellable).toNot(beNil()) } it("uses the Alamofire.Manager.sharedInstance by default") { expect(provider.manager).to(beIdenticalTo(Alamofire.Manager.sharedInstance)) } it("credential closure returns nil") { var called = false let provider = MoyaProvider<HTTPBin>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, credentialClosure: { (target) -> NSURLCredential? in called = true return nil }) let target: HTTPBin = .BasicAuth provider.request(target) { (data, statusCode, response, error) in } expect(called) == true } it("credential closure returns valid username and password") { var called = false let provider = MoyaProvider<HTTPBin>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, credentialClosure: { (target) -> NSURLCredential? in called = true return NSURLCredential(user: "user", password: "passwd", persistence: .None) }) let target: HTTPBin = .BasicAuth provider.request(target) { (data, statusCode, response, error) in } expect(called) == true } it("accepts a custom Alamofire.Manager") { let manager = Manager() let provider = MoyaProvider<GitHub>(manager: manager) expect(provider.manager).to(beIdenticalTo(manager)) } it("uses a custom Alamofire.Manager for session challenges") { var called = false let manager = Manager() manager.delegate.sessionDidReceiveChallenge = { (session, challenge) in called = true let disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling return (disposition, nil) } let provider = MoyaProvider<GitHub>(manager: manager) let target: GitHub = .Zen waitUntil(timeout: 3) { done in provider.request(target) { (data, statusCode, response, error) in done() } return } expect(called) == true } it("notifies at the beginning of network requests") { var called = false let provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, networkActivityClosure: { (change) -> () in if change == .Began { called = true } }) let target: GitHub = .Zen provider.request(target) { (data, statusCode, response, error) in } expect(called) == true } it("notifies at the end of network requests") { var called = false let provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, networkActivityClosure: { (change) -> () in if change == .Ended { called = true } }) let target: GitHub = .Zen provider.request(target) { (data, statusCode, response, error) in } expect(called) == true } it("delays execution when appropriate") { let provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.DelayedStubbingBehaviour(2)) let startDate = NSDate() var endDate: NSDate? let target: GitHub = .Zen waitUntil(timeout: 3) { done in provider.request(target) { (data, statusCode, response, error) in endDate = NSDate() done() } return } expect { return endDate?.timeIntervalSinceDate(startDate) }.to( beGreaterThanOrEqualTo(NSTimeInterval(2)) ) } describe("a provider with a custom endpoint resolver") { var provider: MoyaProvider<GitHub>! var executed = false beforeEach { executed = false let endpointResolution = { (endpoint: Endpoint<GitHub>) -> (NSURLRequest) in executed = true return endpoint.urlRequest } provider = MoyaProvider<GitHub>(endpointResolver: endpointResolution, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour) } it("executes the endpoint resolver") { let target: GitHub = .Zen provider.request(target, completion: { (data, statusCode, response, error) in }) expect(executed).to(beTruthy()) } } describe("with stubbed errors") { var provider: MoyaProvider<GitHub>! beforeEach { provider = MoyaProvider(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour) } it("returns stubbed data for zen request") { var errored = false let target: GitHub = .Zen provider.request(target) { (object, statusCode, response, error) in if error != nil { errored = true } } let _ = target.sampleData expect(errored).toEventually(beTruthy()) } it("returns stubbed data for user profile request") { var errored = false let target: GitHub = .UserProfile("ashfurrow") provider.request(target) { (object, statusCode, response, error) in if error != nil { errored = true } } let _ = target.sampleData expect{errored}.toEventually(beTruthy(), timeout: 1, pollInterval: 0.1) } it("returns stubbed error data when present") { var errorMessage = "" let target: GitHub = .UserProfile("ashfurrow") provider.request(target) { (object, statusCode, response, error) in if let object = object { errorMessage = NSString(data: object, encoding: NSUTF8StringEncoding) as! String } } expect{errorMessage}.toEventually(equal("Houston, we have a problem"), timeout: 1, pollInterval: 0.1) } } describe("with lazy data") { var provider: MoyaProvider<GitHub>! beforeEach { provider = MoyaProvider<GitHub>(endpointClosure: lazyEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour) } it("returns stubbed data for zen request") { var message: String? let target: GitHub = .Zen provider.request(target) { (data, statusCode, response, error) in if let data = data { message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String } } let sampleData = target.sampleData as NSData expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding))) } } } } private extension String { var URLEscapedString: String { return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())! } } private enum GitHub { case Zen case UserProfile(String) } extension GitHub : MoyaTarget { var baseURL: NSURL { return NSURL(string: "https://api.github.com")! } var path: String { switch self { case .Zen: return "/zen" case .UserProfile(let name): return "/users/\(name.URLEscapedString)" } } var method: Moya.Method { return .GET } var parameters: [String: AnyObject] { return [:] } var sampleData: NSData { switch self { case .Zen: return "Half measures are as bad as nothing at all.".dataUsingEncoding(NSUTF8StringEncoding)! case .UserProfile(let name): return "{\"login\": \"\(name)\", \"id\": 100}".dataUsingEncoding(NSUTF8StringEncoding)! } } } private func url(route: MoyaTarget) -> String { return route.baseURL.URLByAppendingPathComponent(route.path).absoluteString } private let lazyEndpointClosure = { (target: GitHub) -> Endpoint<GitHub> in return Endpoint<GitHub>(URL: url(target), sampleResponse: .Closure({.Success(200, {target.sampleData})}), method: target.method, parameters: target.parameters) } private let failureEndpointClosure = { (target: GitHub) -> Endpoint<GitHub> in let errorData = "Houston, we have a problem".dataUsingEncoding(NSUTF8StringEncoding)! return Endpoint<GitHub>(URL: url(target), sampleResponse: .Error(401, NSError(domain: "com.moya.error", code: 0, userInfo: nil), {errorData}), method: target.method, parameters: target.parameters) } private enum HTTPBin: MoyaTarget { case BasicAuth var baseURL: NSURL { return NSURL(string: "http://httpbin.org")! } var path: String { switch self { case .BasicAuth: return "/basic-auth/user/passwd" } } var method: Moya.Method { return .GET } var parameters: [String: AnyObject] { switch self { default: return [:] } } var sampleData: NSData { switch self { case .BasicAuth: return "{\"authenticated\": true, \"user\": \"user\"}".dataUsingEncoding(NSUTF8StringEncoding)! } } }
mit
5f39cf47a44b7351b840cac320402c5d
35.570997
200
0.548368
5.542582
false
false
false
false
tjw/swift
test/stdlib/SmallString.swift
1
4247
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop // REQUIRES: CPU=arm64 || CPU=x86_64 // // Tests for small strings // import StdlibUnittest import Foundation var SmallStringTests = TestSuite("SmallStringTests") extension String: Error {} func verifySmallString(_ small: _SmallUTF8String, _ input: String) { expectEqual(_SmallUTF8String.capacity, small.count + small.unusedCapacity) let tiny = Array(input.utf8) expectEqual(tiny.count, small.count) for (lhs, rhs) in zip(tiny, small) { expectEqual(lhs, rhs) } small.withTranscodedUTF16CodeUnits { let codeUnits = Array(input.utf16) expectEqualSequence(codeUnits, $0) } let smallFromUTF16 = _SmallUTF8String(Array(input.utf16)) expectNotNil(smallFromUTF16) expectEqualSequence(small, smallFromUTF16!) // Test slicing // for i in 0..<small.count { for j in i...small.count { expectEqualSequence(tiny[i..<j], small[i..<j]) if j < small.count { expectEqualSequence(tiny[i...j], small[i...j]) } } } } SmallStringTests.test("FitsInSmall") { func runTest(_ input: String) throws { let tiny = Array(input.utf8) // Constructed from UTF-8 code units guard let small = _SmallUTF8String(tiny) else { throw "Didn't fit" } verifySmallString(small, input) // Constructed from UTF-16 code units guard let fromUTF16Small = _SmallUTF8String(Array(input.utf16)) else { throw "Failed from utf-16" } verifySmallString(fromUTF16Small, input) } // Pass tests // // TODO(UTF-8 SSO): expectDoesNotThrow({ try runTest("ab😇c") }) expectDoesNotThrow({ try runTest("0123456789abcde") }) // TODO(UTF-8 SSO): expectDoesNotThrow({ try runTest("👨‍👦") }) expectDoesNotThrow({ try runTest("") }) // Fail tests // expectThrows("Didn't fit", { try runTest("0123456789abcdef") }) expectThrows("Didn't fit", { try runTest("👩‍👦‍👦") }) } SmallStringTests.test("Bridging") { // Test bridging retains small string form func bridge(_ small: _SmallUTF8String) -> String { return _bridgeToCocoa(small) as! String } func runTestSmall(_ input: String) throws { // Constructed through CF guard let fromCocoaSmall = _SmallUTF8String( _cocoaString: input as NSString ) else { throw "Didn't fit" } verifySmallString(fromCocoaSmall, input) verifySmallString(fromCocoaSmall, bridge(fromCocoaSmall)) } // Pass tests // expectDoesNotThrow({ try runTestSmall("abc") }) expectDoesNotThrow({ try runTestSmall("0123456789abcde") }) expectDoesNotThrow({ try runTestSmall("\u{0}") }) // TODO(UTF-8 SSO): expectDoesNotThrow({ try runTestSmall("👨‍👦") }) expectDoesNotThrow({ try runTestSmall("") }) // TODO(UTF-8 SSO): expectDoesNotThrow({ try runTestSmall("👨‍👦abcd") }) // Fail tests // expectThrows("Didn't fit", { try runTestSmall("👨‍👩‍👦") }) expectThrows("Didn't fit", { try runTestSmall("👨‍👦abcde") }) } SmallStringTests.test("Append, repeating") { let strings = [ "", "a", "bc", "def", "hijk", "lmnop", "qrstuv", "xyzzzzz", "01234567", "890123456", "7890123456", "78901234567", "890123456789", "0123456789012", "34567890123456", "789012345678901", ] let smallstrings = strings.compactMap { _SmallUTF8String(Array($0.utf8)) } expectEqual(strings.count, smallstrings.count) for (small, str) in zip(smallstrings, strings) { verifySmallString(small, str) } for i in 0..<smallstrings.count { for j in i..<smallstrings.count { let lhs = smallstrings[i] let rhs = smallstrings[j] if lhs.count + rhs.count > _SmallUTF8String.capacity { continue } verifySmallString(lhs._appending(rhs)!, (strings[i] + strings[j])) verifySmallString(rhs._appending(lhs)!, (strings[j] + strings[i])) } } for i in 0..<smallstrings.count { for c in 2...15 { let str = String(repeating: strings[i], count: c) if let small = smallstrings[i]._repeated(c) { verifySmallString(small, str) } else { expectTrue(str.utf8.count > 15) } } } } runAllTests()
apache-2.0
474d5cde50ced5f76ea2ba2bf555e1cb
26.006452
76
0.647635
3.688106
false
true
false
false
wangyuanou/Coastline
Coastline/Structure/String+URL.swift
1
1460
// // String+URL.swift // Coastline // // Created by 王渊鸥 on 2016/12/14. // Copyright © 2016年 王渊鸥. All rights reserved. // import Foundation public extension String { public var url:URL? { guard let parts = self.urlParts else { return nil } if let str = String.combineUrl(parts: parts) { return URL(string: str) } return nil } public var fileURL:URL { return URL(fileURLWithPath: self) } public var urlString: String? { return self.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) } public var unUrlString: String? { return self.removingPercentEncoding } public var urlParts: [String:String]? { let reqs = self.components(separatedBy: "?") if reqs.count == 0 { return nil } var result:[String:String] = [:] result["body"] = reqs[0] if reqs.count > 1 { let paramString = reqs[1] let params = paramString.components(separatedBy: "&") for aParam in params { let kv = aParam.head2Parts(gap: "=") if let key = kv.0.unUrlString, let value = kv.1?.unUrlString { result[key] = value } } } return result } static public func combineUrl(parts:[String:String]) -> String? { guard let body = parts["body"] else { return nil } var result = body + "?" for (k,v) in parts { if k == "body" { continue } if let key = k.urlString, let value = v.urlString { result += "\(key)=\(value)&" } } return result } }
mit
69f390b8fa441aefa0da83cc71610b6d
19.642857
76
0.631142
3.23991
false
false
false
false
nameghino/swift-algorithm-club
Boyer-Moore/BoyerMoore.playground/Contents.swift
1
1189
//: Playground - noun: a place where people can play extension String { func indexOf(pattern: String) -> String.Index? { let patternLength = pattern.characters.count assert(patternLength > 0) assert(patternLength <= self.characters.count) var skipTable = [Character: Int]() for (i, c) in pattern.characters.enumerate() { skipTable[c] = patternLength - i - 1 } let p = pattern.endIndex.predecessor() let lastChar = pattern[p] var i = self.startIndex.advancedBy(patternLength - 1) func backwards() -> String.Index? { var q = p var j = i while q > pattern.startIndex { j = j.predecessor() q = q.predecessor() if self[j] != pattern[q] { return nil } } return j } while i < self.endIndex { let c = self[i] if c == lastChar { if let k = backwards() { return k } i = i.successor() } else { i = i.advancedBy(skipTable[c] ?? patternLength) } } return nil } } // A few simple tests let s = "Hello, World" s.indexOf("World") // 7 // Input: let animals = "🐶🐔🐷🐮🐱" animals.indexOf("🐮") // 6
mit
2a59b5ebfe52dd2d0657fa9a97b05e82
22.897959
57
0.566183
3.647975
false
false
false
false
MrAdamBoyd/SwiftBus
Pod/Classes/DictionaryKey.swift
2
400
// // DictionaryKey.swift // Pods // // Created by Adam Boyd on 2017/6/23. // // import Foundation public typealias AgencyTag = String public typealias RouteTag = String public typealias StopTag = String public typealias DirectionName = String public typealias PredictionGroup = [RouteTag: [StopTag: [TransitPrediction]]] public typealias StopRoutePair = (stopTag: StopTag, routeTag: RouteTag)
mit
a5289632322e791691c5cb4e988df857
22.529412
77
0.7625
3.773585
false
false
false
false
shajrawi/swift
test/Sema/struct_equatable_hashable.swift
3
12143
// RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/struct_equatable_hashable_other.swift -verify-ignore-unknown -swift-version 4 var hasher = Hasher() struct Point: Hashable { let x: Int let y: Int } func point() { if Point(x: 1, y: 2) == Point(x: 2, y: 1) { } let _: Int = Point(x: 3, y: 5).hashValue Point(x: 3, y: 5).hash(into: &hasher) Point(x: 1, y: 2) == Point(x: 2, y: 1) // expected-warning {{result of operator '==' is unused}} } struct Pair<T: Hashable>: Hashable { let first: T let second: T func same() -> Bool { return first == second } } func pair() { let p1 = Pair(first: "a", second: "b") let p2 = Pair(first: "a", second: "c") if p1 == p2 { } let _: Int = p1.hashValue p1.hash(into: &hasher) } func localStruct() -> Bool { struct Local: Equatable { let v: Int } return Local(v: 5) == Local(v: 4) } //------------------------------------------------------------------------------ // Verify compiler can derive hash(into:) implementation from hashValue struct CustomHashValue: Hashable { let x: Int let y: Int static func ==(x: CustomHashValue, y: CustomHashValue) -> Bool { return true } func hash(into hasher: inout Hasher) {} } func customHashValue() { if CustomHashValue(x: 1, y: 2) == CustomHashValue(x: 2, y: 3) { } let _: Int = CustomHashValue(x: 1, y: 2).hashValue CustomHashValue(x: 1, y: 2).hash(into: &hasher) } //------------------------------------------------------------------------------ // Verify compiler can derive hashValue implementation from hash(into:) struct CustomHashInto: Hashable { let x: Int let y: Int func hash(into hasher: inout Hasher) { hasher.combine(x) hasher.combine(y) } static func ==(x: CustomHashInto, y: CustomHashInto) -> Bool { return true } } func customHashInto() { if CustomHashInto(x: 1, y: 2) == CustomHashInto(x: 2, y: 3) { } let _: Int = CustomHashInto(x: 1, y: 2).hashValue CustomHashInto(x: 1, y: 2).hash(into: &hasher) } // Check use of an struct's synthesized members before the struct is actually declared. struct UseStructBeforeDeclaration { let eqValue = StructToUseBeforeDeclaration(v: 4) == StructToUseBeforeDeclaration(v: 5) let hashValue = StructToUseBeforeDeclaration(v: 1).hashValue let hashInto: (inout Hasher) -> Void = StructToUseBeforeDeclaration(v: 1).hash(into:) } struct StructToUseBeforeDeclaration: Hashable { let v: Int } func getFromOtherFile() -> AlsoFromOtherFile { return AlsoFromOtherFile(v: 4) } func overloadFromOtherFile() -> YetAnotherFromOtherFile { return YetAnotherFromOtherFile(v: 1.2) } func overloadFromOtherFile() -> Bool { return false } func useStructBeforeDeclaration() { // Check structs from another file in the same module. if FromOtherFile(v: "a") == FromOtherFile(v: "b") {} let _: Int = FromOtherFile(v: "c").hashValue FromOtherFile(v: "d").hash(into: &hasher) if AlsoFromOtherFile(v: 3) == getFromOtherFile() {} if YetAnotherFromOtherFile(v: 1.9) == overloadFromOtherFile() {} } // Even if the struct has only equatable/hashable members, it's not synthesized // implicitly. struct StructWithoutExplicitConformance { let a: Int let b: String } func structWithoutExplicitConformance() { if StructWithoutExplicitConformance(a: 1, b: "b") == StructWithoutExplicitConformance(a: 2, b: "a") { } // expected-error{{binary operator '==' cannot be applied to two 'StructWithoutExplicitConformance' operands}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }} } // Structs with non-hashable/equatable stored properties don't derive conformance. struct NotHashable {} struct StructWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}} let a: NotHashable } // ...but computed properties and static properties are not considered. struct StructIgnoresComputedProperties: Hashable { var a: Int var b: String static var staticComputed = NotHashable() var computed: NotHashable { return NotHashable() } } func structIgnoresComputedProperties() { if StructIgnoresComputedProperties(a: 1, b: "a") == StructIgnoresComputedProperties(a: 2, b: "c") {} let _: Int = StructIgnoresComputedProperties(a: 3, b: "p").hashValue StructIgnoresComputedProperties(a: 4, b: "q").hash(into: &hasher) } // Structs should be able to derive conformances based on the conformances of // their generic arguments. struct GenericHashable<T: Hashable>: Hashable { let value: T } func genericHashable() { if GenericHashable<String>(value: "a") == GenericHashable<String>(value: "b") { } let _: Int = GenericHashable<String>(value: "c").hashValue GenericHashable<String>(value: "c").hash(into: &hasher) } // But it should be an error if the generic argument doesn't have the necessary // constraints to satisfy the conditions for derivation. struct GenericNotHashable<T: Equatable>: Hashable { // expected-error 2 {{does not conform to protocol 'Hashable'}} let value: T } func genericNotHashable() { if GenericNotHashable<String>(value: "a") == GenericNotHashable<String>(value: "b") { } let gnh = GenericNotHashable<String>(value: "b") let _: Int = gnh.hashValue // No error. hashValue is always synthesized, even if Hashable derivation fails gnh.hash(into: &hasher) // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hash'}} } // Synthesis can be from an extension... struct StructConformsInExtension { let v: Int } extension StructConformsInExtension : Equatable {} // and explicit conformance in an extension should also work. public struct StructConformsAndImplementsInExtension { let v: Int } extension StructConformsAndImplementsInExtension : Equatable { public static func ==(lhs: StructConformsAndImplementsInExtension, rhs: StructConformsAndImplementsInExtension) -> Bool { return true } } // No explicit conformance and it cannot be derived. struct NotExplicitlyHashableAndCannotDerive { let v: NotHashable } extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}} // A struct with no stored properties trivially derives conformance. struct NoStoredProperties: Hashable {} // Verify that conformance (albeit manually implemented) can still be added to // a type in a different file. extension OtherFileNonconforming: Hashable { static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool { return true } func hash(into hasher: inout Hasher) {} } // ...but synthesis in a type defined in another file doesn't work yet. extension YetOtherFileNonconforming: Equatable {} // expected-error {{cannot be automatically synthesized in an extension in a different file to the type}} // Verify that we can add Hashable conformance in an extension by only // implementing hash(into:) struct StructConformsAndImplementsHashIntoInExtension: Equatable { let v: String } extension StructConformsAndImplementsHashIntoInExtension: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(v) } } func structConformsAndImplementsHashIntoInExtension() { let _: Int = StructConformsAndImplementsHashIntoInExtension(v: "a").hashValue StructConformsAndImplementsHashIntoInExtension(v: "b").hash(into: &hasher) } struct GenericHashIntoInExtension<T: Hashable>: Equatable { let value: T } extension GenericHashIntoInExtension: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(value) } } func genericHashIntoInExtension() { let _: Int = GenericHashIntoInExtension<String>(value: "a").hashValue GenericHashIntoInExtension(value: "b").hash(into: &hasher) } // Conditional conformances should be able to be synthesized struct GenericDeriveExtension<T> { let value: T } extension GenericDeriveExtension: Equatable where T: Equatable {} extension GenericDeriveExtension: Hashable where T: Hashable {} // Incorrectly/insufficiently conditional shouldn't work struct BadGenericDeriveExtension<T> { let value: T } extension BadGenericDeriveExtension: Equatable {} // expected-error@-1 {{type 'BadGenericDeriveExtension<T>' does not conform to protocol 'Equatable'}} extension BadGenericDeriveExtension: Hashable where T: Equatable {} // expected-error@-1 {{type 'BadGenericDeriveExtension' does not conform to protocol 'Hashable'}} // But some cases don't need to be conditional, even if they look similar to the // above struct AlwaysHashable<T>: Hashable {} struct UnusedGenericDeriveExtension<T> { let value: AlwaysHashable<T> } extension UnusedGenericDeriveExtension: Hashable {} // Cross-file synthesis is still disallowed for conditional cases extension GenericOtherFileNonconforming: Equatable where T: Equatable {} // expected-error@-1{{implementation of 'Equatable' cannot be automatically synthesized in an extension in a different file to the type}} // rdar://problem/41852654 // There is a conformance to Equatable (or at least, one that implies Equatable) // in the same file as the type, so the synthesis is okay. Both orderings are // tested, to catch choosing extensions based on the order of the files, etc. protocol ImplierMain: Equatable {} struct ImpliedMain: ImplierMain {} extension ImpliedOther: ImplierMain {} // Hashable conformances that rely on a manual implementation of `hashValue` // should produce a deprecation warning. struct OldSchoolStruct: Hashable { static func ==(left: OldSchoolStruct, right: OldSchoolStruct) -> Bool { return true } var hashValue: Int { return 42 } // expected-warning@-1{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'OldSchoolStruct' to 'Hashable' by implementing 'hash(into:)' instead}} } enum OldSchoolEnum: Hashable { case foo case bar static func ==(left: OldSchoolEnum, right: OldSchoolEnum) -> Bool { return true } var hashValue: Int { return 23 } // expected-warning@-1{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'OldSchoolEnum' to 'Hashable' by implementing 'hash(into:)' instead}} } class OldSchoolClass: Hashable { static func ==(left: OldSchoolClass, right: OldSchoolClass) -> Bool { return true } var hashValue: Int { return -9000 } // expected-warning@-1{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'OldSchoolClass' to 'Hashable' by implementing 'hash(into:)' instead}} } // However, it's okay to implement `hashValue` as long as `hash(into:)` is also // provided. struct MixedStruct: Hashable { static func ==(left: MixedStruct, right: MixedStruct) -> Bool { return true } func hash(into hasher: inout Hasher) {} var hashValue: Int { return 42 } } enum MixedEnum: Hashable { case foo case bar static func ==(left: MixedEnum, right: MixedEnum) -> Bool { return true } func hash(into hasher: inout Hasher) {} var hashValue: Int { return 23 } } class MixedClass: Hashable { static func ==(left: MixedClass, right: MixedClass) -> Bool { return true } func hash(into hasher: inout Hasher) {} var hashValue: Int { return -9000 } } // Ensure equatable and hashable works with weak/unowned properties as well struct Foo: Equatable, Hashable { weak var foo: Bar? unowned var bar: Bar } class Bar { let bar: String init(bar: String) { self.bar = bar } } extension Bar: Equatable, Hashable { static func == (lhs: Bar, rhs: Bar) -> Bool { return lhs.bar == rhs.bar } func hash(into hasher: inout Hasher) {} } // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected error produced: invalid redeclaration of 'hashValue' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
apache-2.0
726566038b65c843b0d52eeef5431373
34.197101
216
0.718933
3.946376
false
false
false
false
courteouselk/Relations
Sources/Weak1toNRelation.swift
1
12619
// // Weak1toNRelation.swift // Relations // // Created by Anton Bronnikov on 01/01/2017. // Copyright © 2017 Anton Bronnikov. All rights reserved. // /// Helper object for weak 1:N relation. public final class Weak1toNRelation<UnarySide: AnyObject, NarySide: AnyObject> : Collection { // MARK: - Typealiases public typealias Index = Weak1toNRelationIndex<UnarySide, NarySide> /// Helper class for counterpart relation side. public typealias Counterpart = WeakNto1Relation<NarySide, UnarySide> typealias Container = Set<WeakWrapper<Counterpart>> // MARK: - Instance properties unowned let this: UnarySide let getCounterpart: (NarySide) -> Counterpart let didChange: (() -> Void)? var counterparts: Container = [] public var startIndex: Index { return Index(counterparts.startIndex) } public var endIndex: Index { return Index(counterparts.endIndex) } public var count: Int { return counterparts.count } public var underestimatedCount: Int { return counterparts.underestimatedCount } public var first: NarySide? { return counterparts.first?.object.this } public subscript(position: Index) -> NarySide { return counterparts[position.index].object.this } // MARK: - Initializers /// Creates a new instance of 1:N relation helper object. /// /// - parameters: /// - this: Object of "this" side of a relation. /// - getCounterpart: Helper-object getter for the counterpart relation side. /// - didChange: Closure to be triggered on every change made to the relation. public init(this: UnarySide, getCounterpart: @escaping (NarySide) -> Counterpart, didChange: (() -> Void)? = nil) { self.this = this self.getCounterpart = getCounterpart self.didChange = didChange } deinit { guard counterparts.count > 0 else { return } var didChangeNotifications = DidChangeNotifications() do { // 1. Remove self from the relations remotely for counterpart in counterparts.map({ $0.object }) { didChangeNotifications.register(counterpart) } } didChangeNotifications.fire() } // MARK: - Methods public func index(after i: Index) -> Index { return Index(counterparts.index(after: i.index)) } /// Establish relations to, and only to, the elements of the given sequence. /// /// Relation will be established to every sequence element that is not already in the /// relation. At the same time a relation will be broken with every object that is not in the /// sequence. Elements that are both, already present in the relation, and in the sequence /// will remain untouched. /// /// - parameters: /// - relations: Sequence of nary-side objects to set the new relations to. public func assign<Relations : Sequence>(relations: Relations) where Relations.Iterator.Element == NarySide { let newCounterparts = Container(relations.map({ WeakWrapper(getCounterpart($0)) })) let counterpartsToRemove = counterparts.subtracting(newCounterparts) let counterpartsToInsert = newCounterparts.subtracting(counterparts) guard counterpartsToRemove.count > 0 || counterpartsToInsert.count > 0 else { return } var didChangeNotifications = DidChangeNotifications() do { // 1. Break the relation with abandoned counterparts remotely for counterpart in counterpartsToRemove.map({ $0.object }) { assert(counterpart.counterpart === self) counterpart.counterpart = nil didChangeNotifications.register(counterpart) } // 2. Set the relation to new counterparts remotely for counterpart in counterpartsToInsert.map({ $0.object }) { assert(counterpart.counterpart !== self) counterpart.counterpart = self didChangeNotifications.register(counterpart) } // 3. Assign the relation container locally counterparts = newCounterparts didChangeNotifications.register(self) } didChangeNotifications.fire() } /// Establish relations to, and only to, the elements from the specified list. /// /// Relation will be established to every list element that is not already in the /// relation. At the same time a relation will be broken with every object that is not in the /// list. Elements that are both, already present in the relation, and in the list /// will remain unchanged (and not notified). /// /// - parameters: /// - relations: List of counterpart helper objects to set the new relations to. public func assign(relations: NarySide...) { assign(relations: relations) } /// Establish a new relation. /// /// - parameters: /// - relation: Counterpart helper object to set the relation to. /// If `relation` is `nil` then nothing happens. public func insert(relation: NarySide?) { guard let counterpart = relation.map({ getCounterpart($0) }) else { return } let wrappedCounterpart = WeakWrapper(counterpart) guard !counterparts.contains(wrappedCounterpart) else { return } var didChangeNotifications = DidChangeNotifications() do { // 1. If the new counterpart already had a relation, and it was not us, break that relation if let counterpartsPreviousRelation = counterpart.counterpart, counterpartsPreviousRelation !== self { assert(counterpartsPreviousRelation.counterparts.contains(wrappedCounterpart)) counterpartsPreviousRelation.counterparts.remove(wrappedCounterpart) didChangeNotifications.register(counterpartsPreviousRelation) } // 2. Set the relation to a new counterpart locally assert(!counterparts.contains(wrappedCounterpart)) counterparts.insert(wrappedCounterpart) didChangeNotifications.register(self) // 3. Set the relation to a new counterpart remotely assert(counterpart.counterpart !== self) counterpart.counterpart = self didChangeNotifications.register(counterpart) } didChangeNotifications.fire() } /// Establish relations to the elements of a sequence. /// /// - parameters: /// - relations: Sequence of nary-side objects to set the new relations to. public func insert<Relations : Sequence>(relations: Relations) where Relations.Iterator.Element == NarySide { var didChangeNotifications = DidChangeNotifications() do { var doNotifySelf = false traversing: for counterpart in relations.map({ getCounterpart($0) }) { let wrappedCounterpart = WeakWrapper(counterpart) guard !counterparts.contains(wrappedCounterpart) else { continue traversing } // 1. If the new counterpart already had a relation, and it was not us, break that relation if let counterpartsPreviousRelation = counterpart.counterpart, counterpartsPreviousRelation !== self { assert(counterpartsPreviousRelation.counterparts.contains(wrappedCounterpart)) counterpartsPreviousRelation.counterparts.remove(wrappedCounterpart) didChangeNotifications.register(counterpartsPreviousRelation) } // 2. Set the relation to a new counterpart locally assert(!counterparts.contains(wrappedCounterpart)) counterparts.insert(wrappedCounterpart) doNotifySelf = true // 3. Set the relation to a new counterpart remotely assert(counterpart.counterpart !== self) counterpart.counterpart = self didChangeNotifications.register(counterpart) } if doNotifySelf { didChangeNotifications.register(self) } } didChangeNotifications.fire() } /// Establish relations to the elements of a list. /// /// - parameters: /// - relations: List of nary-side objects to set the new relations to. public func insert(relations: NarySide...) { insert(relations: relations) } /// Break an existing relation. /// /// - parameters: /// - relation: Nary-side object to break the relation with. /// If `relation` is `nil` then nothing happens. public func remove(relation: NarySide?) { guard let counterpart = relation.map({ getCounterpart($0) }) else { return } let wrappedCounterpart = WeakWrapper(counterpart) guard counterparts.contains(wrappedCounterpart) else { return } var didChangeNotifications = DidChangeNotifications() do { // 1. Break the relation with current counterpart locally assert(counterparts.contains(wrappedCounterpart)) counterparts.remove(wrappedCounterpart) didChangeNotifications.register(self) // 2. Break the relation with current counterpart remotely assert(counterpart.counterpart === self) counterpart.counterpart = nil didChangeNotifications.register(counterpart) } didChangeNotifications.fire() } /// Break existing relations with the elements of the given sequence. /// /// - parameters: /// - relations: Sequence of nary-side objects to break the relations with. public func remove<Relations : Sequence>(relations: Relations) where Relations.Iterator.Element == NarySide { var didChangeNotifications = DidChangeNotifications() do { var doNotifySelf = false traversing: for counterpart in relations.map({ getCounterpart($0) }) { let wrappedCounterpart = WeakWrapper(counterpart) guard counterparts.contains(wrappedCounterpart) else { continue traversing } // 1. Break the relation with current counterpart locally assert(counterparts.contains(wrappedCounterpart)) counterparts.remove(wrappedCounterpart) doNotifySelf = true // 2. Break the relation with current counterpart remotely assert(counterpart.counterpart === self) counterpart.counterpart = nil didChangeNotifications.register(counterpart) } if doNotifySelf { didChangeNotifications.register(self) } } didChangeNotifications.fire() } /// Break existing relations with the list of elements. /// /// - parameters: /// - relations: List of nary-side objects to break the relations with. public func remove(relations: NarySide...) { remove(relations: relations) } /// Break all existing relations. /// /// - parameters: /// - keepingCapacity: Indicates whether underlying storage buffer capacity should be kept. /// The default is `false`. public func flush(keepingCapacity keepCapacity: Bool = false) { guard counterparts.count > 0 else { return } var didChangeNotifications = DidChangeNotifications() do { // 1. Break the relation with current counterparts remotely for counterpart in counterparts.map({ $0.object }) { assert(counterpart.counterpart === self) counterpart.counterpart = nil didChangeNotifications.register(counterpart) } // 2. Break the relations with current counterparts locally counterparts.removeAll(keepingCapacity: keepCapacity) didChangeNotifications.register(self) } didChangeNotifications.fire() } } // MARK: - extension Weak1toNRelation : DidChangeNotifiable { var objectIdentifier: ObjectIdentifier { return ObjectIdentifier(self) } }
mit
81531200290fe2800bb3212cc013ca8b
34.948718
122
0.623791
5.364796
false
false
false
false
MetalPetal/MetalPetal
Tests/MetalPetalTestHelpers/PixelEnumerator.swift
1
1928
// // File.swift // // // Created by YuAo on 2020/3/17. // import Foundation import CoreGraphics public struct PixelEnumerator { public struct Coordinates: Hashable { public var x: Int public var y: Int public init(x: Int, y: Int) { self.x = x self.y = y } } public struct Pixel: Hashable { public var b: UInt8 public var g: UInt8 public var r: UInt8 public var a: UInt8 public init(b: UInt8, g: UInt8, r: UInt8, a: UInt8) { self.b = b self.g = g self.r = r self.a = a } } public static func enumeratePixels(in cgImage: CGImage, with block:(Pixel, Coordinates) -> Void) { var buffer = [Pixel](repeating: Pixel(b: 0, g: 0, r: 0, a: 0), count: cgImage.width * cgImage.height) let context = CGContext(data: &buffer, width: cgImage.width, height: cgImage.height, bitsPerComponent: 8, bytesPerRow: cgImage.width * 4, space: cgImage.colorSpace ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) context?.draw(cgImage, in: CGRect(x: 0, y: 0, width: cgImage.width, height: cgImage.height)) for x in 0..<cgImage.width { for y in 0..<cgImage.height { block(buffer[y * cgImage.width + x], Coordinates(x: x, y: y)) } } } } extension PixelEnumerator { public static func monochromeImageEqual(image: CGImage, target: [[UInt8]]) -> Bool { var allEqual = true self.enumeratePixels(in: image) { (pixel, coordinate) in if pixel.r == pixel.g && pixel.g == pixel.b && pixel.a == 255 { if pixel.r != target[coordinate.y][coordinate.x] { allEqual = false } } } return allEqual } }
mit
fde60a0f3fa228297701596e5abd20ac
31.677966
305
0.568465
3.918699
false
false
false
false
iOSDevLog/iOSDevLog
Happiness/Happiness/HappinessViewController.swift
1
2982
// // HappinessViewController.swift // Happiness // // Created by jiaxianhua on 15/9/21. // Copyright © 2015年 com.jiaxh. All rights reserved. // import UIKit class HappinessViewController: UIViewController, FaceViewDataSource { @IBOutlet weak var faceView: FaceView! { // the property observer didSet gets called when this outlet gets set // (i.e. when iOS makes the connection to the FaceView in the storyboard) // this is a perfect time to configure the FaceView with its delegate and recognizers didSet { faceView.dataSource = self // this pinch gesture can be handled by the View, so just "turn it on" here in the Controller faceView.addGestureRecognizer(UIPinchGestureRecognizer(target: faceView, action: "scale:")) // this pan gesture recognizer modifies the Model so it must be handled by the Controller // we could add it in code like below, but instead, we added it directly in the storyboard // and wired it up with ctrl-drag // faceView.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: "changeHappiness:")) } } // a property to access our Model // incredibly simplistic Model // most MVCs would have more complicated Models (e.g. CalculatorBrain) var happiness: Int = 25 { // 0 = very sad, 100 = ecstatic didSet { // validate (actually, enforce validity of) modifications to the Model happiness = min(max(happiness, 0), 100) print("happiness = \(happiness)") // any time the Model changes, we need to update our View updateUI() } } func updateUI() { // to update our UI, we just need to ask the FaceView to redraw faceView.setNeedsDisplay() } private struct Constants { static let HappinessGestureScale: CGFloat = 4 } // FaceViewDataSource func smilinessForFaceView(sender: FaceView) -> Double? { // interpret the Model for the View return Double(happiness-50)/50 } @IBAction func changeHappiness(sender: UIPanGestureRecognizer) { switch sender.state { case .Ended: fallthrough case .Changed: let translation = sender.translationInView(faceView) // here we are basically interpreting input from the View for our Model let happinessChange = -Int(translation.y / Constants.HappinessGestureScale) if happinessChange != 0 { happiness += happinessChange // normally the translation of a pan gesture // is relative to the point at which it was first recognized // but we can reset that point so that we are getting "incremental" pan data ... sender.setTranslation(CGPointZero, inView: faceView) } default: break } } }
mit
b1f6c0e73f5c3b1de26968d5461b248b
38.197368
110
0.629406
5.18087
false
false
false
false
Legoless/Analytical
Example/Analytical/Analytics.swift
1
1216
// // Analytics.swift // Analytical // // Created by Dal Rupnik on 15/09/16. // Copyright © 2016 Unified Sense. All rights reserved. // import Analytical public enum Track { public enum Event : String { case secondScreenTap = "SecondScreenTap" case closeTap = "CloseTap" } public enum Screen : String { case first = "first" case second = "second" } } //let analytics = Analytics() <<~ GoogleProvider(trackingId: "<TRACKING-ID>") <<~ MixpanelProvider(token: "<MIXPANEL-ID>") <<~ FacebookProvider() let analytics = Analytics() <<~ LogProvider() extension AnalyticalProvider { func track(event: Track.Event, properties: Properties? = nil) { self.event(name: event.rawValue, properties: properties) } func track(screen: Track.Screen, properties: Properties? = nil) { self.screen(name: screen.rawValue, properties: properties) } func time(event: Track.Event, properties: Properties? = nil) { self.time(name: event.rawValue, properties: properties) } func finish(event: Track.Event, properties: Properties? = nil) { self.finish(name: event.rawValue, properties: properties) } }
mit
f1e53e27dee87a5062e1fd5cd373d64d
27.255814
145
0.647737
3.881789
false
false
false
false
JohnSundell/SwiftKit
Source/Shared/CGSize+SwiftKit.swift
1
1221
import CoreGraphics /// SwiftKit extensions to CGSize public extension CGSize { /// Convenience initializer to create a square size public init(squareSize: CGFloat) { self.init(width: squareSize, height: squareSize) } /// Return a new size that's the product of scaling this size in both dimensions public func sizeWithScale(scale: CGFloat) -> CGSize { var size = self size.width *= scale size.height *= scale return size } /// Return a new size that is the result of resizing this size in either dimension public func resizedSizeByX(x: CGFloat, y: CGFloat) -> CGSize { return CGSize(width: self.width + x, height: self.height + y) } /// Return the point at which this size is centered within another size public func centerPointInSize(size: CGSize) -> CGPoint { return CGPoint( x: floor((size.width - self.width) / 2), y: floor((size.height - self.height) / 2) ) } /// Conver this size structure into a point structure, with x = width, y = height public func toCGPoint() -> CGPoint { return CGPoint(x: self.width, y: self.height) } }
mit
703a9cb74746be6817e3674280c9a92f
32.916667
86
0.624898
4.423913
false
false
false
false
alexiosdev/IBAnimatable
IBAnimatableApp/Functions.swift
1
580
// // Created by Mark Hamilton on 4/9/16. // Copyright © 2016 IBAnimatable. All rights reserved. // import Foundation // Source: https://gist.github.com/TheDarkCode/2f65c1a25d5886ed210c3b33d73fe8a9 // Based on earlier version: http://stackoverflow.com/a/28341290/749786 public func iterateEnum<T: Hashable>(_ from: T.Type) -> AnyIterator<T> { var x = 0 return AnyIterator { let next = withUnsafePointer(to: &x) { $0.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee } } defer { x += 1 } return next.hashValue == x ? next : nil } }
mit
49790d767401df28313a55374bf2973a
26.571429
79
0.663212
3.146739
false
false
false
false
Tsiems/mobile-sensing-apps
AirDrummer/AIToolbox/MarkovDecisionProcess.swift
2
29561
// // MarkovDecisionProcess.swift // AIToolbox // // Created by Kevin Coble on 3/28/16. // Copyright © 2016 Kevin Coble. All rights reserved. // import Foundation import Accelerate /// Errors that MDP routines can throw public enum MDPErrors: Error { case mdpNotSolved case failedSolving case errorCreatingSampleSet case errorCreatingSampleTargetValues case modelInputDimensionError case modelOutputDimensionError case invalidState case noDataForState } /// Structure that defines an episode for a MDP public struct MDPEpisode { public let startState : Int public var events : [(action: Int, resultState: Int, reward: Double)] public init(startState: Int) { self.startState = startState events = [] } public mutating func addEvent(_ event: (action: Int, resultState: Int, reward: Double)) { events.append(event) } } /// Class to solve Markov Decision Process problems open class MDP { var numStates : Int // If discrete states var numActions : Int var γ : Double open var convergenceLimit = 0.0000001 // Continuous state variables var numSamples = 10000 var deterministicModel = true // If true, we don't need to sample end states var nonDeterministicSampleSize = 20 // Number of samples to take if resulting model state is not deterministic // Calculation results for discrete state/actions open var π : [Int]! open var V : [Double]! open var Q : [[(action: Int, count: Int, q_a: Double)]]! // Array of expected rewards when taking the action from the state (array sized to state size) var α = 0.0 // Future weight for TD algorithms /// Init MDP. Set states to 0 for continuous states public init(states: Int, actions: Int, discount: Double) { numStates = states numActions = actions γ = discount } /// Method to set the parameters for continuous state fittedValueIteration MDP's open func setContinousStateParameters(_ sampleSize: Int, deterministic: Bool, nonDetSampleSize: Int = 20) { numSamples = sampleSize deterministicModel = deterministic nonDeterministicSampleSize = nonDetSampleSize } /// Method to solve using value iteration /// Returns array of actions for each state open func valueIteration(_ getActions: ((_ fromState: Int) -> [Int]), getResults: ((_ fromState: Int, _ action : Int) -> [(state: Int, probability: Double)]), getReward: ((_ fromState: Int, _ action : Int, _ toState: Int) -> Double)) -> [Int] { π = [Int](repeating: 0, count: numStates) V = [Double](repeating: 0.0, count: numStates) var difference = convergenceLimit + 1.0 while (difference > convergenceLimit) { // Go till convergence difference = 0.0 // Update each state's value for state in 0..<numStates { // Get the maximum value for all possible actions from this state var maxNewValue = -Double.infinity let actions = getActions(state) if actions.count == 0 { maxNewValue = 0.0 } // If an end state, future value is 0 for action in actions { // Sum the expected rewards from all possible outcomes from the action var newValue = 0.0 let results = getResults(state, action) for result in results { newValue += result.probability * (getReward(state, action, result.state) + (γ * V[result.state])) } // If this is the best so far, store it if (newValue > maxNewValue) { maxNewValue = newValue π[state] = action } } // Accumulate difference for convergence check difference += fabs(V[state] - maxNewValue) V[state] = maxNewValue } } return π } /// Method to solve using policy iteration /// Returns array of actions for each state open func policyIteration(_ getActions: ((_ fromState: Int) -> [Int]), getResults: ((_ fromState: Int, _ action : Int) -> [(state: Int, probability: Double)]), getReward: ((_ fromState: Int, _ action : Int, _ toState: Int) -> Double)) throws -> [Int] { π = [Int](repeating: -1, count: numStates) V = [Double](repeating: 0.0, count: numStates) var policyChanged = true while (policyChanged) { // Go till convergence policyChanged = false // Set the policy to the best action given the current values for state in 0..<numStates { let actions = getActions(state) if (actions.count > 0) { var bestAction = actions[0] var bestReward = -Double.infinity for action in actions { // Determine expected reward for each action var expectedReward = 0.0 let results = getResults(state, action) for result in results { expectedReward += result.probability * (getReward(state, action, result.state) + (γ * V[result.state])) } if (expectedReward > bestReward) { bestReward = expectedReward bestAction = action } } // Set to the best action found if (π[state] != bestAction) { policyChanged = true } π[state] = bestAction } } // Solve for the new values var matrix = [Double](repeating: 0.0, count: numStates * numStates) // Row is state, column is resulting state var constants = [Double](repeating: 0.0, count: numStates) for state in 0..<numStates { matrix[state * numStates + state] = 1.0 if π[state] >= 0 { let results = getResults(state, π[state]) for result in results { matrix[result.state * numStates + state] -= result.probability * γ constants[state] += result.probability * getReward(state, π[state], result.state) } } } var dimA = __CLPK_integer(numStates) var colB = __CLPK_integer(1) var ipiv = [__CLPK_integer](repeating: 0, count: numStates) var info: __CLPK_integer = 0 dgesv_(&dimA, &colB, &matrix, &dimA, &ipiv, &constants, &dimA, &info) if (info == 0) { V = constants } else { throw MDPErrors.failedSolving } } return π } /// Once valueIteration or policyIteration has been used, use this function to get the action for any particular state open func getAction(_ forState: Int) throws -> Int { if (π == nil) { throw MDPErrors.mdpNotSolved } if (forState < 0 || forState >= numStates) { throw MDPErrors.invalidState } return π[forState] } /// Initialize MDP for a discrete state Monte Carlo evaluation open func initDiscreteStateMonteCarlo() { Q = [[(action: Int, count: Int, q_a: Double)]](repeating: [], count: numStates) } // Function to update Q for a state and action, with the given reward func updateQ(_ fromState: Int, action: Int, reward: Double) { // Find the action in the Q array var index = -1 for i in 0..<Q[fromState].count { if (Q[fromState][i].action == action) { index = i break } } // If not found, add one if (index < 0) { Q[fromState].append((action: action, count: 1, q_a: reward)) } // If found, update else { Q[fromState][index].count += 1 Q[fromState][index].q_a += reward } } /// Evaluate an episode of a discrete state Monte Carlo evaluation using 'every-visit' open func evaluateMonteCarloEpisodeEveryVisit(_ episode: MDPEpisode) { // Iterate backwards through the episode, accumulating reward and assigning to Q var accumulatedReward = 0.0 for index in stride(from: (episode.events.count-1), to: 0, by: -1) { // Get the reward accumulatedReward *= γ accumulatedReward += episode.events[index].reward // Get the start state var startState = episode.startState if (index > 0) { startState = episode.events[index-1].resultState } // Update the value updateQ(startState, action: episode.events[index].action, reward: accumulatedReward) } } /// Evaluate an episode of a discrete state Monte Carlo evaluation using 'first-visit' open func evaluateMonteCarloEpisodeFirstVisit(_ episode: MDPEpisode) { // Find the first instance of each state in the episode var firstInstance = [Int](repeating: -1, count: numStates) for index in 0..<episode.events.count { if (firstInstance[episode.events[index].resultState] < 0) { firstInstance[episode.events[index].resultState] = index } } // Iterate backwards through the episode, accumulating reward and assigning to V var accumulatedReward = 0.0 for index in stride(from: (episode.events.count-1), to: 0, by: -1) { // Get the reward accumulatedReward *= γ accumulatedReward += episode.events[index].reward // If this was the first instance of the state, update if (firstInstance[episode.events[index].resultState] >= 0) { // Get the start state var startState = episode.startState if (index > 0) { startState = episode.events[index-1].resultState } // Update the value updateQ(startState, action: episode.events[index].action, reward: accumulatedReward) } } } /// Initialize MDP for a discrete state Temporal-Difference evaluation with given future-reward weighting open func initDiscreteStateTD(_ α: Double) { self.α = α Q = [[(action: Int, count: Int, q_a: Double)]](repeating: [], count: numStates) // Initialize all state/action values to 0 (we don't know what states are terminal, and those must be 0, while others are arbitrary) for state in 0..<numStates { for action in 0..<numActions { Q[state].append((action: action, count: 1, q_a: 0.0)) } } } /// Evaluate an episode of a discrete state Temporal difference evaluation using 'SARSA' open func evaluateTDEpisodeSARSA(_ episode: MDPEpisode) { var S = episode.startState for index in 0..<episode.events.count { // Get SARSA let A = episode.events[index].action let R = episode.events[index].reward let Sp = episode.events[index].resultState var Ap = 0 if (index < episode.events.count-1) { Ap = episode.events[index+1].action } // Update Q Q[S][A].q_a += α * (R + (γ * Q[Sp][Ap].q_a) - Q[S][A].q_a) // Advance S S = Sp } } /// Evaluate an episode of a discrete state Temporal difference evaluation using 'Q-Learning' /// Assumes actions taken during episode are 'exploratory', not just greedy open func evaluateTDEpisodeQLearning(_ episode: MDPEpisode) { var S = episode.startState for index in 0..<episode.events.count { let A = episode.events[index].action let R = episode.events[index].reward let Sp = episode.events[index].resultState // Update Q var maxQ = -Double.infinity for action in 0..<numActions { if (Q[Sp][action].q_a > maxQ) { maxQ = Q[Sp][action].q_a } } Q[S][A].q_a += α * (R + (γ * maxQ) - Q[S][A].q_a) // Advance S S = Sp } } /// Once Monte Carlo or TD episodes have been evaluated, use this function to get the current best (greedy) action for any particular state open func getGreedyAction(_ forState: Int) throws -> Int { // Validate inputs if (Q == nil) { throw MDPErrors.mdpNotSolved } if (forState < 0 || forState >= numStates) { throw MDPErrors.invalidState } if (Q[forState].count <= 0) { throw MDPErrors.noDataForState } // Get the action that has the most expected reward var bestAction = 0 var bestReward = -Double.infinity for index in 0..<Q[forState].count { let expectedReward = Q[forState][index].q_a / Double(Q[forState][index].count) if (expectedReward > bestReward) { bestAction = index bestReward = expectedReward } } return Q[forState][bestAction].action } /// Once Monte Carlo or TD episodes have been evaluated, use this function to get the ε-greedy action for any particular state (greedy except random ε fraction) open func getεGreedyAction(_ forState: Int, ε : Double) throws -> Int { if ((Double(arc4random()) / Double(RAND_MAX)) > ε) { // Return a random action return Int(arc4random_uniform(UInt32(numActions))) } // Return a greedy action return try getGreedyAction(forState) } /// Method to generate an episode, assuming there is an internal model open func generateEpisode(_ getStartingState: (() -> Int), getActions: ((_ fromState: Int) -> [Int]), getResults: ((_ fromState: Int, _ action : Int) -> [(state: Int, probability: Double)]), getReward: ((_ fromState: Int, _ action : Int, _ toState: Int) -> Double)) throws -> MDPEpisode { // Get the start state var currentState = getStartingState() // Initialize the return struct var episode = MDPEpisode(startState: currentState) // Iterate until we get to a termination state while true { do { if let event = try generateEvent(currentState, getActions: getActions, getResults: getResults, getReward: getReward) { // Add the move episode.addEvent(event) // update the state currentState = event.resultState } else { break } } catch let error { throw error } } return episode } /// Method to generate an event, assuming there is an internal model open func generateEvent(_ fromState: Int, getActions: ((_ fromState: Int) -> [Int]), getResults: ((_ fromState: Int, _ action : Int) -> [(state: Int, probability: Double)]), getReward: ((_ fromState: Int, _ action : Int, _ toState: Int) -> Double)) throws -> (action: Int, resultState: Int, reward: Double)! { let actions = getActions(fromState) if (actions.count == 0) { return nil } // Pick an action at random let actionIndex = Int(arc4random_uniform(UInt32(actions.count))) // Get the results let results = getResults(fromState, actions[actionIndex]) // Get the result based on the probability let resultProbability = Double(arc4random()) / Double(RAND_MAX) var accumulatedProbablility = 0.0 var selectedResult = 0 for index in 0..<results.count { if (resultProbability < (accumulatedProbablility + results[index].probability)) { selectedResult = index break } accumulatedProbablility += results[index].probability } // Get the reward let reward = getReward(fromState, actions[actionIndex], results[selectedResult].state) return (action: actions[actionIndex], resultState: results[selectedResult].state, reward: reward) } /// Method to generate an episode, assuming there is an internal model, but actions are ε-greedy from current learning open func generateεEpisode(_ getStartingState: (() -> Int), ε: Double, getResults: ((_ fromState: Int, _ action : Int) -> [(state: Int, probability: Double)]), getReward: ((_ fromState: Int, _ action : Int, _ toState: Int) -> Double)) throws -> MDPEpisode { // Get the start state var currentState = getStartingState() // Initialize the return struct var episode = MDPEpisode(startState: currentState) // Iterate until we get to a termination state while true { do { if let event = try generateεEvent(currentState, ε: ε, getResults: getResults, getReward: getReward) { // Add the move episode.addEvent(event) // update the state currentState = event.resultState } else { break } } catch let error { throw error } } return episode } /// Method to generate an event, assuming there is an internal model, but actions are ε-greedy from current learning open func generateεEvent(_ fromState: Int, ε: Double, getResults: ((_ fromState: Int, _ action : Int) -> [(state: Int, probability: Double)]), getReward: ((_ fromState: Int, _ action : Int, _ toState: Int) -> Double)) throws -> (action: Int, resultState: Int, reward: Double)! { let action = try getεGreedyAction(fromState, ε : ε) // Get the results let results = getResults(fromState, action) if (results.count == 0) { return nil } // Get the result based on the probability let resultProbability = Double(arc4random()) / Double(RAND_MAX) var accumulatedProbablility = 0.0 var selectedResult = 0 for index in 0..<results.count { if (resultProbability < (accumulatedProbablility + results[index].probability)) { selectedResult = index break } accumulatedProbablility += results[index].probability } // Get the reward let reward = getReward(fromState, action, results[selectedResult].state) return (action: action, resultState: results[selectedResult].state, reward: reward) } /// Computes a regression model that translates the state feature mapping to V open func fittedValueIteration(_ getRandomState: (() -> [Double]), getResultingState: ((_ fromState: [Double], _ action : Int) -> [Double]), getReward: ((_ fromState: [Double], _ action:Int, _ toState: [Double]) -> Double), fitModel: Regressor) throws { // Get a set of random states let sample = getRandomState() let sampleStates = DataSet(dataType: .regression, inputDimension: sample.count, outputDimension: 1) do { try sampleStates.addDataPoint(input: sample, output: [0]) // Get the rest of the random state samples for _ in 1..<numSamples { try sampleStates.addDataPoint(input: getRandomState(), output: [0]) } } catch { throw MDPErrors.errorCreatingSampleSet } // Make sure the model fits our usage of it if (fitModel.getInputDimension() != sample.count) {throw MDPErrors.modelInputDimensionError} if (fitModel.getOutputDimension() != 1) {throw MDPErrors.modelOutputDimensionError} // It is recommended that the model starts with parameters as the null vector so initial inresults are 'no expected reward for each position'. let initParameters = [Double](repeating: 0.0, count: fitModel.getParameterDimension()) do { try fitModel.setParameters(initParameters) } catch let error { throw error } var difference = convergenceLimit + 1.0 while (difference > convergenceLimit) { // Go till convergence difference = 0.0 // Get the target value (y) for each sample if (deterministicModel) { // If deterministic, a single sample works for index in 0..<numSamples { var maximumReward = -Double.infinity for action in 0..<numActions { var state : [Double] do { state = try sampleStates.getInput(index) let resultState = getResultingState(state, action) let Vprime = try fitModel.predictOne(resultState) let expectedReward = getReward(state, action, resultState) + γ * Vprime[0] if (expectedReward > maximumReward) { maximumReward = expectedReward } } catch { throw MDPErrors.errorCreatingSampleTargetValues } } do { try sampleStates.setOutput(index, newOutput: [maximumReward]) } catch { throw MDPErrors.errorCreatingSampleTargetValues } } } else { // If not deterministic, sample the possible result states and average for index in 0..<numSamples { var maximumReward = -Double.infinity for action in 0..<numActions { var expectedReward = 0.0 for _ in 0..<nonDeterministicSampleSize { var state : [Double] do { state = try sampleStates.getInput(index) let resultState = getResultingState(state, action) let Vprime = try fitModel.predictOne(resultState) expectedReward += getReward(state, action, resultState) + γ * Vprime[0] } catch { throw MDPErrors.errorCreatingSampleTargetValues } } expectedReward /= Double(nonDeterministicSampleSize) if (expectedReward > maximumReward) { maximumReward = expectedReward } } do { try sampleStates.setOutput(index, newOutput: [maximumReward]) } catch { throw MDPErrors.errorCreatingSampleTargetValues } } } // Use regression to get our estimation for the V function do { try fitModel.trainRegressor(sampleStates) } catch { throw MDPErrors.failedSolving } } } /// Once fittedValueIteration has been used, use this function to get the action for any particular state open func getAction(_ forState: [Double], getResultingState: ((_ fromState: [Double], _ action : Int) -> [Double]), getReward: ((_ fromState: [Double], _ action:Int, _ toState: [Double]) -> Double), fitModel: Regressor) -> Int { var maximumReward = -Double.infinity var bestAction = 0 if (deterministicModel) { for action in 0..<numActions { let resultState = getResultingState(forState, action) do { let Vprime = try fitModel.predictOne(resultState) let expectedReward = getReward(forState, action, resultState) + Vprime[0] if (expectedReward > maximumReward) { maximumReward = expectedReward bestAction = action } } catch { } } } else { for action in 0..<numActions { var expectedReward = 0.0 for _ in 0..<nonDeterministicSampleSize { let resultState = getResultingState(forState, action) do { let Vprime = try fitModel.predictOne(resultState) expectedReward += getReward(forState, action, resultState) + Vprime[0] } catch { expectedReward = 0.0 // Error in system that should be caught elsewhere } } expectedReward /= Double(nonDeterministicSampleSize) if (expectedReward > maximumReward) { maximumReward = expectedReward bestAction = action } } } return bestAction } /// Once fittedValueIteration has been used, use this function to get the ordered list of actions, from best to worst open func getActionOrder(_ forState: [Double], getResultingState: ((_ fromState: [Double], _ action : Int) -> [Double]), getReward: ((_ fromState: [Double], _ action:Int, _ toState: [Double]) -> Double), fitModel: Regressor) -> [Int] { var actionTuple : [(action: Int, expectedReward: Double)] = [] if (deterministicModel) { for action in 0..<numActions { let resultState = getResultingState(forState, action) do { let Vprime = try fitModel.predictOne(resultState) let expectedReward = getReward(forState, action, resultState) + Vprime[0] actionTuple.append((action: action, expectedReward: expectedReward)) } catch { } } } else { for action in 0..<numActions { var expectedReward = 0.0 for _ in 0..<nonDeterministicSampleSize { let resultState = getResultingState(forState, action) do { let Vprime = try fitModel.predictOne(resultState) expectedReward += getReward(forState, action, resultState) + Vprime[0] } catch { expectedReward = 0.0 // Error in system that should be caught elsewhere } } expectedReward /= Double(nonDeterministicSampleSize) actionTuple.append((action: action, expectedReward: expectedReward)) } } // Get the ordered list of actions actionTuple.sort(by: {$0.expectedReward > $1.expectedReward}) var actionList : [Int] = [] for tuple in actionTuple { actionList.append(tuple.action) } return actionList } /// Function to extract the current Q* values (expected reward from each state when following greedy policy) open func getQStar() ->[Double] { var Qstar = [Double](repeating: -Double.infinity, count: numStates) for state in 0..<numStates { for q in Q[state] { let q = q.q_a / Double(q.count) if (q > Qstar[state]) { Qstar[state] = q } } } return Qstar } }
mit
1847a4f0a64597a0a8506ae14bc977f6
40.743989
165
0.525328
4.89761
false
false
false
false
neoneye/SwiftyFORM
Source/Util/UITableView+PrevNext.swift
1
6692
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit public extension IndexPath { /// Indexpath of the previous cell. /// /// This function is complex because it deals with empty sections and invalid indexpaths. func form_indexPathForPreviousCell(_ tableView: UITableView) -> IndexPath? { if section < 0 || row < 0 { return nil } let sectionCount = tableView.numberOfSections if section < 0 || section >= sectionCount { return nil } let firstRowCount = tableView.numberOfRows(inSection: section) if row > 0 && row <= firstRowCount { return IndexPath(row: row - 1, section: section) } var currentSection = section while true { currentSection -= 1 if currentSection < 0 || currentSection >= sectionCount { return nil } let rowCount = tableView.numberOfRows(inSection: currentSection) if rowCount > 0 { return IndexPath(row: rowCount - 1, section: currentSection) } } } /// Indexpath of the next cell. /// /// This function is complex because it deals with empty sections and invalid indexpaths. func form_indexPathForNextCell(_ tableView: UITableView) -> IndexPath? { if section < 0 { return nil } let sectionCount = tableView.numberOfSections var currentRow = row + 1 var currentSection = section while true { if currentSection >= sectionCount { return nil } let rowCount = tableView.numberOfRows(inSection: currentSection) if currentRow >= 0 && currentRow < rowCount { return IndexPath(row: currentRow, section: currentSection) } if currentRow > rowCount { return nil } currentSection += 1 currentRow = 0 } } } extension UITableView { /// Determine where a cell is located in this tableview. Considers cells inside and cells outside the visible area. /// /// Unlike UITableView.indexPathForCell() which only looksup inside the visible area. /// UITableView doesn't let you lookup cells outside the visible area. /// UITableView.indexPathForCell() returns nil when the cell is outside the visible area. func form_indexPathForCell(_ cell: UITableViewCell) -> IndexPath? { guard let dataSource = self.dataSource else { return nil } let sectionCount: Int = dataSource.numberOfSections?(in: self) ?? 0 for section: Int in 0 ..< sectionCount { let rowCount: Int = dataSource.tableView(self, numberOfRowsInSection: section) for row: Int in 0 ..< rowCount { let indexPath = IndexPath(row: row, section: section) let dataSourceCell = dataSource.tableView(self, cellForRowAt: indexPath) if dataSourceCell === cell { return indexPath } } } return nil } /// Find a cell above that can be jumped to. Skip cells that cannot be jumped to. /// /// Usage: when the user types SHIFT TAB on the keyboard, then we want to jump to a cell above. func form_indexPathForPreviousResponder(_ initialIndexPath: IndexPath) -> IndexPath? { guard let dataSource = self.dataSource else { return nil } var indexPath: IndexPath! = initialIndexPath while true { indexPath = indexPath.form_indexPathForPreviousCell(self) if indexPath == nil { return nil } let cell = dataSource.tableView(self, cellForRowAt: indexPath) if cell.canBecomeFirstResponder { return indexPath } } } /// Find a cell below that can be jumped to. Skip cells that cannot be jumped to. /// /// Usage: when the user hits TAB on the keyboard, then we want to jump to a cell below. func form_indexPathForNextResponder(_ initialIndexPath: IndexPath) -> IndexPath? { guard let dataSource = self.dataSource else { return nil } var indexPath: IndexPath! = initialIndexPath while true { indexPath = indexPath.form_indexPathForNextCell(self) if indexPath == nil { return nil } let cell = dataSource.tableView(self, cellForRowAt: indexPath) if cell.canBecomeFirstResponder { return indexPath } } } /// Jump to a cell above. /// /// Usage: when the user types SHIFT TAB on the keyboard, then we want to jump to a cell above. func form_makePreviousCellFirstResponder(_ cell: UITableViewCell) { guard let indexPath0 = form_indexPathForCell(cell) else { return } guard let indexPath1 = form_indexPathForPreviousResponder(indexPath0) else { return } guard let dataSource = self.dataSource else { return } scrollToRow(at: indexPath1, at: .middle, animated: true) let cell = dataSource.tableView(self, cellForRowAt: indexPath1) cell.becomeFirstResponder() } /// Jump to a cell below. /// /// Usage: when the user hits TAB on the keyboard, then we want to jump to a cell below. func form_makeNextCellFirstResponder(_ cell: UITableViewCell) { guard let indexPath0 = form_indexPathForCell(cell) else { return } guard let indexPath1 = form_indexPathForNextResponder(indexPath0) else { return } guard let dataSource = self.dataSource else { return } scrollToRow(at: indexPath1, at: .middle, animated: true) let cell = dataSource.tableView(self, cellForRowAt: indexPath1) cell.becomeFirstResponder() } /// Determines if it's possible to jump to a cell above. func form_canMakePreviousCellFirstResponder(_ cell: UITableViewCell) -> Bool { guard let indexPath0 = form_indexPathForCell(cell) else { return false } if form_indexPathForPreviousResponder(indexPath0) == nil { return false } if self.dataSource == nil { return false } return true } /// Determines if it's possible to jump to a cell below. func form_canMakeNextCellFirstResponder(_ cell: UITableViewCell) -> Bool { guard let indexPath0 = form_indexPathForCell(cell) else { return false } if form_indexPathForNextResponder(indexPath0) == nil { return false } if self.dataSource == nil { return false } return true } } extension UITableViewCell { /// Jump to the previous cell, located above the current cell. /// /// Usage: when the user types SHIFT TAB on the keyboard, then we want to jump to a cell above. func form_makePreviousCellFirstResponder() { form_tableView()?.form_makePreviousCellFirstResponder(self) } /// Jump to the next cell, located below the current cell. /// /// Usage: when the user hits TAB on the keyboard, then we want to jump to a cell below. func form_makeNextCellFirstResponder() { form_tableView()?.form_makeNextCellFirstResponder(self) } /// Determines if it's possible to jump to the cell above. func form_canMakePreviousCellFirstResponder() -> Bool { form_tableView()?.form_canMakePreviousCellFirstResponder(self) ?? false } /// Determines if it's possible to jump to the cell below. func form_canMakeNextCellFirstResponder() -> Bool { form_tableView()?.form_canMakeNextCellFirstResponder(self) ?? false } }
mit
e72b29efe4ecc9289b49d9636dc3b699
34.407407
116
0.722654
4.01199
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/PaymentsShippingMethodController.swift
1
3044
// // PaymentsShippingMethodController.swift // Telegram // // Created by Mikhail Filimonov on 25.02.2021. // Copyright © 2021 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit import TelegramCore import Postbox import CurrencyFormat private final class Arguments { let context: AccountContext let select:(BotPaymentShippingOption)->Void init(context: AccountContext, select: @escaping(BotPaymentShippingOption)->Void) { self.context = context self.select = select } } private struct State : Equatable { var shippingOptions: [BotPaymentShippingOption] var form: BotPaymentForm } private func entries(_ state: State, arguments: Arguments) -> [InputDataEntry] { var entries:[InputDataEntry] = [] var sectionId:Int32 = 0 var index: Int32 = 0 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 for option in state.shippingOptions { entries.append(.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: InputDataIdentifier(option.title), data: .init(name: option.title, color: theme.colors.text, type: .context(formatCurrencyAmount(option.prices.reduce(0, { $0 + $1.amount }), currency: state.form.invoice.currency)), viewType: bestGeneralViewType(state.shippingOptions, for: option), action: { arguments.select(option) }))) index += 1 } // entries entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 return entries } func PaymentsShippingMethodController(context: AccountContext, shippingOptions: [BotPaymentShippingOption], form: BotPaymentForm, select:@escaping(BotPaymentShippingOption)->Void) -> InputDataModalController { var close:(()->Void)? = nil let actionsDisposable = DisposableSet() let initialState = State(shippingOptions: shippingOptions, form: form) let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((State) -> State) -> Void = { f in statePromise.set(stateValue.modify (f)) } let arguments = Arguments(context: context, select: { option in close?() select(option) }) let signal = statePromise.get() |> deliverOnPrepareQueue |> map { state in return InputDataSignalValue(entries: entries(state, arguments: arguments)) } let controller = InputDataController(dataSignal: signal, title: strings().checkoutShippingMethod) controller.onDeinit = { actionsDisposable.dispose() } let modalInteractions = ModalInteractions(acceptTitle: strings().modalCancel, accept: { close?() }, drawBorder: true, height: 50, singleButton: true) let modalController = InputDataModalController(controller, modalInteractions: modalInteractions) close = { [weak modalController] in modalController?.modal?.close() } return modalController }
gpl-2.0
b4dad02903019ebc6e38ae0c752b0f66
28.833333
397
0.693395
4.732504
false
false
false
false
anilkumarbp/ringcentral-swift-v2
RingCentral/Mocks/MockRegistry.swift
1
4430
// // MockRegistry.swift // RingCentral // // Created by Anil Kumar BP on 2/10/16. // Copyright © 2016 Anil Kumar BP. All rights reserved. // import Foundation public class MockRegistry { internal var responses = [Mock]() init() { // self.responses = requestMockResponse as! [Mock] } // commenting for now { as swift does not support default constructors } func add(requestMockResponse: Mock) { self.responses = [requestMockResponse] print("Adding Mock to respsonses array : ") } func find(request: NSMutableURLRequest) -> Mock { let mock = self.responses.removeFirst() print("The mock removed is : ", mock._json) return mock } // Clear Mock public func clear() { return self.responses = [] } // Authentication Mock public func authenticationMock() { let time = NSDate().timeIntervalSince1970 + 3600 return self.add(Mock(method: "POST", path: "restapi/oauth/token", json: [ "access_token": "ACCESS_TOKEN", "token_type": "bearer", "expires_in": "3600", "refresh_token": "REFRESH_TOKEN", "refresh_token_expires_in": "60480", "scope": "SMS RCM Foo Boo", "expireTime": String(time), "owner_id": "foo" ])) } // Logout Mock public func logoutMock() { return self.add(Mock(method: "POST", path: "/restapi/oauth/revoke")) } // Presence Subscription Mock public func presenceSubscriptionMock(id: String = "1", detailed: Bool = true) { let expiresIn = 15 * 60 * 60 let time = NSDate().timeIntervalSince1970 + Double(expiresIn) return self.add(Mock(method: "POST", path: "/restapi/v1.0/subscription", json: [ "eventFilters": ["/restapi/v1.0/account/~/extension/" , id , "/presence" , (detailed ? "?detailedTelephonyState=true" : "")], "expirationTime": String(time), "expiresIn": String(expiresIn), "deliveryMode": [ "transportType": "PubNub", "encryption": "true", "address": "123_foo", "subscriberKey": "sub-c-foo", "secretKey": "sec-c-bar", "encryptionAlgorithm": "AES", "encryptionKey": "e0bMTqmumPfFUbwzppkSbA" ], "creationTime": String(NSDate()), "id": "foo-bar-baz", "status": "Active", "uri": "https://platform.ringcentral.com/restapi/v1.0/subscription/foo-bar-baz" ])) } public func refreshMock(failure: Bool = false, expiresIn: Int = 3600) { let time = NSDate().timeIntervalSince1970 + 3600 var body = [String: AnyObject]() body = failure ? [ "access_token": "ACCESS_TOKEN_FROM_REFRESH", "token_type": "bearer", "expires_in": String(expiresIn), "refresh_token": "REFRESH_TOKEN_FROM_REFRESH", "refresh_token_expires_in": "60480", "scope": "SMS RCM Foo Boo", "expireTime": String(time), "owner_id": "foo" ] : [ "message": "Wrong Token (mock)" ] let status = !failure ? 200 : 400 return self.add(Mock(method: "POST", path: "/restapi/oauth/token", json: body, status: status)) } public func subscriptionMock(expiresIn: Int = 54000, eventFilters: [String] = ["/restapi/v1.0/account/~/extension/1/presence"]) { let expiresIn = 15 * 60 * 60 let time = NSDate().timeIntervalSince1970 + Double(expiresIn) return self.add(Mock(method: "POST", path: "/restapi/v1.0/subscription", json: [ "eventFilters": eventFilters, "expirationTime": String(time), "expiresIn": String(expiresIn), "deliveryMode": [ "transportType": "PubNub", "encryption": "false", "address": "123_foo", "subscriberKey": "sub-c-foo", "secretKey": "sec-c-bar" ], "id": "foo-bar-baz", "creationTime": String(NSDate()), "status": "Active", "uri": "https://platform.ringcentral.com/restapi/v1.0/subscription/foo-bar-baz" ])) } }
mit
52e184b71b0a00e59c8f534cfc998be5
34.150794
137
0.53511
4.154784
false
false
false
false
acastano/swift-bootstrap
foundationkit/Sources/Classes/Cache/CacheUtils.swift
1
2920
import Foundation public final class Path: NSObject { public var path = "" private let cacheFolder = "ImageCache" override init() { let array = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) if array.count > 0 { var path = array[0] if let bundleIdentifier = Bundle.main.bundleIdentifier { path += "/" + bundleIdentifier + "/" + cacheFolder let fm = FileManager.default do { try fm.createDirectory(atPath: path, withIntermediateDirectories:true, attributes:nil) }catch {} self.path = path } } } } public final class CacheUtils: NSObject { public class var path: Path { struct Singleton { static let instance = Path() } return Singleton.instance } public class func keyForURL(_ url:URL) -> String { let h = url.host != nil ? url.host! : "" let p = url.path let q = url.query != nil ? url.query! : "" let path = String(format:"%@%@%@", h, p, q) let doNotWant = CharacterSet(charactersIn: "/:.,") let charactersArray: [String] = path.components(separatedBy: doNotWant) let key = charactersArray.joined(separator: "") return key } public class func cleanseCache() { runOnLowPriorityQueue() { let daysToCleanCacheInSeconds: TimeInterval = 2592000 let path = self.path.path let fm = FileManager.default do { let dirContents = try fm.contentsOfDirectory(atPath: path) for file in dirContents { let filePath = "\(path)/\(file)" let attr = try fm.attributesOfItem(atPath: filePath) if let date = attr[FileAttributeKey.modificationDate] as? Date { let difference = Date().timeIntervalSince(date) if difference > daysToCleanCacheInSeconds { try fm.removeItem(atPath: filePath) } } } } catch {} } } }
apache-2.0
d5a11797a5f5203587062813ffedc56c
25.306306
106
0.407877
6.697248
false
false
false
false
mihaicris/digi-cloud
Digi Cloud/Controller/Listing/LocationsViewController.swift
1
12813
// // LocationsViewController.swift // test // // Created by Mihai Cristescu on 15/09/16. // Copyright © 2016 Mihai Cristescu. All rights reserved. // import UIKit final class LocationsViewController: UITableViewController { // MARK: - Properties enum SectionType { case main case connections case imports case exports } var onFinish: (() -> Void)? private var sections: [SectionType] = [] private var mainMounts: [Mount] = [] private var connectionMounts: [Mount] = [] private var importMounts: [Mount] = [] private var exportMounts: [Mount] = [] // When coping or moving files/folders, this property will hold the source location which is passed between // controllers on navigation stack. private var sourceLocations: [Location]? private let action: ActionType private var isUpdating: Bool = false private var didReceivedNetworkError = false private var errorMessage = "" let activityIndicator: UIActivityIndicatorView = { let activityIndicator = UIActivityIndicatorView() activityIndicator.hidesWhenStopped = true activityIndicator.activityIndicatorViewStyle = .gray activityIndicator.translatesAutoresizingMaskIntoConstraints = false return activityIndicator }() // MARK: - Initializers and Deinitializers init(action: ActionType, sourceLocations: [Location]? = nil) { self.action = action self.sourceLocations = sourceLocations super.init(style: .grouped) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Overridden Methods and Properties override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() setupActivityIndicatorView() setupTableView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.getMounts() } // MARK: - Helper Functions private func setupActivityIndicatorView() { view.addSubview(activityIndicator) NSLayoutConstraint.activate([ activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor), activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -44) ]) } private func setupNavigationBar() { // Create navigation elements when coping or moving let bookmarkButton = UIBarButtonItem(barButtonSystemItem: .bookmarks, target: self, action: #selector(handleShowBookmarksViewController(_:))) navigationItem.setRightBarButton(bookmarkButton, animated: false) if action == .copy || action == .move { self.navigationItem.prompt = NSLocalizedString("Choose a destination", comment: "") let rightButton = UIBarButtonItem(title: NSLocalizedString("Cancel", comment: ""), style: .done, target: self, action: #selector(handleDone)) navigationItem.setRightBarButton(rightButton, animated: false) } else { let settingsButton = UIBarButtonItem(image: #imageLiteral(resourceName: "settings_icon"), style: .done, target: self, action: #selector(handleShowSettings)) self.navigationItem.setLeftBarButton(settingsButton, animated: false) } self.title = NSLocalizedString("Locations", comment: "") } private func setupTableView() { tableView.rowHeight = 80 tableView.tableFooterView = UIView() tableView.separatorInset = UIEdgeInsets(top: 0, left: 15, bottom: 0, right: 0) tableView.cellLayoutMarginsFollowReadableWidth = false refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: #selector(handleRefreshLocations), for: UIControlEvents.valueChanged) } private func presentError(message: String) { let title = NSLocalizedString("Error", comment: "") let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default, handler: nil)) self.present(alertController, animated: true, completion: nil) } private func getMounts() { isUpdating = true didReceivedNetworkError = false DigiClient.shared.getMounts { mountsList, error in self.isUpdating = false guard error == nil else { self.didReceivedNetworkError = true switch error! { case NetworkingError.internetOffline(let msg): self.errorMessage = msg case NetworkingError.requestTimedOut(let msg): self.errorMessage = msg default: self.errorMessage = NSLocalizedString("There was an error while refreshing the locations.", comment: "") } if self.tableView.isDragging { return } DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.presentError(message: self.errorMessage) } return } var mounts = mountsList ?? [] // Remove from list the mounts for which there isn't permission to write to (only in copy / move action). Or to our own export mounts.... if self.action == .copy || self.action == .move { mounts = mounts.filter { $0.canWrite && $0.type != "export" } } self.sections.removeAll() self.mainMounts = mounts.filter { $0.type == "device" && $0.isPrimary } self.connectionMounts = mounts.filter { $0.type == "device" && !$0.isPrimary } self.importMounts = mounts.filter { $0.type == "import" } self.exportMounts = mounts.filter { $0.type == "export" } if !self.mainMounts.isEmpty { self.sections.append(.main) } if !self.connectionMounts.isEmpty { self.sections.append(.connections) } if !self.importMounts.isEmpty { self.sections.append(.imports) } if !self.exportMounts.isEmpty { self.sections.append(.exports) } if self.refreshControl?.isRefreshing == true { if self.tableView.isDragging { return } else { self.endRefreshAndReloadTable() } } else { self.tableView.reloadData() } } } private func endRefreshAndReloadTable() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) { self.refreshControl?.endRefreshing() DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { if self.didReceivedNetworkError { self.presentError(message: self.errorMessage) } else { self.tableView.reloadData() } } } } @objc private func handleRefreshLocations() { if self.isUpdating { self.refreshControl?.endRefreshing() return } self.getMounts() } @objc private func handleShowSettings() { if let user = AppSettings.userLogged { let controller = SettingsViewController(user: user) let navController = UINavigationController(rootViewController: controller) navController.modalPresentationStyle = .popover navController.popoverPresentationController?.barButtonItem = navigationItem.leftBarButtonItem present(navController, animated: true, completion: nil) } } @objc private func handleShowBookmarksViewController(_ sender: UIBarButtonItem) { guard let buttonView = sender.value(forKey: "view") as? UIView else { return } let controller = ManageBookmarksViewController() controller.onSelect = { [weak self] location in let controller = ListingViewController(location: location, action: .noAction) self?.navigationController?.pushViewController(controller, animated: true) } let navController = UINavigationController(rootViewController: controller) navController.modalPresentationStyle = .popover navController.popoverPresentationController?.sourceView = buttonView navController.popoverPresentationController?.sourceRect = buttonView.bounds present(navController, animated: true, completion: nil) } @objc private func handleDone() { dismiss(animated: true) { self.onFinish?() } } // MARK: TableView delegates override func numberOfSections(in tableView: UITableView) -> Int { return sections.count } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch sections[section] { case .main: return mainMounts.isEmpty ? nil : NSLocalizedString("Main storage", comment: "") case .connections: return connectionMounts.isEmpty ? nil : NSLocalizedString("Connections", comment: "") case .imports: return importMounts.isEmpty ? nil : NSLocalizedString("Shared with you", comment: "") case .exports: return exportMounts.isEmpty ? nil : NSLocalizedString("Shared by you", comment: "") } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch sections[section] { case .main: return mainMounts.count case .connections: return connectionMounts.count case .imports: return importMounts.count case .exports: return exportMounts.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = LocationCell() var mount: Mount switch sections[indexPath.section] { case .main: mount = mainMounts[indexPath.row] case .connections: mount = connectionMounts[indexPath.row] case .imports: mount = importMounts[indexPath.row] case .exports: mount = exportMounts[indexPath.row] } cell.mount = mount return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) guard let cell = tableView.cellForRow(at: indexPath) as? LocationCell else { return } guard let mount = cell.mount else { return } if !mount.online { presentError(message: NSLocalizedString("Device is offline.", comment: "")) return } var location: Location = Location(mount: cell.mount, path: "/") if mount.type == "export" { if let rootMount = mount.root { let originalPath = rootMount.path var substituteMount: Mount? if mount.origin == "hosted" { if let index = mainMounts.index (where: { $0.identifier == rootMount.identifier }) { substituteMount = mainMounts[index] } } else if mount.origin == "desktop" { if let index = connectionMounts.index (where: { $0.identifier == rootMount.identifier }) { substituteMount = connectionMounts[index] } } if let substituteMount = substituteMount { location = Location(mount: substituteMount, path: originalPath) } } } let controller = ListingViewController(location: location, action: self.action, sourceLocations: self.sourceLocations) if self.action != .noAction { controller.onFinish = { [weak self] in self?.onFinish?() } } navigationController?.pushViewController(controller, animated: true) } override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { if refreshControl?.isRefreshing == true { if self.isUpdating { return } self.endRefreshAndReloadTable() } } }
mit
3929249aa7505c86dbd269bd681c3be6
33.074468
168
0.608492
5.351713
false
false
false
false
nferocious76/NFImageView
Example/Pods/Alamofire/Source/ParameterEncoding.swift
1
13236
// // ParameterEncoding.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// A dictionary of parameters to apply to a `URLRequest`. public typealias Parameters = [String: Any] /// A type used to define how a set of parameters are applied to a `URLRequest`. public protocol ParameterEncoding { /// Creates a `URLRequest` by encoding parameters and applying them on the passed request. /// /// - Parameters: /// - urlRequest: `URLRequestConvertible` value onto which parameters will be encoded. /// - parameters: `Parameters` to encode onto the request. /// /// - Returns: The encoded `URLRequest`. /// - Throws: Any `Error` produced during parameter encoding. func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest } // MARK: - /// Creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP /// body of the URL request. Whether the query string is set or appended to any existing URL query string or set as /// the HTTP body depends on the destination of the encoding. /// /// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to /// `application/x-www-form-urlencoded; charset=utf-8`. /// /// There is no published specification for how to encode collection types. By default the convention of appending /// `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for /// nested dictionary values (`foo[bar]=baz`) is used. Optionally, `ArrayEncoding` can be used to omit the /// square brackets appended to array keys. /// /// `BoolEncoding` can be used to configure how boolean values are encoded. The default behavior is to encode /// `true` as 1 and `false` as 0. public struct URLEncoding: ParameterEncoding { // MARK: Helper Types /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the /// resulting URL request. public enum Destination { /// Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` requests and /// sets as the HTTP body for requests with any other HTTP method. case methodDependent /// Sets or appends encoded query string result to existing query string. case queryString /// Sets encoded query string result as the HTTP body of the URL request. case httpBody func encodesParametersInURL(for method: HTTPMethod) -> Bool { switch self { case .methodDependent: return [.get, .head, .delete].contains(method) case .queryString: return true case .httpBody: return false } } } /// Configures how `Array` parameters are encoded. public enum ArrayEncoding { /// An empty set of square brackets is appended to the key for every value. This is the default behavior. case brackets /// No brackets are appended. The key is encoded as is. case noBrackets func encode(key: String) -> String { switch self { case .brackets: return "\(key)[]" case .noBrackets: return key } } } /// Configures how `Bool` parameters are encoded. public enum BoolEncoding { /// Encode `true` as `1` and `false` as `0`. This is the default behavior. case numeric /// Encode `true` and `false` as string literals. case literal func encode(value: Bool) -> String { switch self { case .numeric: return value ? "1" : "0" case .literal: return value ? "true" : "false" } } } // MARK: Properties /// Returns a default `URLEncoding` instance with a `.methodDependent` destination. public static var `default`: URLEncoding { URLEncoding() } /// Returns a `URLEncoding` instance with a `.queryString` destination. public static var queryString: URLEncoding { URLEncoding(destination: .queryString) } /// Returns a `URLEncoding` instance with an `.httpBody` destination. public static var httpBody: URLEncoding { URLEncoding(destination: .httpBody) } /// The destination defining where the encoded query string is to be applied to the URL request. public let destination: Destination /// The encoding to use for `Array` parameters. public let arrayEncoding: ArrayEncoding /// The encoding to use for `Bool` parameters. public let boolEncoding: BoolEncoding // MARK: Initialization /// Creates an instance using the specified parameters. /// /// - Parameters: /// - destination: `Destination` defining where the encoded query string will be applied. `.methodDependent` by /// default. /// - arrayEncoding: `ArrayEncoding` to use. `.brackets` by default. /// - boolEncoding: `BoolEncoding` to use. `.numeric` by default. public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, boolEncoding: BoolEncoding = .numeric) { self.destination = destination self.arrayEncoding = arrayEncoding self.boolEncoding = boolEncoding } // MARK: Encoding public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } if let method = urlRequest.method, destination.encodesParametersInURL(for: method) { guard let url = urlRequest.url else { throw AFError.parameterEncodingFailed(reason: .missingURL) } if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { let percentEncodedQuery = (urlComponents.percentEncodedQuery.map { $0 + "&" } ?? "") + query(parameters) urlComponents.percentEncodedQuery = percentEncodedQuery urlRequest.url = urlComponents.url } } else { if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = Data(query(parameters).utf8) } return urlRequest } /// Creates a percent-escaped, URL encoded query string components from the given key-value pair recursively. /// /// - Parameters: /// - key: Key of the query component. /// - value: Value of the query component. /// /// - Returns: The percent-escaped, URL encoded query string components. public func queryComponents(fromKey key: String, value: Any) -> [(String, String)] { var components: [(String, String)] = [] if let dictionary = value as? [String: Any] { for (nestedKey, value) in dictionary { components += queryComponents(fromKey: "\(key)[\(nestedKey)]", value: value) } } else if let array = value as? [Any] { for value in array { components += queryComponents(fromKey: arrayEncoding.encode(key: key), value: value) } } else if let value = value as? NSNumber { if value.isBool { components.append((escape(key), escape(boolEncoding.encode(value: value.boolValue)))) } else { components.append((escape(key), escape("\(value)"))) } } else if let bool = value as? Bool { components.append((escape(key), escape(boolEncoding.encode(value: bool)))) } else { components.append((escape(key), escape("\(value)"))) } return components } /// Creates a percent-escaped string following RFC 3986 for a query string key or value. /// /// - Parameter string: `String` to be percent-escaped. /// /// - Returns: The percent-escaped `String`. public func escape(_ string: String) -> String { string.addingPercentEncoding(withAllowedCharacters: .afURLQueryAllowed) ?? string } private func query(_ parameters: [String: Any]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += queryComponents(fromKey: key, value: value) } return components.map { "\($0)=\($1)" }.joined(separator: "&") } } // MARK: - /// Uses `JSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the /// request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`. public struct JSONEncoding: ParameterEncoding { // MARK: Properties /// Returns a `JSONEncoding` instance with default writing options. public static var `default`: JSONEncoding { JSONEncoding() } /// Returns a `JSONEncoding` instance with `.prettyPrinted` writing options. public static var prettyPrinted: JSONEncoding { JSONEncoding(options: .prettyPrinted) } /// The options for writing the parameters as JSON data. public let options: JSONSerialization.WritingOptions // MARK: Initialization /// Creates an instance using the specified `WritingOptions`. /// /// - Parameter options: `JSONSerialization.WritingOptions` to use. public init(options: JSONSerialization.WritingOptions = []) { self.options = options } // MARK: Encoding public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: parameters, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } return urlRequest } /// Encodes any JSON compatible object into a `URLRequest`. /// /// - Parameters: /// - urlRequest: `URLRequestConvertible` value into which the object will be encoded. /// - jsonObject: `Any` value (must be JSON compatible` to be encoded into the `URLRequest`. `nil` by default. /// /// - Returns: The encoded `URLRequest`. /// - Throws: Any `Error` produced during encoding. public func encode(_ urlRequest: URLRequestConvertible, withJSONObject jsonObject: Any? = nil) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let jsonObject = jsonObject else { return urlRequest } do { let data = try JSONSerialization.data(withJSONObject: jsonObject, options: options) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data } catch { throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error)) } return urlRequest } } // MARK: - extension NSNumber { fileprivate var isBool: Bool { // Use Obj-C type encoding to check whether the underlying type is a `Bool`, as it's guaranteed as part of // swift-corelibs-foundation, per [this discussion on the Swift forums](https://forums.swift.org/t/alamofire-on-linux-possible-but-not-release-ready/34553/22). String(cString: objCType) == "c" } }
mit
b0964d4dcfac2b09f4e05c9649abf24b
40.622642
167
0.650725
4.889546
false
false
false
false
Arcovv/CleanArchitectureRxSwift
Network/Network/Network.swift
1
2503
// // Network.swift // CleanArchitectureRxSwift // // Created by Andrey Yastrebov on 16.03.17. // Copyright © 2017 sergdort. All rights reserved. // import Foundation import Alamofire import Domain import RxAlamofire import RxSwift import ObjectMapper final class Network<T: ImmutableMappable> { private let endPoint: String private let scheduler: ConcurrentDispatchQueueScheduler init(_ endPoint: String) { self.endPoint = endPoint self.scheduler = ConcurrentDispatchQueueScheduler(qos: DispatchQoS(qosClass: DispatchQoS.QoSClass.background, relativePriority: 1)) } func getItems(_ path: String) -> Observable<[T]> { let absolutePath = "\(endPoint)/\(path)" return RxAlamofire .json(.get, absolutePath) .debug() .observeOn(scheduler) .map({ json -> [T] in return try Mapper<T>().mapArray(JSONObject: json) }) } func getItem(_ path: String, itemId: String) -> Observable<T> { let absolutePath = "\(endPoint)/\(path)/\(itemId)" return RxAlamofire .request(.get, absolutePath) .debug() .observeOn(scheduler) .map({ json -> T in return try Mapper<T>().map(JSONObject: json) }) } func postItem(_ path: String, parameters: [String: Any]) -> Observable<T> { let absolutePath = "\(endPoint)/\(path)" return RxAlamofire .request(.post, absolutePath, parameters: parameters) .debug() .observeOn(scheduler) .map({ json -> T in return try Mapper<T>().map(JSONObject: json) }) } func updateItem(_ path: String, itemId: String, parameters: [String: Any]) -> Observable<T> { let absolutePath = "\(endPoint)/\(path)/\(itemId)" return RxAlamofire .request(.put, absolutePath, parameters: parameters) .debug() .observeOn(scheduler) .map({ json -> T in return try Mapper<T>().map(JSONObject: json) }) } func deleteItem(_ path: String, itemId: String) -> Observable<T> { let absolutePath = "\(endPoint)/\(path)/\(itemId)" return RxAlamofire .request(.delete, absolutePath) .debug() .observeOn(scheduler) .map({ json -> T in return try Mapper<T>().map(JSONObject: json) }) } }
mit
71f95d957fff15363377ac7fa31c4fb9
30.275
139
0.569145
4.793103
false
false
false
false
kean/Arranged
Example/Example/BaseStackViewController.swift
1
12597
// // BaseStackViewController.swift // Example // // Created by Alexander Grebenyuk on 02/03/16. // Copyright © 2016 Alexander Grebenyuk. All rights reserved. // import UIKit import Arranged let loggingEnabled = true let logAffectingViewsConstraints = false // MARK: BaseStackViewController enum ContentType { case view case label } class BaseStackViewController<T>: UIViewController where T: UIView, T: StackViewAdapter { var stackView: T! var views = [UIView]() var widthConstraint: NSLayoutConstraint! var heightConstraint: NSLayoutConstraint! // Options var animated = true var contentType: ContentType = .view { didSet { if oldValue != contentType { refreshContent() } } } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func createStackView() -> T { fatalError("abstract method") } override func viewDidLoad() { super.viewDidLoad() // Creat stack view stackView = createStackView() refreshContent() stackView.layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) view.layoutMargins = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16) view.addSubview(stackView) stackView.autoPin(toTopLayoutGuideOf: self, withInset: 16) stackView.autoPinEdge(toSuperviewMargin: .leading) stackView.autoPinEdge(toSuperviewMargin: .trailing, relation: .greaterThanOrEqual) widthConstraint = stackView.autoSetDimension(.width, toSize: 100) widthConstraint.isActive = false heightConstraint = stackView.autoSetDimension(.height, toSize: 100) heightConstraint.isActive = false // Disambiguate stack view size stackView.addConstraint(NSLayoutConstraint(item: stackView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0).then { $0.priority = UILayoutPriority(rawValue: 100) }) stackView.addConstraint(NSLayoutConstraint(item: stackView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 0).then { $0.priority = UILayoutPriority(rawValue: 100) }) // Create background for stack view let background = UIView() background.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0) view.insertSubview(background, belowSubview: stackView) background.autoMatch(.width, to: .width, of: stackView) background.autoMatch(.height, to: .height, of: stackView) background.autoAlignAxis(.horizontal, toSameAxisOf: stackView) background.autoAlignAxis(.vertical, toSameAxisOf: stackView) // Create controls let controls = UIStackView() controls.spacing = 2 controls.axis = .vertical controls.isLayoutMarginsRelativeArrangement = true controls.alignment = .leading controls.addArrangedSubview(AxisPicker(value: self.stackView.axis, presenter: self) { axis in self.perform { self.stackView.axis = axis } }.view) controls.addArrangedSubview(SpacingPicker(value: self.stackView.spacing, presenter: self) { value in self.perform { self.stackView.spacing = value } }.view) controls.addArrangedSubview(DistrubituonPicker(value: self.stackView.ar_distribution, presenter: self) { value in self.perform { self.stackView.ar_distribution = value } }.view) controls.addArrangedSubview(AlignmentPicker(value: self.stackView.ar_alignment, presenter: self) { value in self.perform { self.stackView.ar_alignment = value } }.view) controls.addArrangedSubview(MarginsPicker(value: self.stackView.layoutMargins, presenter: self) { value in self.perform { self.stackView.layoutMargins = value } }.view) controls.addArrangedSubview(BaselineRelativeArrangementPicker(value: self.stackView.isBaselineRelativeArrangement , presenter: self) { value in self.perform { self.stackView.isBaselineRelativeArrangement = value } }.view) controls.addArrangedSubview(LayoutMarginsRelativeArrangementPicker(value: self.stackView.isLayoutMarginsRelativeArrangement , presenter: self) { value in self.perform { self.stackView.isLayoutMarginsRelativeArrangement = value } }.view) let controls2 = UIStackView() controls2.spacing = 2 controls2.axis = .vertical controls2.isLayoutMarginsRelativeArrangement = true controls2.alignment = .trailing controls2.addArrangedSubview(UIButton(type: .system).then { $0.setTitle("show all subviews", for: UIControl.State()) $0.addTarget(self, action: #selector(BaseStackViewController.buttonShowAllTapped(_:)), for: .touchUpInside) }) controls2.addArrangedSubview(AnimatedPicker(value: self.animated, presenter: self) { self.animated = $0 }.view) controls2.addArrangedSubview(ContentTypePicker(value: self.contentType, presenter: self) { self.contentType = $0 }.view) controls2.addArrangedSubview(SizePicker(value: (false, 0.5), type: .width, presenter: self) { active, ratio in self.widthConstraint.isActive = active let bound = self.view.bounds.size.width self.widthConstraint.constant = ratio * bound }.view) controls2.addArrangedSubview(SizePicker(value: (false, 0.5), type: .height, presenter: self) { active, ratio in self.heightConstraint.isActive = active let bound = self.view.bounds.size.width self.heightConstraint.constant = ratio * bound }.view) view.addSubview(controls) view.addSubview(controls2) controls.autoPin(toBottomLayoutGuideOf: self, withInset: 16) controls2.autoPinEdge(.top, to: .top, of: controls) controls.autoPinEdge(toSuperviewMargin: .leading) controls2.autoPinEdge(toSuperviewMargin: .trailing) controls.autoPinEdge(.top, to: .bottom, of: stackView, withOffset: 16, relation: .greaterThanOrEqual) } func refreshContent() { views.forEach { stackView.removeArrangedSubview($0) $0.removeFromSuperview() } views.removeAll() switch self.contentType { case .view: views.append(ContentView().then { $0.contentSize = CGSize(width: 40, height: 40) $0.backgroundColor = UIColor.red }) views.append(ContentView().then { $0.contentSize = CGSize(width: 20, height: 100) $0.backgroundColor = UIColor.blue }) views.append(ContentView().then { $0.contentSize = CGSize(width: 80, height: 60) $0.backgroundColor = UIColor.green }) case .label: views.append(UILabel().then { $0.text = "Sed ut perspiciatis unde omnis iste natus" $0.font = UIFont.systemFont(ofSize: 26) $0.numberOfLines = 0 $0.backgroundColor = UIColor.red }) views.append(UILabel().then { $0.text = "Neque porro quisquam est, qui dolorem ipsum" $0.font = UIFont.systemFont(ofSize: 20) $0.numberOfLines = 0 $0.backgroundColor = UIColor.blue }) views.append(UILabel().then { $0.text = "Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt." $0.font = UIFont.systemFont(ofSize: 14) $0.numberOfLines = 0 $0.backgroundColor = UIColor.green }) } for (index, view) in views.enumerated() { view.accessibilityIdentifier = "content-view-\(index + 1)" view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(BaseStackViewController.viewTapped(_:)))) stackView.addArrangedSubview(view) } if views.first is UILabel { // Disambiguate stack view size stackView.ar_distribution = .fillEqually } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if loggingEnabled { print("\n\n") print("===========================") print("constraints:") printConstraints(constraints(for: stackView)) if logAffectingViewsConstraints { print("") print("horizontal") print("==========") print("\naffecting stack view:") printConstraints(stackView.constraintsAffectingLayout(for: .horizontal)) for view in views { print("\naffecting view \(view.accessibilityIdentifier):") printConstraints(view.constraintsAffectingLayout(for: .horizontal)) } print("") print("vertical") print("==========") print("\naffecting stack view:") printConstraints(stackView.constraintsAffectingLayout(for: .vertical)) for view in views { print("\naffecting view \(view.accessibilityIdentifier):") printConstraints(view.constraintsAffectingLayout(for: .vertical)) } } } } @objc func buttonShowAllTapped(_ sender: UIButton) { perform { self.stackView.subviews.forEach{ if let stack = self.stackView as? Arranged.StackView { stack.setArrangedView($0, hidden: false) } else { $0.isHidden = false } } } } @objc func viewTapped(_ sender: UITapGestureRecognizer) { perform { if let stack = self.stackView as? Arranged.StackView { stack.setArrangedView(sender.view!, hidden: true) } else { sender.view?.isHidden = true } } } func perform(_ closure: @escaping () -> Void) { if (animated) { UIView.animate(withDuration: 0.33, animations: { closure() // Arranged.StackView requires call to layoutIfNeeded if !(self.stackView is UIStackView) { self.view.layoutIfNeeded() } }) } else { closure() } } func printConstraints(_ constraints: [NSLayoutConstraint]) { constraints.forEach { print($0) } } func constraints(for item: UIView) -> [NSLayoutConstraint] { var constraints = [NSLayoutConstraint]() constraints.append(contentsOf: item.constraints) for subview in item.subviews { constraints.append(contentsOf: subview.constraints) } return constraints } } // MARK: ContentView class ContentView: UIView { var contentSize = CGSize(width: 44, height: 44) convenience init() { self.init(frame: CGRect.zero) } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var intrinsicContentSize : CGSize { return contentSize } } // MARK: Then protocol Then {} extension Then where Self: Any { func then(_ block: (inout Self) -> Void) -> Self { var copy = self block(&copy) return copy } } extension Then where Self: AnyObject { func then(_ block: (Self) -> Void) -> Self { block(self) return self } } extension NSObject: Then {}
mit
35d8b7b87a74aaca95172cc78fcb9a22
33.891967
182
0.595268
4.953205
false
false
false
false
benlangmuir/swift
stdlib/public/core/ContiguousArray.swift
6
55880
//===--- ContiguousArray.swift --------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Three generic, mutable array-like types with value semantics. // // - `ContiguousArray<Element>` is a fast, contiguous array of `Element` with // a known backing store. // //===----------------------------------------------------------------------===// /// A contiguously stored array. /// /// The `ContiguousArray` type is a specialized array that always stores its /// elements in a contiguous region of memory. This contrasts with `Array`, /// which can store its elements in either a contiguous region of memory or an /// `NSArray` instance if its `Element` type is a class or `@objc` protocol. /// /// If your array's `Element` type is a class or `@objc` protocol and you do /// not need to bridge the array to `NSArray` or pass the array to Objective-C /// APIs, using `ContiguousArray` may be more efficient and have more /// predictable performance than `Array`. If the array's `Element` type is a /// struct or enumeration, `Array` and `ContiguousArray` should have similar /// efficiency. /// /// For more information about using arrays, see `Array` and `ArraySlice`, with /// which `ContiguousArray` shares most properties and methods. @frozen public struct ContiguousArray<Element>: _DestructorSafeContainer { @usableFromInline internal typealias _Buffer = _ContiguousArrayBuffer<Element> @usableFromInline internal var _buffer: _Buffer /// Initialization from an existing buffer does not have "array.init" /// semantics because the caller may retain an alias to buffer. @inlinable internal init(_buffer: _Buffer) { self._buffer = _buffer } } //===--- private helpers---------------------------------------------------===// extension ContiguousArray { @inlinable @_semantics("array.get_count") internal func _getCount() -> Int { return _buffer.immutableCount } @inlinable @_semantics("array.get_capacity") internal func _getCapacity() -> Int { return _buffer.immutableCapacity } @inlinable @_semantics("array.make_mutable") internal mutating func _makeMutableAndUnique() { if _slowPath(!_buffer.beginCOWMutation()) { _buffer = _buffer._consumeAndCreateNew() } } /// Marks the end of an Array mutation. /// /// After a call to `_endMutation` the buffer must not be mutated until a call /// to `_makeMutableAndUnique`. @_alwaysEmitIntoClient @_semantics("array.end_mutation") internal mutating func _endMutation() { _buffer.endCOWMutation() } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inlinable @inline(__always) internal func _checkSubscript_native(_ index: Int) { _buffer._checkValidSubscript(index) } /// Check that the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. /// /// - Precondition: The buffer must be uniquely referenced and native. @_alwaysEmitIntoClient @_semantics("array.check_subscript") internal func _checkSubscript_mutating(_ index: Int) { _buffer._checkValidSubscriptMutating(index) } /// Check that the specified `index` is valid, i.e. `0 ≤ index ≤ count`. @inlinable @_semantics("array.check_index") internal func _checkIndex(_ index: Int) { _precondition(index <= endIndex, "ContiguousArray index is out of range") _precondition(index >= startIndex, "Negative ContiguousArray index is out of range") } @inlinable @_semantics("array.get_element_address") internal func _getElementAddress(_ index: Int) -> UnsafeMutablePointer<Element> { return _buffer.firstElementAddress + index } } extension ContiguousArray: _ArrayProtocol { /// The total number of elements that the array can contain without /// allocating new storage. /// /// Every array reserves a specific amount of memory to hold its contents. /// When you add elements to an array and that array begins to exceed its /// reserved capacity, the array allocates a larger region of memory and /// copies its elements into the new storage. The new storage is a multiple /// of the old storage's size. This exponential growth strategy means that /// appending an element happens in constant time, averaging the performance /// of many append operations. Append operations that trigger reallocation /// have a performance cost, but they occur less and less often as the array /// grows larger. /// /// The following example creates an array of integers from an array literal, /// then appends the elements of another collection. Before appending, the /// array allocates new storage that is large enough store the resulting /// elements. /// /// var numbers = [10, 20, 30, 40, 50] /// // numbers.count == 5 /// // numbers.capacity == 5 /// /// numbers.append(contentsOf: stride(from: 60, through: 100, by: 10)) /// // numbers.count == 10 /// // numbers.capacity == 10 @inlinable public var capacity: Int { return _getCapacity() } /// An object that guarantees the lifetime of this array's elements. @inlinable public // @testable var _owner: AnyObject? { return _buffer.owner } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, `nil`. @inlinable public var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? { @inline(__always) // FIXME(TODO: JIRA): Hack around test failure get { return _buffer.firstElementAddressIfContiguous } } @inlinable internal var _baseAddress: UnsafeMutablePointer<Element> { return _buffer.firstElementAddress } } extension ContiguousArray: RandomAccessCollection, MutableCollection { /// The index type for arrays, `Int`. public typealias Index = Int /// The type that represents the indices that are valid for subscripting an /// array, in ascending order. public typealias Indices = Range<Int> /// The type that allows iteration over an array's elements. public typealias Iterator = IndexingIterator<ContiguousArray> /// The position of the first element in a nonempty array. /// /// For an instance of `ContiguousArray`, `startIndex` is always zero. If the array /// is empty, `startIndex` is equal to `endIndex`. @inlinable public var startIndex: Int { return 0 } /// The array's "past the end" position---that is, the position one greater /// than the last valid subscript argument. /// /// When you need a range that includes the last element of an array, use the /// half-open range operator (`..<`) with `endIndex`. The `..<` operator /// creates a range that doesn't include the upper bound, so it's always /// safe to use with `endIndex`. For example: /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.firstIndex(of: 30) { /// print(numbers[i ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" /// /// If the array is empty, `endIndex` is equal to `startIndex`. public var endIndex: Int { @inlinable get { return _getCount() } } /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index immediately after `i`. @inlinable public func index(after i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + 1 } /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. @inlinable public func formIndex(after i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i += 1 } /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index immediately before `i`. @inlinable public func index(before i: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i - 1 } /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. @inlinable public func formIndex(before i: inout Int) { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. i -= 1 } /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. /// /// let numbers = [10, 20, 30, 40, 50] /// let i = numbers.index(numbers.startIndex, offsetBy: 4) /// print(numbers[i]) /// // Prints "50" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. @inlinable public func index(_ i: Int, offsetBy distance: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return i + distance } /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from an /// array's starting index and then prints the element at that position. The /// operation doesn't require going beyond the limiting `numbers.endIndex` /// value, so it succeeds. /// /// let numbers = [10, 20, 30, 40, 50] /// if let i = numbers.index(numbers.startIndex, /// offsetBy: 4, /// limitedBy: numbers.endIndex) { /// print(numbers[i]) /// } /// // Prints "50" /// /// The next example attempts to retrieve an index ten positions from /// `numbers.startIndex`, but fails, because that distance is beyond the /// index passed as `limit`. /// /// let j = numbers.index(numbers.startIndex, /// offsetBy: 10, /// limitedBy: numbers.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the array. /// - distance: The distance to offset `i`. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, `limit` has no effect if it is less than `i`. /// Likewise, if `distance < 0`, `limit` has no effect if it is greater /// than `i`. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) @inlinable public func index( _ i: Int, offsetBy distance: Int, limitedBy limit: Int ) -> Int? { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. let l = limit - i if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l { return nil } return i + distance } /// Returns the distance between two indices. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. @inlinable public func distance(from start: Int, to end: Int) -> Int { // NOTE: this is a manual specialization of index movement for a Strideable // index that is required for Array performance. The optimizer is not // capable of creating partial specializations yet. // NOTE: Range checks are not performed here, because it is done later by // the subscript function. return end - start } @inlinable public func _failEarlyRangeCheck(_ index: Int, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } @inlinable public func _failEarlyRangeCheck(_ range: Range<Int>, bounds: Range<Int>) { // NOTE: This method is a no-op for performance reasons. } /// Accesses the element at the specified position. /// /// The following example uses indexed subscripting to update an array's /// second element. After assigning the new value (`"Butler"`) at a specific /// position, that value is immediately available at that same position. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// streets[1] = "Butler" /// print(streets[1]) /// // Prints "Butler" /// /// - Parameter index: The position of the element to access. `index` must be /// greater than or equal to `startIndex` and less than `endIndex`. /// /// - Complexity: Reading an element from an array is O(1). Writing is O(1) /// unless the array's storage is shared with another array, in which case /// writing is O(*n*), where *n* is the length of the array. @inlinable public subscript(index: Int) -> Element { get { _checkSubscript_native(index) return _buffer.getElement(index) } _modify { _makeMutableAndUnique() _checkSubscript_mutating(index) let address = _buffer.mutableFirstElementAddress + index yield &address.pointee _endMutation(); } } /// Accesses a contiguous subrange of the array's elements. /// /// The returned `ArraySlice` instance uses the same indices for the same /// elements as the original array. In particular, that slice, unlike an /// array, may have a nonzero `startIndex` and an `endIndex` that is not /// equal to `count`. Always use the slice's `startIndex` and `endIndex` /// properties instead of assuming that its indices start or end at a /// particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let i = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[i!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of integers. The bounds of the range must be /// valid indices of the array. @inlinable public subscript(bounds: Range<Int>) -> ArraySlice<Element> { get { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) return ArraySlice(_buffer: _buffer[bounds]) } set(rhs) { _checkIndex(bounds.lowerBound) _checkIndex(bounds.upperBound) // If the replacement buffer has same identity, and the ranges match, // then this was a pinned in-place modification, nothing further needed. if self[bounds]._buffer.identity != rhs._buffer.identity || bounds != rhs.startIndex..<rhs.endIndex { self.replaceSubrange(bounds, with: rhs) } } } /// The number of elements in the array. @inlinable public var count: Int { return _getCount() } } extension ContiguousArray: ExpressibleByArrayLiteral { /// Creates an array from the given array literal. /// /// Do not call this initializer directly. It is used by the compiler when /// you use an array literal. Instead, create a new array by using an array /// literal as its value. To do this, enclose a comma-separated list of /// values in square brackets. /// /// Here, an array of strings is created from an array literal holding only /// strings: /// /// let ingredients: ContiguousArray = /// ["cocoa beans", "sugar", "cocoa butter", "salt"] /// /// - Parameter elements: A variadic list of elements of the new array. @inlinable public init(arrayLiteral elements: Element...) { self.init(_buffer: ContiguousArray(elements)._buffer) } } extension ContiguousArray: RangeReplaceableCollection { /// Creates a new, empty array. /// /// This is equivalent to initializing with an empty array literal. /// For example: /// /// var emptyArray = Array<Int>() /// print(emptyArray.isEmpty) /// // Prints "true" /// /// emptyArray = [] /// print(emptyArray.isEmpty) /// // Prints "true" @inlinable @_semantics("array.init.empty") public init() { _buffer = _Buffer() } /// Creates an array containing the elements of a sequence. /// /// You can use this initializer to create an array from any other type that /// conforms to the `Sequence` protocol. For example, you might want to /// create an array with the integers from 1 through 7. Use this initializer /// around a range instead of typing all those numbers in an array literal. /// /// let numbers = Array(1...7) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 6, 7]" /// /// You can also use this initializer to convert a complex sequence or /// collection type back to an array. For example, the `keys` property of /// a dictionary isn't an array with its own storage, it's a collection /// that maps its elements from the dictionary only when they're /// accessed, saving the time and space needed to allocate an array. If /// you need to pass those keys to a method that takes an array, however, /// use this initializer to convert that list from its type of /// `LazyMapCollection<Dictionary<String, Int>, Int>` to a simple /// `[String]`. /// /// func cacheImagesWithNames(names: [String]) { /// // custom image loading and caching /// } /// /// let namedHues: [String: Int] = ["Vermillion": 18, "Magenta": 302, /// "Gold": 50, "Cerise": 320] /// let colorNames = Array(namedHues.keys) /// cacheImagesWithNames(colorNames) /// /// print(colorNames) /// // Prints "["Gold", "Cerise", "Magenta", "Vermillion"]" /// /// - Parameter s: The sequence of elements to turn into an array. @inlinable public init<S: Sequence>(_ s: S) where S.Element == Element { self.init(_buffer: s._copyToContiguousArray()._buffer) } /// Creates a new array containing the specified number of a single, repeated /// value. /// /// Here's an example of creating an array initialized with five strings /// containing the letter *Z*. /// /// let fiveZs = Array(repeating: "Z", count: 5) /// print(fiveZs) /// // Prints "["Z", "Z", "Z", "Z", "Z"]" /// /// - Parameters: /// - repeatedValue: The element to repeat. /// - count: The number of times to repeat the value passed in the /// `repeating` parameter. `count` must be zero or greater. @inlinable @_semantics("array.init") public init(repeating repeatedValue: Element, count: Int) { var p: UnsafeMutablePointer<Element> (self, p) = ContiguousArray._allocateUninitialized(count) for _ in 0..<count { p.initialize(to: repeatedValue) p += 1 } _endMutation() } @inline(never) @usableFromInline internal static func _allocateBufferUninitialized( minimumCapacity: Int ) -> _Buffer { let newBuffer = _ContiguousArrayBuffer<Element>( _uninitializedCount: 0, minimumCapacity: minimumCapacity) return _Buffer(_buffer: newBuffer, shiftedToStartIndex: 0) } /// Construct a ContiguousArray of `count` uninitialized elements. @inlinable internal init(_uninitializedCount count: Int) { _precondition(count >= 0, "Can't construct ContiguousArray with count < 0") // Note: Sinking this constructor into an else branch below causes an extra // Retain/Release. _buffer = _Buffer() if count > 0 { // Creating a buffer instead of calling reserveCapacity saves doing an // unnecessary uniqueness check. We disable inlining here to curb code // growth. _buffer = ContiguousArray._allocateBufferUninitialized(minimumCapacity: count) _buffer.mutableCount = count } // Can't store count here because the buffer might be pointing to the // shared empty array. } /// Entry point for `Array` literal construction; builds and returns /// a ContiguousArray of `count` uninitialized elements. @inlinable @_semantics("array.uninitialized") internal static func _allocateUninitialized( _ count: Int ) -> (ContiguousArray, UnsafeMutablePointer<Element>) { let result = ContiguousArray(_uninitializedCount: count) return (result, result._buffer.firstElementAddress) } //===--- basic mutations ------------------------------------------------===// /// Reserves enough space to store the specified number of elements. /// /// If you are adding a known number of elements to an array, use this method /// to avoid multiple reallocations. This method ensures that the array has /// unique, mutable, contiguous storage, with space allocated for at least /// the requested number of elements. /// /// For performance reasons, the size of the newly allocated storage might be /// greater than the requested capacity. Use the array's `capacity` property /// to determine the size of the new storage. /// /// Preserving an Array's Geometric Growth Strategy /// =============================================== /// /// If you implement a custom data structure backed by an array that grows /// dynamically, naively calling the `reserveCapacity(_:)` method can lead /// to worse than expected performance. Arrays need to follow a geometric /// allocation pattern for appending elements to achieve amortized /// constant-time performance. The `Array` type's `append(_:)` and /// `append(contentsOf:)` methods take care of this detail for you, but /// `reserveCapacity(_:)` allocates only as much space as you tell it to /// (padded to a round value), and no more. This avoids over-allocation, but /// can result in insertion not having amortized constant-time performance. /// /// The following code declares `values`, an array of integers, and the /// `addTenQuadratic()` function, which adds ten more values to the `values` /// array on each call. /// /// var values: [Int] = [0, 1, 2, 3] /// /// // Don't use 'reserveCapacity(_:)' like this /// func addTenQuadratic() { /// let newCount = values.count + 10 /// values.reserveCapacity(newCount) /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// The call to `reserveCapacity(_:)` increases the `values` array's capacity /// by exactly 10 elements on each pass through `addTenQuadratic()`, which /// is linear growth. Instead of having constant time when averaged over /// many calls, the function may decay to performance that is linear in /// `values.count`. This is almost certainly not what you want. /// /// In cases like this, the simplest fix is often to simply remove the call /// to `reserveCapacity(_:)`, and let the `append(_:)` method grow the array /// for you. /// /// func addTen() { /// let newCount = values.count + 10 /// for n in values.count..<newCount { /// values.append(n) /// } /// } /// /// If you need more control over the capacity of your array, implement your /// own geometric growth strategy, passing the size you compute to /// `reserveCapacity(_:)`. /// /// - Parameter minimumCapacity: The requested number of elements to store. /// /// - Complexity: O(*n*), where *n* is the number of elements in the array. @inlinable @_semantics("array.mutate_unknown") public mutating func reserveCapacity(_ minimumCapacity: Int) { _reserveCapacityImpl(minimumCapacity: minimumCapacity, growForAppend: false) _endMutation() } /// Reserves enough space to store `minimumCapacity` elements. /// If a new buffer needs to be allocated and `growForAppend` is true, /// the new capacity is calculated using `_growArrayCapacity`. @_alwaysEmitIntoClient internal mutating func _reserveCapacityImpl( minimumCapacity: Int, growForAppend: Bool ) { let isUnique = _buffer.beginCOWMutation() if _slowPath(!isUnique || _buffer.mutableCapacity < minimumCapacity) { _createNewBuffer(bufferIsUnique: isUnique, minimumCapacity: Swift.max(minimumCapacity, _buffer.count), growForAppend: growForAppend) } _internalInvariant(_buffer.mutableCapacity >= minimumCapacity) _internalInvariant(_buffer.mutableCapacity == 0 || _buffer.isUniquelyReferenced()) } /// Creates a new buffer, replacing the current buffer. /// /// If `bufferIsUnique` is true, the buffer is assumed to be uniquely /// referenced by this array and the elements are moved - instead of copied - /// to the new buffer. /// The `minimumCapacity` is the lower bound for the new capacity. /// If `growForAppend` is true, the new capacity is calculated using /// `_growArrayCapacity`. @_alwaysEmitIntoClient @inline(never) internal mutating func _createNewBuffer( bufferIsUnique: Bool, minimumCapacity: Int, growForAppend: Bool ) { _internalInvariant(!bufferIsUnique || _buffer.isUniquelyReferenced()) _buffer = _buffer._consumeAndCreateNew(bufferIsUnique: bufferIsUnique, minimumCapacity: minimumCapacity, growForAppend: growForAppend) } /// Copy the contents of the current buffer to a new unique mutable buffer. /// The count of the new buffer is set to `oldCount`, the capacity of the /// new buffer is big enough to hold 'oldCount' + 1 elements. @inline(never) @inlinable // @specializable internal mutating func _copyToNewBuffer(oldCount: Int) { let newCount = oldCount &+ 1 var newBuffer = _buffer._forceCreateUniqueMutableBuffer( countForNewBuffer: oldCount, minNewCapacity: newCount) _buffer._arrayOutOfPlaceUpdate( &newBuffer, oldCount, 0) } @inlinable @_semantics("array.make_mutable") internal mutating func _makeUniqueAndReserveCapacityIfNotUnique() { if _slowPath(!_buffer.beginCOWMutation()) { _createNewBuffer(bufferIsUnique: false, minimumCapacity: count &+ 1, growForAppend: true) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _reserveCapacityAssumingUniqueBuffer(oldCount: Int) { // Due to make_mutable hoisting the situation can arise where we hoist // _makeMutableAndUnique out of loop and use it to replace // _makeUniqueAndReserveCapacityIfNotUnique that precedes this call. If the // array was empty _makeMutableAndUnique does not replace the empty array // buffer by a unique buffer (it just replaces it by the empty array // singleton). // This specific case is okay because we will make the buffer unique in this // function because we request a capacity > 0 and therefore _copyToNewBuffer // will be called creating a new buffer. let capacity = _buffer.mutableCapacity _internalInvariant(capacity == 0 || _buffer.isMutableAndUniquelyReferenced()) if _slowPath(oldCount &+ 1 > capacity) { _createNewBuffer(bufferIsUnique: capacity > 0, minimumCapacity: oldCount &+ 1, growForAppend: true) } } @inlinable @_semantics("array.mutate_unknown") internal mutating func _appendElementAssumeUniqueAndCapacity( _ oldCount: Int, newElement: __owned Element ) { _internalInvariant(_buffer.isMutableAndUniquelyReferenced()) _internalInvariant(_buffer.mutableCapacity >= _buffer.mutableCount &+ 1) _buffer.mutableCount = oldCount &+ 1 (_buffer.mutableFirstElementAddress + oldCount).initialize(to: newElement) } /// Adds a new element at the end of the array. /// /// Use this method to append a single element to the end of a mutable array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(100) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 100]" /// /// Because arrays increase their allocated capacity using an exponential /// strategy, appending a single element to an array is an O(1) operation /// when averaged over many calls to the `append(_:)` method. When an array /// has additional capacity and is not sharing its storage with another /// instance, appending an element is O(1). When an array needs to /// reallocate storage before appending or its storage is shared with /// another copy, appending is O(*n*), where *n* is the length of the array. /// /// - Parameter newElement: The element to append to the array. /// /// - Complexity: O(1) on average, over many calls to `append(_:)` on the /// same array. @inlinable @_semantics("array.append_element") public mutating func append(_ newElement: __owned Element) { // Separating uniqueness check and capacity check allows hoisting the // uniqueness check out of a loop. _makeUniqueAndReserveCapacityIfNotUnique() let oldCount = _buffer.mutableCount _reserveCapacityAssumingUniqueBuffer(oldCount: oldCount) _appendElementAssumeUniqueAndCapacity(oldCount, newElement: newElement) _endMutation() } /// Adds the elements of a sequence to the end of the array. /// /// Use this method to append the elements of a sequence to the end of this /// array. This example appends the elements of a `Range<Int>` instance /// to an array of integers. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.append(contentsOf: 10...15) /// print(numbers) /// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]" /// /// - Parameter newElements: The elements to append to the array. /// /// - Complexity: O(*m*) on average, where *m* is the length of /// `newElements`, over many calls to `append(contentsOf:)` on the same /// array. @inlinable @_semantics("array.append_contentsOf") public mutating func append<S: Sequence>(contentsOf newElements: __owned S) where S.Element == Element { defer { _endMutation() } let newElementsCount = newElements.underestimatedCount _reserveCapacityImpl(minimumCapacity: self.count + newElementsCount, growForAppend: true) let oldCount = _buffer.mutableCount let startNewElements = _buffer.mutableFirstElementAddress + oldCount let buf = UnsafeMutableBufferPointer( start: startNewElements, count: _buffer.mutableCapacity - oldCount) var (remainder,writtenUpTo) = buf.initialize(from: newElements) // trap on underflow from the sequence's underestimate: let writtenCount = buf.distance(from: buf.startIndex, to: writtenUpTo) _precondition(newElementsCount <= writtenCount, "newElements.underestimatedCount was an overestimate") // can't check for overflow as sequences can underestimate // This check prevents a data race writing to _swiftEmptyArrayStorage if writtenCount > 0 { _buffer.mutableCount = _buffer.mutableCount + writtenCount } if writtenUpTo == buf.endIndex { // there may be elements that didn't fit in the existing buffer, // append them in slow sequence-only mode var newCount = _buffer.mutableCount var nextItem = remainder.next() while nextItem != nil { _reserveCapacityAssumingUniqueBuffer(oldCount: newCount) let currentCapacity = _buffer.mutableCapacity let base = _buffer.mutableFirstElementAddress // fill while there is another item and spare capacity while let next = nextItem, newCount < currentCapacity { (base + newCount).initialize(to: next) newCount += 1 nextItem = remainder.next() } _buffer.mutableCount = newCount } } } @inlinable @_semantics("array.reserve_capacity_for_append") internal mutating func reserveCapacityForAppend(newElementsCount: Int) { // Ensure uniqueness, mutability, and sufficient storage. Note that // for consistency, we need unique self even if newElements is empty. _reserveCapacityImpl(minimumCapacity: self.count + newElementsCount, growForAppend: true) _endMutation() } @inlinable @_semantics("array.mutate_unknown") public mutating func _customRemoveLast() -> Element? { _makeMutableAndUnique() let newCount = _buffer.mutableCount - 1 _precondition(newCount >= 0, "Can't removeLast from an empty ContiguousArray") let pointer = (_buffer.mutableFirstElementAddress + newCount) let element = pointer.move() _buffer.mutableCount = newCount _endMutation() return element } /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved up to /// close the gap. /// /// var measurements: [Double] = [1.1, 1.5, 2.9, 1.2, 1.5, 1.3, 1.2] /// let removed = measurements.remove(at: 2) /// print(measurements) /// // Prints "[1.1, 1.5, 1.2, 1.5, 1.3, 1.2]" /// /// - Parameter index: The position of the element to remove. `index` must /// be a valid index of the array. /// - Returns: The element at the specified index. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable @discardableResult @_semantics("array.mutate_unknown") public mutating func remove(at index: Int) -> Element { _makeMutableAndUnique() let currentCount = _buffer.mutableCount _precondition(index < currentCount, "Index out of range") _precondition(index >= 0, "Index out of range") let newCount = currentCount - 1 let pointer = (_buffer.mutableFirstElementAddress + index) let result = pointer.move() pointer.moveInitialize(from: pointer + 1, count: newCount - index) _buffer.mutableCount = newCount _endMutation() return result } /// Inserts a new element at the specified position. /// /// The new element is inserted before the element currently at the specified /// index. If you pass the array's `endIndex` property as the `index` /// parameter, the new element is appended to the array. /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.insert(100, at: 3) /// numbers.insert(200, at: numbers.endIndex) /// /// print(numbers) /// // Prints "[1, 2, 3, 100, 4, 5, 200]" /// /// - Parameter newElement: The new element to insert into the array. /// - Parameter i: The position at which to insert the new element. /// `index` must be a valid index of the array or equal to its `endIndex` /// property. /// /// - Complexity: O(*n*), where *n* is the length of the array. If /// `i == endIndex`, this method is equivalent to `append(_:)`. @inlinable public mutating func insert(_ newElement: __owned Element, at i: Int) { _checkIndex(i) self.replaceSubrange(i..<i, with: CollectionOfOne(newElement)) } /// Removes all elements from the array. /// /// - Parameter keepCapacity: Pass `true` to keep the existing capacity of /// the array after removing its elements. The default value is /// `false`. /// /// - Complexity: O(*n*), where *n* is the length of the array. @inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if !keepCapacity { _buffer = _Buffer() } else { self.replaceSubrange(indices, with: EmptyCollection()) } } //===--- algorithms -----------------------------------------------------===// @inlinable @available(*, deprecated, renamed: "withContiguousMutableStorageIfAvailable") public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in return try body(&bufferPointer) } } @inlinable public mutating func withContiguousMutableStorageIfAvailable<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeMutableBufferPointer { (bufferPointer) -> R in return try body(&bufferPointer) } } @inlinable public func withContiguousStorageIfAvailable<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R? { return try withUnsafeBufferPointer { (bufferPointer) -> R in return try body(bufferPointer) } } @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> { if let n = _buffer.requestNativeBuffer() { return ContiguousArray(_buffer: n) } return _copyCollectionToContiguousArray(self) } } #if SWIFT_ENABLE_REFLECTION extension ContiguousArray: CustomReflectable { /// A mirror that reflects the array. public var customMirror: Mirror { return Mirror( self, unlabeledChildren: self, displayStyle: .collection) } } #endif extension ContiguousArray: CustomStringConvertible, CustomDebugStringConvertible { /// A textual representation of the array and its elements. public var description: String { return _makeCollectionDescription() } /// A textual representation of the array and its elements, suitable for /// debugging. public var debugDescription: String { return _makeCollectionDescription(withTypeName: "ContiguousArray") } } extension ContiguousArray { @usableFromInline @_transparent internal func _cPointerArgs() -> (AnyObject?, UnsafeRawPointer?) { let p = _baseAddressIfContiguous if _fastPath(p != nil || isEmpty) { return (_owner, UnsafeRawPointer(p)) } let n = ContiguousArray(self._buffer)._buffer return (n.owner, UnsafeRawPointer(n.firstElementAddress)) } } extension ContiguousArray { /// Creates an array with the specified capacity, then calls the given /// closure with a buffer covering the array's uninitialized memory. /// /// Inside the closure, set the `initializedCount` parameter to the number of /// elements that are initialized by the closure. The memory in the range /// `buffer[0..<initializedCount]` must be initialized at the end of the /// closure's execution, and the memory in the range /// `buffer[initializedCount...]` must be uninitialized. This postcondition /// must hold even if the `initializer` closure throws an error. /// /// - Note: While the resulting array may have a capacity larger than the /// requested amount, the buffer passed to the closure will cover exactly /// the requested number of elements. /// /// - Parameters: /// - unsafeUninitializedCapacity: The number of elements to allocate /// space for in the new array. /// - initializer: A closure that initializes elements and sets the count /// of the new array. /// - Parameters: /// - buffer: A buffer covering uninitialized memory with room for the /// specified number of elements. /// - initializedCount: The count of initialized elements in the array, /// which begins as zero. Set `initializedCount` to the number of /// elements you initialize. @_alwaysEmitIntoClient @inlinable public init( unsafeUninitializedCapacity: Int, initializingWith initializer: ( _ buffer: inout UnsafeMutableBufferPointer<Element>, _ initializedCount: inout Int) throws -> Void ) rethrows { self = try ContiguousArray(Array( _unsafeUninitializedCapacity: unsafeUninitializedCapacity, initializingWith: initializer)) } /// Calls a closure with a pointer to the array's contiguous storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how you can iterate over the contents of the /// buffer pointer: /// /// let numbers = [1, 2, 3, 4, 5] /// let sum = numbers.withUnsafeBufferPointer { buffer -> Int in /// var result = 0 /// for i in stride(from: buffer.startIndex, to: buffer.endIndex, by: 2) { /// result += buffer[i] /// } /// return result /// } /// // 'sum' == 9 /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeBufferPointer(_:)`. Do not store or return the /// pointer for later use. /// /// - Parameter body: A closure with an `UnsafeBufferPointer` parameter that /// points to the contiguous storage for the array. If /// `body` has a return value, that value is also used as the return value /// for the `withUnsafeBufferPointer(_:)` method. The pointer argument is /// valid only for the duration of the method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { return try _buffer.withUnsafeBufferPointer(body) } /// Calls the given closure with a pointer to the array's mutable contiguous /// storage. /// /// Often, the optimizer can eliminate bounds checks within an array /// algorithm, but when that fails, invoking the same algorithm on the /// buffer pointer passed into your closure lets you trade safety for speed. /// /// The following example shows how modifying the contents of the /// `UnsafeMutableBufferPointer` argument to `body` alters the contents of /// the array: /// /// var numbers = [1, 2, 3, 4, 5] /// numbers.withUnsafeMutableBufferPointer { buffer in /// for i in stride(from: buffer.startIndex, to: buffer.endIndex - 1, by: 2) { /// buffer.swapAt(i, i + 1) /// } /// } /// print(numbers) /// // Prints "[2, 1, 4, 3, 5]" /// /// The pointer passed as an argument to `body` is valid only during the /// execution of `withUnsafeMutableBufferPointer(_:)`. Do not store or /// return the pointer for later use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableBufferPointer` /// parameter that points to the contiguous storage for the array. /// If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBufferPointer(_:)` /// method. The pointer argument is valid only for the duration of the /// method's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @_semantics("array.withUnsafeMutableBufferPointer") @inlinable // FIXME(inline-always) @inline(__always) // Performance: This method should get inlined into the // caller such that we can combine the partial apply with the apply in this // function saving on allocating a closure context. This becomes unnecessary // once we allocate noescape closures on the stack. public mutating func withUnsafeMutableBufferPointer<R>( _ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { _makeMutableAndUnique() let count = _buffer.mutableCount // Create an UnsafeBufferPointer that we can pass to body let pointer = _buffer.mutableFirstElementAddress var inoutBufferPointer = UnsafeMutableBufferPointer( start: pointer, count: count) defer { _precondition( inoutBufferPointer.baseAddress == pointer && inoutBufferPointer.count == count, "ContiguousArray withUnsafeMutableBufferPointer: replacing the buffer is not allowed") _endMutation() _fixLifetime(self) } // Invoke the body. return try body(&inoutBufferPointer) } @inlinable public __consuming func _copyContents( initializing buffer: UnsafeMutableBufferPointer<Element> ) -> (Iterator,UnsafeMutableBufferPointer<Element>.Index) { guard !self.isEmpty else { return (makeIterator(),buffer.startIndex) } // It is not OK for there to be no pointer/not enough space, as this is // a precondition and Array never lies about its count. guard var p = buffer.baseAddress else { _preconditionFailure("Attempt to copy contents into nil buffer pointer") } _precondition(self.count <= buffer.count, "Insufficient space allocated to copy array contents") if let s = _baseAddressIfContiguous { p.initialize(from: s, count: self.count) // Need a _fixLifetime bracketing the _baseAddressIfContiguous getter // and all uses of the pointer it returns: _fixLifetime(self._owner) } else { for x in self { p.initialize(to: x) p += 1 } } var it = IndexingIterator(_elements: self) it._position = endIndex return (it,buffer.index(buffer.startIndex, offsetBy: self.count)) } } extension ContiguousArray { /// Replaces a range of elements with the elements in the specified /// collection. /// /// This method has the effect of removing the specified range of elements /// from the array and inserting the new elements at the same location. The /// number of new elements need not match the number of elements being /// removed. /// /// In this example, three elements in the middle of an array of integers are /// replaced by the five elements of a `Repeated<Int>` instance. /// /// var nums = [10, 20, 30, 40, 50] /// nums.replaceSubrange(1...3, with: repeatElement(1, count: 5)) /// print(nums) /// // Prints "[10, 1, 1, 1, 1, 1, 50]" /// /// If you pass a zero-length range as the `subrange` parameter, this method /// inserts the elements of `newElements` at `subrange.startIndex`. Calling /// the `insert(contentsOf:at:)` method instead is preferred. /// /// Likewise, if you pass a zero-length collection as the `newElements` /// parameter, this method removes the elements in the given subrange /// without replacement. Calling the `removeSubrange(_:)` method instead is /// preferred. /// /// - Parameters: /// - subrange: The subrange of the array to replace. The start and end of /// a subrange must be valid indices of the array. /// - newElements: The new elements to add to the array. /// /// - Complexity: O(*n* + *m*), where *n* is length of the array and /// *m* is the length of `newElements`. If the call to this method simply /// appends the contents of `newElements` to the array, this method is /// equivalent to `append(contentsOf:)`. @inlinable @_semantics("array.mutate_unknown") public mutating func replaceSubrange<C>( _ subrange: Range<Int>, with newElements: __owned C ) where C: Collection, C.Element == Element { _precondition(subrange.lowerBound >= self._buffer.startIndex, "ContiguousArray replace: subrange start is negative") _precondition(subrange.upperBound <= _buffer.endIndex, "ContiguousArray replace: subrange extends past the end") let eraseCount = subrange.count let insertCount = newElements.count let growth = insertCount - eraseCount _reserveCapacityImpl(minimumCapacity: self.count + growth, growForAppend: true) _buffer.replaceSubrange(subrange, with: insertCount, elementsOf: newElements) _endMutation() } } extension ContiguousArray: Equatable where Element: Equatable { /// Returns a Boolean value indicating whether two arrays contain the same /// elements in the same order. /// /// You can use the equal-to operator (`==`) to compare any two arrays /// that store the same, `Equatable`-conforming element type. /// /// - Parameters: /// - lhs: An array to compare. /// - rhs: Another array to compare. @inlinable public static func ==(lhs: ContiguousArray<Element>, rhs: ContiguousArray<Element>) -> Bool { let lhsCount = lhs.count if lhsCount != rhs.count { return false } // Test referential equality. if lhsCount == 0 || lhs._buffer.identity == rhs._buffer.identity { return true } _internalInvariant(lhs.startIndex == 0 && rhs.startIndex == 0) _internalInvariant(lhs.endIndex == lhsCount && rhs.endIndex == lhsCount) // We know that lhs.count == rhs.count, compare element wise. for idx in 0..<lhsCount { if lhs[idx] != rhs[idx] { return false } } return true } } extension ContiguousArray: Hashable where Element: Hashable { /// 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. @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(count) // discriminator for element in self { hasher.combine(element) } } } extension ContiguousArray { /// Calls the given closure with a pointer to the underlying bytes of the /// array's mutable contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies bytes from the `byteValues` array into /// `numbers`, an array of `Int32`: /// /// var numbers: [Int32] = [0, 0] /// var byteValues: [UInt8] = [0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00] /// /// numbers.withUnsafeMutableBytes { destBytes in /// byteValues.withUnsafeBytes { srcBytes in /// destBytes.copyBytes(from: srcBytes) /// } /// } /// // numbers == [1, 2] /// /// - Note: This example shows the behavior on a little-endian platform. /// /// The pointer passed as an argument to `body` is valid only for the /// lifetime of the closure. Do not escape it from the closure for later /// use. /// /// - Warning: Do not rely on anything about the array that is the target of /// this method during execution of the `body` closure; it might not /// appear to have its correct value. Instead, use only the /// `UnsafeMutableRawBufferPointer` argument to `body`. /// /// - Parameter body: A closure with an `UnsafeMutableRawBufferPointer` /// parameter that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeMutableBytes(_:)` method. /// The argument is valid only for the duration of the closure's /// execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public mutating func withUnsafeMutableBytes<R>( _ body: (UnsafeMutableRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeMutableBufferPointer { return try body(UnsafeMutableRawBufferPointer($0)) } } /// Calls the given closure with a pointer to the underlying bytes of the /// array's contiguous storage. /// /// The array's `Element` type must be a *trivial type*, which can be copied /// with just a bit-for-bit copy without any indirection or /// reference-counting operations. Generally, native Swift types that do not /// contain strong or weak references are trivial, as are imported C structs /// and enums. /// /// The following example copies the bytes of the `numbers` array into a /// buffer of `UInt8`: /// /// var numbers: [Int32] = [1, 2, 3] /// var byteBuffer: [UInt8] = [] /// numbers.withUnsafeBytes { /// byteBuffer.append(contentsOf: $0) /// } /// // byteBuffer == [1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0] /// /// - Note: This example shows the behavior on a little-endian platform. /// /// - Parameter body: A closure with an `UnsafeRawBufferPointer` parameter /// that points to the contiguous storage for the array. /// If no such storage exists, it is created. If `body` has a return value, that value is also /// used as the return value for the `withUnsafeBytes(_:)` method. The /// argument is valid only for the duration of the closure's execution. /// - Returns: The return value, if any, of the `body` closure parameter. @inlinable public func withUnsafeBytes<R>( _ body: (UnsafeRawBufferPointer) throws -> R ) rethrows -> R { return try self.withUnsafeBufferPointer { try body(UnsafeRawBufferPointer($0)) } } } extension ContiguousArray: @unchecked Sendable where Element: Sendable { }
apache-2.0
d179d342d93569f8f063efc85a4f1f76
38.071329
99
0.660295
4.488792
false
false
false
false
benrosen78/2015-WWDC-Scholarship-app
Ben Rosen/About Me Home View Controller/Cells/BRProfileTableViewCell.swift
1
5167
// // BRProfileTableViewCell.swift // Ben Rosen // // Created by Ben Rosen on 4/26/15. // Copyright (c) 2015 Ben Rosen. All rights reserved. // import UIKit class BRProfileTableViewCell: BRHomeTableViewCell { var profileImageView = UIImageView() var fullNameLabel = UILabel() var bioLabel = UILabel() var user: BRUser = BRUser() { didSet { profileImageView.image = user.profileImage fullNameLabel.text = user.fullName.uppercaseString profileImageView.layer.borderColor = user.profileImage.dominantColor().CGColor bioLabel.text = user.userBio } } class func heightForUser(user: BRUser!, size: CGSize) -> CGFloat { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = .Center let font = UIFont(name: "Avenir-Book", size: 18.0) ?? UIFont.systemFontOfSize(20.0) var bioAttributedString = NSMutableAttributedString(string: user.userBio, attributes: [NSFontAttributeName : font]) let nameSize = bioAttributedString.boundingRectWithSize(CGSizeMake(size.width - 84.0, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, context: nil).size return nameSize.height+200.0; } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) profileImageView.layer.masksToBounds = true profileImageView.layer.cornerRadius = 60.0 profileImageView.layer.borderWidth = 1.0 profileImageView.setTranslatesAutoresizingMaskIntoConstraints(false) innerContentView.addSubview(profileImageView) let profileImageViewCenterX = NSLayoutConstraint(item: profileImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: innerContentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0) let profileImageViewTop = NSLayoutConstraint(item: profileImageView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: innerContentView, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 10.0) let profileImageViewWidth = NSLayoutConstraint(item: profileImageView, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: 120.0) let profileImageViewHeight = NSLayoutConstraint(item: profileImageView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1.0, constant: 120.0) innerContentView.addConstraints([profileImageViewCenterX, profileImageViewTop, profileImageViewWidth, profileImageViewHeight]) fullNameLabel.font = UIFont(name: "Avenir-Roman", size: 26.0) fullNameLabel.textAlignment = .Center fullNameLabel.textColor = UIColor(white: 0.9, alpha: 1.0) fullNameLabel.setTranslatesAutoresizingMaskIntoConstraints(false) innerContentView.addSubview(fullNameLabel) let fullNameLabelCenterX = NSLayoutConstraint(item: fullNameLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: innerContentView, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0.0) let fullNameLabelTop = NSLayoutConstraint(item: fullNameLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: profileImageView, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 10.0) let fullNameLabelWidth = NSLayoutConstraint(item: fullNameLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: innerContentView, attribute: NSLayoutAttribute.Width, multiplier: 1.0, constant: -10) innerContentView.addConstraints([fullNameLabelCenterX, fullNameLabelTop, fullNameLabelWidth]) bioLabel.font = UIFont(name: "Avenir-Book", size: 18.0) bioLabel.textColor = UIColor(white: 0.7, alpha: 1.0) bioLabel.numberOfLines = 0 bioLabel.textAlignment = .Center bioLabel.setTranslatesAutoresizingMaskIntoConstraints(false) innerContentView.addSubview(bioLabel) let bioLabelTop = NSLayoutConstraint(item: bioLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: fullNameLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1.0, constant: 0.0) let bioLabelLeft = NSLayoutConstraint(item: bioLabel, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: innerContentView, attribute: NSLayoutAttribute.Left, multiplier: 1.0, constant: 10.0) let bioLabelRight = NSLayoutConstraint(item: bioLabel, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: innerContentView, attribute: NSLayoutAttribute.Right, multiplier: 1.0, constant: -10.0) innerContentView.addConstraints([bioLabelTop, bioLabelLeft, bioLabelRight]) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
lgpl-3.0
1bc04bb320bef9215f0e567db8f1acb4
63.5875
249
0.746662
5.095661
false
false
false
false
michaelborgmann/handshake
Handshake/MainViewController.swift
1
2358
// // LoginViewController.swift // Handshake // // Created by Michael Borgmann on 27/06/15. // Copyright (c) 2015 Michael Borgmann. All rights reserved. // import UIKit class MainViewController: UIViewController { override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { let mainView = MainView() self.view = mainView } override func viewDidAppear(animated: Bool) { let isLoggedIn = NSUserDefaults.standardUserDefaults().boolForKey("isLoggedIn") if (!isLoggedIn) { showLoginView() } else { showAppView() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func showLoginView() { let userAccountViewController = UserAccountViewController() let navigationController = UINavigationController(rootViewController: userAccountViewController) navigationController.modalTransitionStyle = .FlipHorizontal navigationController.modalPresentationStyle = .FormSheet presentViewController(navigationController, animated: true, completion: nil) } func showAppView() { let handshakeViewController = HandshakeViewController(style: UITableViewStyle.Plain) let navigationController = UINavigationController(rootViewController: handshakeViewController) presentViewController(navigationController, animated: true, completion: nil) } func logoutButton() { let button = UIButton(); button.setTitle("Logout", forState: .Normal) button.setTitleColor(UIColor.blueColor(), forState: .Normal) button.frame = CGRectMake(15, 50, 200, 100) button.addTarget(self, action: "buttonPressed:", forControlEvents: .TouchUpInside) self.view.addSubview(button) } func buttonPressed(sender: UIButton) { NSUserDefaults.standardUserDefaults().setBool(false, forKey: "isLoggedIn") NSUserDefaults.standardUserDefaults().synchronize() showLoginView() } }
gpl-2.0
37cdaf46d2727d36f4f485a57b1f0aa4
33.173913
104
0.68151
5.574468
false
false
false
false
kuyazee/WarpSDK-iOS
WarpSDK/WarpQuery.swift
1
13018
// // WarpQuery.swift // Practice // // Created by Zonily Jame Pesquera on 28/10/2016. // // import Foundation import PromiseKit public extension Warp { public class Query <Class> where Class: Warp.Object { public typealias SingleResultQueryBlock = (_ warpObject: Class?, _ error: WarpError?) -> Void public typealias MultiResultQueryBlock = (_ warpObjects: [Class]?, _ error: WarpError?) -> Void fileprivate let className: String fileprivate var queryParameters: Warp.QueryBuilder.Parameters = Warp.QueryBuilder.Parameters() fileprivate var queryBuilder: Warp.QueryBuilder { return Warp.QueryBuilder(parameters: self.queryParameters) } /// Description /// /// - Parameter className: creates a Warp.Query<Warp.Object> instance public init(className: String) { self.className = className } /// private initializer for userQuery init() { self.className = "user" } } } // MARK: - Since static stored properties can't be placed inside Generic classes yet I placed this here. public extension Warp { public static func UserQuery() -> Warp.Query<Warp.User> { return Warp.Query<Warp.User>() } public static func ObjectQuery(className: String) -> Warp.Query<Warp.Object> { return Warp.Query(className: className) } } // MARK: - Warp.Object where Class: Warp.Object public extension Warp.Query where Class: Warp.Object { public func get(_ objectId: Int, completion: @escaping SingleResultQueryBlock) -> WarpDataRequest { guard let warp = Warp.shared else { fatalError("[Warp] WarpServer is not yet initialized") } let endPoint: String = warp.generateEndpoint(.classes(className: self.className, id: objectId)) let request = Warp.API.get(endPoint, parameters: self.queryBuilder.dictionary, headers: warp.HEADER()) return request.warpResponse { (warpResult) in switch warpResult { case .success(let JSON): let warpResponse = WarpResponse(json: JSON, result: [String: Any].self) switch warpResponse.statusType { case .success: completion(Class(className: self.className, json: warpResponse.result!), nil) default: completion(nil, WarpError(message: warpResponse.message, status: warpResponse.status)) } case .failure(let error): completion(nil, error) } } } public func find(_ completion: @escaping MultiResultQueryBlock) -> WarpDataRequest { guard let warp = Warp.shared else { fatalError("[Warp] WarpServer is not yet initialized") } let endPoint: String = warp.generateEndpoint(.classes(className: self.className, id: nil)) let request = Warp.API.get(endPoint, parameters: self.queryBuilder.dictionary, headers: warp.HEADER()) return request.warpResponse { (warpResult) in switch warpResult { case .success(let JSON): let warpResponse = WarpResponse(json: JSON, result: [[String: Any]].self) switch warpResponse.statusType { case .success: let warpObjects: [Class] = (warpResponse.result ?? []).map({ Class(className: self.className, json: $0) }) completion(warpObjects, nil) default: completion(nil, WarpError(message: warpResponse.message, status: warpResponse.status)) } case .failure(let error): completion(nil, error) } } } public func first(_ completion: @escaping SingleResultQueryBlock) -> WarpDataRequest { return self.limit(1).find { (warpObjects, error) in completion(warpObjects?.first, error) } } public func find() -> Promise<[Class]?> { return Promise { fulfill, reject in _ = self.find({ (result, error) in if let error = error { reject(error) } else { fulfill(result) } }) } } public func get(_ objectId: Int) -> Promise<Class?> { return Promise { fulfill, reject in _ = self.get(objectId, completion: { (result, error) in if let error = error { reject(error) } else { fulfill(result) } }) } } public func first() -> Promise<Class?> { return Promise { fulfill, reject in _ = self.first({ (result, error) in if let error = error { reject(error) } else { fulfill(result) } }) } } } // MARK: - Warp.Query where Class: Warp.User public extension Warp.Query where Class: Warp.User { public func get(_ objectId: Int, completion: @escaping SingleResultQueryBlock) -> WarpDataRequest { guard let warp = Warp.shared else { fatalError("[Warp] WarpServer is not yet initialized") } let endPoint: String = warp.generateEndpoint(.users(id: objectId)) let request = Warp.API.get(endPoint, parameters: self.queryBuilder.dictionary, headers: warp.HEADER()) return request.warpResponse { (warpResult) in switch warpResult { case .success(let JSON): let warpResponse = WarpResponse(json: JSON, result: [String: Any].self) switch warpResponse.statusType { case .success: completion(Class(className: self.className, json: warpResponse.result!), nil) default: completion(nil, WarpError(message: warpResponse.message, status: warpResponse.status)) } case .failure(let error): completion(nil, error) } } } public func find(_ completion: @escaping MultiResultQueryBlock) -> WarpDataRequest { guard let warp = Warp.shared else { fatalError("[Warp] WarpServer is not yet initialized") } let endPoint: String = warp.generateEndpoint(.users(id: nil)) let request = Warp.API.get(endPoint, parameters: self.queryBuilder.dictionary, headers: warp.HEADER()) return request.warpResponse { (warpResult) in switch warpResult { case .success(let JSON): let warpResponse = WarpResponse(json: JSON, result: [[String: Any]].self) switch warpResponse.statusType { case .success: let warpObjects: [Class] = (warpResponse.result ?? []).map({ Class(className: self.className, json: $0) }) completion(warpObjects, nil) default: completion(nil, WarpError(message: warpResponse.message, status: warpResponse.status)) } case .failure(let error): completion(nil, error) } } } public func first(_ completion: @escaping SingleResultQueryBlock) -> WarpDataRequest { return self.limit(1).find { (warpObjects, error) in completion(warpObjects?.first, error) } } public func find() -> Promise<[Class]?> { return Promise { fulfill, reject in _ = self.find({ (result, error) in if let error = error { reject(error) } else { fulfill(result) } }) } } public func get(_ objectId: Int) -> Promise<Class?> { return Promise { fulfill, reject in _ = self.get(objectId, completion: { (result, error) in if let error = error { reject(error) } else { fulfill(result) } }) } } public func first() -> Promise<Class?> { return Promise { fulfill, reject in _ = self.first({ (result, error) in if let error = error { reject(error) } else { fulfill(result) } }) } } } // MARK: - Query Functions public extension Warp.Query { public func limit(_ value: Int) -> Warp.Query<Class> { self.queryParameters.limit = value return self } public func skip(_ value: Int) -> Warp.Query<Class> { self.queryParameters.skip = value return self } public func include(_ values: String...) -> Warp.Query<Class> { self.queryParameters.include = values return self } public func sort(_ values: WarpSort...) -> Warp.Query<Class> { self.queryParameters.sort = values return self } public func equalTo(_ value: Any, forKey key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(equalTo: value, key: key)) return self } public func notEqualTo(_ value: Any, forKey key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(notEqualTo: value, key: key)) return self } public func greaterThan(_ value: Any, forKey key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(greaterThan: value, key: key)) return self } public func greaterThanOrEqualTo(_ value: Any, forKey key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(greaterThanOrEqualTo: value, key: key)) return self } public func lessThan(_ value: Any, forKey key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(lessThan: value, key: key)) return self } public func lessThanOrEqualTo(_ value: Any, forKey key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(lessThanOrEqualTo: value, key: key)) return self } public func existsKey(_ key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(existsKey: key)) return self } public func notExistsKey(_ key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(notExistsKey: key)) return self } public func containedIn(_ values: Any..., forKey key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(containedIn: values, key: key)) return self } public func notContainedIn(_ values: [Any], forKey key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(notContainedIn: values, key: key)) return self } public func containedInOrDoesNotExist(_ values: [Any], key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(containedInOrDoesNotExist: values, key: key)) return self } public func startsWith(_ value: String, forKey key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(startsWith: value, key: key)) return self } public func endsWith(_ value: String, forKey key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(endsWith: value, key: key)) return self } public func contains(_ value: String, forKey key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(contains: value, key: key)) return self } public func contains(_ value: String, keys: String...) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(contains: value, keys: keys)) return self } public func containsEitherStrings(_ values: [String], forKey key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint(containsEither: values, key: key)) return self } public func containsAllStrings(_ values: [String], forKey key: String) -> Warp.Query<Class> { self.queryParameters.where.append(Warp.QueryBuilder.Constraint.init(containsAll: values, key: key)) return self } }
mit
55a4cde17c8ed6b7be096ed0501aebc5
35.982955
126
0.580043
4.624512
false
false
false
false
codercd/DesignPatternDemo
策略模式/StrategyPattern.playground/Contents.swift
1
2442
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" //基本实现 protocol Strategy { func algorithmInterface() } class ConcreateStrategyA: Strategy { func algorithmInterface() { print("算法A实现") } } class ConcreateStragegyB: Strategy { func algorithmInterface() { print("算法B实现") } } class ConcreateStrategyC: Strategy { func algorithmInterface() { print("算法C实现") } } class Context { var strategy:Strategy init (strategy: Strategy) { self.strategy = strategy } func contextInterface() { strategy.algorithmInterface() } } let context = Context(strategy: ConcreateStrategyA()) context.contextInterface() // print: "算法A实现" //收银场景 protocol CashProtocol { func acceptCash(money: Double) -> Double } //正常收费 class CashNormal: CashProtocol { func acceptCash(money: Double) -> Double { return money } } //打折 class CashRebate: CashProtocol { private var moneyRebate = 1.0 init(moneyRebate: Double) { self.moneyRebate = moneyRebate } func acceptCash(money: Double) -> Double { return money * moneyRebate } } //返利 class CashReturn: CashProtocol { private var moneyCondition = 0.0 private var moneyReturn = 0.0 init(moneyCondition: Double, moneyReturn: Double) { self.moneyCondition = moneyCondition self.moneyReturn = moneyReturn } func acceptCash(money: Double) -> Double { var result = money if money >= moneyCondition { result = money - floor(money / moneyCondition) * moneyReturn } return result } } class CashContext { var cs:CashProtocol? init(type: String) { switch type { case "正常收费": cs = CashNormal() case "打八折": cs = CashRebate(moneyRebate: 0.8) case "满300返100": cs = CashReturn(moneyCondition: 300, moneyReturn: 100) default: return } } func getResult(money: Double) -> Double { return cs!.acceptCash(money) } } var cashContext = CashContext(type: "打八折") let totalPrice = cashContext.getResult(10000) print(totalPrice) cashContext = CashContext(type: "满300返100") let totalPrice2 = cashContext.getResult(10000)
mit
939ea9395d362b73ada1f078bbcd8069
18.262295
72
0.622553
3.778135
false
false
false
false
ryanipete/timelinebar
ExampleProject/ExampleProject/MasterViewController.swift
1
1612
// // MasterViewController.swift // ExampleProject // // Created by Ryan Peterson on 9/13/14. // Copyright (c) 2014 Ryan Peterson. All rights reserved. // import UIKit class MasterViewController: UIViewController { // MARK: # Properties @IBOutlet weak var timelineBar: TimelineBar! var displayLink: CADisplayLink? let duration = 20.0 var startDate: NSDate! // MARK: # Private methods func updateTimeline() { let elapsed = NSDate().timeIntervalSinceDate(self.startDate) let progress = CGFloat(elapsed/duration) self.timelineBar.progress = progress if progress >= 1.0 { displayLink!.invalidate() displayLink = nil } } func reset() { self.timelineBar.reset() } @IBAction func resetButtonTapped(sender: AnyObject) { UIView.animateWithDuration(0.5, animations: { self.reset() }) } // MARK: # UIViewController overrides override func viewDidLoad() { super.viewDidLoad() self.reset() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) startDate = NSDate() self.timelineBar.startTimeSpan("first", startProgress: CGFloat(0.1), runningColor: UIColor.yellowColor()) self.timelineBar.endTimeSpan("first", endProgress: CGFloat(0.2), completedColor: UIColor.greenColor()) displayLink = CADisplayLink(target: self, selector: "updateTimeline") displayLink!.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) } }
apache-2.0
d48d159692f7e2ce77bc55dad65dd5cd
26.810345
113
0.64268
4.741176
false
false
false
false
lyle-luan/firefox-ios
FxAClient/Frontend/SignIn/FxASignInViewController.swift
2
3447
/* 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 Snappy import UIKit import WebKit let FxASignUpEndpoint = "https://latest.dev.lcip.org/signup?service=sync&context=fx_desktop_v1" let FxASignInEndpoint = "https://latest.dev.lcip.org/signin?service=sync&context=fx_desktop_v1" protocol FxASignInViewControllerDelegate { func signInViewControllerDidCancel(vc: FxASignInViewController) func signInViewControllerDidSignIn(vc: FxASignInViewController, data: JSON) } /** * A controller that connects an interstitial view with a background web view. */ class FxASignInViewController: UINavigationController, FxASignInWebViewControllerDelegate, FxAGetStartedViewControllerDelegate { var signInDelegate: FxASignInViewControllerDelegate? private var webViewController: FxASignInWebViewController! private var getStartedViewController: FxAGetStartedViewController! override func loadView() { super.loadView() webViewController = FxASignInWebViewController() webViewController.delegate = self getStartedViewController = FxAGetStartedViewController() getStartedViewController.delegate = self webViewController.startLoad(getUrl()) } func getUrl() -> NSURL { return NSURL(string: FxASignInEndpoint)! } override func viewDidLoad() { super.viewDidLoad() // Prevent child views from extending under navigation bar. navigationBar.translucent = false // This background agrees with the content server background. // Keeping the background constant prevents a pop of mismatched color. view.backgroundColor = UIColor(red: 242 / 255.0, green: 242 / 255.0, blue: 242 / 255.0, alpha: 1.0) self.pushViewController(webViewController, animated: false) self.pushViewController(getStartedViewController, animated: false) } func getStartedViewControllerDidStart(vc: FxAGetStartedViewController) { popViewControllerAnimated(true) } func getStartedViewControllerDidCancel(vc: FxAGetStartedViewController) { signInDelegate?.signInViewControllerDidCancel(self) } func signInWebViewControllerDidLoad(vc: FxASignInWebViewController) { getStartedViewController.notifyReadyToStart() } func signInWebViewControllerDidCancel(vc: FxASignInWebViewController) { signInDelegate?.signInViewControllerDidCancel(self) } func signInWebViewControllerDidSignIn(vc: FxASignInWebViewController, data: JSON) { signInDelegate?.signInViewControllerDidSignIn(self, data: data) } func signInWebViewControllerDidFailProvisionalNavigation(vc: FxASignInWebViewController, withError error: NSError!) { // Assume that all provisional navigation failures mean we can't reach the Firefox Accounts server. let errorString = NSLocalizedString("Could not connect to Firefox Account server. Try again later.", comment: "Error shown when we can't connect to Firefox Accounts.") getStartedViewController.showError(errorString) } func signInWebViewControllerDidFailNavigation(vc: FxASignInWebViewController, withError error: NSError!) { // Ignore inner navigation failures for now. } }
mpl-2.0
89e636deb2dcc67fc7be69ef9fd22157
38.62069
128
0.744415
4.896307
false
false
false
false
sumnerevans/wireless-debugging
mobile/ios/WirelessDebug/WirelessDebugger/SwiftyJSON.swift
2
39856
// SwiftyJSON.swift // // Copyright (c) 2014 - 2017 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - Error ///Error domain @available(*, deprecated, message: "Use the `SwiftyJSONError.errorDomain` instead") public let ErrorDomain: String = "SwiftyJSONErrorDomain" ///Error code @available(*, deprecated, message: "Use the `SwiftyJSONError.unsupportedType` instead") public let ErrorUnsupportedType: Int = 999 @available(*, deprecated, message: "Use the `SwiftyJSONError.indexOutOfBounds` instead") public let ErrorIndexOutOfBounds: Int = 900 @available(*, deprecated, message: "Use the `SwiftyJSONError.wrongType` instead") public let ErrorWrongType: Int = 901 @available(*, deprecated, message: "Use the `SwiftyJSONError.notExist` instead") public let ErrorNotExist: Int = 500 @available(*, deprecated, message: "Use the `SwiftyJSONError.invalidJSON` instead") public let ErrorInvalidJSON: Int = 490 public enum SwiftyJSONError: Int, Swift.Error { case unsupportedType = 999 case indexOutOfBounds = 900 case elementTooDeep = 902 case wrongType = 901 case notExist = 500 case invalidJSON = 490 } extension SwiftyJSONError: CustomNSError { public static var errorDomain: String { return "com.swiftyjson.SwiftyJSON" } public var errorCode: Int { return self.rawValue } public var errorUserInfo: [String : Any] { switch self { case .unsupportedType: return [NSLocalizedDescriptionKey: "It is an unsupported type."] case .indexOutOfBounds: return [NSLocalizedDescriptionKey: "Array Index is out of bounds."] case .wrongType: return [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."] case .notExist: return [NSLocalizedDescriptionKey: "Dictionary key does not exist."] case .invalidJSON: return [NSLocalizedDescriptionKey: "JSON is invalid."] case .elementTooDeep: return [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop."] } } } // MARK: - JSON Type /** JSON's type definitions. See http://www.json.org */ public enum Type: Int { case number case string case bool case array case dictionary case null case unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `[]` by default. - returns: The created JSON */ public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws { let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) self.init(jsonObject: object) } /** Creates a JSON object - parameter object: the object - note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)` - returns: the created JSON object */ public init(_ object: Any) { switch object { case let object as Data: do { try self.init(data: object) } catch { self.init(jsonObject: NSNull()) } default: self.init(jsonObject: object) } } /** Parses the JSON string into a JSON object - parameter json: the JSON string - returns: the created JSON object */ public init(parseJSON jsonString: String) { if let data = jsonString.data(using: .utf8) { self.init(data) } else { self.init(NSNull()) } } /** Creates a JSON from JSON string - parameter string: Normal json string like '{"a":"b"}' - returns: The created JSON */ @available(*, deprecated, message: "Use instead `init(parseJSON: )`") public static func parse(_ json: String) -> JSON { return json.data(using: String.Encoding.utf8) .flatMap { try? JSON(data: $0) } ?? JSON(NSNull()) } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ fileprivate init(jsonObject: Any) { self.object = jsonObject } /** Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONs getting merged the same way. - parameter other: The JSON which gets merged into this JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ public mutating func merge(with other: JSON) throws { try self.merge(with: other, typecheck: true) } /** Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added, present values getting overwritten, array values getting appended and nested JSONS getting merged the same way. - parameter other: The JSON which gets merged into this JSON - returns: New merged JSON - throws `ErrorWrongType` if the other JSONs differs in type on the top level. */ public func merged(with other: JSON) throws -> JSON { var merged = self try merged.merge(with: other, typecheck: true) return merged } // Private woker function which does the actual merging // Typecheck is set to true for the first recursion level to prevent total override of the source JSON fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws { if self.type == other.type { switch self.type { case .dictionary: for (key, _) in other { try self[key].merge(with: other[key], typecheck: false) } case .array: self = JSON(self.arrayValue + other.arrayValue) default: self = other } } else { if typecheck { throw SwiftyJSONError.wrongType } else { self = other } } } /// Private object fileprivate var rawArray: [Any] = [] fileprivate var rawDictionary: [String : Any] = [:] fileprivate var rawString: String = "" fileprivate var rawNumber: NSNumber = 0 fileprivate var rawNull: NSNull = NSNull() fileprivate var rawBool: Bool = false /// JSON type, fileprivate setter public fileprivate(set) var type: Type = .null /// Error in JSON, fileprivate setter public fileprivate(set) var error: SwiftyJSONError? /// Object in JSON public var object: Any { get { switch self.type { case .array: return self.rawArray case .dictionary: return self.rawDictionary case .string: return self.rawString case .number: return self.rawNumber case .bool: return self.rawBool default: return self.rawNull } } set { error = nil switch unwrap(newValue) { case let number as NSNumber: if number.isBool { type = .bool self.rawBool = number.boolValue } else { type = .number self.rawNumber = number } case let string as String: type = .string self.rawString = string case _ as NSNull: type = .null case nil: type = .null case let array as [Any]: type = .array self.rawArray = array case let dictionary as [String : Any]: type = .dictionary self.rawDictionary = dictionary default: type = .unknown error = SwiftyJSONError.unsupportedType } } } /// The static null JSON @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { return null } public static var null: JSON { return JSON(NSNull()) } } // unwrap nested JSON private func unwrap(_ object: Any) -> Any { switch object { case let json as JSON: return unwrap(json.object) case let array as [Any]: return array.map(unwrap) case let dictionary as [String : Any]: var unwrappedDic = dictionary for (k, v) in dictionary { unwrappedDic[k] = unwrap(v) } return unwrappedDic default: return object } } public enum Index<T: Any>: Comparable { case array(Int) case dictionary(DictionaryIndex<String, T>) case null static public func == (lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left == right case (.dictionary(let left), .dictionary(let right)): return left == right case (.null, .null): return true default: return false } } static public func < (lhs: Index, rhs: Index) -> Bool { switch (lhs, rhs) { case (.array(let left), .array(let right)): return left < right case (.dictionary(let left), .dictionary(let right)): return left < right default: return false } } } public typealias JSONIndex = Index<JSON> public typealias JSONRawIndex = Index<Any> extension JSON: Swift.Collection { public typealias Index = JSONRawIndex public var startIndex: Index { switch type { case .array: return .array(rawArray.startIndex) case .dictionary: return .dictionary(rawDictionary.startIndex) default: return .null } } public var endIndex: Index { switch type { case .array: return .array(rawArray.endIndex) case .dictionary: return .dictionary(rawDictionary.endIndex) default: return .null } } public func index(after i: Index) -> Index { switch i { case .array(let idx): return .array(rawArray.index(after: idx)) case .dictionary(let idx): return .dictionary(rawDictionary.index(after: idx)) default: return .null } } public subscript (position: Index) -> (String, JSON) { switch position { case .array(let idx): return (String(idx), JSON(self.rawArray[idx])) case .dictionary(let idx): let (key, value) = self.rawDictionary[idx] return (key, JSON(value)) default: return ("", JSON.null) } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public enum JSONKey { case index(Int) case key(String) } public protocol JSONSubscriptType { var jsonKey: JSONKey { get } } extension Int: JSONSubscriptType { public var jsonKey: JSONKey { return JSONKey.index(self) } } extension String: JSONSubscriptType { public var jsonKey: JSONKey { return JSONKey.key(self) } } extension JSON { /// If `type` is `.array`, return json whose object is `array[index]`, otherwise return null json with error. fileprivate subscript(index index: Int) -> JSON { get { if self.type != .array { var r = JSON.null r.error = self.error ?? SwiftyJSONError.wrongType return r } else if self.rawArray.indices.contains(index) { return JSON(self.rawArray[index]) } else { var r = JSON.null r.error = SwiftyJSONError.indexOutOfBounds return r } } set { if self.type == .array && self.rawArray.indices.contains(index) && newValue.error == nil { self.rawArray[index] = newValue.object } } } /// If `type` is `.dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. fileprivate subscript(key key: String) -> JSON { get { var r = JSON.null if self.type == .dictionary { if let o = self.rawDictionary[key] { r = JSON(o) } else { r.error = SwiftyJSONError.notExist } } else { r.error = self.error ?? SwiftyJSONError.wrongType } return r } set { if self.type == .dictionary && newValue.error == nil { self.rawDictionary[key] = newValue.object } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. fileprivate subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { case .index(let index): return self[index: index] case .key(let key): return self[key: key] } } set { switch sub.jsonKey { case .index(let index): self[index: index] = newValue case .key(let key): self[key: key] = newValue } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } } set { switch path.count { case 0: return case 1: self[sub:path[0]].object = newValue.object default: var aPath = path; aPath.remove(at: 0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structures by using array of Int and/or String as path. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.ExpressibleByStringLiteral { public init(stringLiteral value: StringLiteralType) { self.init(value as Any) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value as Any) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByIntegerLiteral { public init(integerLiteral value: IntegerLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByBooleanLiteral { public init(booleanLiteral value: BooleanLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByFloatLiteral { public init(floatLiteral value: FloatLiteralType) { self.init(value as Any) } } extension JSON: Swift.ExpressibleByDictionaryLiteral { public init(dictionaryLiteral elements: (String, Any)...) { var dictionary = [String: Any](minimumCapacity: elements.count) for (k, v) in elements { dictionary[k] = v } self.init(dictionary as Any) } } extension JSON: Swift.ExpressibleByArrayLiteral { public init(arrayLiteral elements: Any...) { self.init(elements as Any) } } extension JSON: Swift.ExpressibleByNilLiteral { @available(*, deprecated, message: "use JSON.null instead. Will be removed in future versions") public init(nilLiteral: ()) { self.init(NSNull() as Any) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: Any) { if JSON(rawValue).type == .unknown { return nil } else { self.init(rawValue) } } public var rawValue: Any { return self.object } public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard JSONSerialization.isValidJSONObject(self.object) else { throw SwiftyJSONError.invalidJSON } return try JSONSerialization.data(withJSONObject: self.object, options: opt) } public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { do { return try _rawString(encoding, options: [.jsonSerialization: opt]) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } public func rawString(_ options: [writingOptionsKeys: Any]) -> String? { let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8 let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10 do { return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth) } catch { print("Could not serialize object to JSON because:", error.localizedDescription) return nil } } fileprivate func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? { if maxObjectDepth < 0 { throw SwiftyJSONError.invalidJSON } switch self.type { case .dictionary: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try self.rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let dict = self.object as? [String: Any?] else { return nil } let body = try dict.keys.map { key throws -> String in guard let value = dict[key] else { return "\"\(key)\": null" } guard let unwrappedValue = value else { return "\"\(key)\": null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw SwiftyJSONError.elementTooDeep } if nestedValue.type == .string { return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return "\"\(key)\": \(nestedString)" } } return "{\(body.joined(separator: ","))}" } catch _ { return nil } case .array: do { if !(options[.castNilToNSNull] as? Bool ?? false) { let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted let data = try self.rawData(options: jsonOption) return String(data: data, encoding: encoding) } guard let array = self.object as? [Any?] else { return nil } let body = try array.map { value throws -> String in guard let unwrappedValue = value else { return "null" } let nestedValue = JSON(unwrappedValue) guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else { throw SwiftyJSONError.invalidJSON } if nestedValue.type == .string { return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\"" } else { return nestedString } } return "[\(body.joined(separator: ","))]" } catch _ { return nil } case .string: return self.rawString case .number: return self.rawNumber.stringValue case .bool: return self.rawBool.description case .null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible { public var description: String { if let string = self.rawString(options:.prettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { if self.type == .array { return self.rawArray.map { JSON($0) } } else { return nil } } //Non-optional [JSON] public var arrayValue: [JSON] { return self.array ?? [] } //Optional [Any] public var arrayObject: [Any]? { get { switch self.type { case .array: return self.rawArray default: return nil } } set { if let array = newValue { self.object = array as Any } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .dictionary { var d = [String: JSON](minimumCapacity: rawDictionary.count) for (key, value) in rawDictionary { d[key] = JSON(value) } return d } else { return nil } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { return self.dictionary ?? [:] } //Optional [String : Any] public var dictionaryObject: [String : Any]? { get { switch self.type { case .dictionary: return self.rawDictionary default: return nil } } set { if let v = newValue { self.object = v as Any } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON { // : Swift.Bool //Optional bool public var bool: Bool? { get { switch self.type { case .bool: return self.rawBool default: return nil } } set { if let newValue = newValue { self.object = newValue as Bool } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .bool: return self.rawBool case .number: return self.rawNumber.boolValue case .string: return ["true", "y", "t"].contains { (truthyString) in return self.rawString.caseInsensitiveCompare(truthyString) == .orderedSame } default: return false } } set { self.object = newValue } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .string: return self.object as? String default: return nil } } set { if let newValue = newValue { self.object = NSString(string:newValue) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .string: return self.object as? String ?? "" case .number: return self.rawNumber.stringValue case .bool: return (self.object as? Bool).map { String($0) } ?? "" default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .number: return self.rawNumber case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return nil } } set { self.object = newValue ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .string: let decimal = NSDecimalNumber(string: self.object as? String) if decimal == NSDecimalNumber.notANumber { // indicates parse error return NSDecimalNumber.zero } return decimal case .number: return self.object as? NSNumber ?? NSNumber(value: 0) case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return NSNumber(value: 0.0) } } set { self.object = newValue } } } // MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .null: return self.rawNull default: return nil } } set { self.object = NSNull() } } public func exists() -> Bool { if let errorValue = error, (400...1000).contains(errorValue.errorCode) { return false } return true } } // MARK: - URL extension JSON { //Optional URL public var url: URL? { get { switch self.type { case .string: // Check for existing percent escapes first to prevent double-escaping of % character if self.rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil { return Foundation.URL(string: self.rawString) } else if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { // We have to use `Foundation.URL` otherwise it conflicts with the variable name. return Foundation.URL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(value: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(value: newValue) } } public var int: Int? { get { return self.number?.intValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.intValue } set { self.object = NSNumber(value: newValue) } } public var uInt: UInt? { get { return self.number?.uintValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.uintValue } set { self.object = NSNumber(value: newValue) } } public var int8: Int8? { get { return self.number?.int8Value } set { if let newValue = newValue { self.object = NSNumber(value: Int(newValue)) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.int8Value } set { self.object = NSNumber(value: Int(newValue)) } } public var uInt8: UInt8? { get { return self.number?.uint8Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.uint8Value } set { self.object = NSNumber(value: newValue) } } public var int16: Int16? { get { return self.number?.int16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.int16Value } set { self.object = NSNumber(value: newValue) } } public var uInt16: UInt16? { get { return self.number?.uint16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.uint16Value } set { self.object = NSNumber(value: newValue) } } public var int32: Int32? { get { return self.number?.int32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.int32Value } set { self.object = NSNumber(value: newValue) } } public var uInt32: UInt32? { get { return self.number?.uint32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.uint32Value } set { self.object = NSNumber(value: newValue) } } public var int64: Int64? { get { return self.number?.int64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.int64Value } set { self.object = NSNumber(value: newValue) } } public var uInt64: UInt64? { get { return self.number?.uint64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.uint64Value } set { self.object = NSNumber(value: newValue) } } } // MARK: - Comparable extension JSON : Swift.Comparable {} public func == (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber == rhs.rawNumber case (.string, .string): return lhs.rawString == rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func <= (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber <= rhs.rawNumber case (.string, .string): return lhs.rawString <= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func >= (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber >= rhs.rawNumber case (.string, .string): return lhs.rawString >= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): return lhs.rawArray as NSArray == rhs.rawArray as NSArray case (.dictionary, .dictionary): return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary case (.null, .null): return true default: return false } } public func > (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber > rhs.rawNumber case (.string, .string): return lhs.rawString > rhs.rawString default: return false } } public func < (lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber < rhs.rawNumber case (.string, .string): return lhs.rawString < rhs.rawString default: return false } } private let trueNumber = NSNumber(value: true) private let falseNumber = NSNumber(value: false) private let trueObjCType = String(cString: trueNumber.objCType) private let falseObjCType = String(cString: falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { var isBool: Bool { let objCType = String(cString: self.objCType) if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .orderedSame && objCType == falseObjCType) { return true } else { return false } } } func == (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedSame } } func != (lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } func < (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == .orderedAscending } } func > (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedDescending } } func <= (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedDescending } } func >= (lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != .orderedAscending } } public enum writingOptionsKeys { case jsonSerialization case castNilToNSNull case maxObjextDepth case encoding }
apache-2.0
806c1d63f0a74d8f6bc0e8ca2c7f62e0
26.697012
265
0.55003
4.653357
false
false
false
false
kitasuke/SwiftProtobufSample
Client/Carthage/Checkouts/swift-protobuf/Sources/protoc-gen-swift/MessageFieldGenerator.swift
1
23268
// Sources/protoc-gen-swift/MessageFieldGenerator.swift - Facts about a single message field // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// This code mostly handles the complex mapping between proto types and /// the types provided by the Swift Protobuf Runtime. /// // ----------------------------------------------------------------------------- import Foundation import PluginLibrary import SwiftProtobuf /// This must be exactly the same as the corresponding code in the /// SwiftProtobuf library. Changing it will break compatibility of /// the generated code with old library version. /// private func toJsonFieldName(_ s: String) -> String { var result = "" var capitalizeNext = false for c in s.characters { if c == "_" { capitalizeNext = true } else if capitalizeNext { result.append(String(c).uppercased()) capitalizeNext = false } else { result.append(String(c)) } } return result; } extension Google_Protobuf_FieldDescriptorProto { var isRepeated: Bool {return label == .repeated} var isMessage: Bool {return type == .message} var isEnum: Bool {return type == .enum} var isGroup: Bool {return type == .group} var isPackable: Bool { switch type { case .string,.bytes,.group,.message: return false default: return label == .repeated } } var bareTypeName: String { if typeName.hasPrefix(".") { var t = "" for c in typeName.characters { if c == "." { t = "" } else { t.append(c) } } return t } else { return typeName } } func getIsMap(context: Context) -> Bool { if type != .message {return false} let m = context.getMessageForPath(path: typeName)! return m.options.mapEntry } func getProtoTypeName(context: Context) -> String { switch type { case .double: return "Double" case .float: return "Float" case .int64: return "Int64" case .uint64: return "UInt64" case .int32: return "Int32" case .fixed64: return "Fixed64" case .fixed32: return "Fixed32" case .bool: return "Bool" case .string: return "String" case .group: return context.getMessageNameForPath(path: typeName)! case .message: return context.getMessageNameForPath(path: typeName)! case .bytes: return "Bytes" case .uint32: return "UInt32" case .enum: return "Enum" case .sfixed32: return "SFixed32" case .sfixed64: return "SFixed64" case .sint32: return "SInt32" case .sint64: return "SInt64" } } func getSwiftBaseType(context: Context) -> String { switch type { case .double: return "Double" case .float: return "Float" case .int64: return "Int64" case .uint64: return "UInt64" case .int32: return "Int32" case .fixed64: return "UInt64" case .fixed32: return "UInt32" case .bool: return "Bool" case .string: return "String" case .group: return context.getMessageNameForPath(path: typeName)! case .message: return context.getMessageNameForPath(path: typeName)! case .bytes: return "Data" case .uint32: return "UInt32" case .enum: return context.getEnumNameForPath(path: typeName)! case .sfixed32: return "Int32" case .sfixed64: return "Int64" case .sint32: return "Int32" case .sint64: return "Int64" } } func getSwiftApiType(context: Context, isProto3: Bool) -> String { if getIsMap(context: context) { let m = context.getMessageForPath(path: typeName)! let keyField = m.field[0] let keyType = keyField.getSwiftBaseType(context: context) let valueField = m.field[1] let valueType = valueField.getSwiftBaseType(context: context) return "Dictionary<" + keyType + "," + valueType + ">" } switch label { case .repeated: return "[" + getSwiftBaseType(context: context) + "]" case .required, .optional: return getSwiftBaseType(context: context) } } func getSwiftStorageType(context: Context, isProto3: Bool) -> String { if getIsMap(context: context) { let m = context.getMessageForPath(path: typeName)! let keyField = m.field[0] let keyType = keyField.getSwiftBaseType(context: context) let valueField = m.field[1] let valueType = valueField.getSwiftBaseType(context: context) return "Dictionary<" + keyType + "," + valueType + ">" } else if isRepeated { return "[" + getSwiftBaseType(context: context) + "]" } else if isMessage || isGroup { return getSwiftBaseType(context: context) + "?" } else if isProto3 { return getSwiftBaseType(context: context) } else { return getSwiftBaseType(context: context) + "?" } } func getSwiftStorageDefaultValue(context: Context, isProto3: Bool) -> String { if getIsMap(context: context) { return "[:]" } else if isRepeated { return "[]" } else if isMessage || isGroup || !isProto3 { return "nil" } else { return getSwiftDefaultValue(context: context, isProto3: isProto3) } } func getSwiftDefaultValue(context: Context, isProto3: Bool) -> String { if getIsMap(context: context) {return "[:]"} if isRepeated {return "[]"} if let d = getSwiftProto2DefaultValue(context: context) { return d } switch type { case .bool: return "false" case .string: return "String()" case .bytes: return "SwiftProtobuf.Internal.emptyData" case .group, .message: return context.getMessageNameForPath(path: typeName)! + "()" case .enum: let e = context.enumByProtoName[typeName]! if e.value.count == 0 { return "nil" } else { let defaultCase = e.value[0].name return context.getSwiftNameForEnumCase(path: typeName, caseName: defaultCase) } default: return "0" } } func getTraitsType(context: Context) -> String { if getIsMap(context: context) { let m = context.getMessageForPath(path: typeName)! let keyField = m.field[0] let keyTraits = keyField.getTraitsType(context: context) let valueField = m.field[1] let valueTraits = valueField.getTraitsType(context: context) if valueField.isMessage { return "SwiftProtobuf._ProtobufMessageMap<" + keyTraits + "," + valueTraits + ">" } else if valueField.isEnum { return "SwiftProtobuf._ProtobufEnumMap<" + keyTraits + "," + valueTraits + ">" } else { return "SwiftProtobuf._ProtobufMap<" + keyTraits + "," + valueTraits + ">" } } switch type { case .double: return "SwiftProtobuf.ProtobufDouble" case .float: return "SwiftProtobuf.ProtobufFloat" case .int64: return "SwiftProtobuf.ProtobufInt64" case .uint64: return "SwiftProtobuf.ProtobufUInt64" case .int32: return "SwiftProtobuf.ProtobufInt32" case .fixed64: return "SwiftProtobuf.ProtobufFixed64" case .fixed32: return "SwiftProtobuf.ProtobufFixed32" case .bool: return "SwiftProtobuf.ProtobufBool" case .string: return "SwiftProtobuf.ProtobufString" case .group: return getSwiftBaseType(context: context) case .message: return getSwiftBaseType(context: context) case .bytes: return "SwiftProtobuf.ProtobufBytes" case .uint32: return "SwiftProtobuf.ProtobufUInt32" case .enum: return getSwiftBaseType(context: context) case .sfixed32: return "SwiftProtobuf.ProtobufSFixed32" case .sfixed64: return "SwiftProtobuf.ProtobufSFixed64" case .sint32: return "SwiftProtobuf.ProtobufSInt32" case .sint64: return "SwiftProtobuf.ProtobufSInt64" } } func getSwiftProto2DefaultValue(context: Context) -> String? { guard hasDefaultValue else {return nil} switch type { case .double: switch defaultValue { case "inf": return "Double.infinity" case "-inf": return "-Double.infinity" case "nan": return "Double.nan" default: return defaultValue } case .float: switch defaultValue { case "inf": return "Float.infinity" case "-inf": return "-Float.infinity" case "nan": return "Float.nan" default: return defaultValue } case .bool: return defaultValue case .string: if defaultValue.isEmpty { // proto file listed the default as "", just pretend it wasn't set since // this is the default. return nil } else { return stringToEscapedStringLiteral(defaultValue) } case .bytes: if defaultValue.isEmpty { // proto file listed the default as "", just pretend it wasn't set since // this is the default. return nil } else { return escapedToDataLiteral(defaultValue) } case .enum: return context.getSwiftNameForEnumCase(path: typeName, caseName: defaultValue) default: return defaultValue } } } struct MessageFieldGenerator { let descriptor: Google_Protobuf_FieldDescriptorProto let oneof: Google_Protobuf_OneofDescriptorProto? let jsonName: String? let swiftName: String let swiftHasName: String let swiftClearName: String let swiftStorageName: String var protoName: String {return descriptor.name} var number: Int {return Int(descriptor.number)} let path: [Int32] let comments: String let isProto3: Bool let context: Context let generatorOptions: GeneratorOptions init(descriptor: Google_Protobuf_FieldDescriptorProto, path: [Int32], messageDescriptor: Google_Protobuf_DescriptorProto, file: FileGenerator, context: Context) { self.descriptor = descriptor self.jsonName = descriptor.jsonName if descriptor.type == .group { let g = context.getMessageForPath(path: descriptor.typeName)! let lowerName = toLowerCamelCase(g.name) self.swiftName = sanitizeFieldName(lowerName) let sanitizedUpper = sanitizeFieldName(toUpperCamelCase(g.name), basedOn: lowerName) self.swiftHasName = "has" + sanitizedUpper self.swiftClearName = "clear" + sanitizedUpper } else { let lowerName = toLowerCamelCase(descriptor.name) self.swiftName = sanitizeFieldName(lowerName) let sanitizedUpper = sanitizeFieldName(toUpperCamelCase(descriptor.name), basedOn: lowerName) self.swiftHasName = "has" + sanitizedUpper self.swiftClearName = "clear" + sanitizedUpper } if descriptor.hasOneofIndex { self.oneof = messageDescriptor.oneofDecl[Int(descriptor.oneofIndex)] } else { self.oneof = nil } self.swiftStorageName = "_" + self.swiftName self.path = path self.comments = file.commentsFor(path: path) self.isProto3 = file.isProto3 self.context = context self.generatorOptions = file.generatorOptions } var fieldMapNames: String { // Protobuf Text uses the unqualified group name for the field // name instead of the field name provided by protoc. As far // as I can tell, no one uses the fieldname provided by protoc, // so let's just put the field name that Protobuf Text // actually uses here. let protoName: String let jsonName: String if isGroup { protoName = descriptor.bareTypeName } else { protoName = self.protoName } jsonName = self.jsonName ?? protoName if jsonName == protoName { /// The proto and JSON names are identical: return ".same(proto: \"\(protoName)\")" } else { let libraryGeneratedJsonName = toJsonFieldName(protoName) if jsonName == libraryGeneratedJsonName { /// The library will generate the same thing protoc gave, so /// we can let the library recompute this: return ".standard(proto: \"\(protoName)\")" } else { /// The library's generation didn't match, so specify this explicitly. return ".unique(proto: \"\(protoName)\", json: \"\(jsonName)\")" } } } var isGroup: Bool {return descriptor.isGroup} var isMap: Bool {return descriptor.getIsMap(context: context)} var isMessage: Bool {return descriptor.isMessage} var isEnum: Bool {return descriptor.type == .enum} var isString: Bool {return descriptor.type == .string} var isBytes: Bool {return descriptor.type == .bytes} var isPacked: Bool {return descriptor.isPackable && (descriptor.options.hasPacked ? descriptor.options.packed : isProto3)} var isRepeated: Bool {return descriptor.isRepeated} // True/False if the field will be hold a Message. If the field is a map, // the value type for the map is checked. var fieldHoldsMessage: Bool { switch descriptor.label { case .required, .optional: let type = descriptor.type return type == .message || type == .group case .repeated: let type = descriptor.type if type == .group { return true } if type == .message { let m = context.getMessageForPath(path: descriptor.typeName)! if m.options.mapEntry { let valueField = m.field[1] return valueField.type == .message } else { return true } } else { return false } } } var name: String {return descriptor.name} var protoTypeName: String {return descriptor.getProtoTypeName(context: context)} var swiftBaseType: String {return descriptor.getSwiftBaseType(context: context)} var swiftApiType: String {return descriptor.getSwiftApiType(context: context, isProto3: isProto3)} var swiftDefaultValue: String { return descriptor.getSwiftDefaultValue(context: context, isProto3: isProto3) } var swiftProto2DefaultValue: String? { return descriptor.getSwiftProto2DefaultValue(context: context) } var swiftStorageType: String { return descriptor.getSwiftStorageType(context: context, isProto3: isProto3) } var swiftStorageDefaultValue: String { return descriptor.getSwiftStorageDefaultValue(context: context, isProto3: isProto3) } var traitsType: String {return descriptor.getTraitsType(context: context)} func generateTopIvar(printer p: inout CodePrinter) { p.print("\n") if !comments.isEmpty { p.print(comments) } if let oneof = oneof { p.print("\(generatorOptions.visibilitySourceSnippet)var \(swiftName): \(swiftApiType) {\n") p.indent() p.print("get {\n") p.indent() p.print("if case .\(swiftName)(let v)? = \(oneof.swiftFieldName) {return v}\n") p.print("return \(swiftDefaultValue)\n") p.outdent() p.print("}\n") p.print("set {\(oneof.swiftFieldName) = .\(swiftName)(newValue)}\n") p.outdent() p.print("}\n") } else if !isRepeated && !isMap && !isProto3 { p.print("fileprivate var \(swiftStorageName): \(swiftStorageType) = \(swiftStorageDefaultValue)\n") p.print("\(generatorOptions.visibilitySourceSnippet)var \(swiftName): \(swiftApiType) {\n") p.indent() p.print("get {return \(swiftStorageName) ?? \(swiftDefaultValue)}\n") p.print("set {\(swiftStorageName) = newValue}\n") p.outdent() p.print("}\n") } else { p.print("\(generatorOptions.visibilitySourceSnippet)var \(swiftName): \(swiftStorageType) = \(swiftStorageDefaultValue)\n") } } func generateProxyIvar(printer p: inout CodePrinter) { p.print("\n") if !comments.isEmpty { p.print(comments) } p.print("\(generatorOptions.visibilitySourceSnippet)var \(swiftName): \(swiftApiType) {\n") p.indent() if let oneof = oneof { p.print("get {\n") p.indent() p.print("if case .\(swiftName)(let v)? = _storage.\(oneof.swiftStorageFieldName) {return v}\n") p.print("return \(swiftDefaultValue)\n") p.outdent() p.print("}\n") p.print("set {_uniqueStorage().\(oneof.swiftStorageFieldName) = .\(swiftName)(newValue)}\n") } else { let defaultClause: String if isMap || isRepeated { defaultClause = "" } else if isMessage || isGroup { defaultClause = " ?? " + swiftDefaultValue } else if let d = swiftProto2DefaultValue { defaultClause = " ?? " + d } else { defaultClause = isProto3 ? "" : " ?? " + swiftDefaultValue } p.print("get {return _storage.\(swiftStorageName)\(defaultClause)}\n") p.print("set {_uniqueStorage().\(swiftStorageName) = newValue}\n") } p.outdent() p.print("}\n") } func generateHasProperty(printer p: inout CodePrinter, usesHeapStorage: Bool) { if isRepeated || isMap || oneof != nil || (isProto3 && !isMessage) { return } let storagePrefix = usesHeapStorage ? "_storage." : "self." p.print("\(generatorOptions.visibilitySourceSnippet)var \(swiftHasName): Bool {\n") p.indent() p.print("return \(storagePrefix)\(swiftStorageName) != nil\n") p.outdent() p.print("}\n") } func generateClearMethod(printer p: inout CodePrinter, usesHeapStorage: Bool) { if isRepeated || isMap || oneof != nil || (isProto3 && !isMessage) { return } let storagePrefix = usesHeapStorage ? "_storage." : "self." p.print("\(generatorOptions.visibilitySourceSnippet)mutating func \(swiftClearName)() {\n") p.indent() p.print("\(storagePrefix)\(swiftStorageName) = nil\n") p.outdent() p.print("}\n") } func generateDecodeFieldCase(printer p: inout CodePrinter, usesStorage: Bool) { let prefix: String if usesStorage { prefix = "_storage._" } else if !isRepeated && !isMap && !isProto3 { prefix = "self._" } else { prefix = "self." } let decoderMethod: String let traitsArg: String let valueArg: String if isMap { // Map fields decoderMethod = "decodeMapField" traitsArg = "fieldType: \(traitsType).self" valueArg = "value: &\(prefix)\(swiftName)" } else if isGroup || isMessage || isEnum { // Message, Group, Enum fields let modifier = (isRepeated ? "Repeated" : "Singular") let special = isGroup ? "Group" : isMessage ? "Message" : isEnum ? "Enum" : "" decoderMethod = "decode\(modifier)\(special)Field" traitsArg = "" valueArg = "value: &\(prefix)\(swiftName)" } else { // Primitive fields let modifier = (isRepeated ? "Repeated" : "Singular") let protoType = descriptor.getProtoTypeName(context: context) decoderMethod = "decode\(modifier)\(protoType)Field" traitsArg = "" valueArg = "value: &\(prefix)\(swiftName)" } let separator = traitsArg.isEmpty ? "" : ", " p.print("case \(number): try decoder.\(decoderMethod)(\(traitsArg)\(separator)\(valueArg))\n") } func generateTraverse(printer p: inout CodePrinter, usesStorage: Bool) { let prefix: String if usesStorage { prefix = "_storage._" } else if !isRepeated && !isMap && !isProto3 { prefix = "self._" } else { prefix = "self." } let visitMethod: String let fieldTypeArg: String if isMap { visitMethod = "visitMapField" fieldTypeArg = "fieldType: \(traitsType).self, " } else if isGroup || isMessage || isEnum { let modifier = (isPacked ? "Packed" : isRepeated ? "Repeated" : "Singular") let special = isGroup ? "Group" : isMessage ? "Message" : isEnum ? "Enum" : "" visitMethod = "visit\(modifier)\(special)Field" fieldTypeArg = "" } else if !isRepeated && descriptor.type == .int64 { visitMethod = "visitSingularInt64Field" fieldTypeArg = "" } else { let modifier = (isPacked ? "Packed" : isRepeated ? "Repeated" : "Singular") let protoType = descriptor.getProtoTypeName(context: context) visitMethod = "visit\(modifier)\(protoType)Field" fieldTypeArg = "" } let varName: String let conditional: String if isRepeated { varName = prefix + swiftName conditional = "!\(varName).isEmpty" } else if isGroup || isMessage || !isProto3 { varName = "v" conditional = "let v = \(prefix)\(swiftName)" } else { assert(isProto3) varName = prefix + swiftName if isString || isBytes { conditional = ("!\(varName).isEmpty") } else { conditional = ("\(varName) != \(swiftDefaultValue)") } } p.print("if \(conditional) {\n") p.indent() p.print("try visitor.\(visitMethod)(\(fieldTypeArg)value: \(varName), fieldNumber: \(number))\n") p.outdent() p.print("}\n") } }
mit
541c475802a38dfc13fd2bfa6d17bd3d
37.651163
135
0.572976
4.642458
false
false
false
false
anlaital/Swan
Swan/Swan/UILabelExtensions.swift
1
502
// // UILabelExtensions.swift // Swan // // Created by Antti Laitala on 03/06/15. // // import Foundation import UIKit public extension UILabel { final func sizeHeightToFit() { var frame = self.frame; sizeToFit() frame.size.height = self.frame.size.height self.frame = frame } final func sizeWidthToFit() { var frame = self.frame sizeToFit() frame.size.width = self.frame.size.width self.frame = frame } }
mit
ed46db3382d5ec55245b8c2e7577edb6
16.928571
50
0.591633
3.774436
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift
10
4890
// // UISearchBar+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 3/28/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation #if !RX_NO_MODULE import RxSwift #endif import UIKit #if os(iOS) extension UISearchBar { /// Factory method that enables subclasses to implement their own `delegate`. /// /// - returns: Instance of delegate proxy that wraps `delegate`. public func createRxDelegateProxy() -> RxSearchBarDelegateProxy { return RxSearchBarDelegateProxy(parentObject: self) } } #endif extension Reactive where Base: UISearchBar { /// Reactive wrapper for `delegate`. /// /// For more information take a look at `DelegateProxyType` protocol documentation. public var delegate: DelegateProxy { return RxSearchBarDelegateProxy.proxyForObject(base) } /// Reactive wrapper for `text` property. public var text: ControlProperty<String?> { return value } /// Reactive wrapper for `text` property. public var value: ControlProperty<String?> { let source: Observable<String?> = Observable.deferred { [weak searchBar = self.base as UISearchBar] () -> Observable<String?> in let text = searchBar?.text return (searchBar?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:textDidChange:))) ?? Observable.empty()) .map { a in return a[1] as? String } .startWith(text) } let bindingObserver = UIBindingObserver(UIElement: self.base) { (searchBar, text: String?) in searchBar.text = text } return ControlProperty(values: source, valueSink: bindingObserver) } /// Reactive wrapper for `selectedScopeButtonIndex` property. public var selectedScopeButtonIndex: ControlProperty<Int> { let source: Observable<Int> = Observable.deferred { [weak source = self.base as UISearchBar] () -> Observable<Int> in let index = source?.selectedScopeButtonIndex ?? 0 return (source?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:selectedScopeButtonIndexDidChange:))) ?? Observable.empty()) .map { a in return try castOrThrow(Int.self, a[1]) } .startWith(index) } let bindingObserver = UIBindingObserver(UIElement: self.base) { (searchBar, index: Int) in searchBar.selectedScopeButtonIndex = index } return ControlProperty(values: source, valueSink: bindingObserver) } #if os(iOS) /// Reactive wrapper for delegate method `searchBarCancelButtonClicked`. public var cancelButtonClicked: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarCancelButtonClicked(_:))) .map { _ in return () } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `searchBarBookmarkButtonClicked`. public var bookmarkButtonClicked: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarBookmarkButtonClicked(_:))) .map { _ in return () } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `searchBarResultsListButtonClicked`. public var resultsListButtonClicked: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarResultsListButtonClicked(_:))) .map { _ in return () } return ControlEvent(events: source) } #endif /// Reactive wrapper for delegate method `searchBarSearchButtonClicked`. public var searchButtonClicked: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarSearchButtonClicked(_:))) .map { _ in return () } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `searchBarTextDidBeginEditing`. public var textDidBeginEditing: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidBeginEditing(_:))) .map { _ in return () } return ControlEvent(events: source) } /// Reactive wrapper for delegate method `searchBarTextDidEndEditing`. public var textDidEndEditing: ControlEvent<Void> { let source: Observable<Void> = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidEndEditing(_:))) .map { _ in return () } return ControlEvent(events: source) } } #endif
apache-2.0
db01e673d1235849ef35100f3be93872
33.921429
156
0.662099
5.004094
false
false
false
false
sbcmadn1/swift
swiftweibo05/GZWeibo05/Class/Library/PhotoSelector/CZPhotoSelectorViewController.swift
2
9037
// // CZPhotoSelectorViewController.swift // 02.照片选择器UI搭建 // // Created by zhangping on 15/11/7. // Copyright © 2015年 zhangping. All rights reserved. // import UIKit private let reuseIdentifier = "Cell" class CZPhotoSelectorViewController: UICollectionViewController, CZPhotoSelectorCellDelegate { // MRAK: - 属性 /// 选择的图片 var photos = [UIImage]() /// 记录点击的cell indexPath var currentIndexPath: NSIndexPath? /// 最大照片张数 private let maxPhotoCount = 6 /// collectionView 的 布局 private var layout = UICollectionViewFlowLayout() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init() { super.init(collectionViewLayout: layout) } override func viewDidLoad() { super.viewDidLoad() prepareCollectionView() } /// 准备CollectionView func prepareCollectionView() { // 注册cell collectionView?.registerClass(CZPhotoSelectorCell.self, forCellWithReuseIdentifier: "cell") collectionView?.backgroundColor = UIColor.clearColor() // 设置itemSize layout.itemSize = CGSize(width: 80, height: 80) // layout设置section间距 layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10) } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 当图片数量小于最大张数, cell的数量 = 照片的张数 + 1 // 当图片数量等于最大张数, cell的数量 = 照片的张数 return photos.count < maxPhotoCount ? photos.count + 1 : photos.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CZPhotoSelectorCell cell.backgroundColor = UIColor.brownColor() cell.cellDelegate = self /* 照片的数量 cell的数量 indexPath 0 1 0 1 2 0,1 2, 3 0,1,2 */ // 当有图片的时候才设置图片 if indexPath.item < photos.count { cell.image = photos[indexPath.item] } else { // 设置图片防止cell复用 cell.setAddButton() } return cell } /// 添加图片 func photoSelectorCellAddPhoto(cell: CZPhotoSelectorCell) { // 判断相册是否可用 if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) { print("相册不可用") return } // 弹出系统的相册 let picker = UIImagePickerController() picker.delegate = self // 记录当前点击的cell的indexPath currentIndexPath = collectionView?.indexPathForCell(cell) presentViewController(picker, animated: true, completion: nil) } /// 删除图片 func photoSelectorCellRemovePhoto(cell: CZPhotoSelectorCell) { // 点击的是哪个cell的删除按钮 let indexPath = collectionView!.indexPathForCell(cell)! // 删除photos对应的图片 photos.removeAtIndex(indexPath.item) // 刷新collectionView,某一行 // deleteItemsAtIndexPaths cell需要少一个 if photos.count < 5 { collectionView?.deleteItemsAtIndexPaths([indexPath]) } else { collectionView?.reloadData() } } } extension CZPhotoSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { /// 选择照片时的代理方法 func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { print("image:\(image)") let newImage = image.scaleImage() print("newImage:\(newImage)") // 当图片比较大的时候将它图片缩小 // 将选择的照片添加到数组,让collectionView去显示 // 如果点击的是图片,就是替换图片,如果点击的是加号按钮,添加图片 if currentIndexPath?.item < photos.count { // 点击的是图片,替换图片 photos[currentIndexPath!.item] = newImage } else { // 点击的是加号按钮 photos.append(newImage) } // 刷新数据 collectionView?.reloadData() // 关闭系统的相册 picker.dismissViewControllerAnimated(true, completion: nil) } } // MARK: - cell点击时间代理 @objc protocol CZPhotoSelectorCellDelegate: NSObjectProtocol { // 点击加号代理方法 func photoSelectorCellAddPhoto(cell: CZPhotoSelectorCell) // 点击删除代理方法 func photoSelectorCellRemovePhoto(cell: CZPhotoSelectorCell) // 可选的方法 协议需要加 @objc optional func test() } // MARK: - 自定义cell class CZPhotoSelectorCell: UICollectionViewCell { // image 用来显示, 替换加号按钮的图片 var image: UIImage? { didSet { addButton.setImage(image, forState: UIControlState.Normal) addButton.setImage(image, forState: UIControlState.Highlighted) // 显示删除按钮 removeButton.hidden = false } } /// 设置加号按钮的图片 func setAddButton() { // 设置按钮图片 addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal) addButton.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted) // 隐藏删除按钮 removeButton.hidden = true } // MARK: - 属性 weak var cellDelegate: CZPhotoSelectorCellDelegate? // MARK: - 构造函数 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) prepareUI() } // MARK: - 按钮点击事件 func addPhoto() { cellDelegate?.photoSelectorCellAddPhoto(self) } func removePhoto() { cellDelegate?.photoSelectorCellRemovePhoto(self) // cellDelegate?.test?() } // MARK: - 准备UI private func prepareUI() { // 添加子控件 contentView.addSubview(addButton) contentView.addSubview(removeButton) addButton.translatesAutoresizingMaskIntoConstraints = false removeButton.translatesAutoresizingMaskIntoConstraints = false let views = ["ab": addButton, "rb": removeButton] // 添加约束 // 加号按钮 contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) // 删除按钮 contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[rb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rb]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) } // MARK: - 懒加载 /// 加号按钮 private lazy var addButton: UIButton = { let button = UIButton() // 设置按钮图片 button.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal) button.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted) // 设置按钮图片的显示模式 button.imageView?.contentMode = UIViewContentMode.ScaleAspectFill // 添加点击事件 button.addTarget(self, action: "addPhoto", forControlEvents: UIControlEvents.TouchUpInside) return button }() /// 删除按钮 private lazy var removeButton: UIButton = { let button = UIButton() button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal) // 添加点击事件 button.addTarget(self, action: "removePhoto", forControlEvents: UIControlEvents.TouchUpInside) return button }() }
mit
7826bac5c069705cbd1092e46ac4ae6a
29.641791
173
0.614954
5.171285
false
false
false
false
NunoAlexandre/broccoli_mobile
ios/Carthage/Checkouts/Eureka/Source/Rows/Common/FieldRow.swift
2
16598
// FieldRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public protocol InputTypeInitiable { init?(string stringValue: String) } public protocol FieldRowConformance : FormatterConformance { var textFieldPercentage : CGFloat? { get set } var placeholder : String? { get set } var placeholderColor : UIColor? { get set } } extension Int: InputTypeInitiable { public init?(string stringValue: String){ self.init(stringValue, radix: 10) } } extension Float: InputTypeInitiable { public init?(string stringValue: String){ self.init(stringValue) } } extension String: InputTypeInitiable { public init?(string stringValue: String){ self.init(stringValue) } } extension URL: InputTypeInitiable {} extension Double: InputTypeInitiable { public init?(string stringValue: String){ self.init(stringValue) } } open class FormatteableRow<Cell: CellType>: Row<Cell>, FormatterConformance where Cell: BaseCell, Cell: TextInputCell { /// A formatter to be used to format the user's input open var formatter: Formatter? /// If the formatter should be used while the user is editing the text. open var useFormatterDuringInput = false open var useFormatterOnDidBeginEditing: Bool? public required init(tag: String?) { super.init(tag: tag) displayValueFor = { [unowned self] value in guard let v = value else { return nil } guard let formatter = self.formatter else { return String(describing: v) } if (self.cell.textInput as? UIView)?.isFirstResponder == true { return self.useFormatterDuringInput ? formatter.editingString(for: v) : String(describing: v) } return formatter.string(for: v) } } } open class FieldRow<Cell: CellType>: FormatteableRow<Cell>, FieldRowConformance, KeyboardReturnHandler where Cell: BaseCell, Cell: TextFieldCell { /// Configuration for the keyboardReturnType of this row open var keyboardReturnType : KeyboardReturnTypeConfiguration? /// The percentage of the cell that should be occupied by the textField open var textFieldPercentage : CGFloat? /// The placeholder for the textField open var placeholder : String? /// The textColor for the textField's placeholder open var placeholderColor : UIColor? public required init(tag: String?) { super.init(tag: tag) } } /** * Protocol for cells that contain a UITextField */ public protocol TextInputCell { var textInput : UITextInput { get } } public protocol TextFieldCell: TextInputCell { var textField: UITextField { get } } extension TextFieldCell { public var textInput: UITextInput { return textField } } open class _FieldCell<T> : Cell<T>, UITextFieldDelegate, TextFieldCell where T: Equatable, T: InputTypeInitiable { public var textField: UITextField open var titleLabel : UILabel? { textLabel?.translatesAutoresizingMaskIntoConstraints = false textLabel?.setContentHuggingPriority(500, for: .horizontal) textLabel?.setContentCompressionResistancePriority(1000, for: .horizontal) return textLabel } fileprivate var observingTitleText: Bool = false open var dynamicConstraints = [NSLayoutConstraint]() public required init(style: UITableViewCellStyle, reuseIdentifier: String?) { textField = UITextField() textField.translatesAutoresizingMaskIntoConstraints = false super.init(style: style, reuseIdentifier: reuseIdentifier) NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationWillResignActive, object: nil, queue: nil){ [weak self] notification in guard let me = self else { return } guard me.observingTitleText else { return } me.titleLabel?.removeObserver(me, forKeyPath: "text") me.observingTitleText = false } NotificationCenter.default.addObserver(forName: Notification.Name.UIApplicationDidBecomeActive, object: nil, queue: nil){ [weak self] notification in guard let me = self else { return } guard !me.observingTitleText else { return } me.titleLabel?.addObserver(me, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil) me.observingTitleText = true } NotificationCenter.default.addObserver(forName: Notification.Name.UIContentSizeCategoryDidChange, object: nil, queue: nil){ [weak self] notification in self?.setNeedsUpdateConstraints() } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { textField.delegate = nil textField.removeTarget(self, action: nil, for: .allEvents) if observingTitleText { titleLabel?.removeObserver(self, forKeyPath: "text") } imageView?.removeObserver(self, forKeyPath: "image") NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationWillResignActive, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIApplicationDidBecomeActive, object: nil) NotificationCenter.default.removeObserver(self, name: Notification.Name.UIContentSizeCategoryDidChange, object: nil) } open override func setup() { super.setup() selectionStyle = .none contentView.addSubview(titleLabel!) contentView.addSubview(textField) titleLabel?.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions.old.union(.new), context: nil) observingTitleText = true imageView?.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions.old.union(.new), context: nil) textField.addTarget(self, action: #selector(_FieldCell.textFieldDidChange(_:)), for: .editingChanged) } open override func update() { super.update() detailTextLabel?.text = nil if let title = row.title { textField.textAlignment = title.isEmpty ? .left : .right textField.clearButtonMode = title.isEmpty ? .whileEditing : .never } else{ textField.textAlignment = .left textField.clearButtonMode = .whileEditing } textField.delegate = self textField.text = row.displayValueFor?(row.value) textField.isEnabled = !row.isDisabled textField.textColor = row.isDisabled ? .gray : .black textField.font = .preferredFont(forTextStyle: .body) if let placeholder = (row as? FieldRowConformance)?.placeholder { if let color = (row as? FieldRowConformance)?.placeholderColor { textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color]) } else{ textField.placeholder = (row as? FieldRowConformance)?.placeholder } } if row.isHighlighted { textLabel?.textColor = tintColor } } open override func cellCanBecomeFirstResponder() -> Bool { return !row.isDisabled && textField.canBecomeFirstResponder } open override func cellBecomeFirstResponder(withDirection: Direction) -> Bool { return textField.becomeFirstResponder() } open override func cellResignFirstResponder() -> Bool { return textField.resignFirstResponder() } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { let obj = object as AnyObject? if let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKey.kindKey], ((obj === titleLabel && keyPathValue == "text") || (obj === imageView && keyPathValue == "image")) && (changeType as? NSNumber)?.uintValue == NSKeyValueChange.setting.rawValue { setNeedsUpdateConstraints() updateConstraintsIfNeeded() } } // Mark: Helpers open func customConstraints() { contentView.removeConstraints(dynamicConstraints) dynamicConstraints = [] var views : [String: AnyObject] = ["textField": textField] dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[textField]-11-|", options: .alignAllLastBaseline, metrics: nil, views: ["textField": textField]) if let label = titleLabel, let text = label.text, !text.isEmpty { dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-11-[titleLabel]-11-|", options: .alignAllLastBaseline, metrics: nil, views: ["titleLabel": label]) dynamicConstraints.append(NSLayoutConstraint(item: label, attribute: .centerY, relatedBy: .equal, toItem: textField, attribute: .centerY, multiplier: 1, constant: 0)) } if let imageView = imageView, let _ = imageView.image { views["imageView"] = imageView if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty { views["label"] = titleLabel dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[label]-[textField]-|", options: NSLayoutFormatOptions(), metrics: nil, views: views) dynamicConstraints.append(NSLayoutConstraint(item: textField, attribute: .width, relatedBy: (row as? FieldRowConformance)?.textFieldPercentage != nil ? .equal : .greaterThanOrEqual, toItem: contentView, attribute: .width, multiplier: (row as? FieldRowConformance)?.textFieldPercentage ?? 0.3, constant: 0.0)) } else{ dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-(15)-[textField]-|", options: [], metrics: nil, views: views) } } else{ if let titleLabel = titleLabel, let text = titleLabel.text, !text.isEmpty { views["label"] = titleLabel dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[label]-[textField]-|", options: [], metrics: nil, views: views) dynamicConstraints.append(NSLayoutConstraint(item: textField, attribute: .width, relatedBy: (row as? FieldRowConformance)?.textFieldPercentage != nil ? .equal : .greaterThanOrEqual, toItem: contentView, attribute: .width, multiplier: (row as? FieldRowConformance)?.textFieldPercentage ?? 0.3, constant: 0.0)) } else{ dynamicConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[textField]-|", options: .alignAllLeft, metrics: nil, views: views) } } contentView.addConstraints(dynamicConstraints) } open override func updateConstraints(){ customConstraints() super.updateConstraints() } open func textFieldDidChange(_ textField : UITextField){ guard let textValue = textField.text else { row.value = nil return } guard let fieldRow = row as? FieldRowConformance, let formatter = fieldRow.formatter else { row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value) return } if fieldRow.useFormatterDuringInput { let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1)) let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) { row.value = value.pointee as? T guard var selStartPos = textField.selectedTextRange?.start else { return } let oldVal = textField.text textField.text = row.displayValueFor?(row.value) selStartPos = (formatter as? FormatterProtocol)?.getNewPosition(forPosition: selStartPos, inTextInput: textField, oldValue: oldVal, newValue: textField.text) ?? selStartPos textField.selectedTextRange = textField.textRange(from: selStartPos, to: selStartPos) return } } else { let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.allocate(capacity: 1)) let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?>? = nil if formatter.getObjectValue(value, for: textValue, errorDescription: errorDesc) { row.value = value.pointee as? T } else{ row.value = textValue.isEmpty ? nil : (T.init(string: textValue) ?? row.value) } } } //Mark: Helpers private func displayValue(useFormatter: Bool) -> String? { guard let v = row.value else { return nil } if let formatter = (row as? FormatterConformance)?.formatter, useFormatter { return textField.isFirstResponder ? formatter.editingString(for: v) : formatter.string(for: v) } return String(describing: v) } //MARK: TextFieldDelegate open func textFieldDidBeginEditing(_ textField: UITextField) { formViewController()?.beginEditing(of: self) formViewController()?.textInputDidBeginEditing(textField, cell: self) if let fieldRowConformance = row as? FormatterConformance, let _ = fieldRowConformance.formatter, fieldRowConformance.useFormatterOnDidBeginEditing ?? fieldRowConformance.useFormatterDuringInput { textField.text = displayValue(useFormatter: true) } else { textField.text = displayValue(useFormatter: false) } } open func textFieldDidEndEditing(_ textField: UITextField) { formViewController()?.endEditing(of: self) formViewController()?.textInputDidEndEditing(textField, cell: self) textFieldDidChange(textField) textField.text = displayValue(useFormatter: (row as? FormatterConformance)?.formatter != nil) } open func textFieldShouldReturn(_ textField: UITextField) -> Bool { return formViewController()?.textInputShouldReturn(textField, cell: self) ?? true } open func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return formViewController()?.textInput(textField, shouldChangeCharactersInRange:range, replacementString:string, cell: self) ?? true } open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return formViewController()?.textInputShouldBeginEditing(textField, cell: self) ?? true } open func textFieldShouldClear(_ textField: UITextField) -> Bool { return formViewController()?.textInputShouldClear(textField, cell: self) ?? true } open func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return formViewController()?.textInputShouldEndEditing(textField, cell: self) ?? true } }
mit
73b3d9647ad2f9869e333ad7effd5884
43.98103
324
0.674178
5.340412
false
false
false
false
gang462234887/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/homePage/controller/CookBookViewController.swift
1
7371
// // CookBookViewController.swift // TestKitchen // // Created by qianfeng on 16/8/15. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit class CookBookViewController: BaseViewController { //滚动视图 var scrollView:UIScrollView? //食材首页的推荐视图 private var recommendView:CBRecommendView? //首页的食材视图 private var foodView:CBMaterialView? ////首页的分类视图 private var categoryView:CBMaterialView? private var segCtrl:KTCSegmentCtrl? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.createMyNav() self.createHomePageView() //下载推荐的数据 self.downloadFoodData() //下载食材的数据 self.downloaderRecommendData() //下载分类的数据 self.downloadCategoryData() } //下载分类的数据 func downloadCategoryData(){ //methodName=CategoryIndex&token=&user_id=&version=4.32 let params = ["methodName":"CategoryIndex"] let downloader = KTCDownloader() downloader.delegate = self downloader.type = .Category downloader.postWithUrl(kHostUrl, params: params) } //下载食材的数据 func downloadFoodData(){ let dict = ["methodName":"MaterialSubtype"] let downloader = KTCDownloader() downloader.delegate = self downloader.type = .FoodMaterial downloader.postWithUrl(kHostUrl, params: dict) } //下载推荐的数据 func createHomePageView(){ self.automaticallyAdjustsScrollViewInsets = false //1.创建滚动视图 scrollView = UIScrollView() scrollView!.pagingEnabled = true scrollView!.showsHorizontalScrollIndicator = false scrollView?.delegate = self view.addSubview(scrollView!) scrollView!.snp_makeConstraints { [weak self] (make) in make.edges.equalTo((self?.view)!).inset(UIEdgeInsetsMake(64, 0, 49, 0)) } //2.创建容器视图 let containerView = UIView.createView() scrollView!.addSubview(containerView) containerView.snp_makeConstraints { [weak self] (make) in make.edges.equalTo(self!.scrollView!) make.height.equalTo(self!.scrollView!) } //3.添加子视图 //3.1推荐 recommendView = CBRecommendView() containerView.addSubview(recommendView!) recommendView?.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo(containerView) }) //3.2食材 foodView = CBMaterialView() containerView.addSubview(foodView!) foodView?.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo((recommendView?.snp_right)!) }) //3.3分类 categoryView = CBMaterialView() containerView.addSubview(categoryView!) categoryView?.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo((foodView?.snp_right)!) }) containerView.snp_makeConstraints { (make) in make.right.equalTo(categoryView!) } } //创建导航 func createMyNav(){ segCtrl = KTCSegmentCtrl(frame: CGRectMake(80, 0, kScreenWidth-80*2, 44), titleNames: ["推荐","食材","分类"]) navigationItem.titleView = segCtrl segCtrl?.delegate = self addNavBtn("saoyisao", target: self, action: #selector(scanAction), isLeft: true) addNavBtn("search", target: self, action: #selector(searchAction), isLeft: false) } //下载推荐的数据 func downloaderRecommendData(){ let dict = ["methodName":"SceneHome"] let downloader = KTCDownloader() downloader.delegate = self downloader.type = .Recommend downloader.postWithUrl(kHostUrl, params: dict) } //扫一扫 func scanAction(){ } //搜索 func searchAction(){ } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension CookBookViewController:KTCDownloaderDelegate{ func downloader(downloader: KTCDownloader, didFailWithError error: NSError) { print(error) } func downloader(downloader: KTCDownloader, didFinishWithData data: NSData?) { if downloader.type == .Recommend { //推荐 if let jsonData = data{ let model = CBRecommendModel.parseModel(jsonData) dispatch_async(dispatch_get_main_queue(), { [weak self] in self!.recommendView?.model = model }) } }else if downloader.type == .FoodMaterial{ //食材 /* let str = NSString(data: data!, encoding: NSUTF8StringEncoding) print(str!) */ if let jsonData = data{ let model = CBMaterialModel.parseModelWithData(jsonData) dispatch_async(dispatch_get_main_queue(), { [weak self] in self!.foodView?.model = model }) } }else if downloader.type == .Category{ //分类 if let jsonData = data{ let model = CBMaterialModel.parseModelWithData(jsonData) dispatch_async(dispatch_get_main_queue(), { [weak self] in self?.categoryView?.model = model }) } } } } extension CookBookViewController:KTCSegmentCtrlDelegate{ func didSelectSegCtrl(segCtrl: KTCSegmentCtrl, atIndex index: Int) { scrollView?.setContentOffset(CGPointMake(kScreenWidth*CGFloat(index), 0), animated: true) } } extension CookBookViewController:UIScrollViewDelegate{ func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let index = Int(scrollView.contentOffset.x/scrollView.bounds.size.width) segCtrl?.selectIndex = index } }
mit
e7807a57081a4a7a814d2747ea654e91
25.10989
111
0.566498
5.20672
false
false
false
false