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
overtake/TelegramSwift
packages/TGUIKit/Sources/MajorNavigationController.swift
1
13450
// // SingleChatNavigationController.swift // Telegram-Mac // // Created by keepcoder on 13/10/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import SwiftSignalKit public protocol MajorControllerListener : class { func navigationWillShowMajorController(_ controller:ViewController); } open class MajorNavigationController: NavigationViewController, SplitViewDelegate { public var alwaysAnimate: Bool = false private var majorClass:AnyClass private var defaultEmpty:ViewController private var listeners:[WeakReference<ViewController>] = [] private let container:GenericViewController<BackgroundView> = GenericViewController<BackgroundView>() override var containerView:BackgroundView { get { return container.genericView } set { super.containerView = newValue } } deinit { var bp:Int = 0 bp += 1 } open override func loadView() { super.loadView() genericView.setProportion(proportion: SplitProportion(min:380, max: .greatestFiniteMagnitude), state: .single) controller._frameRect = bounds controller.viewWillAppear(false) controller.navigationController = self containerView.addSubview(navigationBar) containerView.frame = bounds navigationBar.frame = NSMakeRect(0, 0, containerView.frame.width, controller.bar.height) controller.view.frame = NSMakeRect(0, controller.bar.height , containerView.frame.width, containerView.frame.height - controller.bar.height) navigationBar.switchViews(left: controller.leftBarView, center: controller.centerBarView, right: controller.rightBarView, controller: controller, style: .none, animationStyle: controller.animationStyle, liveSwiping: false) containerView.addSubview(controller.view) Queue.mainQueue().justDispatch { self.controller.viewDidAppear(false) } containerView.customHandler.layout = { [weak self] view in guard let `self` = self else { return } self.navigationBar.frame = NSMakeRect(self.navigationBar.frame.minX, self.navigationBar.frame.minY, self.controller.frame.width, self.navigationBar.frame.height) self.navigationRightBorder.frame = NSMakeRect(view.frame.width - .borderSize, 0, .borderSize, self.navigationBar.frame.height) } } public func closeSidebar() { genericView.removeProportion(state: .dual) genericView.setProportion(proportion: SplitProportion(min:380, max: .greatestFiniteMagnitude), state: .single) genericView.layout() viewDidChangedNavigationLayout(.single) } override var containerSize: NSSize { switch genericView.state { case .dual: return NSMakeSize(frame.width - 350, frame.height) default: return super.containerSize } } open override func viewDidResized(_ size: NSSize) { super.viewDidResized(size) self.genericView.setFrameSize(size) //_ = atomicSize.swap(size) // self.genericView.frame = NSMakeRect(0, barInset, <#T##w: CGFloat##CGFloat#>, <#T##h: CGFloat##CGFloat#>) } public init(_ majorClass:AnyClass, _ empty:ViewController, _ window: Window) { self.majorClass = majorClass self.defaultEmpty = empty container.bar = .init(height: 0) assert(majorClass is ViewController.Type) super.init(empty, window) } open override func currentControllerDidChange() { if let view = view as? DraggingView { view.controller = controller } for listener in listeners { listener.value?.navigationWillChangeController() } } open override func viewDidLoad() { //super.viewDidLoad() genericView.delegate = self genericView.layout() } public func splitViewDidNeedSwapToLayout(state: SplitViewState) { genericView.removeAllControllers(); switch state { case .dual: genericView.addController(controller: container, proportion: SplitProportion(min: 800, max: .greatestFiniteMagnitude)) if let sidebar = sidebar { genericView.addController(controller: sidebar, proportion: SplitProportion(min:350, max: 350)) } case .single: genericView.addController(controller: container, proportion: SplitProportion(min: 800, max: .greatestFiniteMagnitude)) default: break } for listener in listeners { listener.value?.viewDidChangedNavigationLayout(state) } viewDidResized(self.frame.size) } public func splitViewDidNeedMinimisize(controller: ViewController) { } public func splitViewDidNeedFullsize(controller: ViewController) { } public func splitViewIsCanMinimisize() -> Bool { return false; } public func splitViewDrawBorder() -> Bool { return true } open override func viewClass() ->AnyClass { return DraggingView.self } public var genericView:SplitView { return view as! SplitView } override open func push(_ controller: ViewController, _ animated: Bool = true, style:ViewControllerStyle? = nil) { assertOnMainThread() if controller.abolishWhenNavigationSame, controller.className == self.controller.className { return } controller.navigationController = self if genericView.nextLayout == .dual { controller.loadViewIfNeeded(NSMakeRect(0, 0, genericView.frame.width - 350, genericView.frame.height)) } else { var offset: CGFloat = controller.bar.height if let header = header, header.isShown { offset += header.height } if let header = callHeader, header.isShown { offset += header.height } let bounds = genericView.bounds let frame = NSMakeRect(0, offset, bounds.width, bounds.height - offset) controller.loadViewIfNeeded(frame) } self.genericView.update() self.controller.ableToNextController(controller, { [weak self] controller, result in if result { self?.pushDisposable.set((controller.ready.get() |> deliverOnMainQueue |> take(1)).start(next: {[weak self] _ in if let strongSelf = self { let isMajorController = controller.className == NSStringFromClass(strongSelf.majorClass) let removeAnimateFlag = strongSelf.stackCount == 2 && isMajorController && !strongSelf.alwaysAnimate if isMajorController { let stack = strongSelf.stack strongSelf.stack.removeAll() for controller in stack { controller.didRemovedFromStack() } strongSelf.stack.append(strongSelf.empty) } if let index = strongSelf.stack.firstIndex(of: controller) { strongSelf.stack.remove(at: index) } strongSelf.stack.append(controller) let anim = animated && (!isMajorController || strongSelf.controller != strongSelf.defaultEmpty) && !removeAnimateFlag let newStyle:ViewControllerStyle if let style = style { newStyle = style } else { newStyle = anim ? .push : .none } CATransaction.begin() strongSelf.show(controller, newStyle) CATransaction.commit() } })) } }) } open override func back(animated:Bool = true, forceAnimated: Bool = false, animationStyle: ViewControllerStyle = .pop) -> Void { if !isLocked, let last = stack.last, last.invokeNavigationBack() { if stackCount > 1 { let ncontroller = stack[stackCount - 2] let removeAnimateFlag = ((ncontroller == defaultEmpty || !animated) && !alwaysAnimate) && !forceAnimated stack.removeLast() last.didRemovedFromStack() show(ncontroller, removeAnimateFlag ? .none : animationStyle) } else { doSomethingOnEmptyBack?() } } } public func removeExceptMajor() { let index = stack.firstIndex(where: { current in return current.className == NSStringFromClass(self.majorClass) }) if let index = index { while stack.count > index { stack.removeLast() } } else { while stack.count > 1 { stack.removeLast() } } } open override var responderPriority: HandlerPriority { return empty.responderPriority } open override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.window?.set(handler: { [weak self] _ in if let strongSelf = self { return strongSelf.escapeKeyAction() } return .rejected }, with: self, for: .Escape, priority: self.responderPriority) self.window?.set(handler: { [weak self] _ in if let strongSelf = self { return strongSelf.returnKeyAction() } return .rejected }, with: self, for: .Return, priority: self.responderPriority) self.window?.set(handler: { [weak self] _ in if let strongSelf = self { return strongSelf.backKeyAction() } return .rejected }, with: self, for: .LeftArrow, priority: self.responderPriority) self.window?.set(handler: { [weak self] _ in if let strongSelf = self { return strongSelf.nextKeyAction() } return .rejected }, with: self, for: .RightArrow, priority: self.responderPriority) } open override var canSwipeBack: Bool { return (self.genericView.state == .single || self.stackCount > 2) } open override func viewWillDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.window?.removeAllHandlers(for: self) self.window?.removeAllHandlers(for: self.containerView) } open override func backKeyAction() -> KeyHandlerResult { let status:KeyHandlerResult = stackCount > 1 ? .invoked : .rejected if isLocked { return .invoked } let cInvoke = self.controller.backKeyAction() if cInvoke == .invokeNext { return .invokeNext } else if cInvoke == .invoked { return .invoked } self.back() return status } open override func nextKeyAction() -> KeyHandlerResult { if isLocked { return .invoked } return self.controller.nextKeyAction() } open override func escapeKeyAction() -> KeyHandlerResult { let status:KeyHandlerResult = stackCount > 1 ? .invoked : .rejected if isLocked { return .invoked } let cInvoke = self.controller.escapeKeyAction() if cInvoke == .invokeNext { return .invokeNext } else if cInvoke == .invoked { return .invoked } self.back() return status } open override func returnKeyAction() -> KeyHandlerResult { let status:KeyHandlerResult = .rejected let cInvoke = self.controller.returnKeyAction() if cInvoke == .invokeNext { return .invokeNext } else if cInvoke == .invoked { return .invoked } return status } public func add(listener:WeakReference<ViewController>) -> Void { let index = listeners.firstIndex(where: { (weakView) -> Bool in return listener.value == weakView.value }) if index == nil { listeners.append(listener) } } public func remove(listener:WeakReference<ViewController>) -> Void { let index = listeners.firstIndex(where: { (weakView) -> Bool in return listener.value == weakView.value }) if let index = index { listeners.remove(at: index) } } }
gpl-2.0
7df8f443f471ba9c4cdb19aebbcefe49
32.706767
230
0.56428
5.420798
false
false
false
false
sgr-ksmt/PDFGenerator
Demo/Controllers/WebViewController.swift
1
1196
// // WebViewController.swift // PDFGenerator // // Created by Suguru Kishimoto on 2016/03/23. // // import UIKit import WebKit import PDFGenerator class WebViewController: UIViewController { @IBOutlet fileprivate weak var webView: WKWebView! override func viewDidLoad() { super.viewDidLoad() let req = NSMutableURLRequest(url: URL(string: "http://www.yahoo.co.jp")!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 60) webView.load(req as URLRequest) } @IBAction func generatePDF() { do { let dst = NSHomeDirectory() + "/sample_tblview.pdf" try PDFGenerator.generate(webView, to: dst) openPDFViewer(dst) } catch let error { print(error) } } fileprivate func openPDFViewer(_ pdfPath: String) { self.performSegue(withIdentifier: "PreviewVC", sender: pdfPath) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let pdfPreviewVC = segue.destination as? PDFPreviewVC, let pdfPath = sender as? String { let url = URL(fileURLWithPath: pdfPath) pdfPreviewVC.setupWithURL(url) } } }
mit
e213921039e29c3f262e135b7d5728a8
26.181818
142
0.642977
4.364964
false
false
false
false
eneko/DSAA
DSAATests/DataStructures/ListTests.swift
1
7973
// // ListTests.swift // DSAA // // Created by Eneko Alonso on 2/11/16. // Copyright © 2016 Eneko Alonso. All rights reserved. // import XCTest @testable import DSAA class ListTests: XCTestCase { func testEmpty() { let list = List<Int>() XCTAssertTrue(list.isEmpty()) } func testEmptyCount() { let list = List<Int>() XCTAssertEqual(list.count(), 0) } func testEmptyFirst() { let list = List<Int>() XCTAssertNil(list.first()) } func testEmptyLast() { let list = List<Int>() XCTAssertNil(list.last()) } func testInsert() { var list = List<Int>() list.insertAt(0, element: 1) list.insertAt(0, element: 2) list.insertAt(0, element: 3) XCTAssertEqual(list.first(), 3) XCTAssertEqual(list.elementAt(0), 3) XCTAssertEqual(list.elementAt(1), 2) XCTAssertEqual(list.elementAt(2), 1) } func testInsertMiddle() { var list = List<Int>() list.insertAt(0, element: 1) list.insertAt(1, element: 2) list.insertAt(1, element: 3) XCTAssertEqual(list.first(), 1) XCTAssertEqual(list.elementAt(0), 1) XCTAssertEqual(list.elementAt(1), 3) XCTAssertEqual(list.elementAt(2), 2) } func testInsertAtEnd() { var list = List<Int>() list.insertAt(0, element: 1) list.insertAt(1, element: 2) list.insertAt(2, element: 3) XCTAssertEqual(list.first(), 1) XCTAssertEqual(list.elementAt(0), 1) XCTAssertEqual(list.elementAt(1), 2) XCTAssertEqual(list.elementAt(2), 3) } func testEmptyRemoveFirst() { var list = List<Int>() XCTAssertNil(list.removeFirst()) } func testRemoveFirst() { var list = List<Int>() list.append(1) list.append(1) list.append(2) list.append(3) list.append(5) list.append(8) XCTAssertEqual(list.removeFirst(), 1) XCTAssertEqual(list.removeFirst(), 1) XCTAssertEqual(list.removeFirst(), 2) XCTAssertEqual(list.removeFirst(), 3) XCTAssertEqual(list.removeFirst(), 5) XCTAssertEqual(list.removeFirst(), 8) XCTAssertNil(list.removeFirst()) } func testEmptyRemoveLast() { var list = List<Int>() XCTAssertNil(list.removeLast()) } func testRemoveLast() { var list = List<Int>() list.append(1) list.append(1) list.append(2) list.append(3) list.append(5) list.append(8) XCTAssertEqual(list.removeLast(), 8) XCTAssertEqual(list.removeLast(), 5) XCTAssertEqual(list.removeLast(), 3) XCTAssertEqual(list.removeLast(), 2) XCTAssertEqual(list.removeLast(), 1) XCTAssertEqual(list.removeLast(), 1) XCTAssertNil(list.removeLast()) } func testRemoveAt() { var list = List<Int>() list.append(1) list.append(2) list.append(3) XCTAssertEqual(list.removeAt(0), 1) XCTAssertEqual(list.removeAt(1), 3) XCTAssertEqual(list.removeAt(0), 2) XCTAssertNil(list.removeAt(1)) } func testRemoveAtEmpty() { var list = List<Int>() XCTAssertNil(list.removeAt(0)) } func testCompareEqualLists() { var listA = List<Int>() listA.append(1) listA.append(2) listA.append(3) listA.append(4) var listB = List<Int>() listB.insertAt(0, element: 4) listB.insertAt(0, element: 3) listB.insertAt(0, element: 2) listB.insertAt(0, element: 1) XCTAssertEqual(listA, listB) } func testCompareDifferentValueLists() { var listA = List<Int>() listA.append(1) listA.append(2) listA.append(3) listA.append(4) var listB = List<Int>() listB.insertAt(0, element: 4) listB.insertAt(0, element: 4) listB.insertAt(0, element: 4) listB.insertAt(0, element: 4) XCTAssertNotEqual(listA, listB) } func testCompareDifferentLengthLists() { var listA = List<Int>() listA.append(1) listA.append(2) listA.append(3) listA.append(4) var listB = List<Int>() listB.append(1) listB.append(2) listB.append(3) XCTAssertNotEqual(listA, listB) } /// Find last element on a list /// Source: Problem 1, 99-scala problems (http://aperiodic.net/phil/scala/s-99) func testFindLast() { var list = List<Int>() list.append(1) list.append(1) list.append(2) list.append(3) list.append(5) list.append(8) XCTAssertEqual(list.last(), 8) } /// Find the last but one element on a list /// Source: Problem 2, 99-scala problems (http://aperiodic.net/phil/scala/s-99) func testFindPenultimate() { var list = List<Int>() list.append(1) list.append(1) list.append(2) list.append(3) list.append(5) list.append(8) let count = list.count() XCTAssertEqual(list.elementAt(count - 2), 5) } /// Find the nth element on a list /// Source: Problem 3, 99-scala problems (http://aperiodic.net/phil/scala/s-99) func testFindNth() { var list = List<Int>() list.append(1) list.append(1) list.append(2) list.append(3) list.append(5) list.append(8) XCTAssertEqual(list.elementAt(2), 2) XCTAssertEqual(list.elementAt(5), 8) XCTAssertNil(list.elementAt(6)) } /// Find the number of elements on a list /// Source: Problem 4, 99-scala problems (http://aperiodic.net/phil/scala/s-99) func testCount() { var list = List<Int>() list.append(1) list.append(1) list.append(2) list.append(3) list.append(5) list.append(8) XCTAssertEqual(list.count(), 6) } /// Reverse a list /// Source: Problem 5, 99-scala problems (http://aperiodic.net/phil/scala/s-99) func testReverse() { var list = List<Int>() list.append(1) list.append(1) list.append(2) list.append(3) list.append(5) list.append(8) list.reverse() XCTAssertEqual(list.elementAt(0), 8) XCTAssertEqual(list.elementAt(1), 5) XCTAssertEqual(list.elementAt(2), 3) XCTAssertEqual(list.elementAt(3), 2) XCTAssertEqual(list.elementAt(4), 1) XCTAssertEqual(list.elementAt(5), 1) } func testReverseEmpty() { var list = List<Int>() list.reverse() XCTAssertNil(list.first()) } func testReverseOne() { var list = List<Int>() list.append(1) list.reverse() XCTAssertEqual(list.first(), 1) } func testCopyEmpty() { let list = List<Int>() XCTAssertEqual(list, list.copy()) } func testCopy() { var list = List<Int>() list.append(1) list.append(1) list.append(2) list.append(3) list.append(5) list.append(8) XCTAssertEqual(list, list.copy()) } /// Find out whether a list is a palindrome /// Source: Problem 6, 99-scala problems (http://aperiodic.net/phil/scala/s-99) func testPalindrome() { var list = List<Int>() list.append(1) list.append(2) list.append(3) list.append(2) list.append(1) var copy = list.copy() copy.reverse() XCTAssertEqual(list, copy) } func testNotPalindrome() { var list = List<Int>() list.append(1) list.append(2) list.append(3) list.append(2) list.append(2) var copy = list.copy() copy.reverse() XCTAssertNotEqual(list, copy) } }
mit
d2d24b340ec3559910d92dd8e8fcb722
25.662207
83
0.562845
3.762152
false
true
false
false
zhuxietong/Eelay
Sources/Eelay/object/NSDictionary+snyc.swift
1
4021
// // NSDictionary+snyc.swift // // Created by 朱撷潼 on 15/3/12. // Copyright (c) 2015年 zhuxietong. All rights reserved. // import Foundation public typealias SnycBlock = (_:NSDictionaryChangeInfo) -> Void public struct SyncScheme { public let keys:[String] public let primaryKey:String public let table:String public init(keys:[String],primaryKey:String,table:String){ self.keys = keys self.primaryKey = primaryKey self.table = table } } public struct NSDictionaryChangeInfo { public let key:String public let value:Any public let dict:NSMutableDictionary } extension NSMutableDictionary{ public var snycBlock:SnycBlock?{ get{ return syncOBJ.snycBlock } set{ syncOBJ.snycBlock = newValue } } public func stopSync() { } public func startSync(scheme:SyncScheme){ syncOBJ.syncScheme = scheme } public func syncUpdate(value:Any,for key:String) { self.setValue(value, forKey: key) guard let scheme = syncOBJ.syncScheme else { return } guard let primaryValue = self.value(forKey: scheme.primaryKey) else { return } let notice = "NSMutableDictionary.\(scheme.table).change.\(scheme.primaryKey)=\(primaryValue)" let change = NSDictionaryChangeInfo(key: key, value: value, dict: self) NotificationCenter.default.post(name: notice.__notice_name, object: change) } private struct ValueAssociatedKeys { static var valueObserver = "valueObserver" } var syncOBJ: ValueObserver { get { let v = objc_getAssociatedObject(self, &ValueAssociatedKeys.valueObserver) as? ValueObserver if let v_ = v{ return v_ }else{ let obs = ValueObserver() obs.obj = self objc_setAssociatedObject(self, &ValueAssociatedKeys.valueObserver, obs, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) return obs } } } } class ValueObserver:NSObject{ override init() { super.init() } @objc func changeValue(_ notify:Notification){ guard let scheme = syncScheme,let dict = obj else { return } if let info = notify.object as? NSDictionaryChangeInfo{ if scheme.keys.contains(info.key){ dict[info.key] = info.value snycBlock?(info) } } } var syncScheme:SyncScheme? = nil{ didSet{ updateObserver() } } var snycBlock:SnycBlock? = nil var observerKey:String? = nil{ didSet{ if let oldV = oldValue{ NotificationCenter.default.removeObserver(self, name: oldV.__notice_name, object: nil) } if let newV = observerKey{ NotificationCenter.default.addObserver(self, selector: #selector(changeValue(_:)), name: newV.__notice_name, object: nil) } } } weak var obj:NSMutableDictionary? = nil{ didSet{ updateObserver() } } func updateObserver() { guard let obj_ = obj, let scheme = syncScheme else { return } guard let primaryValue = obj_.value(forKey: scheme.primaryKey) else { return } let notice = "NSMutableDictionary.\(scheme.table).change.\(scheme.primaryKey)=\(primaryValue)" observerKey = notice } func removeObserver() { NotificationCenter.default.removeObserver(self, name: observerKey?.__notice_name, object: nil) observerKey = nil } deinit { removeObserver() } } extension String{ var __notice_name:NSNotification.Name{ get{ return NSNotification.Name(rawValue: self) } } }
mit
8d82ee3fd78d43be9b410dfbb6528625
24.890323
147
0.578619
4.628604
false
false
false
false
kuznetsovVladislav/KVSpinnerView
KVSpinnerView/Layers/ProgressLayer.swift
1
652
// // ProgressLayer.swift // CALayer // // Created by Владислав on 31.01.17. // Copyright © 2017 Владислав . All rights reserved. // import UIKit class ProgressLayer: CATextLayer { var progress: CGFloat = 0 override init() { super.init() string = "\(progress)" // foregroundColor = KVSpinnerViewSettings.progressTextColor.cgColor frame = CGRect(x: 0, y: 0, width: 100, height: 40) fontSize = 24.0 alignmentMode = kCAAlignmentJustified } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
c513c6cf679cb3e32f499e362d775a7e
21.607143
75
0.619273
3.907407
false
false
false
false
actilot/tesseract-swift
Source/Tesseract/Extensions/UIViewExtensions.swift
1
2582
// // UIViewExtensions.swift // Tesseract // // Created by Axel Ros Campaña on 9/14/17. // Copyright © 2017 Axel Ros Campaña. All rights reserved. // import Foundation public extension UIView { var parentStackView: UIStackView? { var parentResponder: UIResponder? = self while parentResponder != nil { parentResponder = parentResponder!.next if let stackView = parentResponder as? UIStackView { return stackView } } return nil } var parentViewController: UIViewController? { var parentResponder: UIResponder? = self while parentResponder != nil { parentResponder = parentResponder!.next if let viewController = parentResponder as? UIViewController { return viewController } } return nil } func generateImage() -> UIImage? { UIGraphicsBeginImageContextWithOptions(self.frame.size, false, UIScreen.main.scale) self.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } func hideAnimated(completion: (()->())? = nil) { if isHidden { return } UIView.animate(withDuration: 0.3, animations: { self.alpha = 0.0 }) { Bool in self.isHidden = true completion?() } } func showAnimated(completion: (()->())? = nil) { if !isHidden { return } self.alpha = 0.0 self.isHidden = false UIView.animate(withDuration: 0.3, animations: { self.alpha = 1.0 }) { Bool in completion?() } } func changeBackgroundColorAnimated(_ color: UIColor) { UIView.animate(withDuration: 0.3) { self.backgroundColor = color } } func addShadow(_ opacity: CGFloat = 0.4, radius: CGFloat = 7.0) { self.layer.shadowColor = UIColor.gray.cgColor self.layer.shadowOpacity = Float(opacity) self.layer.shadowOffset = CGSize.zero self.layer.shadowRadius = radius } @available(iOS 11.0, *) func setCustomSpacingInStackSuperview(_ spacing: CGFloat, animated: Bool = false) { guard let stack = self.superview as? UIStackView else { return } UIView.animate(withDuration: animated ? 0.3 : 0.0) { stack.setCustomSpacing(spacing, after: self) } } }
mit
7ab436cb152b97fa399a1fbb1f421c60
27.032609
91
0.581233
5.046967
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/CognitoIdentityProvider/CognitoIdentityProvider_Paginator.swift
1
24906
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore // MARK: Paginators extension CognitoIdentityProvider { /// Lists the groups that the user belongs to. Calling this action requires developer credentials. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func adminListGroupsForUserPaginator<Result>( _ input: AdminListGroupsForUserRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, AdminListGroupsForUserResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: adminListGroupsForUser, tokenKey: \AdminListGroupsForUserResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func adminListGroupsForUserPaginator( _ input: AdminListGroupsForUserRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (AdminListGroupsForUserResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: adminListGroupsForUser, tokenKey: \AdminListGroupsForUserResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists a history of user activity and any risks detected as part of Amazon Cognito advanced security. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func adminListUserAuthEventsPaginator<Result>( _ input: AdminListUserAuthEventsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, AdminListUserAuthEventsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: adminListUserAuthEvents, tokenKey: \AdminListUserAuthEventsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func adminListUserAuthEventsPaginator( _ input: AdminListUserAuthEventsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (AdminListUserAuthEventsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: adminListUserAuthEvents, tokenKey: \AdminListUserAuthEventsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the groups associated with a user pool. Calling this action requires developer credentials. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listGroupsPaginator<Result>( _ input: ListGroupsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListGroupsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listGroups, tokenKey: \ListGroupsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listGroupsPaginator( _ input: ListGroupsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListGroupsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listGroups, tokenKey: \ListGroupsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists information about all identity providers for a user pool. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listIdentityProvidersPaginator<Result>( _ input: ListIdentityProvidersRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListIdentityProvidersResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listIdentityProviders, tokenKey: \ListIdentityProvidersResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listIdentityProvidersPaginator( _ input: ListIdentityProvidersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListIdentityProvidersResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listIdentityProviders, tokenKey: \ListIdentityProvidersResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the resource servers for a user pool. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listResourceServersPaginator<Result>( _ input: ListResourceServersRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListResourceServersResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listResourceServers, tokenKey: \ListResourceServersResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listResourceServersPaginator( _ input: ListResourceServersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListResourceServersResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listResourceServers, tokenKey: \ListResourceServersResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the clients that have been created for the specified user pool. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listUserPoolClientsPaginator<Result>( _ input: ListUserPoolClientsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListUserPoolClientsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listUserPoolClients, tokenKey: \ListUserPoolClientsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listUserPoolClientsPaginator( _ input: ListUserPoolClientsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListUserPoolClientsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listUserPoolClients, tokenKey: \ListUserPoolClientsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the user pools associated with an AWS account. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listUserPoolsPaginator<Result>( _ input: ListUserPoolsRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListUserPoolsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listUserPools, tokenKey: \ListUserPoolsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listUserPoolsPaginator( _ input: ListUserPoolsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListUserPoolsResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listUserPools, tokenKey: \ListUserPoolsResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Lists the users in the Amazon Cognito user pool. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listUsersPaginator<Result>( _ input: ListUsersRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListUsersResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listUsers, tokenKey: \ListUsersResponse.paginationToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listUsersPaginator( _ input: ListUsersRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListUsersResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listUsers, tokenKey: \ListUsersResponse.paginationToken, on: eventLoop, onPage: onPage ) } /// Lists the users in the specified group. Calling this action requires developer credentials. /// /// Provide paginated results to closure `onPage` for it to combine them into one result. /// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`. /// /// Parameters: /// - input: Input for request /// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called. /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned /// along with a boolean indicating if the paginate operation should continue. public func listUsersInGroupPaginator<Result>( _ input: ListUsersInGroupRequest, _ initialValue: Result, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (Result, ListUsersInGroupResponse, EventLoop) -> EventLoopFuture<(Bool, Result)> ) -> EventLoopFuture<Result> { return client.paginate( input: input, initialValue: initialValue, command: listUsersInGroup, tokenKey: \ListUsersInGroupResponse.nextToken, on: eventLoop, onPage: onPage ) } /// Provide paginated results to closure `onPage`. /// /// - Parameters: /// - input: Input for request /// - logger: Logger used flot logging /// - eventLoop: EventLoop to run this process on /// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue. public func listUsersInGroupPaginator( _ input: ListUsersInGroupRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil, onPage: @escaping (ListUsersInGroupResponse, EventLoop) -> EventLoopFuture<Bool> ) -> EventLoopFuture<Void> { return client.paginate( input: input, command: listUsersInGroup, tokenKey: \ListUsersInGroupResponse.nextToken, on: eventLoop, onPage: onPage ) } } extension CognitoIdentityProvider.AdminListGroupsForUserRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CognitoIdentityProvider.AdminListGroupsForUserRequest { return .init( limit: self.limit, nextToken: token, username: self.username, userPoolId: self.userPoolId ) } } extension CognitoIdentityProvider.AdminListUserAuthEventsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CognitoIdentityProvider.AdminListUserAuthEventsRequest { return .init( maxResults: self.maxResults, nextToken: token, username: self.username, userPoolId: self.userPoolId ) } } extension CognitoIdentityProvider.ListGroupsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CognitoIdentityProvider.ListGroupsRequest { return .init( limit: self.limit, nextToken: token, userPoolId: self.userPoolId ) } } extension CognitoIdentityProvider.ListIdentityProvidersRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CognitoIdentityProvider.ListIdentityProvidersRequest { return .init( maxResults: self.maxResults, nextToken: token, userPoolId: self.userPoolId ) } } extension CognitoIdentityProvider.ListResourceServersRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CognitoIdentityProvider.ListResourceServersRequest { return .init( maxResults: self.maxResults, nextToken: token, userPoolId: self.userPoolId ) } } extension CognitoIdentityProvider.ListUserPoolClientsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CognitoIdentityProvider.ListUserPoolClientsRequest { return .init( maxResults: self.maxResults, nextToken: token, userPoolId: self.userPoolId ) } } extension CognitoIdentityProvider.ListUserPoolsRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CognitoIdentityProvider.ListUserPoolsRequest { return .init( maxResults: self.maxResults, nextToken: token ) } } extension CognitoIdentityProvider.ListUsersRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CognitoIdentityProvider.ListUsersRequest { return .init( attributesToGet: self.attributesToGet, filter: self.filter, limit: self.limit, paginationToken: token, userPoolId: self.userPoolId ) } } extension CognitoIdentityProvider.ListUsersInGroupRequest: AWSPaginateToken { public func usingPaginationToken(_ token: String) -> CognitoIdentityProvider.ListUsersInGroupRequest { return .init( groupName: self.groupName, limit: self.limit, nextToken: token, userPoolId: self.userPoolId ) } }
apache-2.0
b1d863cbe222764fd7abfd90c9497a14
42.390244
168
0.647033
5.07044
false
false
false
false
btanner/Eureka
Source/Core/BaseRow.swift
1
10550
// BaseRow.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 import UIKit open class BaseRow: BaseRowType { //BT for FPS var callbackOnVisChange: (()->Void)? var callbackOnChange: (() -> Void)? var callbackCellUpdate: (() -> Void)? var callbackCellSetup: Any? var callbackCellOnSelection: (() -> Void)? var callbackOnExpandInlineRow: Any? var callbackOnCollapseInlineRow: Any? var callbackOnCellHighlightChanged: (() -> Void)? var callbackOnRowValidationChanged: (() -> Void)? var _inlineRow: BaseRow? var _cachedOptionsData: Any? public var validationOptions: ValidationOptions = .validatesOnBlur // validation state public internal(set) var validationErrors = [ValidationError]() { didSet { guard validationErrors != oldValue else { return } RowDefaults.onRowValidationChanged["\(type(of: self))"]?(baseCell, self) callbackOnRowValidationChanged?() updateCell() } } public internal(set) var wasBlurred = false public internal(set) var wasChanged = false public var isValid: Bool { return validationErrors.isEmpty } public var isHighlighted: Bool = false /// The title will be displayed in the textLabel of the row. public var title: String? /// Parameter used when creating the cell for this row. public var cellStyle = UITableViewCell.CellStyle.value1 /// String that uniquely identifies a row. Must be unique among rows and sections. public var tag: String? /// The untyped cell associated to this row. public var baseCell: BaseCell! { return nil } /// The untyped value of this row. public var baseValue: Any? { set {} get { return nil } } open func validate(quietly: Bool = false) -> [ValidationError] { return [] } // Reset validation open func cleanValidationErrors() { validationErrors = [] } public static var estimatedRowHeight: CGFloat = 44.0 /// Condition that determines if the row should be disabled or not. public var disabled: Condition? { willSet { removeFromDisabledRowObservers() } didSet { addToDisabledRowObservers() } } /// Condition that determines if the row should be hidden or not. public var hidden: Condition? { willSet { removeFromHiddenRowObservers() } didSet { addToHiddenRowObservers() } } /// Returns if this row is currently disabled or not public var isDisabled: Bool { return disabledCache } /// Returns if this row is currently hidden or not public var isHidden: Bool { return hiddenCache } /// The section to which this row belongs. open weak var section: Section? public lazy var trailingSwipe = {[unowned self] in SwipeConfiguration(self)}() //needs the accessor because if marked directly this throws "Stored properties cannot be marked potentially unavailable with '@available'" private lazy var _leadingSwipe = {[unowned self] in SwipeConfiguration(self)}() @available(iOS 11,*) public var leadingSwipe: SwipeConfiguration{ get { return self._leadingSwipe } set { self._leadingSwipe = newValue } } public required init(tag: String? = nil) { self.tag = tag } /** Method that reloads the cell */ open func updateCell() {} /** Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell. */ open func didSelect() {} open func prepare(for segue: UIStoryboardSegue) {} /** Helps to pick destination part of the cell after scrolling */ open var destinationScrollPosition: UITableView.ScrollPosition? = UITableView.ScrollPosition.bottom /** Returns the IndexPath where this row is in the current form. */ public final var indexPath: IndexPath? { guard let sectionIndex = section?.index, let rowIndex = section?.firstIndex(of: self) else { return nil } return IndexPath(row: rowIndex, section: sectionIndex) } //BT for FPS var hiddenCache : Bool = false{ didSet{ callbackOnVisChange?() } } var disabledCache = false { willSet { if newValue && !disabledCache { baseCell.cellResignFirstResponder() } } } } extension BaseRow { /** Evaluates if the row should be hidden or not and updates the form accordingly */ public final func evaluateHidden() { guard let h = hidden, let form = section?.form else { return } switch h { case .function(_, let callback): hiddenCache = callback(form) case .predicate(let predicate): hiddenCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate()) } if hiddenCache { section?.hide(row: self) } else { section?.show(row: self) } } /** Evaluates if the row should be disabled or not and updates it accordingly */ public final func evaluateDisabled() { guard let d = disabled, let form = section?.form else { return } switch d { case .function(_, let callback): disabledCache = callback(form) case .predicate(let predicate): disabledCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate()) } updateCell() } final func wasAddedTo(section: Section) { self.section = section if let t = tag { assert(section.form?.rowsByTag[t] == nil, "Duplicate tag \(t)") self.section?.form?.rowsByTag[t] = self self.section?.form?.tagToValues[t] = baseValue != nil ? baseValue! : NSNull() } addToRowObservers() evaluateHidden() evaluateDisabled() } final func addToHiddenRowObservers() { guard let h = hidden else { return } switch h { case .function(let tags, _): section?.form?.addRowObservers(to: self, rowTags: tags, type: .hidden) case .predicate(let predicate): section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .hidden) } } final func addToDisabledRowObservers() { guard let d = disabled else { return } switch d { case .function(let tags, _): section?.form?.addRowObservers(to: self, rowTags: tags, type: .disabled) case .predicate(let predicate): section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .disabled) } } final func addToRowObservers() { addToHiddenRowObservers() addToDisabledRowObservers() } final func willBeRemovedFromForm() { (self as? BaseInlineRowType)?.collapseInlineRow() if let t = tag { section?.form?.rowsByTag[t] = nil section?.form?.tagToValues[t] = nil } removeFromRowObservers() } final func willBeRemovedFromSection() { willBeRemovedFromForm() section = nil } final func removeFromHiddenRowObservers() { guard let h = hidden else { return } switch h { case .function(let tags, _): section?.form?.removeRowObservers(from: self, rowTags: tags, type: .hidden) case .predicate(let predicate): section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .hidden) } } final func removeFromDisabledRowObservers() { guard let d = disabled else { return } switch d { case .function(let tags, _): section?.form?.removeRowObservers(from: self, rowTags: tags, type: .disabled) case .predicate(let predicate): section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .disabled) } } final func removeFromRowObservers() { removeFromHiddenRowObservers() removeFromDisabledRowObservers() } } extension BaseRow: Equatable, Hidable, Disableable {} extension BaseRow { public func reload(with rowAnimation: UITableView.RowAnimation = .none) { guard let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView, let indexPath = indexPath else { return } tableView.reloadRows(at: [indexPath], with: rowAnimation) } public func deselect(animated: Bool = true) { guard let indexPath = indexPath, let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return } tableView.deselectRow(at: indexPath, animated: animated) } public func select(animated: Bool = false, scrollPosition: UITableView.ScrollPosition = .none) { guard let indexPath = indexPath, let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return } tableView.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition) } } public func == (lhs: BaseRow, rhs: BaseRow) -> Bool { return lhs === rhs }
mit
6ef22e7d0f4be0cedd5f9bf137389850
33.933775
177
0.652796
5.043021
false
false
false
false
grpc/grpc-swift
Tests/GRPCTests/EchoHelpers/Interceptors/EchoInterceptorFactories.swift
1
2889
/* * Copyright 2021, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import EchoModel import GRPC // MARK: - Client internal final class EchoClientInterceptors: Echo_EchoClientInterceptorFactoryProtocol { #if swift(>=5.6) internal typealias Factory = @Sendable () -> ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse> #else internal typealias Factory = () -> ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse> #endif // swift(>=5.6) private let factories: [Factory] internal init(_ factories: Factory...) { self.factories = factories } private func makeInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.factories.map { $0() } } func makeGetInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeExpandInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeCollectInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeUpdateInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } } // MARK: - Server internal final class EchoServerInterceptors: Echo_EchoServerInterceptorFactoryProtocol { internal typealias Factory = () -> ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse> private var factories: [Factory] = [] internal init(_ factories: Factory...) { self.factories = factories } internal func register(_ factory: @escaping Factory) { self.factories.append(factory) } private func makeInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.factories.map { $0() } } func makeGetInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeExpandInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeCollectInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } func makeUpdateInterceptors() -> [ServerInterceptor<Echo_EchoRequest, Echo_EchoResponse>] { return self.makeInterceptors() } }
apache-2.0
7249bf1cd77cc95deda00f3c059dbbae
31.829545
95
0.734856
4.444615
false
false
false
false
jpush/jchat-swift
JChat/Src/ChatModule/Chat/View/JCChatViewLayout.swift
1
14010
// // JCChatViewLayout.swift // JChat // // Created by JIGUANG on 2017/2/28. // Copyright © 2017年 HXHG. All rights reserved. // import UIKit @objc open class JCChatViewLayout: UICollectionViewFlowLayout { public override init() { super.init() _commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _commonInit() } internal weak var _chatView: JCChatView? open override class var layoutAttributesClass: AnyClass { return JCChatViewLayoutAttributes.self } open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { let attributes = super.layoutAttributesForItem(at: indexPath) if let attributes = attributes as? JCChatViewLayoutAttributes, attributes.info == nil { attributes.info = layoutAttributesInfoForItem(at: indexPath) } return attributes } open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let arr = super.layoutAttributesForElements(in: rect) arr?.forEach({ guard let attributes = $0 as? JCChatViewLayoutAttributes, attributes.info == nil else { return } attributes.info = layoutAttributesInfoForItem(at: attributes.indexPath) }) return arr } open func layoutAttributesInfoForItem(at indexPath: IndexPath) -> JCChatViewLayoutAttributesInfo? { guard let collectionView = collectionView, let _ = collectionView.delegate as? JCChatViewLayoutDelegate, let message = _message(at: indexPath) else { return nil } let size = CGSize(width: collectionView.frame.width, height: .greatestFiniteMagnitude) if let info = _allLayoutAttributesInfo[message.identifier] { // 这不是合理的做法 if !message.updateSizeIfNeeded { return info } } let options = message.options var allRect: CGRect = .zero var allBoxRect: CGRect = .zero var cardRect: CGRect = .zero var cardBoxRect: CGRect = .zero var avatarRect: CGRect = .zero var avatarBoxRect: CGRect = .zero var bubbleRect: CGRect = .zero var bubbleBoxRect: CGRect = .zero var contentRect: CGRect = .zero var contentBoxRect: CGRect = .zero var tipsRect: CGRect = .zero var tipsBoxRect: CGRect = .zero // 计算的时候以左对齐为基准 // +---------------------------------------+ r0 // |+---------------------------------+ r1 | // ||+---+ <NAME> | | // ||| A | +---------------------\ r4 | | // ||+---+ |+---------------+ r5 | | | // || || CONTENT | | | | // || |+---------------+ | | | // || \---------------------/ | | +---+ r6 // |+---------------------------------+ <-|- | ! | // +---------------------------------------+ +---+ let edg0 = _inset(with: options.style, for: .all) var r0 = CGRect(x: 0, y: 0, width: size.width, height: .greatestFiniteMagnitude) var r1 = r0.inset(by: edg0) var x1 = r1.minX var y1 = r1.minY var x2 = r1.maxX var y2 = r1.maxY if options.showsAvatar { let edg = _inset(with: options.style, for: .avatar) let size = _size(with: options.style, for: .avatar) let box = CGRect(x: x1, y: y1, width: edg.left + size.width + edg.right, height: edg.top + size.height + edg.bottom) let rect = box.inset(by: edg) avatarRect = rect avatarBoxRect = box x1 = box.maxX } if options.showsCard { let edg = _inset(with: options.style, for: .card) let size = _size(with: options.style, for: .card) let box = CGRect(x: x1, y: y1, width: x2 - x1, height: edg.top + size.height + edg.bottom) let rect = box.inset(by: edg) cardRect = rect cardBoxRect = box y1 = box.maxY } if options.showsBubble { let edg = _inset(with: options.style, for: .bubble) let box = CGRect(x: x1, y: y1, width: x2 - x1, height: y2 - y1) let rect = box.inset(by: edg) bubbleRect = rect bubbleBoxRect = box x1 = rect.minX x2 = rect.maxX y1 = rect.minY y2 = rect.maxY } if true { let edg0 = _inset(with: options.style, for: .content) let edg1 = message.content.layoutMargins // let edg = UIEdgeInsets.init(top: edg0.top + edg1.top, left: edg0.left + edg1.left, bottom: edg0.bottom + edg1.bottom, right: edg0.right + edg1.right) var box = CGRect(x: x1, y: y1, width: x2 - x1, height: y2 - y1) var rect = box.inset(by: edg) // calc content size let size = message.content.sizeThatFits(rect.size) // restore offset box.size.width = edg.left + size.width + edg.right box.size.height = edg.top + size.height + edg.bottom rect.size.width = size.width rect.size.height = size.height contentRect = rect contentBoxRect = box x1 = box.maxX y1 = box.maxY } if options.showsBubble { let edg = _inset(with: options.style, for: .bubble) bubbleRect.size.width = contentBoxRect.width bubbleRect.size.height = contentBoxRect.height bubbleBoxRect.size.width = edg.left + contentBoxRect.width + edg.right bubbleBoxRect.size.height = edg.top + contentBoxRect.height + edg.bottom } if options.showsTips { let edg = _inset(with: options.style, for: .tips) let size = _size(with: options.style, for: .tips) let box = CGRect(x: x1 + 3, y: y1 - size.height - edg0.bottom, width: edg.left + size.width + edg.right, height: edg.top + size.height + edg.bottom) let rect = box.inset(by: edg) tipsRect = rect tipsBoxRect = box x1 = box.maxX } // adjust r1.size.width = x1 - r1.minX r1.size.height = y1 - r1.minY r0.size.width = x1 r0.size.height = y1 + edg0.bottom allRect = r1 allBoxRect = r0 // algin switch options.alignment { case .right: // to right allRect.origin.x = size.width - allRect.maxX allBoxRect.origin.x = size.width - allBoxRect.maxX cardRect.origin.x = size.width - cardRect.maxX cardBoxRect.origin.x = size.width - cardBoxRect.maxX avatarRect.origin.x = size.width - avatarRect.maxX avatarBoxRect.origin.x = size.width - avatarBoxRect.maxX bubbleRect.origin.x = size.width - bubbleRect.maxX bubbleBoxRect.origin.x = size.width - bubbleBoxRect.maxX contentRect.origin.x = size.width - contentRect.maxX contentBoxRect.origin.x = size.width - contentBoxRect.maxX tipsRect.origin.x = size.width - tipsRect.maxX tipsBoxRect.origin.x = size.width - tipsBoxRect.maxX case .center: allRect.origin.x = (size.width - allRect.width) / 2 allBoxRect.origin.x = (size.width - allBoxRect.width) / 2 bubbleRect.origin.x = (size.width - bubbleRect.width) / 2 bubbleBoxRect.origin.x = (size.width - bubbleBoxRect.width) / 2 contentRect.origin.x = (size.width - contentRect.width) / 2 contentBoxRect.origin.x = (size.width - contentBoxRect.width) / 2 case .left: break } // save let rects: [JCChatViewLayoutItem: CGRect] = [ .all: allRect, .card: cardRect, .avatar: avatarRect, .bubble: bubbleRect, .content: contentRect, .tips: tipsRect ] let boxRects: [JCChatViewLayoutItem: CGRect] = [ .all: allBoxRect, .card: cardBoxRect, .avatar: avatarBoxRect, .bubble: bubbleBoxRect, .content: contentBoxRect, .tips: tipsBoxRect ] let info = JCChatViewLayoutAttributesInfo(message: message, size: size, rects: rects, boxRects: boxRects) _allLayoutAttributesInfo[message.identifier] = info return info } private func _size(with style: JCMessageStyle, for item: JCChatViewLayoutItem) -> CGSize { let key = "\(style.rawValue)-\(item.rawValue)" if let size = _cachedAllLayoutSize[key] { return size // hit cache } var size: CGSize? if let collectionView = collectionView, let delegate = collectionView.delegate as? JCChatViewLayoutDelegate { switch item { case .all: size = .zero case .card: size = delegate.collectionView?(collectionView, layout: self, sizeForItemCardOf: style) case .avatar: size = delegate.collectionView?(collectionView, layout: self, sizeForItemAvatarOf: style) case .bubble: size = .zero case .content: size = .zero case .tips: size = delegate.collectionView?(collectionView, layout: self, sizeForItemTipsOf: style) } } _cachedAllLayoutSize[key] = size ?? .zero return size ?? .zero } private func _inset(with style: JCMessageStyle, for item: JCChatViewLayoutItem) -> UIEdgeInsets { let key = "\(style.rawValue)-\(item.rawValue)" if let edg = _cachedAllLayoutInset[key] { return edg // hit cache } var edg: UIEdgeInsets? if let collectionView = collectionView, let delegate = collectionView.delegate as? JCChatViewLayoutDelegate { switch item { case .all: edg = delegate.collectionView?(collectionView, layout: self, insetForItemOf: style) case .card: edg = delegate.collectionView?(collectionView, layout: self, insetForItemCardOf: style) case .tips: edg = delegate.collectionView?(collectionView, layout: self, insetForItemTipsOf: style) case .avatar: edg = delegate.collectionView?(collectionView, layout: self, insetForItemAvatarOf: style) case .bubble: edg = delegate.collectionView?(collectionView, layout: self, insetForItemBubbleOf: style) case .content: edg = delegate.collectionView?(collectionView, layout: self, insetForItemContentOf: style) } } _cachedAllLayoutInset[key] = edg ?? .zero return edg ?? .zero } private func _message(at indexPath: IndexPath) -> JCMessageType? { guard let collectionView = collectionView, let delegate = collectionView.delegate as? JCChatViewLayoutDelegate else { return nil } return delegate.collectionView(collectionView, layout: self, itemAt: indexPath) } private func _commonInit() { minimumLineSpacing = 0 minimumInteritemSpacing = 0 } private lazy var _cachedAllLayoutSize: [String: CGSize] = [:] private lazy var _cachedAllLayoutInset: [String: UIEdgeInsets] = [:] private lazy var _allLayoutAttributesInfo: [UUID: JCChatViewLayoutAttributesInfo] = [:] } @objc public protocol JCChatViewLayoutDelegate: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, itemAt indexPath: IndexPath) -> JCMessageType @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemCardOf style: JCMessageStyle) -> CGSize @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemTipsOf style: JCMessageStyle) -> CGSize @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAvatarOf style: JCMessageStyle) -> CGSize @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForItemOf style: JCMessageStyle) -> UIEdgeInsets @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForItemCardOf style: JCMessageStyle) -> UIEdgeInsets @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForItemTipsOf style: JCMessageStyle) -> UIEdgeInsets @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForItemAvatarOf style: JCMessageStyle) -> UIEdgeInsets @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForItemBubbleOf style: JCMessageStyle) -> UIEdgeInsets @objc optional func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForItemContentOf style: JCMessageStyle) -> UIEdgeInsets }
mit
107adbc01c3886ae1afa5cf946afbfac
42.108025
188
0.587027
4.549511
false
false
false
false
dymx101/Gamers
Gamers/Dao/SystemDao.swift
1
1395
// // SystemDao.swift // Gamers // // Created by 虚空之翼 on 15/9/1. // Copyright (c) 2015年 Freedom. All rights reserved. // import UIKit import Alamofire import Bolts import SwiftyJSON struct SystemDao {} extension SystemDao { // 获取版本信息 static func getVersion() -> BFTask { var URLRequest = Router.Version() return fetchVersion(URLRequest: URLRequest) } // 解析版本JSON结构 private static func fetchVersion(#URLRequest: URLRequestConvertible) -> BFTask { var source = BFTaskCompletionSource() Alamofire.request(URLRequest).responseJSON { (_, _, JSONDictionary, error) in if error == nil { if let JSONDictionary: AnyObject = JSONDictionary { if JSON(JSONDictionary)["errCode"] == nil { let version = Version.collection(json: JSON(JSONDictionary)) source.setResult(version) } else { let response = Response.collection(json: JSON(JSONDictionary)) source.setResult(response) } } else { source.setResult(Response()) } } else { source.setError(error) } } return source.task } }
apache-2.0
ed2587496c99877113bb5f813ce2aef7
25.686275
86
0.531227
5.174905
false
false
false
false
developerY/Swift2_Playgrounds
GuidedTour.playground/Pages/Functions and Closures.xcplaygroundpage/Contents.swift
1
5786
//: ## Functions and Closures //: //: Use `func` to declare a function. Call a function by following its name with a list of arguments in parentheses. Use `->` to separate the parameter names and types from the function’s return type. //: //: ### Functions and Methods //: //: A _function_ is a reusable, named piece of code that can be referred to from many places in a program. //: //: Use `func` to declare a function. A function declaration can include zero or more _parameters_, written as `name: Type`, which are additional pieces of information that must be passed into the function when it’s called. Optionally, a function can have a return type, written after the `->`, which indicates what the function returns as its result. A function’s implementation goes inside of a pair of curly braces (`{}`). func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } //: Call a function by following its name with a list of _arguments_ (the values you pass in to satisfy a function’s parameters) in parentheses. When you call a function, you pass in the first argument value without writing its name, and every subsequent value with its name. //: greet("Anna", day: "Tuesday") greet("Bob", day: "Friday") greet("Charlie", day: "a nice day") //: > **Experiment**: //: > Remove the `day` parameter. Add a parameter to include today’s lunch special in the greeting. //: //: Functions that are defined within a specific type are called _methods_. Methods are explicitly tied to the type they’re defined in, and can only be called on that type (or one of its subclasses, as you’ll learn about soon). In the earlier `switch` statement example, you saw a method that’s defined on the `String` type called `hasSuffix()`, shown again here: //: let exampleString = "hello" if exampleString.hasSuffix("lo") { print("ends in lo") } //: As you see, you call a method using the dot syntax. When you call a method, you pass in the first argument value without writing its name, and every subsequent value with its name. For example, this method on `Array` takes two parameters, and you only pass in the name for the second one: //: var array = ["apple", "banana", "dragonfruit"] array.insert("cherry", atIndex: 2) array //: //: Use a tuple to make a compound value—for example, to return multiple values from a function. The elements of a tuple can be referred to either by name or by number. //: func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sumNum: Int) { var min = scores[0] var max = 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) } let statistics = calculateStatistics([5, 3, 100, 3, 9]) print(statistics.sumNum) print(statistics.2) statistics.max;statistics.min;statistics.sumNum //: Functions can also take a variable number of arguments, collecting them into an array. //: func sumOf(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum } sumOf() sumOf(42, 597, 12) //: > **Experiment**: //: > Write a function that calculates the average of its arguments. //: //: Functions can be nested. Nested functions have access to variables that were declared in the outer function. You can use nested functions to organize the code in a function that is long or complex. //: func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y } returnFifteen() //: Functions are a first-class type. This means that a function can return another function as its value. //: func makeIncrementer() -> (Int -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7) //: A function can take another function as one of its arguments. //: func hasAnyMatches(list: [Int], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers, condition: lessThanTen) //: Functions are actually a special case of closures: blocks of code that can be called later. The code in a closure has access to things like variables and functions that were available in the scope where the closure was created, even if the closure is in a different scope when it is executed—you saw an example of this already with nested functions. You can write a closure without a name by surrounding code with braces (`{}`). Use `in` to separate the arguments and return type from the body. //: numbers.map({ (number: Int) -> Int in let result = 3 * number return result }) //: > **Experiment**: //: > Rewrite the closure to return zero for all odd numbers. //: //: You have several options for writing closures more concisely. When a closure’s type is already known, such as the callback for a delegate, you can omit the type of its parameters, its return type, or both. Single statement closures implicitly return the value of their only statement. //: let mappedNumbers = numbers.map({ number in 3 * number }) print(mappedNumbers) //: You can refer to parameters by number instead of by name—this approach is especially useful in very short closures. A closure passed as the last argument to a function can appear immediately after the parentheses. When a closure is the only argument to a function, you can omit the parentheses entirely. //: let sortedNumbers = numbers.sort { $0 > $1 } print(sortedNumbers) //: [Previous](@previous) | [Next](@next)
mit
b32b4ef3c373d4ec5338db52b7d5bdde
39.293706
498
0.698716
4.103989
false
false
false
false
salesforce-ux/design-system-ios
Demo-Swift/slds-sample-app/demo/controllers/AccountMasterListViewController.swift
1
6180
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license import UIKit enum AccountType : String { case direct = "Customer - Direct" case channel = "Customer - Channel" } struct AccountObject { var name : String! var state : String! var phone : String! var type : AccountType! var owner : String! var industry : String! var number : String! var url : String! } class AccountMasterListViewController: UITableViewController { var superNavigationController : UINavigationController! let accounts = [ AccountObject(name: "Burlington Textiles Corp of America", state: "NC", phone: "(336) 222-7000", type: .direct, owner: "Joe Green", industry: "Apparel", number: "CD656092", url: "www.burlington.com"), AccountObject(name: "Dickenson Plc", state: "KS", phone: "(785) 241-6200", type: .channel, owner: "Joe Green", industry: "Consulting", number: "CC634267", url: "dickenson-consulting.com"), AccountObject(name: "Edge Communications", state: "TX", phone: "(512) 757-6000", type: .direct, owner: "Joe Green", industry: "Electronics", number: "CD451796", url: "www.edgecomm.com"), AccountObject(name: "Express Logistics and Transport", state: "OR", phone: "(503) 421-7800", type: .channel, owner: "Joe Green", industry: "Transportation", number: "CC947211", url: "www.expresslandt.net"), AccountObject(name: "GenePoint", state: "CA", phone: "(650) 867-3450", type: .channel, owner: "Joe Green", industry: "Biotechnology", number: "CC978213", url: "www.genepoint.com") ] //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func viewDidLoad() { super.viewDidLoad() self.tableView.separatorInset = UIEdgeInsets.zero self.tableView.separatorColor = UIColor.sldsBorderColor(.colorBorderSeparatorAlt) self.tableView.register(AccountMasterCell.self, forCellReuseIdentifier: "cell") } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– func popController() { NotificationCenter.default.post(name: NSNotification.Name("returnToLibrary"), object: self) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return accounts.count } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 150 } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let controller = AccountDetailViewController() controller.dataProvider = accounts[indexPath.item] self.superNavigationController.pushViewController(controller, animated: true) } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> AccountMasterCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AccountMasterCell cell.dataProvider = accounts[indexPath.item] return cell } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– }
bsd-3-clause
ee4143a3df293ae734e517432b9543e1
36.363636
111
0.477494
5.857482
false
false
false
false
brentdax/swift
test/decl/var/properties.swift
1
32449
// RUN: %target-typecheck-verify-swift func markUsed<T>(_ t: T) {} struct X { } var _x: X class SomeClass {} func takeTrailingClosure(_ fn: () -> ()) -> Int {} func takeIntTrailingClosure(_ fn: () -> Int) -> Int {} //===--- // Stored properties //===--- var stored_prop_1: Int = 0 var stored_prop_2: Int = takeTrailingClosure {} //===--- // Computed properties -- basic parsing //===--- var a1: X { get { return _x } } var a2: X { get { return _x } set { _x = newValue } } var a3: X { get { return _x } set(newValue) { _x = newValue } } var a4: X { set { _x = newValue } get { return _x } } var a5: X { set(newValue) { _x = newValue } get { return _x } } // Reading/writing properties func accept_x(_ x: X) { } func accept_x_inout(_ x: inout X) { } func test_global_properties(_ x: X) { accept_x(a1) accept_x(a2) accept_x(a3) accept_x(a4) accept_x(a5) a1 = x // expected-error {{cannot assign to value: 'a1' is a get-only property}} a2 = x a3 = x a4 = x a5 = x accept_x_inout(&a1) // expected-error {{cannot pass immutable value as inout argument: 'a1' is a get-only property}} accept_x_inout(&a2) accept_x_inout(&a3) accept_x_inout(&a4) accept_x_inout(&a5) } //===--- Implicit 'get'. var implicitGet1: X { return _x } var implicitGet2: Int { var zzz = 0 // For the purpose of this test, any other function attribute work as well. @inline(__always) func foo() {} return 0 } var implicitGet3: Int { @inline(__always) func foo() {} return 0 } // Here we used apply weak to the getter itself, not to the variable. var x15: Int { // For the purpose of this test we need to use an attribute that cannot be // applied to the getter. weak var foo: SomeClass? = SomeClass() // expected-warning {{variable 'foo' was written to, but never read}} // expected-warning@-1 {{instance will be immediately deallocated because variable 'foo' is 'weak'}} // expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}} // expected-note@-3 {{'foo' declared here}} return 0 } // Disambiguated as stored property with a trailing closure in the initializer. // var disambiguateGetSet1a: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} get {} } var disambiguateGetSet1b: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} get { return 42 } } var disambiguateGetSet1c: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} set {} // expected-error {{variable with a setter must also have a getter}} } var disambiguateGetSet1d: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} set(newValue) {} // expected-error {{variable with a setter must also have a getter}} } // Disambiguated as stored property with a trailing closure in the initializer. func disambiguateGetSet2() { func get(_ fn: () -> ()) {} var a: Int = takeTrailingClosure { get {} } // Check that the property is read-write. a = a + 42 } func disambiguateGetSet2Attr() { func get(_ fn: () -> ()) {} var a: Int = takeTrailingClosure { @inline(__always) func foo() {} get {} } // Check that the property is read-write. a = a + 42 } // Disambiguated as stored property with a trailing closure in the initializer. func disambiguateGetSet3() { func set(_ fn: () -> ()) {} var a: Int = takeTrailingClosure { set {} } // Check that the property is read-write. a = a + 42 } func disambiguateGetSet3Attr() { func set(_ fn: () -> ()) {} var a: Int = takeTrailingClosure { @inline(__always) func foo() {} set {} } // Check that the property is read-write. a = a + 42 } // Disambiguated as stored property with a trailing closure in the initializer. func disambiguateGetSet4() { func set(_ x: Int, fn: () -> ()) {} let newValue: Int = 0 var a: Int = takeTrailingClosure { set(newValue) {} } // Check that the property is read-write. a = a + 42 } func disambiguateGetSet4Attr() { func set(_ x: Int, fn: () -> ()) {} var newValue: Int = 0 var a: Int = takeTrailingClosure { @inline(__always) func foo() {} set(newValue) {} } // Check that the property is read-write. a = a + 42 } // Disambiguated as stored property with a trailing closure in the initializer. var disambiguateImplicitGet1: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}} return 42 } var disambiguateImplicitGet2: Int = takeIntTrailingClosure { return 42 } //===--- // Observed properties //===--- class C { var prop1 = 42 { didSet { } } var prop2 = false { willSet { } } var prop3: Int? = nil { didSet { } } var prop4: Bool? = nil { willSet { } } } protocol TrivialInit { init() } class CT<T : TrivialInit> { var prop1 = 42 { didSet { } } var prop2 = false { willSet { } } var prop3: Int? = nil { didSet { } } var prop4: Bool? = nil { willSet { } } var prop5: T? = nil { didSet { } } var prop6: T? = nil { willSet { } } var prop7 = T() { didSet { } } var prop8 = T() { willSet { } } } //===--- // Parsing problems //===--- var computed_prop_with_init_1: X { get {} } = X() // expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{2-2=;}} var x2 { // expected-error{{computed property must have an explicit type}} {{7-7=: <# Type #>}} expected-error{{type annotation missing in pattern}} get { return _x } } var (x3): X { // expected-error{{getter/setter can only be defined for a single variable}} get { return _x } } var duplicateAccessors1: X { get { // expected-note {{previous definition of getter here}} return _x } set { // expected-note {{previous definition of setter here}} _x = newValue } get { // expected-error {{variable already has a getter}} return _x } set(v) { // expected-error {{variable already has a setter}} _x = v } } var duplicateAccessors2: Int = 0 { willSet { // expected-note {{previous definition of 'willSet' here}} } didSet { // expected-note {{previous definition of 'didSet' here}} } willSet { // expected-error {{variable already has 'willSet'}} } didSet { // expected-error {{variable already has 'didSet'}} } } var extraTokensInAccessorBlock1: X { get {} a // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}} } var extraTokensInAccessorBlock2: X { get {} weak // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}} a } var extraTokensInAccessorBlock3: X { get {} a = b // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}} set {} get {} } var extraTokensInAccessorBlock4: X { get blah wibble // expected-error{{expected '{' to start getter definition}} } var extraTokensInAccessorBlock5: X { set blah wibble // expected-error{{expected '{' to start setter definition}} } var extraTokensInAccessorBlock6: X { // expected-error{{non-member observing properties require an initializer}} willSet blah wibble // expected-error{{expected '{' to start 'willSet' definition}} } var extraTokensInAccessorBlock7: X { // expected-error{{non-member observing properties require an initializer}} didSet blah wibble // expected-error{{expected '{' to start 'didSet' definition}} } var extraTokensInAccessorBlock8: X { foo // expected-error {{use of unresolved identifier 'foo'}} get {} // expected-error{{use of unresolved identifier 'get'}} set {} // expected-error{{use of unresolved identifier 'set'}} } var extraTokensInAccessorBlock9: Int { get // expected-error {{expected '{' to start getter definition}} var a = b } struct extraTokensInAccessorBlock10 { var x: Int { get // expected-error {{expected '{' to start getter definition}} var a = b } init() {} } var x9: X { get ( ) { // expected-error{{expected '{' to start getter definition}} } } var x10: X { set ( : ) { // expected-error{{expected setter parameter name}} } get {} } var x11 : X { set { // expected-error{{variable with a setter must also have a getter}} } } var x12: X { set(newValue %) { // expected-error {{expected ')' after setter parameter name}} expected-note {{to match this opening '('}} // expected-error@-1 {{expected '{' to start setter definition}} } } var x13: X {} // expected-error {{computed property must have accessors specified}} // Type checking problems struct Y { } var y: Y var x20: X { get { return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}} } set { y = newValue // expected-error{{cannot assign value of type 'X' to type 'Y'}} } } var x21: X { get { return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}} } set(v) { y = v // expected-error{{cannot assign value of type 'X' to type 'Y'}} } } var x23: Int, x24: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}} return 42 } var x25: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}} return 42 }, x26: Int // Properties of struct/enum/extensions struct S { var _backed_x: X, _backed_x2: X var x: X { get { return _backed_x } mutating set(v) { _backed_x = v } } } extension S { var x2: X { get { return self._backed_x2 } mutating set { _backed_x2 = newValue } } var x3: X { get { return self._backed_x2 } } } struct StructWithExtension1 { var foo: Int static var fooStatic = 4 } extension StructWithExtension1 { var fooExt: Int // expected-error {{extensions must not contain stored properties}} static var fooExtStatic = 4 } class ClassWithExtension1 { var foo: Int = 0 class var fooStatic = 4 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} } extension ClassWithExtension1 { var fooExt: Int // expected-error {{extensions must not contain stored properties}} class var fooExtStatic = 4 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}} } enum EnumWithExtension1 { var foo: Int // expected-error {{enums must not contain stored properties}} static var fooStatic = 4 } extension EnumWithExtension1 { var fooExt: Int // expected-error {{extensions must not contain stored properties}} static var fooExtStatic = 4 } protocol ProtocolWithExtension1 { var foo: Int { get } static var fooStatic : Int { get } } extension ProtocolWithExtension1 { var fooExt: Int // expected-error{{extensions must not contain stored properties}} static var fooExtStatic = 4 // expected-error{{static stored properties not supported in protocol extensions}} } protocol ProtocolWithExtension2 { var bar: String { get } } struct StructureImplementingProtocolWithExtension2: ProtocolWithExtension2 { let bar: String } extension ProtocolWithExtension2 { static let baz: ProtocolWithExtension2 = StructureImplementingProtocolWithExtension2(bar: "baz") // expected-error{{static stored properties not supported in protocol extensions}} } func getS() -> S { let s: S return s } func test_extension_properties(_ s: inout S, x: inout X) { accept_x(s.x) accept_x(s.x2) accept_x(s.x3) accept_x(getS().x) accept_x(getS().x2) accept_x(getS().x3) s.x = x s.x2 = x s.x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}} getS().x = x // expected-error{{cannot assign to property: 'getS' returns immutable value}} getS().x2 = x // expected-error{{cannot assign to property: 'getS' returns immutable value}} getS().x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}} accept_x_inout(&getS().x) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}} accept_x_inout(&getS().x2) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}} accept_x_inout(&getS().x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}} x = getS().x x = getS().x2 x = getS().x3 accept_x_inout(&s.x) accept_x_inout(&s.x2) accept_x_inout(&s.x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}} } extension S { mutating func test(other_x: inout X) { x = other_x x2 = other_x x3 = other_x // expected-error{{cannot assign to property: 'x3' is a get-only property}} other_x = x other_x = x2 other_x = x3 } } // Accessor on non-settable type struct Aleph { var b: Beth { get { return Beth(c: 1) } } } struct Beth { var c: Int } func accept_int_inout(_ c: inout Int) { } func accept_int(_ c: Int) { } func test_settable_of_nonsettable(_ a: Aleph) { a.b.c = 1 // expected-error{{cannot assign}} let x:Int = a.b.c _ = x accept_int(a.b.c) accept_int_inout(&a.b.c) // expected-error {{cannot pass immutable value as inout argument: 'b' is a get-only property}} } // TODO: Static properties are only implemented for nongeneric structs yet. struct MonoStruct { static var foo: Int = 0 static var (bar, bas): (String, UnicodeScalar) = ("zero", "0") static var zim: UInt8 { return 0 } static var zang = UnicodeScalar("\0") static var zung: UInt16 { get { return 0 } set {} } var a: Double var b: Double } struct MonoStructOneProperty { static var foo: Int = 22 } enum MonoEnum { static var foo: Int = 0 static var zim: UInt8 { return 0 } } struct GenStruct<T> { static var foo: Int = 0 // expected-error{{static stored properties not supported in generic types}} } class MonoClass { class var foo: Int = 0 // expected-error{{class stored properties not supported in classes; did you mean 'static'?}} } protocol Proto { static var foo: Int { get } } func staticPropRefs() -> (Int, Int, String, UnicodeScalar, UInt8) { return (MonoStruct.foo, MonoEnum.foo, MonoStruct.bar, MonoStruct.bas, MonoStruct.zim) } func staticPropRefThroughInstance(_ foo: MonoStruct) -> Int { return foo.foo //expected-error{{static member 'foo' cannot be used on instance of type 'MonoStruct'}} } func memberwiseInitOnlyTakesInstanceVars() -> MonoStruct { return MonoStruct(a: 1.2, b: 3.4) } func getSetStaticProperties() -> (UInt8, UInt16) { MonoStruct.zim = 12 // expected-error{{cannot assign}} MonoStruct.zung = 34 return (MonoStruct.zim, MonoStruct.zung) } var selfRefTopLevel: Int { return selfRefTopLevel // expected-warning {{attempting to access 'selfRefTopLevel' within its own getter}} } var selfRefTopLevelSetter: Int { get { return 42 } set { markUsed(selfRefTopLevelSetter) // no-warning selfRefTopLevelSetter = newValue // expected-warning {{attempting to modify 'selfRefTopLevelSetter' within its own setter}} } } var selfRefTopLevelSilenced: Int { get { return properties.selfRefTopLevelSilenced // no-warning } set { properties.selfRefTopLevelSilenced = newValue // no-warning } } class SelfRefProperties { var getter: Int { return getter // expected-warning {{attempting to access 'getter' within its own getter}} // expected-note@-1 {{access 'self' explicitly to silence this warning}} {{12-12=self.}} } var setter: Int { get { return 42 } set { markUsed(setter) // no-warning var unused = setter + setter // expected-warning {{initialization of variable 'unused' was never used; consider replacing with assignment to '_' or removing it}} {{7-17=_}} setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}} // expected-note@-1 {{access 'self' explicitly to silence this warning}} {{7-7=self.}} } } var silenced: Int { get { return self.silenced // no-warning } set { self.silenced = newValue // no-warning } } var someOtherInstance: SelfRefProperties = SelfRefProperties() var delegatingVar: Int { // This particular example causes infinite access, but it's easily possible // for the delegating instance to do something else. return someOtherInstance.delegatingVar // no-warning } } func selfRefLocal() { var getter: Int { return getter // expected-warning {{attempting to access 'getter' within its own getter}} } var setter: Int { get { return 42 } set { markUsed(setter) // no-warning setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}} } } } struct WillSetDidSetProperties { var a: Int { willSet { markUsed("almost") } didSet { markUsed("here") } } var b: Int { willSet { markUsed(b) markUsed(newValue) } } var c: Int { willSet(newC) { markUsed(c) markUsed(newC) } } var d: Int { didSet { // expected-error {{'didSet' cannot be provided together with a getter}} markUsed("woot") } get { return 4 } } var e: Int { willSet { // expected-error {{'willSet' cannot be provided together with a setter}} markUsed("woot") } set { // expected-error {{variable with a setter must also have a getter}} return 4 // expected-error {{unexpected non-void return value in void function}} } } var f: Int { willSet(5) {} // expected-error {{expected willSet parameter name}} didSet(^) {} // expected-error {{expected didSet parameter name}} } var g: Int { willSet(newValue 5) {} // expected-error {{expected ')' after willSet parameter name}} expected-note {{to match this opening '('}} // expected-error@-1 {{expected '{' to start 'willSet' definition}} } var h: Int { didSet(oldValue ^) {} // expected-error {{expected ')' after didSet parameter name}} expected-note {{to match this opening '('}} // expected-error@-1 {{expected '{' to start 'didSet' definition}} } // didSet/willSet with initializers. // Disambiguate trailing closures. var disambiguate1: Int = 42 { // simple initializer, simple label didSet { markUsed("eek") } } var disambiguate2: Int = 42 { // simple initializer, complex label willSet(v) { markUsed("eek") } } var disambiguate3: Int = takeTrailingClosure {} { // Trailing closure case. willSet(v) { markUsed("eek") } } var disambiguate4: Int = 42 { willSet {} } var disambiguate5: Int = 42 { didSet {} } var disambiguate6: Int = takeTrailingClosure { @inline(__always) func f() {} return () } var inferred1 = 42 { willSet { markUsed("almost") } didSet { markUsed("here") } } var inferred2 = 40 { willSet { markUsed(b) markUsed(newValue) } } var inferred3 = 50 { willSet(newC) { markUsed(c) markUsed(newC) } } } // Disambiguated as accessor. struct WillSetDidSetDisambiguate1 { var willSet: Int var x: (() -> ()) -> Int = takeTrailingClosure { willSet = 42 // expected-error {{expected '{' to start 'willSet' definition}} } } struct WillSetDidSetDisambiguate1Attr { var willSet: Int var x: (() -> ()) -> Int = takeTrailingClosure { willSet = 42 // expected-error {{expected '{' to start 'willSet' definition}} } } // Disambiguated as accessor. struct WillSetDidSetDisambiguate2 { func willSet(_: () -> Int) {} var x: (() -> ()) -> Int = takeTrailingClosure { willSet {} } } struct WillSetDidSetDisambiguate2Attr { func willSet(_: () -> Int) {} var x: (() -> ()) -> Int = takeTrailingClosure { willSet {} } } // No need to disambiguate -- this is clearly a function call. func willSet(_: () -> Int) {} struct WillSetDidSetDisambiguate3 { var x: Int = takeTrailingClosure({ willSet { 42 } }) } protocol ProtocolGetSet1 { var a: Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{13-13= { get <#set#> \}}} } protocol ProtocolGetSet2 { var a: Int {} // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-16={ get <#set#> \}}} } protocol ProtocolGetSet3 { var a: Int { get } } protocol ProtocolGetSet4 { var a: Int { set } // expected-error {{variable with a setter must also have a getter}} } protocol ProtocolGetSet5 { var a: Int { get set } } protocol ProtocolGetSet6 { var a: Int { set get } } protocol ProtocolWillSetDidSet1 { var a: Int { willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-25={ get <#set#> \}}} expected-error {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet2 { var a: Int { didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-24={ get <#set#> \}}} expected-error {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet3 { var a: Int { willSet didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-32={ get <#set#> \}}} expected-error 2 {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet4 { var a: Int { didSet willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-32={ get <#set#> \}}} expected-error 2 {{expected get or set in a protocol property}} } protocol ProtocolWillSetDidSet5 { let a: Int { didSet willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-32={ get <#set#> \}}} {{none}} expected-error 2 {{expected get or set in a protocol property}} expected-error {{'let' declarations cannot be computed properties}} {{3-6=var}} } var globalDidsetWillSet: Int { // expected-error {{non-member observing properties require an initializer}} didSet {} } var globalDidsetWillSet2 : Int = 42 { didSet {} } class Box { var num: Int init(num: Int) { self.num = num } } func double(_ val: inout Int) { val *= 2 } class ObservingPropertiesNotMutableInWillSet { var anotherObj : ObservingPropertiesNotMutableInWillSet init() {} var property: Int = 42 { willSet { // <rdar://problem/16826319> willSet immutability behavior is incorrect anotherObj.property = 19 // ok property = 19 // expected-warning {{attempting to store to property 'property' within its own willSet}} double(&property) // expected-warning {{attempting to store to property 'property' within its own willSet}} double(&self.property) // no-warning } } // <rdar://problem/21392221> - call to getter through BindOptionalExpr was not viewed as a load var _oldBox : Int weak var weakProperty: Box? { willSet { _oldBox = weakProperty?.num ?? -1 } } func localCase() { var localProperty: Int = 42 { willSet { localProperty = 19 // expected-warning {{attempting to store to property 'localProperty' within its own willSet}} } } } } func doLater(_ fn : () -> ()) {} // rdar://<rdar://problem/16264989> property not mutable in closure inside of its willSet class MutableInWillSetInClosureClass { var bounds: Int = 0 { willSet { let oldBounds = bounds doLater { self.bounds = oldBounds } } } } // <rdar://problem/16191398> add an 'oldValue' to didSet so you can implement "didChange" properties var didSetPropertyTakingOldValue : Int = 0 { didSet(oldValue) { markUsed(oldValue) markUsed(didSetPropertyTakingOldValue) } } // rdar://16280138 - synthesized getter is defined in terms of archetypes, not interface types protocol AbstractPropertyProtocol { associatedtype Index var a : Index { get } } struct AbstractPropertyStruct<T> : AbstractPropertyProtocol { typealias Index = T var a : T } // Allow _silgen_name accessors without bodies. var _silgen_nameGet1: Int { @_silgen_name("get1") get set { } } var _silgen_nameGet2: Int { set { } @_silgen_name("get2") get } var _silgen_nameGet3: Int { @_silgen_name("get3") get } var _silgen_nameGetSet: Int { @_silgen_name("get4") get @_silgen_name("set4") set } // <rdar://problem/16375910> reject observing properties overriding readonly properties class Base16375910 { var x : Int { // expected-note {{attempt to override property here}} return 42 } var y : Int { // expected-note {{attempt to override property here}} get { return 4 } set {} } } class Derived16375910 : Base16375910 { override init() {} override var x : Int { // expected-error {{cannot observe read-only property 'x'; it can't change}} willSet { markUsed(newValue) } } } // <rdar://problem/16382967> Observing properties have no storage, so shouldn't prevent initializer synth class Derived16382967 : Base16375910 { override var y : Int { willSet { markUsed(newValue) } } } // <rdar://problem/16659058> Read-write properties can be made read-only in a property override class Derived16659058 : Base16375910 { override var y : Int { // expected-error {{cannot override mutable property with read-only property 'y'}} get { return 42 } } } // <rdar://problem/16406886> Observing properties don't work with ownership types struct PropertiesWithOwnershipTypes { unowned var p1 : SomeClass { didSet { } } init(res: SomeClass) { p1 = res } } // <rdar://problem/16608609> Assert (and incorrect error message) when defining a constant stored property with observers class Test16608609 { let constantStored: Int = 0 { // expected-error {{'let' declarations cannot be observing properties}} {{4-7=var}} willSet { } didSet { } } } // <rdar://problem/16941124> Overriding property observers warn about using the property value "within its own getter" class rdar16941124Base { var x = 0 } class rdar16941124Derived : rdar16941124Base { var y = 0 override var x: Int { didSet { y = x + 1 // no warning. } } } // Overrides of properties with custom ownership. class OwnershipBase { class var defaultObject: AnyObject { fatalError("") } var strongVar: AnyObject? // expected-note{{overridden declaration is here}} weak var weakVar: AnyObject? // expected-note{{overridden declaration is here}} // FIXME: These should be optional to properly test overriding. unowned var unownedVar: AnyObject = defaultObject unowned var optUnownedVar: AnyObject? = defaultObject unowned(unsafe) var unownedUnsafeVar: AnyObject = defaultObject // expected-note{{overridden declaration is here}} unowned(unsafe) var optUnownedUnsafeVar: AnyObject? = defaultObject } class OwnershipExplicitSub : OwnershipBase { override var strongVar: AnyObject? { didSet {} } override weak var weakVar: AnyObject? { didSet {} } override unowned var unownedVar: AnyObject { didSet {} } override unowned var optUnownedVar: AnyObject? { didSet {} } override unowned(unsafe) var unownedUnsafeVar: AnyObject { didSet {} } override unowned(unsafe) var optUnownedUnsafeVar: AnyObject? { didSet {} } } class OwnershipImplicitSub : OwnershipBase { override var strongVar: AnyObject? { didSet {} } override weak var weakVar: AnyObject? { didSet {} } override unowned var unownedVar: AnyObject { didSet {} } override unowned var optUnownedVar: AnyObject? { didSet {} } override unowned(unsafe) var unownedUnsafeVar: AnyObject { didSet {} } override unowned(unsafe) var optUnownedUnsafeVar: AnyObject? { didSet {} } } class OwnershipBadSub : OwnershipBase { override weak var strongVar: AnyObject? { // expected-error {{cannot override 'strong' property with 'weak' property}} didSet {} } override unowned var weakVar: AnyObject? { // expected-error {{cannot override 'weak' property with 'unowned' property}} didSet {} } override weak var unownedVar: AnyObject { // expected-error {{'weak' variable should have optional type 'AnyObject?'}} didSet {} } override unowned var unownedUnsafeVar: AnyObject { // expected-error {{cannot override 'unowned(unsafe)' property with 'unowned' property}} didSet {} } } // <rdar://problem/17391625> Swift Compiler Crashes when Declaring a Variable and didSet in an Extension class rdar17391625 { var prop = 42 // expected-note {{overri}} } extension rdar17391625 { var someStoredVar: Int // expected-error {{extensions must not contain stored properties}} var someObservedVar: Int { // expected-error {{extensions must not contain stored properties}} didSet { } } } class rdar17391625derived : rdar17391625 { } extension rdar17391625derived { // Not a stored property, computed because it is an override. override var prop: Int { // expected-error {{overri}} didSet { } } } // <rdar://problem/27671033> Crash when defining property inside an invalid extension // (This extension is no longer invalid.) public protocol rdar27671033P {} struct rdar27671033S<Key, Value> {} extension rdar27671033S : rdar27671033P where Key == String { let d = rdar27671033S<Int, Int>() // expected-error {{extensions must not contain stored properties}} } // <rdar://problem/19874152> struct memberwise initializer violates new sanctity of previously set `let` property struct r19874152S1 { let number : Int = 42 } _ = r19874152S1(number:64) // expected-error {{argument passed to call that takes no arguments}} _ = r19874152S1() // Ok struct r19874152S2 { var number : Int = 42 } _ = r19874152S2(number:64) // Ok, property is a var. _ = r19874152S2() // Ok struct r19874152S3 { // expected-note {{'init(flavor:)' declared here}} let number : Int = 42 let flavor : Int } _ = r19874152S3(number:64) // expected-error {{incorrect argument label in call (have 'number:', expected 'flavor:')}} {{17-23=flavor}} _ = r19874152S3(number:64, flavor: 17) // expected-error {{extra argument 'number' in call}} _ = r19874152S3(flavor: 17) // ok _ = r19874152S3() // expected-error {{missing argument for parameter 'flavor' in call}} struct r19874152S4 { let number : Int? = nil } _ = r19874152S4(number:64) // expected-error {{argument passed to call that takes no arguments}} _ = r19874152S4() // Ok struct r19874152S5 { } _ = r19874152S5() // ok struct r19874152S6 { let (a,b) = (1,2) // Cannot handle implicit synth of this yet. } _ = r19874152S5() // ok // <rdar://problem/24314506> QoI: Fix-it for dictionary initializer on required class var suggests [] instead of [:] class r24314506 { // expected-error {{class 'r24314506' has no initializers}} var myDict: [String: AnyObject] // expected-note {{stored property 'myDict' without initial value prevents synthesized initializers}} {{34-34= = [:]}} } // https://bugs.swift.org/browse/SR-3893 // Generic type is not inferenced from its initial value for properties with // will/didSet struct SR3893Box<Foo> { let value: Foo } struct SR3893 { // Each of these "bad" properties used to produce errors. var bad: SR3893Box = SR3893Box(value: 0) { willSet { print(newValue.value) } } var bad2: SR3893Box = SR3893Box(value: 0) { willSet(new) { print(new.value) } } var bad3: SR3893Box = SR3893Box(value: 0) { didSet { print(oldValue.value) } } var good: SR3893Box<Int> = SR3893Box(value: 0) { didSet { print(oldValue.value) } } var plain: SR3893Box = SR3893Box(value: 0) } protocol WFI_P1 : class {} protocol WFI_P2 : class {} class WeakFixItTest { init() {} // expected-error @+1 {{'weak' variable should have optional type 'WeakFixItTest?'}} {{31-31=?}} weak var foo : WeakFixItTest // expected-error @+1 {{'weak' variable should have optional type '(WFI_P1 & WFI_P2)?'}} {{18-18=(}} {{33-33=)?}} weak var bar : WFI_P1 & WFI_P2 }
apache-2.0
fd6681bedfdb009d0aac4463a73ac3fc
24.570528
307
0.65737
3.743971
false
false
false
false
talk2junior/iOSND-Beginning-iOS-Swift-3.0
Playground Collection/Part 3 - Alien Adventure 1/Arrays/Arrays.playground/Pages/Exercises.xcplaygroundpage/Contents.swift
1
1615
//: [Previous](@previous) //: ### Exercise 1 //: 1a) Initialize the array, cuteAnimals. It should be of type CuddlyCreature. Type your answer below. //: 1b) Initialize an array of 5 bools using array literal syntax. //: ### Exercise 2 //: Print out the number of spaniels in the array below. var spaniels = ["American Cocker", "Cavalier King Charles", "English Springer", "French", "Irish Water","Papillon", "Picardy","Russian", "French", "Welsh Springer"] //: ### Exercise 3 //: Insert "indigo" into the array below so that its index is after "blue" and before "violet". var colors = ["red", "orange", "yellow", "green", "blue", "violet"] //: ### Exercise 4 //: Insert "English Cocker" into the spaniels array so that its index is before "English Springer". //: ### Exercise 5 //: Append "Barcelona" to the end of the olympicHosts array. var olympicHosts = ["London", "Beijing","Athens", "Sydney", "Atlanta"] //: ### Exercise 6 //: Remove "Lyla" and "Daniel" from the waitingList array and add them to the end of the admitted array. var admitted = ["Jennifer", "Vijay", "James"] var waitingList = ["Lyla", "Daniel", "Isabel", "Eric"] //: ### Exercise 7 //: Using subscript syntax, print out the 2nd and 3rd names from the admitted array. //: ### Exercise 8 //: We'd like to reverse the string, stringToReverse. We can do this by filling in one line of code in the for-in loop below. Try it out! let stringToReverse = "desserts" var reversedString = "" for character in stringToReverse.characters { //reversedString = //TODO: Fill in code here } print(reversedString, terminator: "") //: [Next](@next)
mit
09fec8495dc809ea530a97b48d4c6c68
41.5
164
0.687926
3.51087
false
false
false
false
TCA-Team/iOS
TUM Campus App/Station.swift
1
3510
// // Station.swift // Abfahrt // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import CoreLocation import Sweeft public enum Line { case bus(Int) case nachtbus(Int) case tram(Int) case nachttram(Int) case ubahn(Int) case sbahn(Int) case other(Int) } extension Line { init?(key: String, number: Int) { switch key { case "bus": self = .bus(number) case "nachtbus": self = .nachtbus(number) case "tram": self = .tram(number) case "nachttram": self = .nachttram(number) case "ubahn": self = .ubahn(number) case "sbahn": self = .sbahn(number) case "otherlines": self = .other(number) default: return nil } } } public struct Station: Hashable { public var hashValue: Int { return self.id.hashValue } public let name: String public let id: Int public let type: String public let place: String public let hasZoomData: Bool public let hasLiveData: Bool public let latitude: Double public let longitude: Double public let lines: [Line] /// Distance from the search location public let distance: Int? } extension Station: Deserializable { public init?(from json: JSON) { guard let name = json["name"].string, let id = json["id"].int, let type = json["type"].string, let hasLiveData = json["hasLiveData"].double?.bool, let hasZoomData = json["hasZoomData"].double?.bool, let latitude = json["latitude"].double, let longitude = json["longitude"].double, let place = json["place"].string, let lines = json["lines"].dict else { return nil } self.name = name self.id = id self.type = type self.hasLiveData = hasLiveData self.hasZoomData = hasZoomData self.latitude = latitude self.longitude = longitude self.place = place self.distance = json["distance"].int self.lines = lines.flatMap { key, value -> [Line] in guard let numbers = value.array?.compactMap({ $0.int }) else { return [] } return numbers.compactMap { Line(key: key, number: $0) } } } } extension Station { var location: CLLocation { return .init(latitude: latitude, longitude: longitude) } } extension Station: DataElement { var text: String { return name } func getCellIdentifier() -> String { return "station" } } public func ==(lhs: Station, rhs: Station) -> Bool { return lhs.id == rhs.id }
gpl-3.0
d5eb5bc4c75f1946ae98c940ea71c487
23.893617
88
0.580627
4.090909
false
false
false
false
InsectQY/HelloSVU_Swift
HelloSVU_Swift/Classes/Module/Home/WallPaper/Vertical/Controller/WallperVerticalViewController.swift
1
4158
// // WallperVerticalViewController.swift // HelloSVU_Swift // // Created by Insect on 2017/9/27. //Copyright © 2017年 Insect. All rights reserved. // import UIKit /// cell 之间间距 private let kItemMargin: CGFloat = 5 /// 左右间距 private let kEdge: CGFloat = 4 /// 每行最大列数 private let kMaxCol: CGFloat = 3 /// cell 宽度 private let kItemW = (ScreenW - (2 * kEdge) - ((kMaxCol - 1) * kItemMargin)) / kMaxCol /// cell 高度 private let kItemH = kItemW * 1.7 private let ImgVerticalCellID = "ImgVerticalCellID" class WallperVerticalViewController: BaseViewController { var id = "" // MARK: - LazyLoad private lazy var verticalData = [ImgVertical]() private lazy var collectionView: UICollectionView = { let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSize(width: kItemW, height: kItemH) flowLayout.minimumLineSpacing = kEdge flowLayout.minimumInteritemSpacing = kEdge flowLayout.sectionInset = UIEdgeInsetsMake(kEdge, kEdge, kEdge, kEdge) let collectionView = UICollectionView(frame: UIScreen.main.bounds, collectionViewLayout: flowLayout) collectionView.backgroundColor = .white collectionView.dataSource = self collectionView.delegate = self collectionView.register(cellType: ImgVerticalCell.self) collectionView.contentInset = UIEdgeInsetsMake(kTopH, 0, 0, 0) return collectionView }() // MARK: - LifeCycle override func viewDidLoad() { super.viewDidLoad() setUpUI() setUpRefresh() } } // MARK: - 设置 UI 界面 extension WallperVerticalViewController { private func setUpUI() { view.addSubview(collectionView) automaticallyAdjustsScrollViewInsets = false } private func setUpRefresh() { collectionView.mj_header = SVURefreshHeader(refreshingTarget: self, refreshingAction: #selector(loadNewVerticalData)) collectionView.mj_footer = SVURefreshFooter(refreshingTarget: self, refreshingAction: #selector(loadMoreVerticalData)) collectionView.mj_header.beginRefreshing() } } // MARK: - 加载数据 extension WallperVerticalViewController { @objc private func loadNewVerticalData() { collectionView.mj_footer.endRefreshing() ApiProvider.request(Api.wallpaperCategory(id, 0), arrayModel: ImgVertical.self, path: "res.vertical", success: { self.verticalData = $0 self.collectionView.reloadData() self.collectionView.mj_header.endRefreshing() }) { self.collectionView.mj_header.endRefreshing() } } @objc private func loadMoreVerticalData() { collectionView.mj_header.endRefreshing() ApiProvider.request(Api.wallpaperCategory(id, verticalData.count), arrayModel: ImgVertical.self, path: "res.vertical", success: { self.verticalData += $0 self.collectionView.reloadData() self.collectionView.mj_footer.endRefreshing() }) { self.collectionView.mj_footer.endRefreshing() } } } // MARK: - UICollectionViewDataSource extension WallperVerticalViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return verticalData.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(for: indexPath, cellType: ImgVerticalCell.self) cell.vertical = verticalData[indexPath.item] return cell } } // MARK: - UICollectionViewDelegate extension WallperVerticalViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let vc = WallPaperDetailViewController() vc.vertical = verticalData[indexPath.item] presentVC(vc) } }
apache-2.0
bcd26619951ef20a55312f389aa429fe
31.307087
137
0.676334
4.991484
false
false
false
false
blockchain/My-Wallet-V3-iOS
Blockchain/Wallet/Ethereum/EthereumWallet.swift
1
8175
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BigInt import Combine import DIKit import ERC20Kit import EthereumKit import FeatureAppUI import Foundation import JavaScriptCore import PlatformKit import RxRelay import RxSwift import ToolKit import WalletPayloadKit final class EthereumWallet: NSObject { // MARK: Types typealias EthereumDispatcher = EthereumJSInteropDispatcherAPI & EthereumJSInteropDelegateAPI typealias WalletAPI = LegacyEthereumWalletAPI & LegacyWalletAPI & LegacyMnemonicAccessAPI enum EthereumWalletError: Error { case recordLastEthereumTransactionFailed case ethereumAccountsFailed } // MARK: Properties weak var reactiveWallet: ReactiveWalletAPI! var delegate: EthereumJSInteropDelegateAPI { dispatcher } @available(*, deprecated, message: "making this so tests will compile") var interopDispatcher: EthereumJSInteropDispatcherAPI { dispatcher } // MARK: Private Properties private weak var wallet: WalletAPI? private let secondPasswordPrompter: SecondPasswordPromptable private let dispatcher: EthereumDispatcher // MARK: Initializer @objc convenience init(legacyWallet: Wallet) { self.init(wallet: legacyWallet) } init( secondPasswordPrompter: SecondPasswordPromptable = resolve(), wallet: WalletAPI, dispatcher: EthereumDispatcher = EthereumJSInteropDispatcher.shared ) { self.secondPasswordPrompter = secondPasswordPrompter self.wallet = wallet self.dispatcher = dispatcher super.init() } @objc func setup(with context: JSContext) { context.setJsFunction(named: "objc_on_didGetEtherAccountsAsync" as NSString) { [weak self] accounts in self?.delegate.didGetAccounts(accounts) } context.setJsFunction(named: "objc_on_error_gettingEtherAccountsAsync" as NSString) { [weak self] errorMessage in self?.delegate.didFailToGetAccounts(errorMessage: errorMessage) } context.setJsFunction(named: "objc_on_recordLastTransactionAsync_success" as NSString) { [weak self] in self?.delegate.didRecordLastTransaction() } context.setJsFunction(named: "objc_on_recordLastTransactionAsync_error" as NSString) { [weak self] errorMessage in self?.delegate.didFailToRecordLastTransaction(errorMessage: errorMessage) } } } extension EthereumWallet: EthereumWalletBridgeAPI { func update(accountIndex: Int, label: String) -> Completable { reactiveWallet .waitUntilInitializedFirst .asObservable() .take(1) .asSingle() .flatMapCompletable(weak: self) { (self, _) -> Completable in guard let wallet = self.wallet else { return .error(WalletError.notInitialized) } return wallet.updateAccountLabel(.ethereum, index: accountIndex, label: label) } } func note(for transactionHash: String) -> Single<String?> { Single<String?> .create(weak: self) { (self, observer) -> Disposable in guard let wallet = self.wallet else { observer(.error(WalletError.notInitialized)) return Disposables.create() } wallet.getEthereumNote( for: transactionHash, success: { note in observer(.success(note)) }, error: { _ in observer(.error(WalletError.notInitialized)) } ) return Disposables.create() } } func updateNote(for transactionHash: String, note: String?) -> Completable { reactiveWallet .waitUntilInitializedFirst .asObservable() .take(1) .asSingle() .flatMapCompletable { [wallet] in Completable.create { completable in wallet?.setEthereumNote(for: transactionHash, note: note) completable(.completed) return Disposables.create() } } } func recordLast(transaction: EthereumTransactionPublished) -> Single<EthereumTransactionPublished> { Single .create(weak: self) { (self, observer) -> Disposable in guard let wallet = self.wallet else { observer(.error(WalletError.notInitialized)) return Disposables.create() } wallet.recordLastEthereumTransaction( transactionHash: transaction.transactionHash, success: { observer(.success(transaction)) }, error: { _ in observer(.error(EthereumWalletError.recordLastEthereumTransactionFailed)) } ) return Disposables.create() } .subscribe(on: MainScheduler.instance) } } extension EthereumWallet: EthereumWalletAccountBridgeAPI { var wallets: AnyPublisher<[EthereumWalletAccount], Error> { reactiveWallet .waitUntilInitializedFirst .setFailureType(to: SecondPasswordError.self) .flatMap { [secondPasswordPrompter] _ in secondPasswordPrompter.secondPasswordIfNeeded(type: .actionRequiresPassword) } .eraseError() .flatMap { [weak self] secondPassword -> AnyPublisher<[EthereumWalletAccount], Error> in guard let self = self else { return .failure(WalletError.notInitialized) } return self.ethereumWallets(secondPassword: secondPassword) } .eraseError() .eraseToAnyPublisher() } private func ethereumWallets( secondPassword: String? ) -> AnyPublisher<[EthereumWalletAccount], Error> { Deferred { [weak self] in Future<[[String: Any]], Error> { promise in guard let wallet = self?.wallet else { return promise(.failure(WalletError.notInitialized)) } wallet.ethereumAccounts( with: secondPassword, success: { accounts in promise(.success(accounts)) }, error: { _ in promise(.failure(EthereumWalletError.ethereumAccountsFailed)) } ) } } .map { accounts in accounts.decodeJSONObjects(type: LegacyEthereumWalletAccount.self) } .map { legacyWallets in legacyWallets.enumerated() .map { offset, account in EthereumWalletAccount( index: offset, publicKey: account.addr, label: account.label, archived: false ) } } .eraseError() .eraseToAnyPublisher() } } extension Dictionary where Key == String, Value == [String: Any] { /// Cast the `[String: [String: Any]]` objects in this Dictionary to instances of `Type` /// /// - Parameter type: the type /// - Returns: the casted array public func decodeJSONObjects<T: Codable>(type: T.Type) -> [String: T] { let jsonDecoder = JSONDecoder() return compactMapValues { value -> T? in guard let data = try? JSONSerialization.data(withJSONObject: value, options: []) else { Logger.shared.warning("Failed to serialize dictionary.") return nil } do { return try jsonDecoder.decode(type.self, from: data) } catch { Logger.shared.error("Failed to decode \(error)") } return nil } } }
lgpl-3.0
f438ba2e34c6dfcfcfbd5f96eae00431
34.081545
122
0.578297
5.406085
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Chocotastic/Models/CardType.swift
1
5681
/** * Copyright (c) 2016 Razeware LLC * * 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 enum CardType { case Unknown, Amex, Mastercard, Visa, Discover //https://en.wikipedia.org/wiki/Payment_card_number static func fromString(string: String) -> CardType { if string.isEmpty { //We definitely can't determine from an empty string. return .Unknown } guard string.rw_allCharactersAreNumbers() else { assertionFailure("One of these characters is not a number!") return .Unknown } //Visa: Starts with 4 //Mastercard: Starts with 2221-2720 or 51-55 //Amex: Starts with 34 or 37 //Discover: Starts with 6011, 622126-622925, 644-649, or 65 if string.hasPrefix("4") { //If the first # is a 4, it's a visa return .Visa } //Else, we need more info, keep going let firstTwo = string.rw_integerValueOfFirst(characters: 2) guard firstTwo != NSNotFound else { return .Unknown } switch firstTwo { case 51...55: return .Mastercard case 65: return .Discover case 34, 37: return .Amex default: //Can't determine type yet break } let firstThree = string.rw_integerValueOfFirst(characters: 3) guard firstThree != NSNotFound else { return .Unknown } switch firstThree { case 644...649: return .Discover default: //Can't determine type yet break } let firstFour = string.rw_integerValueOfFirst(characters: 4) guard firstFour != NSNotFound else { return .Unknown } switch firstFour { case 2221...2720: return .Mastercard case 6011: return .Discover default: //Can't determine type yet break } let firstSix = string.rw_integerValueOfFirst(characters: 6) guard firstSix != NSNotFound else { return .Unknown } switch firstSix { case 622126...622925: return .Discover default: //If we've gotten here, ¯\_(ツ)_/¯ return .Unknown } } var expectedDigits: Int { switch self { case .Amex: return 15 default: return 16 } } var image: UIImage { switch self { case .Amex: return ImageName.Amex.image case .Discover: return ImageName.Discover.image case .Mastercard: return ImageName.Mastercard.image case .Visa: return ImageName.Visa.image case .Unknown: return ImageName.UnknownCard.image } } var cvvDigits: Int { switch self { case .Amex: return 4 default: return 3 } } func format(noSpaces: String) -> String { guard noSpaces.characters.count >= 4 else { //No formatting necessary if <= 4 return noSpaces } let startIndex = noSpaces.startIndex let index4 = noSpaces.index(startIndex, offsetBy: 4) //All cards start with four digits before the get to spaces let firstFour = noSpaces.substring(to: index4) var formattedString = firstFour + " " switch self { case .Amex: //Amex format is xxxx xxxxxx xxxxx guard noSpaces.characters.count > 10 else { //No further formatting required. return formattedString + noSpaces.substring(from: index4) } let index10 = noSpaces.index(startIndex, offsetBy: 10) let nextSixRange = Range(index4..<index10) let nextSix = noSpaces.substring(with: nextSixRange) let remaining = noSpaces.substring(from: index10) return formattedString + nextSix + " " + remaining default: //Other cards are formatted as xxxx xxxx xxxx xxxx guard noSpaces.characters.count > 8 else { //No further formatting required. return formattedString + noSpaces.substring(from: index4) } let index8 = noSpaces.index(startIndex, offsetBy: 8) let nextFourRange = Range(index4..<index8) let nextFour = noSpaces.substring(with: nextFourRange) formattedString += nextFour + " " guard noSpaces.characters.count > 12 else { //Just add the remaining spaces let remaining = noSpaces.substring(from: index8) return formattedString + remaining } let index12 = noSpaces.index(startIndex, offsetBy: 12) let followingFourRange = Range(index8..<index12) let followingFour = noSpaces.substring(with: followingFourRange) let remaining = noSpaces.substring(from: index12) return formattedString + followingFour + " " + remaining } } }
mit
691ccbbbee0bbde1ec0bea557f514f88
26.828431
80
0.648406
4.297502
false
false
false
false
gouyz/GYZBaking
baking/Classes/Orders/View/GYZSelectReceivedGoodsCell.swift
1
2205
// // GYZSelectReceivedGoodsCell.swift // baking // 选择收货商品cell // Created by gouyz on 2017/6/8. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit class GYZSelectReceivedGoodsCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?){ super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.backgroundColor = kWhiteColor setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupUI(){ contentView.addSubview(checkBtn) contentView.addSubview(logoImgView) contentView.addSubview(nameLab) checkBtn.snp.makeConstraints { (make) in make.left.equalTo(kMargin) make.centerY.equalTo(contentView) make.size.equalTo(CGSize.init(width: 20, height: 20)) } logoImgView.snp.makeConstraints { (make) in make.left.equalTo(checkBtn.snp.right).offset(kMargin) make.centerY.equalTo(contentView) make.size.equalTo(CGSize.init(width: 40, height: 40)) } nameLab.snp.makeConstraints { (make) in make.top.bottom.equalTo(logoImgView) make.left.equalTo(logoImgView.snp.right).offset(kMargin) make.right.equalTo(-kMargin) } } /// 选择图标 lazy var checkBtn : UIButton = { let btn = UIButton.init(type: .custom) btn.setImage(UIImage.init(named: "icon_pay_check_normal"), for: .normal) btn.setImage(UIImage.init(named: "icon_pay_check_selected"), for: .selected) return btn }() /// 商品图片 lazy var logoImgView : UIImageView = { let view = UIImageView() view.borderColor = kGrayLineColor view.borderWidth = klineWidth view.layer.masksToBounds = true view.contentMode = .scaleAspectFill return view }() /// 商品名称 lazy var nameLab : UILabel = { let lab = UILabel() lab.font = k14Font lab.textColor = kBlackFontColor return lab }() }
mit
37f0f5974a04139a3158c2277b94ecb4
28.671233
84
0.610803
4.375758
false
false
false
false
tjw/swift
test/SILGen/implicitly_unwrapped_optional.swift
1
3806
// RUN: %target-swift-frontend -module-name implicitly_unwrapped_optional -emit-silgen -enable-sil-ownership %s | %FileCheck %s func foo(f f: (() -> ())!) { var f: (() -> ())! = f f?() } // CHECK: sil hidden @{{.*}}foo{{.*}} : $@convention(thin) (@guaranteed Optional<@callee_guaranteed () -> ()>) -> () { // CHECK: bb0([[T0:%.*]] : @guaranteed $Optional<@callee_guaranteed () -> ()>): // CHECK: [[F:%.*]] = alloc_box ${ var Optional<@callee_guaranteed () -> ()> } // CHECK: [[PF:%.*]] = project_box [[F]] // CHECK: [[T0_COPY:%.*]] = copy_value [[T0]] // CHECK: store [[T0_COPY]] to [init] [[PF]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PF]] : $*Optional<@callee_guaranteed () -> ()> // CHECK: [[HASVALUE:%.*]] = select_enum_addr [[READ]] // CHECK: cond_br [[HASVALUE]], bb2, bb1 // // If it does, project and load the value out of the implicitly unwrapped // optional... // CHECK: bb2: // CHECK-NEXT: [[FN0_ADDR:%.*]] = unchecked_take_enum_data_addr [[READ]] // CHECK-NEXT: [[FN0:%.*]] = load [copy] [[FN0_ADDR]] // .... then call it // CHECK: [[B:%.*]] = begin_borrow [[FN0]] // CHECK: apply [[B]]() : $@callee_guaranteed () -> () // CHECK: end_borrow [[B]] // CHECK: br bb3 // CHECK: bb3( // CHECK: destroy_value [[F]] // CHECK: return // CHECK: bb4: // CHECK: enum $Optional<()>, #Optional.none!enumelt // CHECK: br bb3 // The rest of this is tested in optional.swift // } // end sil function '{{.*}}foo{{.*}}' func wrap<T>(x x: T) -> T! { return x } // CHECK-LABEL: sil hidden @$S29implicitly_unwrapped_optional16wrap_then_unwrap{{[_0-9a-zA-Z]*}}F func wrap_then_unwrap<T>(x x: T) -> T { // CHECK: switch_enum_addr {{%.*}}, case #Optional.some!enumelt.1: [[OK:bb[0-9]+]], case #Optional.none!enumelt: [[FAIL:bb[0-9]+]] // CHECK: [[FAIL]]: // CHECK: unreachable // CHECK: [[OK]]: return wrap(x: x)! } // CHECK-LABEL: sil hidden @$S29implicitly_unwrapped_optional10tuple_bind1xSSSgSi_SStSg_tF : $@convention(thin) (@guaranteed Optional<(Int, String)>) -> @owned Optional<String> { func tuple_bind(x x: (Int, String)!) -> String? { return x?.1 // CHECK: switch_enum {{%.*}}, case #Optional.some!enumelt.1: [[NONNULL:bb[0-9]+]], case #Optional.none!enumelt: [[NULL:bb[0-9]+]] // CHECK: [[NONNULL]]( // CHECK: [[STRING:%.*]] = tuple_extract {{%.*}} : $(Int, String), 1 // CHECK-NOT: destroy_value [[STRING]] } // CHECK-LABEL: sil hidden @$S29implicitly_unwrapped_optional011tuple_bind_a1_B01xSSSi_SStSg_tF func tuple_bind_implicitly_unwrapped(x x: (Int, String)!) -> String { return x.1 } func return_any() -> AnyObject! { return nil } func bind_any() { let object : AnyObject? = return_any() } // CHECK-LABEL: sil hidden @$S29implicitly_unwrapped_optional6sr3758yyF func sr3758() { // Verify that there are no additional reabstractions introduced. // CHECK: [[CLOSURE:%.+]] = function_ref @$S29implicitly_unwrapped_optional6sr3758yyFyypSgcfU_ : $@convention(thin) (@in_guaranteed Optional<Any>) -> () // CHECK: [[F:%.+]] = thin_to_thick_function [[CLOSURE]] : $@convention(thin) (@in_guaranteed Optional<Any>) -> () to $@callee_guaranteed (@in_guaranteed Optional<Any>) -> () // CHECK: [[BORROWED_F:%.*]] = begin_borrow [[F]] // CHECK: [[CALLEE:%.+]] = copy_value [[BORROWED_F]] : $@callee_guaranteed (@in_guaranteed Optional<Any>) -> () // CHECK: [[BORROWED_CALLEE:%.*]] = begin_borrow [[CALLEE]] // CHECK: = apply [[BORROWED_CALLEE]]({{%.+}}) : $@callee_guaranteed (@in_guaranteed Optional<Any>) -> () // CHECK: end_borrow [[BORROWED_CALLEE]] // destroy_value [[CALLEE]] // CHECK: end_borrow [[BORROWED_F]] from [[F]] // CHECK: destroy_value [[F]] let f: ((Any?) -> Void) = { (arg: Any!) in } f(nil) } // CHECK: end sil function '$S29implicitly_unwrapped_optional6sr3758yyF'
apache-2.0
d07f6f3249764d3fd10955f27f5732ca
45.414634
178
0.600893
3.174312
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/Support/Support_Error.swift
1
3642
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for Support public struct SupportErrorType: AWSErrorType { enum Code: String { case attachmentIdNotFound = "AttachmentIdNotFound" case attachmentLimitExceeded = "AttachmentLimitExceeded" case attachmentSetExpired = "AttachmentSetExpired" case attachmentSetIdNotFound = "AttachmentSetIdNotFound" case attachmentSetSizeLimitExceeded = "AttachmentSetSizeLimitExceeded" case caseCreationLimitExceeded = "CaseCreationLimitExceeded" case caseIdNotFound = "CaseIdNotFound" case describeAttachmentLimitExceeded = "DescribeAttachmentLimitExceeded" case internalServerError = "InternalServerError" } private let error: Code public let context: AWSErrorContext? /// initialize Support public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// An attachment with the specified ID could not be found. public static var attachmentIdNotFound: Self { .init(.attachmentIdNotFound) } /// The limit for the number of attachment sets created in a short period of time has been exceeded. public static var attachmentLimitExceeded: Self { .init(.attachmentLimitExceeded) } /// The expiration time of the attachment set has passed. The set expires 1 hour after it is created. public static var attachmentSetExpired: Self { .init(.attachmentSetExpired) } /// An attachment set with the specified ID could not be found. public static var attachmentSetIdNotFound: Self { .init(.attachmentSetIdNotFound) } /// A limit for the size of an attachment set has been exceeded. The limits are three attachments and 5 MB per attachment. public static var attachmentSetSizeLimitExceeded: Self { .init(.attachmentSetSizeLimitExceeded) } /// The case creation limit for the account has been exceeded. public static var caseCreationLimitExceeded: Self { .init(.caseCreationLimitExceeded) } /// The requested caseId could not be located. public static var caseIdNotFound: Self { .init(.caseIdNotFound) } /// The limit for the number of DescribeAttachment requests in a short period of time has been exceeded. public static var describeAttachmentLimitExceeded: Self { .init(.describeAttachmentLimitExceeded) } /// An internal server error occurred. public static var internalServerError: Self { .init(.internalServerError) } } extension SupportErrorType: Equatable { public static func == (lhs: SupportErrorType, rhs: SupportErrorType) -> Bool { lhs.error == rhs.error } } extension SupportErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
f52f327ca5f88262a7a45307ce51c6f0
43.962963
126
0.695497
5.016529
false
false
false
false
calkinssean/woodshopBMX
WoodshopBMX/Pods/Charts/Charts/Classes/Filters/ChartDataApproximatorFilter.swift
7
7322
// // ChartDataApproximator.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/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 public class ChartDataApproximatorFilter: ChartDataBaseFilter { @objc public enum ApproximatorType: Int { case None case RamerDouglasPeucker } /// the type of filtering algorithm to use public var type = ApproximatorType.None /// the tolerance to be filtered with /// When using the Douglas-Peucker-Algorithm, the tolerance is an angle in degrees, that will trigger the filtering public var tolerance = Double(0.0) public var scaleRatio = Double(1.0) public var deltaRatio = Double(1.0) public override init() { super.init() } /// Initializes the approximator with the given type and tolerance. /// If toleranec <= 0, no filtering will be done. public init(type: ApproximatorType, tolerance: Double) { super.init() setup(type, tolerance: tolerance) } /// Sets type and tolerance. /// If tolerance <= 0, no filtering will be done. public func setup(type: ApproximatorType, tolerance: Double) { self.type = type self.tolerance = tolerance } /// Sets the ratios for x- and y-axis, as well as the ratio of the scale levels public func setRatios(deltaRatio: Double, scaleRatio: Double) { self.deltaRatio = deltaRatio self.scaleRatio = scaleRatio } /// Filters according to type. Uses the pre set set tolerance /// /// - parameter points: the points to filter public override func filter(points: [ChartDataEntry]) -> [ChartDataEntry] { return filter(points, tolerance: tolerance) } /// Filters according to type. /// /// - parameter points: the points to filter /// - parameter tolerance: the angle in degrees that will trigger the filtering public func filter(points: [ChartDataEntry], tolerance: Double) -> [ChartDataEntry] { if (tolerance <= 0) { return points } switch (type) { case .RamerDouglasPeucker: return reduceWithDouglasPeuker(points, epsilon: tolerance) case .None: return points } } /// uses the douglas peuker algorithm to reduce the given arraylist of entries private func reduceWithDouglasPeuker(entries: [ChartDataEntry], epsilon: Double) -> [ChartDataEntry] { // if a shape has 2 or less points it cannot be reduced if (epsilon <= 0 || entries.count < 3) { return entries } var keep = [Bool](count: entries.count, repeatedValue: false) // first and last always stay keep[0] = true keep[entries.count - 1] = true // first and last entry are entry point to recursion algorithmDouglasPeucker(entries, epsilon: epsilon, start: 0, end: entries.count - 1, keep: &keep) // create a new array with series, only take the kept ones var reducedEntries = [ChartDataEntry]() for i in 0 ..< entries.count { if (keep[i]) { let curEntry = entries[i] reducedEntries.append(ChartDataEntry(value: curEntry.value, xIndex: curEntry.xIndex)) } } return reducedEntries } /// apply the Douglas-Peucker-Reduction to an ArrayList of Entry with a given epsilon (tolerance) /// /// - parameter entries: /// - parameter epsilon: as y-value /// - parameter start: /// - parameter end: private func algorithmDouglasPeucker(entries: [ChartDataEntry], epsilon: Double, start: Int, end: Int, inout keep: [Bool]) { if (end <= start + 1) { // recursion finished return } // find the greatest distance between start and endpoint var maxDistIndex = Int(0) var distMax = Double(0.0) let firstEntry = entries[start] let lastEntry = entries[end] for i in start + 1 ..< end { let dist = calcAngleBetweenLines(firstEntry, end1: lastEntry, start2: firstEntry, end2: entries[i]) // keep the point with the greatest distance if (dist > distMax) { distMax = dist maxDistIndex = i } } if (distMax > epsilon) { // keep max dist point keep[maxDistIndex] = true // recursive call algorithmDouglasPeucker(entries, epsilon: epsilon, start: start, end: maxDistIndex, keep: &keep) algorithmDouglasPeucker(entries, epsilon: epsilon, start: maxDistIndex, end: end, keep: &keep) } // else don't keep the point... } /// calculate the distance between a line between two entries and an entry (point) /// /// - parameter startEntry: line startpoint /// - parameter endEntry: line endpoint /// - parameter entryPoint: the point to which the distance is measured from the line private func calcPointToLineDistance(startEntry: ChartDataEntry, endEntry: ChartDataEntry, entryPoint: ChartDataEntry) -> Double { let xDiffEndStart = Double(endEntry.xIndex) - Double(startEntry.xIndex) let xDiffEntryStart = Double(entryPoint.xIndex) - Double(startEntry.xIndex) let normalLength = sqrt((xDiffEndStart) * (xDiffEndStart) + (endEntry.value - startEntry.value) * (endEntry.value - startEntry.value)) return Double(fabs((xDiffEntryStart) * (endEntry.value - startEntry.value) - (entryPoint.value - startEntry.value) * (xDiffEndStart))) / Double(normalLength) } /// Calculates the angle between two given lines. The provided entries mark the starting and end points of the lines. private func calcAngleBetweenLines(start1: ChartDataEntry, end1: ChartDataEntry, start2: ChartDataEntry, end2: ChartDataEntry) -> Double { let angle1 = calcAngleWithRatios(start1, p2: end1) let angle2 = calcAngleWithRatios(start2, p2: end2) return fabs(angle1 - angle2) } /// calculates the angle between two entries (points) in the chart taking ratios into consideration private func calcAngleWithRatios(p1: ChartDataEntry, p2: ChartDataEntry) -> Double { let dx = Double(p2.xIndex) * Double(deltaRatio) - Double(p1.xIndex) * Double(deltaRatio) let dy = p2.value * scaleRatio - p1.value * scaleRatio return atan2(Double(dy), dx) * ChartUtils.Math.RAD2DEG } // calculates the angle between two entries (points) in the chart private func calcAngle(p1: ChartDataEntry, p2: ChartDataEntry) -> Double { let dx = p2.xIndex - p1.xIndex let dy = p2.value - p1.value return atan2(Double(dy), Double(dx)) * ChartUtils.Math.RAD2DEG } }
apache-2.0
b91e354feefeda296f7d1094cafb116f
33.219626
140
0.609396
4.530941
false
false
false
false
jhaigler94/cs4720-iOS
Pensieve/Pensieve/GoogleDataProvider.swift
1
4055
// // GoogleDataProvider.swift // Feed Me // /* * Copyright (c) 2015 Razeware LLC * * 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 Foundation import CoreLocation //import SwiftyJSON class GoogleDataProvider { var photoCache = [String:UIImage]() var placesTask: NSURLSessionDataTask? var session: NSURLSession { return NSURLSession.sharedSession() } func fetchPlacesNearCoordinate(coordinate: CLLocationCoordinate2D, radius: Double, types:[String], completion: (([GooglePlace]) -> Void)) -> () { var urlString = "http://localhost:10000/maps/api/place/nearbysearch/json?location=\(coordinate.latitude),\(coordinate.longitude)&radius=\(radius)&rankby=prominence&sensor=true" let typesString = types.count > 0 ? types.joinWithSeparator("|") : "food" urlString += "&types=\(typesString)" urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! if let task = placesTask where task.taskIdentifier > 0 && task.state == .Running { task.cancel() } UIApplication.sharedApplication().networkActivityIndicatorVisible = true placesTask = session.dataTaskWithURL(NSURL(string: urlString)!) {data, response, error in UIApplication.sharedApplication().networkActivityIndicatorVisible = false var placesArray = [GooglePlace]() if let aData = data { let json = JSON(data:aData, options:NSJSONReadingOptions.MutableContainers, error:nil) if let results = json["results"].arrayObject as? [[String : AnyObject]] { for rawPlace in results { let place = GooglePlace(dictionary: rawPlace, acceptedTypes: types) placesArray.append(place) if let reference = place.photoReference { self.fetchPhotoFromReference(reference) { image in place.photo = image } } } } } dispatch_async(dispatch_get_main_queue()) { completion(placesArray) } } placesTask?.resume() } func fetchPhotoFromReference(reference: String, completion: ((UIImage?) -> Void)) -> () { if let photo = photoCache[reference] as UIImage? { completion(photo) } else { let urlString = "http://localhost:10000/maps/api/place/photo?maxwidth=200&photoreference=\(reference)" UIApplication.sharedApplication().networkActivityIndicatorVisible = true session.downloadTaskWithURL(NSURL(string: urlString)!) {url, response, error in UIApplication.sharedApplication().networkActivityIndicatorVisible = false if let url = url { let downloadedPhoto = UIImage(data: NSData(contentsOfURL: url)!) self.photoCache[reference] = downloadedPhoto dispatch_async(dispatch_get_main_queue()) { completion(downloadedPhoto) } } else { dispatch_async(dispatch_get_main_queue()) { completion(nil) } } }.resume() } } }
apache-2.0
825ab993f73b1d316847782bd66e59e1
39.959596
180
0.693465
4.731622
false
false
false
false
josipbernat/Hasher
Pods/CryptoSwift/Sources/CryptoSwift/Updatable.swift
4
4295
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // /// A type that supports incremental updates. For example Digest or Cipher may be updatable /// and calculate result incerementally. public protocol Updatable { /// Update given bytes in chunks. /// /// - parameter bytes: Bytes to process. /// - parameter isLast: Indicate if given chunk is the last one. No more updates after this call. /// - returns: Processed partial result data or empty array. mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool) throws -> Array<UInt8> /// Update given bytes in chunks. /// /// - Parameters: /// - bytes: Bytes to process. /// - isLast: Indicate if given chunk is the last one. No more updates after this call. /// - output: Resulting bytes callback. /// - Returns: Processed partial result data or empty array. mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool, output: (_ bytes: Array<UInt8>) -> Void) throws } extension Updatable { public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false, output: (_ bytes: Array<UInt8>) -> Void) throws { let processed = try update(withBytes: bytes, isLast: isLast) if !processed.isEmpty { output(processed) } } public mutating func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { return try update(withBytes: bytes, isLast: isLast) } public mutating func update(withBytes bytes: Array<UInt8>, isLast: Bool = false) throws -> Array<UInt8> { return try update(withBytes: bytes.slice, isLast: isLast) } public mutating func update(withBytes bytes: Array<UInt8>, isLast: Bool = false, output: (_ bytes: Array<UInt8>) -> Void) throws { return try update(withBytes: bytes.slice, isLast: isLast, output: output) } /// Finish updates. This may apply padding. /// - parameter bytes: Bytes to process /// - returns: Processed data. public mutating func finish(withBytes bytes: ArraySlice<UInt8>) throws -> Array<UInt8> { return try update(withBytes: bytes, isLast: true) } public mutating func finish(withBytes bytes: Array<UInt8>) throws -> Array<UInt8> { return try finish(withBytes: bytes.slice) } /// Finish updates. May add padding. /// /// - Returns: Processed data /// - Throws: Error public mutating func finish() throws -> Array<UInt8> { return try update(withBytes: [], isLast: true) } /// Finish updates. This may apply padding. /// - parameter bytes: Bytes to process /// - parameter output: Resulting data /// - returns: Processed data. public mutating func finish(withBytes bytes: ArraySlice<UInt8>, output: (_ bytes: Array<UInt8>) -> Void) throws { let processed = try update(withBytes: bytes, isLast: true) if !processed.isEmpty { output(processed) } } public mutating func finish(withBytes bytes: Array<UInt8>, output: (_ bytes: Array<UInt8>) -> Void) throws { return try finish(withBytes: bytes.slice, output: output) } /// Finish updates. May add padding. /// /// - Parameter output: Processed data /// - Throws: Error public mutating func finish(output: (Array<UInt8>) -> Void) throws { try finish(withBytes: [], output: output) } }
mit
5f3bd80aa5c63c6f6078e0eecac5e786
42.816327
217
0.676991
4.372709
false
false
false
false
badoo/Chatto
ChattoApp/ChattoApp/Source/BaseMessagesSelector.swift
1
2421
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. 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 ChattoAdditions import Foundation public class BaseMessagesSelector: MessagesSelectorProtocol { public weak var delegate: MessagesSelectorDelegate? public var isActive = false { didSet { guard oldValue != self.isActive else { return } if self.isActive { self.selectedMessagesDictionary.removeAll() } } } public func canSelectMessage(_ message: MessageModelProtocol) -> Bool { return true } public func isMessageSelected(_ message: MessageModelProtocol) -> Bool { return self.selectedMessagesDictionary[message.uid] != nil } public func selectMessage(_ message: MessageModelProtocol) { self.selectedMessagesDictionary[message.uid] = message self.delegate?.messagesSelector(self, didSelectMessage: message) } public func deselectMessage(_ message: MessageModelProtocol) { self.selectedMessagesDictionary[message.uid] = nil self.delegate?.messagesSelector(self, didDeselectMessage: message) } public func selectedMessages() -> [MessageModelProtocol] { return Array(self.selectedMessagesDictionary.values) } // MARK: - Private private var selectedMessagesDictionary = [String: MessageModelProtocol]() }
mit
5fa1232052f27892b0e76dd546872478
35.681818
78
0.73482
5.022822
false
false
false
false
nathawes/swift
test/decl/protocol/special/coding/struct_codable_failure_diagnostics.swift
19
3768
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -parse-as-library -swift-version 4 %s -verify // Codable struct with non-Codable property. struct S1 : Codable { // expected-error@-1 {{type 'S1' does not conform to protocol 'Decodable'}} // expected-error@-2 {{type 'S1' does not conform to protocol 'Encodable'}} struct Nested {} var a: String = "" var b: Int = 0 var c: Nested = Nested() // expected-note@-1 {{cannot automatically synthesize 'Decodable' because 'Nested' does not conform to 'Decodable'}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because 'Nested' does not conform to 'Encodable'}} } // Codable struct with non-enum CodingKeys. struct S2 : Codable { // expected-error@-1 {{type 'S2' does not conform to protocol 'Decodable'}} // expected-error@-2 {{type 'S2' does not conform to protocol 'Encodable'}} var a: String = "" var b: Int = 0 var c: Double? struct CodingKeys : CodingKey { // expected-note@-1 {{cannot automatically synthesize 'Decodable' because 'CodingKeys' is not an enum}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because 'CodingKeys' is not an enum}} var stringValue: String = "" var intValue: Int? = nil init?(stringValue: String) {} init?(intValue: Int) {} } } // Codable struct with CodingKeys not conforming to CodingKey. struct S3 : Codable { // expected-error@-1 {{type 'S3' does not conform to protocol 'Decodable'}} // expected-error@-2 {{type 'S3' does not conform to protocol 'Encodable'}} var a: String = "" var b: Int = 0 var c: Double? enum CodingKeys : String { // expected-note@-1 {{cannot automatically synthesize 'Decodable' because 'CodingKeys' does not conform to CodingKey}} // expected-note@-2 {{cannot automatically synthesize 'Encodable' because 'CodingKeys' does not conform to CodingKey}} case a case b case c } } // Codable struct with extraneous CodingKeys struct S4 : Codable { // expected-error@-1 {{type 'S4' does not conform to protocol 'Decodable'}} // expected-error@-2 {{type 'S4' does not conform to protocol 'Encodable'}} var a: String = "" var b: Int = 0 var c: Double? enum CodingKeys : String, CodingKey { case a case a2 // expected-note@-1 {{CodingKey case 'a2' does not match any stored properties}} // expected-note@-2 {{CodingKey case 'a2' does not match any stored properties}} case b case b2 // expected-note@-1 {{CodingKey case 'b2' does not match any stored properties}} // expected-note@-2 {{CodingKey case 'b2' does not match any stored properties}} case c case c2 // expected-note@-1 {{CodingKey case 'c2' does not match any stored properties}} // expected-note@-2 {{CodingKey case 'c2' does not match any stored properties}} } } // Codable struct with non-decoded property (which has no default value). struct S5 : Codable { // expected-error@-1 {{type 'S5' does not conform to protocol 'Decodable'}} var a: String = "" var b: Int // expected-note@-1 {{cannot automatically synthesize 'Decodable' because 'b' does not have a matching CodingKey and does not have a default value}} var c: Double? enum CodingKeys : String, CodingKey { case a case c } } struct NotCodable {} struct S6 { var x: NotCodable = NotCodable() // expected-note@-1 {{cannot automatically synthesize 'Encodable' because 'NotCodable' does not conform to 'Encodable'}} // expected-note@-2 {{cannot automatically synthesize 'Decodable' because 'NotCodable' does not conform to 'Decodable'}} } extension S6: Codable {} // expected-error@-1 {{type 'S6' does not conform to protocol 'Encodable'}} // expected-error@-2 {{type 'S6' does not conform to protocol 'Decodable'}}
apache-2.0
6b43e4f364590f2fc9330327571dfb86
36.306931
150
0.688429
3.904663
false
false
false
false
xedin/swift
stdlib/public/core/DictionaryBridging.swift
2
25883
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// #if _runtime(_ObjC) import SwiftShims /// Equivalent to `NSDictionary.allKeys`, but does not leave objects on the /// autorelease pool. internal func _stdlib_NSDictionary_allKeys( _ object: AnyObject ) -> _BridgingBuffer { let nsd = unsafeBitCast(object, to: _NSDictionary.self) let count = nsd.count let storage = _BridgingBuffer(count) nsd.getObjects(nil, andKeys: storage.baseAddress, count: count) return storage } extension _NativeDictionary { // Bridging @usableFromInline __consuming internal func bridged() -> AnyObject { // We can zero-cost bridge if our keys are verbatim // or if we're the empty singleton. // Temporary var for SOME type safety. let nsDictionary: _NSDictionaryCore if _storage === __RawDictionaryStorage.empty || count == 0 { nsDictionary = __RawDictionaryStorage.empty } else if _isBridgedVerbatimToObjectiveC(Key.self), _isBridgedVerbatimToObjectiveC(Value.self) { nsDictionary = unsafeDowncast( _storage, to: _DictionaryStorage<Key, Value>.self) } else { nsDictionary = _SwiftDeferredNSDictionary(self) } return nsDictionary } } /// An NSEnumerator that works with any _NativeDictionary of /// verbatim bridgeable elements. Used by the various NSDictionary impls. final internal class _SwiftDictionaryNSEnumerator<Key: Hashable, Value> : __SwiftNativeNSEnumerator, _NSEnumerator { @nonobjc internal var base: _NativeDictionary<Key, Value> @nonobjc internal var bridgedKeys: __BridgingHashBuffer? @nonobjc internal var nextBucket: _NativeDictionary<Key, Value>.Bucket @nonobjc internal var endBucket: _NativeDictionary<Key, Value>.Bucket @objc internal override required init() { _internalInvariantFailure("don't call this designated initializer") } internal init(_ base: __owned _NativeDictionary<Key, Value>) { _internalInvariant(_isBridgedVerbatimToObjectiveC(Key.self)) self.base = base self.bridgedKeys = nil self.nextBucket = base.hashTable.startBucket self.endBucket = base.hashTable.endBucket super.init() } @nonobjc internal init(_ deferred: __owned _SwiftDeferredNSDictionary<Key, Value>) { _internalInvariant(!_isBridgedVerbatimToObjectiveC(Key.self)) self.base = deferred.native self.bridgedKeys = deferred.bridgeKeys() self.nextBucket = base.hashTable.startBucket self.endBucket = base.hashTable.endBucket super.init() } private func bridgedKey(at bucket: _HashTable.Bucket) -> AnyObject { _internalInvariant(base.hashTable.isOccupied(bucket)) if let bridgedKeys = self.bridgedKeys { return bridgedKeys[bucket] } return _bridgeAnythingToObjectiveC(base.uncheckedKey(at: bucket)) } @objc internal func nextObject() -> AnyObject? { if nextBucket == endBucket { return nil } let bucket = nextBucket nextBucket = base.hashTable.occupiedBucket(after: nextBucket) return self.bridgedKey(at: bucket) } @objc(countByEnumeratingWithState:objects:count:) internal func countByEnumerating( with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>, count: Int ) -> Int { var theState = state.pointee if theState.state == 0 { theState.state = 1 // Arbitrary non-zero value. theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects) theState.mutationsPtr = _fastEnumerationStorageMutationsPtr } if nextBucket == endBucket { state.pointee = theState return 0 } // Return only a single element so that code can start iterating via fast // enumeration, terminate it, and continue via NSEnumerator. let unmanagedObjects = _UnmanagedAnyObjectArray(objects) unmanagedObjects[0] = self.bridgedKey(at: nextBucket) nextBucket = base.hashTable.occupiedBucket(after: nextBucket) state.pointee = theState return 1 } } /// This class exists for Objective-C bridging. It holds a reference to a /// _NativeDictionary, and can be upcast to NSSelf when bridging is /// necessary. This is the fallback implementation for situations where /// toll-free bridging isn't possible. On first access, a _NativeDictionary /// of AnyObject will be constructed containing all the bridged elements. final internal class _SwiftDeferredNSDictionary<Key: Hashable, Value> : __SwiftNativeNSDictionary, _NSDictionaryCore { @usableFromInline internal typealias Bucket = _HashTable.Bucket // This stored property must be stored at offset zero. We perform atomic // operations on it. // // Do not access this property directly. @nonobjc private var _bridgedKeys_DoNotUse: AnyObject? // This stored property must be stored at offset one. We perform atomic // operations on it. // // Do not access this property directly. @nonobjc private var _bridgedValues_DoNotUse: AnyObject? /// The unbridged elements. internal var native: _NativeDictionary<Key, Value> internal init(_ native: __owned _NativeDictionary<Key, Value>) { _internalInvariant(native.count > 0) _internalInvariant(!_isBridgedVerbatimToObjectiveC(Key.self) || !_isBridgedVerbatimToObjectiveC(Value.self)) self.native = native super.init() } @objc internal required init( objects: UnsafePointer<AnyObject?>, forKeys: UnsafeRawPointer, count: Int ) { _internalInvariantFailure("don't call this designated initializer") } @nonobjc private var _bridgedKeysPtr: UnsafeMutablePointer<AnyObject?> { return _getUnsafePointerToStoredProperties(self) .assumingMemoryBound(to: Optional<AnyObject>.self) } @nonobjc private var _bridgedValuesPtr: UnsafeMutablePointer<AnyObject?> { return _bridgedKeysPtr + 1 } /// The buffer for bridged keys, if present. @nonobjc private var _bridgedKeys: __BridgingHashBuffer? { guard let ref = _stdlib_atomicLoadARCRef(object: _bridgedKeysPtr) else { return nil } return unsafeDowncast(ref, to: __BridgingHashBuffer.self) } /// The buffer for bridged values, if present. @nonobjc private var _bridgedValues: __BridgingHashBuffer? { guard let ref = _stdlib_atomicLoadARCRef(object: _bridgedValuesPtr) else { return nil } return unsafeDowncast(ref, to: __BridgingHashBuffer.self) } /// Attach a buffer for bridged Dictionary keys. @nonobjc private func _initializeBridgedKeys(_ storage: __BridgingHashBuffer) { _stdlib_atomicInitializeARCRef(object: _bridgedKeysPtr, desired: storage) } /// Attach a buffer for bridged Dictionary values. @nonobjc private func _initializeBridgedValues(_ storage: __BridgingHashBuffer) { _stdlib_atomicInitializeARCRef(object: _bridgedValuesPtr, desired: storage) } @nonobjc internal func bridgeKeys() -> __BridgingHashBuffer? { if _isBridgedVerbatimToObjectiveC(Key.self) { return nil } if let bridgedKeys = _bridgedKeys { return bridgedKeys } // Allocate and initialize heap storage for bridged keys. let bridged = __BridgingHashBuffer.allocate( owner: native._storage, hashTable: native.hashTable) for bucket in native.hashTable { let object = _bridgeAnythingToObjectiveC(native.uncheckedKey(at: bucket)) bridged.initialize(at: bucket, to: object) } // Atomically put the bridged keys in place. _initializeBridgedKeys(bridged) return _bridgedKeys! } @nonobjc internal func bridgeValues() -> __BridgingHashBuffer? { if _isBridgedVerbatimToObjectiveC(Value.self) { return nil } if let bridgedValues = _bridgedValues { return bridgedValues } // Allocate and initialize heap storage for bridged values. let bridged = __BridgingHashBuffer.allocate( owner: native._storage, hashTable: native.hashTable) for bucket in native.hashTable { let value = native.uncheckedValue(at: bucket) let cocoaValue = _bridgeAnythingToObjectiveC(value) bridged.initialize(at: bucket, to: cocoaValue) } // Atomically put the bridged values in place. _initializeBridgedValues(bridged) return _bridgedValues! } @objc(copyWithZone:) internal func copy(with zone: _SwiftNSZone?) -> AnyObject { // Instances of this class should be visible outside of standard library as // having `NSDictionary` type, which is immutable. return self } @inline(__always) private func _key( at bucket: Bucket, bridgedKeys: __BridgingHashBuffer? ) -> AnyObject { if let bridgedKeys = bridgedKeys { return bridgedKeys[bucket] } return _bridgeAnythingToObjectiveC(native.uncheckedKey(at: bucket)) } @inline(__always) private func _value( at bucket: Bucket, bridgedValues: __BridgingHashBuffer? ) -> AnyObject { if let bridgedValues = bridgedValues { return bridgedValues[bucket] } return _bridgeAnythingToObjectiveC(native.uncheckedValue(at: bucket)) } @objc(objectForKey:) internal func object(forKey aKey: AnyObject) -> AnyObject? { guard let nativeKey = _conditionallyBridgeFromObjectiveC(aKey, Key.self) else { return nil } let (bucket, found) = native.find(nativeKey) guard found else { return nil } return _value(at: bucket, bridgedValues: bridgeValues()) } @objc internal func keyEnumerator() -> _NSEnumerator { if _isBridgedVerbatimToObjectiveC(Key.self) { return _SwiftDictionaryNSEnumerator<Key, Value>(native) } return _SwiftDictionaryNSEnumerator<Key, Value>(self) } @objc(getObjects:andKeys:count:) internal func getObjects( _ objects: UnsafeMutablePointer<AnyObject>?, andKeys keys: UnsafeMutablePointer<AnyObject>?, count: Int ) { _precondition(count >= 0, "Invalid count") guard count > 0 else { return } let bridgedKeys = bridgeKeys() let bridgedValues = bridgeValues() var i = 0 // Current position in the output buffers let bucketCount = native._storage._bucketCount defer { _fixLifetime(self) } switch (_UnmanagedAnyObjectArray(keys), _UnmanagedAnyObjectArray(objects)) { case (let unmanagedKeys?, let unmanagedObjects?): for bucket in native.hashTable { unmanagedKeys[i] = _key(at: bucket, bridgedKeys: bridgedKeys) unmanagedObjects[i] = _value(at: bucket, bridgedValues: bridgedValues) i += 1 guard i < count else { break } } case (let unmanagedKeys?, nil): for bucket in native.hashTable { unmanagedKeys[i] = _key(at: bucket, bridgedKeys: bridgedKeys) i += 1 guard i < count else { break } } case (nil, let unmanagedObjects?): for bucket in native.hashTable { unmanagedObjects[i] = _value(at: bucket, bridgedValues: bridgedValues) i += 1 guard i < count else { break } } case (nil, nil): // Do nothing break } } @objc(enumerateKeysAndObjectsWithOptions:usingBlock:) internal func enumerateKeysAndObjects( options: Int, using block: @convention(block) ( Unmanaged<AnyObject>, Unmanaged<AnyObject>, UnsafeMutablePointer<UInt8> ) -> Void) { let bridgedKeys = bridgeKeys() let bridgedValues = bridgeValues() defer { _fixLifetime(self) } var stop: UInt8 = 0 for bucket in native.hashTable { let key = _key(at: bucket, bridgedKeys: bridgedKeys) let value = _value(at: bucket, bridgedValues: bridgedValues) block( Unmanaged.passUnretained(key), Unmanaged.passUnretained(value), &stop) if stop != 0 { return } } } @objc internal var count: Int { return native.count } @objc(countByEnumeratingWithState:objects:count:) internal func countByEnumerating( with state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>?, count: Int ) -> Int { defer { _fixLifetime(self) } let hashTable = native.hashTable var theState = state.pointee if theState.state == 0 { theState.state = 1 // Arbitrary non-zero value. theState.itemsPtr = AutoreleasingUnsafeMutablePointer(objects) theState.mutationsPtr = _fastEnumerationStorageMutationsPtr theState.extra.0 = CUnsignedLong(hashTable.startBucket.offset) } // Test 'objects' rather than 'count' because (a) this is very rare anyway, // and (b) the optimizer should then be able to optimize away the // unwrapping check below. if _slowPath(objects == nil) { return 0 } let unmanagedObjects = _UnmanagedAnyObjectArray(objects!) var bucket = _HashTable.Bucket(offset: Int(theState.extra.0)) let endBucket = hashTable.endBucket _precondition(bucket == endBucket || hashTable.isOccupied(bucket), "Invalid fast enumeration state") var stored = 0 // Only need to bridge once, so we can hoist it out of the loop. let bridgedKeys = bridgeKeys() for i in 0..<count { if bucket == endBucket { break } unmanagedObjects[i] = _key(at: bucket, bridgedKeys: bridgedKeys) stored += 1 bucket = hashTable.occupiedBucket(after: bucket) } theState.extra.0 = CUnsignedLong(bucket.offset) state.pointee = theState return stored } } // NOTE: older runtimes called this struct _CocoaDictionary. The two // must coexist without conflicting ObjC class names from the nested // classes, so it was renamed. The old names must not be used in the new // runtime. @usableFromInline @frozen internal struct __CocoaDictionary { @usableFromInline internal let object: AnyObject @inlinable internal init(_ object: __owned AnyObject) { self.object = object } } extension __CocoaDictionary { @usableFromInline internal func isEqual(to other: __CocoaDictionary) -> Bool { return _stdlib_NSObject_isEqual(self.object, other.object) } } extension __CocoaDictionary: _DictionaryBuffer { @usableFromInline internal typealias Key = AnyObject @usableFromInline internal typealias Value = AnyObject @usableFromInline // FIXME(cocoa-index): Should be inlinable internal var startIndex: Index { @_effects(releasenone) get { let allKeys = _stdlib_NSDictionary_allKeys(self.object) return Index(Index.Storage(self, allKeys), offset: 0) } } @usableFromInline // FIXME(cocoa-index): Should be inlinable internal var endIndex: Index { @_effects(releasenone) get { let allKeys = _stdlib_NSDictionary_allKeys(self.object) return Index(Index.Storage(self, allKeys), offset: allKeys.count) } } @usableFromInline // FIXME(cocoa-index): Should be inlinable @_effects(releasenone) internal func index(after index: Index) -> Index { validate(index) var result = index result._offset += 1 return result } internal func validate(_ index: Index) { _precondition(index.storage.base.object === self.object, "Invalid index") _precondition(index._offset < index.storage.allKeys.count, "Attempt to access endIndex") } @usableFromInline // FIXME(cocoa-index): Should be inlinable internal func formIndex(after index: inout Index, isUnique: Bool) { validate(index) index._offset += 1 } @usableFromInline // FIXME(cocoa-index): Should be inlinable @_effects(releasenone) internal func index(forKey key: Key) -> Index? { // Fast path that does not involve creating an array of all keys. In case // the key is present, this lookup is a penalty for the slow path, but the // potential savings are significant: we could skip a memory allocation and // a linear search. if lookup(key) == nil { return nil } let allKeys = _stdlib_NSDictionary_allKeys(object) for i in 0..<allKeys.count { if _stdlib_NSObject_isEqual(key, allKeys[i]) { return Index(Index.Storage(self, allKeys), offset: i) } } _internalInvariantFailure( "An NSDictionary key wassn't listed amongst its enumerated contents") } @usableFromInline internal var count: Int { let nsd = unsafeBitCast(object, to: _NSDictionary.self) return nsd.count } @usableFromInline internal func contains(_ key: Key) -> Bool { let nsd = unsafeBitCast(object, to: _NSDictionary.self) return nsd.object(forKey: key) != nil } @usableFromInline internal func lookup(_ key: Key) -> Value? { let nsd = unsafeBitCast(object, to: _NSDictionary.self) return nsd.object(forKey: key) } @usableFromInline // FIXME(cocoa-index): Should be inlinable @_effects(releasenone) internal func lookup(_ index: Index) -> (key: Key, value: Value) { _precondition(index.storage.base.object === self.object, "Invalid index") let key: Key = index.storage.allKeys[index._offset] let value: Value = index.storage.base.object.object(forKey: key)! return (key, value) } @usableFromInline // FIXME(cocoa-index): Make inlinable @_effects(releasenone) func key(at index: Index) -> Key { _precondition(index.storage.base.object === self.object, "Invalid index") return index.key } @usableFromInline // FIXME(cocoa-index): Make inlinable @_effects(releasenone) func value(at index: Index) -> Value { _precondition(index.storage.base.object === self.object, "Invalid index") let key = index.storage.allKeys[index._offset] return index.storage.base.object.object(forKey: key)! } } extension __CocoaDictionary { @inlinable internal func mapValues<Key: Hashable, Value, T>( _ transform: (Value) throws -> T ) rethrows -> _NativeDictionary<Key, T> { var result = _NativeDictionary<Key, T>(capacity: self.count) for (cocoaKey, cocoaValue) in self { let key = _forceBridgeFromObjectiveC(cocoaKey, Key.self) let value = _forceBridgeFromObjectiveC(cocoaValue, Value.self) try result.insertNew(key: key, value: transform(value)) } return result } } extension __CocoaDictionary { @frozen @usableFromInline internal struct Index { internal var _storage: Builtin.BridgeObject internal var _offset: Int internal var storage: Storage { @inline(__always) get { let storage = _bridgeObject(toNative: _storage) return unsafeDowncast(storage, to: Storage.self) } } internal init(_ storage: Storage, offset: Int) { self._storage = _bridgeObject(fromNative: storage) self._offset = offset } } } extension __CocoaDictionary.Index { // FIXME(cocoa-index): Try using an NSEnumerator to speed this up. internal class Storage { // Assumption: we rely on NSDictionary.getObjects when being // repeatedly called on the same NSDictionary, returning items in the same // order every time. // Similarly, the same assumption holds for NSSet.allObjects. /// A reference to the NSDictionary, which owns members in `allObjects`, /// or `allKeys`, for NSSet and NSDictionary respectively. internal let base: __CocoaDictionary // FIXME: swift-3-indexing-model: try to remove the cocoa reference, but // make sure that we have a safety check for accessing `allKeys`. Maybe // move both into the dictionary/set itself. /// An unowned array of keys. internal var allKeys: _BridgingBuffer internal init( _ base: __owned __CocoaDictionary, _ allKeys: __owned _BridgingBuffer ) { self.base = base self.allKeys = allKeys } } } extension __CocoaDictionary.Index { @usableFromInline internal var handleBitPattern: UInt { @_effects(readonly) get { return unsafeBitCast(storage, to: UInt.self) } } @usableFromInline internal var dictionary: __CocoaDictionary { @_effects(releasenone) get { return storage.base } } } extension __CocoaDictionary.Index { @usableFromInline // FIXME(cocoa-index): Make inlinable @nonobjc internal var key: AnyObject { @_effects(readonly) get { _precondition(_offset < storage.allKeys.count, "Attempting to access Dictionary elements using an invalid index") return storage.allKeys[_offset] } } @usableFromInline // FIXME(cocoa-index): Make inlinable @nonobjc internal var age: Int32 { @_effects(readonly) get { return _HashTable.age(for: storage.base.object) } } } extension __CocoaDictionary.Index: Equatable { @usableFromInline // FIXME(cocoa-index): Make inlinable @_effects(readonly) internal static func == ( lhs: __CocoaDictionary.Index, rhs: __CocoaDictionary.Index ) -> Bool { _precondition(lhs.storage.base.object === rhs.storage.base.object, "Comparing indexes from different dictionaries") return lhs._offset == rhs._offset } } extension __CocoaDictionary.Index: Comparable { @usableFromInline // FIXME(cocoa-index): Make inlinable @_effects(readonly) internal static func < ( lhs: __CocoaDictionary.Index, rhs: __CocoaDictionary.Index ) -> Bool { _precondition(lhs.storage.base.object === rhs.storage.base.object, "Comparing indexes from different dictionaries") return lhs._offset < rhs._offset } } extension __CocoaDictionary: Sequence { @usableFromInline final internal class Iterator { // Cocoa Dictionary iterator has to be a class, otherwise we cannot // guarantee that the fast enumeration struct is pinned to a certain memory // location. // This stored property should be stored at offset zero. There's code below // relying on this. internal var _fastEnumerationState: _SwiftNSFastEnumerationState = _makeSwiftNSFastEnumerationState() // This stored property should be stored right after // `_fastEnumerationState`. There's code below relying on this. internal var _fastEnumerationStackBuf = _CocoaFastEnumerationStackBuf() internal let base: __CocoaDictionary internal var _fastEnumerationStatePtr: UnsafeMutablePointer<_SwiftNSFastEnumerationState> { return _getUnsafePointerToStoredProperties(self).assumingMemoryBound( to: _SwiftNSFastEnumerationState.self) } internal var _fastEnumerationStackBufPtr: UnsafeMutablePointer<_CocoaFastEnumerationStackBuf> { return UnsafeMutableRawPointer(_fastEnumerationStatePtr + 1) .assumingMemoryBound(to: _CocoaFastEnumerationStackBuf.self) } // These members have to be word-sized integers, they cannot be limited to // Int8 just because our storage holds 16 elements: fast enumeration is // allowed to return inner pointers to the container, which can be much // larger. internal var itemIndex: Int = 0 internal var itemCount: Int = 0 internal init(_ base: __owned __CocoaDictionary) { self.base = base } } @usableFromInline @_effects(releasenone) internal __consuming func makeIterator() -> Iterator { return Iterator(self) } } extension __CocoaDictionary.Iterator: IteratorProtocol { @usableFromInline internal typealias Element = (key: AnyObject, value: AnyObject) @usableFromInline internal func nextKey() -> AnyObject? { if itemIndex < 0 { return nil } let base = self.base if itemIndex == itemCount { let stackBufCount = _fastEnumerationStackBuf.count // We can't use `withUnsafeMutablePointer` here to get pointers to // properties, because doing so might introduce a writeback storage, but // fast enumeration relies on the pointer identity of the enumeration // state struct. itemCount = base.object.countByEnumerating( with: _fastEnumerationStatePtr, objects: UnsafeMutableRawPointer(_fastEnumerationStackBufPtr) .assumingMemoryBound(to: AnyObject.self), count: stackBufCount) if itemCount == 0 { itemIndex = -1 return nil } itemIndex = 0 } let itemsPtrUP = UnsafeMutableRawPointer(_fastEnumerationState.itemsPtr!) .assumingMemoryBound(to: AnyObject.self) let itemsPtr = _UnmanagedAnyObjectArray(itemsPtrUP) let key: AnyObject = itemsPtr[itemIndex] itemIndex += 1 return key } @usableFromInline internal func next() -> Element? { guard let key = nextKey() else { return nil } let value: AnyObject = base.object.object(forKey: key)! return (key, value) } } //===--- Bridging ---------------------------------------------------------===// extension Dictionary { @inlinable public __consuming func _bridgeToObjectiveCImpl() -> AnyObject { guard _variant.isNative else { return _variant.asCocoa.object } return _variant.asNative.bridged() } /// Returns the native Dictionary hidden inside this NSDictionary; /// returns nil otherwise. public static func _bridgeFromObjectiveCAdoptingNativeStorageOf( _ s: __owned AnyObject ) -> Dictionary<Key, Value>? { // Try all three NSDictionary impls that we currently provide. if let deferred = s as? _SwiftDeferredNSDictionary<Key, Value> { return Dictionary(_native: deferred.native) } if let nativeStorage = s as? _DictionaryStorage<Key, Value> { return Dictionary(_native: _NativeDictionary(nativeStorage)) } if s === __RawDictionaryStorage.empty { return Dictionary() } // FIXME: what if `s` is native storage, but for different key/value type? return nil } } #endif // _runtime(_ObjC)
apache-2.0
f794023daa3f6716dfd0ee4a92910f30
30.797297
80
0.690376
4.566514
false
false
false
false
xuzhuoxi/SearchKit
Source/cs/search/SearchTypeResult.swift
1
1587
// // SearchTypeResult.swift // SearchKit // // Created by 许灼溪 on 15/12/21. // // import Foundation /** * 单个字(词)的单个检索类型结果 * * @author xuzhuoxi * */ public struct SearchTypeResult: Comparable { fileprivate static let fullMatchingValue: Double = 2.0 /** * 检索类型 * * @return 检索类型 */ public let searchType: SearchType /** * 检索结果 * * @return 检索结果(匹配度) */ fileprivate(set) public var value: Double = 0 /** * 是否为全匹配 * * @return 是true否false * @see #fullMatchingValue */ public var isFullMatching: Bool { return value >= SearchTypeResult.fullMatchingValue } public init(_ searchType: SearchType) { self.searchType = searchType } /** * 更新检索结果 * * @param value * 检索结果(匹配度) * * @see #fullMatchingValue */ mutating public func updateBiggerValue(_ value: Double) { if (value <= SearchTypeResult.fullMatchingValue && self.value < value) { self.value = value } } } public func ==(lhs: SearchTypeResult, rhs: SearchTypeResult) -> Bool { return (lhs.isFullMatching == rhs.isFullMatching) && (lhs.value == rhs.value) } public func <(lhs: SearchTypeResult, rhs: SearchTypeResult) -> Bool { if lhs.isFullMatching != rhs.isFullMatching { return lhs.isFullMatching ? false : true } else { return lhs.value < rhs.value } }
mit
60ef82c6ac91cd761a30e0636d5b48f9
18.932432
81
0.576271
3.753181
false
false
false
false
edragoev1/pdfjet
Sources/Example_33/main.swift
1
811
import Foundation import PDFjet /** * Example_33.swift * */ public class Example_33 { public init() throws { if let stream = OutputStream(toFileAtPath: "Example_33.pdf", append: false) { let pdf = PDF(stream) let page = Page(pdf, Letter.PORTRAIT) let image = try Image( pdf, InputStream(fileAtPath: "images/photoshop.jpg")!, ImageType.JPG) image.setLocation(10.0, 10.0) image.scaleBy(0.25) image.drawOn(page) pdf.complete() } } } // End of Example_33.swift let time0 = Int64(Date().timeIntervalSince1970 * 1000) _ = try Example_33() let time1 = Int64(Date().timeIntervalSince1970 * 1000) print("Example_33 => \(time1 - time0)")
mit
3b8151cfb9715fbb99086c4749ae2f7e
22.171429
85
0.556104
3.861905
false
false
false
false
glaurent/MessagesHistoryBrowser
MessagesHistoryBrowser/MOCController.swift
1
1486
// // MOCController.swift // MessagesHistoryBrowser // // Created by Guillaume Laurent on 26/12/15. // Copyright © 2015 Guillaume Laurent. All rights reserved. // import Cocoa class MOCController: NSObject { public static let sharedInstance = MOCController() var managedObjectContext:NSManagedObjectContext { let appDelegate = NSApp.delegate as! AppDelegate return appDelegate.persistentContainer.viewContext } override init() { } func save() { let appDelegate = NSApp.delegate as! AppDelegate appDelegate.saveAction(self) } func clearAllCoreData() { // let allContacts = ChatContact.allContacts() // // for contact in allContacts { // managedObjectContext.delete(contact) // } let contactsFetchRequest = ChatContact.fetchRequest() // NSFetchRequest<NSFetchRequestResult>(entityName: "Contact") let deleteContactsRequest = NSBatchDeleteRequest(fetchRequest: contactsFetchRequest) do { let context = workerContext() try context.execute(deleteContactsRequest) try context.save() } catch let error { NSLog("ERROR when deleting contacts : \(error)") } } func workerContext() -> NSManagedObjectContext { let appDelegate = NSApp.delegate as! AppDelegate let worker = appDelegate.persistentContainer.newBackgroundContext() return worker } }
gpl-3.0
db845983a515e5713d31d2e539eedf14
23.75
124
0.656566
5.24735
false
false
false
false
banjun/Caerula
Example/Caerula/ViewController.swift
1
2018
import UIKit import NorthLayout import Ikemen class ViewController: UIViewController { private var defaultsUUIDs: [String] { get {return UserDefaults.standard.array(forKey: "uuids") as? [String] ?? []} set {UserDefaults.standard.set(newValue, forKey: "uuids")} } private lazy var uuid1Field: UITextField = UITextField() ※ { $0.placeholder = "UUID to monitor" $0.text = self.defaultsUUIDs.count > 0 ? self.defaultsUUIDs[0] : nil $0.borderStyle = .roundedRect } private lazy var uuid2Field: UITextField = UITextField() ※ { $0.placeholder = "UUID to monitor" $0.text = self.defaultsUUIDs.count > 1 ? self.defaultsUUIDs[1] : nil $0.borderStyle = .roundedRect } init() { super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) {fatalError()} override func viewDidLoad() { super.viewDidLoad() title = "Caerula" view.backgroundColor = .white navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Radar", style: .plain, target: self, action: #selector(showRadar)) let autolayout = northLayoutFormat([:], [ "uuid1": uuid1Field, "uuid2": uuid2Field, ]) autolayout("H:||[uuid1]||") autolayout("H:||[uuid2]||") autolayout("V:||-[uuid1]-[uuid2]") } @objc private func showRadar() { let uuids = [uuid1Field, uuid2Field].compactMap {$0.text}.compactMap {UUID(uuidString: $0)} func showVC() { show(RadarViewController(uuids: uuids), sender: nil) } defaultsUUIDs = uuids.map {$0.uuidString} if uuids.isEmpty { let ac = UIAlertController(title: nil, message: "No UUIDs monitored", preferredStyle: .alert) ac.addAction(UIAlertAction(title: "Proceed", style: .default) {_ in showVC()}) present(ac, animated: true, completion: nil) } else { showVC() } } }
mit
099df6e6e4cd9229a1abe86ba031dc24
33.135593
134
0.601787
4.110204
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL/GLRect.swift
1
2236
// // GLRect.swift // SwiftGL // // Created by jerry on 2016/5/10. // Copyright © 2016年 Jerry Chan. All rights reserved. // public struct GLRect { public var leftTop:Vec2 public var rightButtom:Vec2 public var center:Vec2{ get { return (leftTop+rightButtom)/2 } } public var width:Float{ get{ return rightButtom.x - leftTop.x } } public var height:Float{ get{ return rightButtom.y - leftTop.y } } public init(p1:Vec2,p2:Vec2) { leftTop = p1 rightButtom = p2 _area = (leftTop.x-rightButtom.x)*(leftTop.y-rightButtom.y) } // intersect of another rectanble, include overlapping public func intersect(_ rect:GLRect)->Bool { return intersect(rect.leftTop) || intersect(rect.rightButtom) || rect.intersect(leftTop) || rect.intersect(rightButtom) } // if the point inside the rect public func intersect(_ point:Vec2)->Bool { if leftTop <= point && rightButtom >= point { return true } return false } public func getUnionRect(_ point:Vec2)->GLRect { return getUnionRect(GLRect(p1: point, p2: point)) } public func getUnionRect(_ rect:GLRect)->GLRect { let ltx = min(leftTop.x, rect.leftTop.x) let lty = min(leftTop.y, rect.leftTop.y) let rbx = max(rightButtom.x, rect.rightButtom.x) let rby = max(rightButtom.y, rect.rightButtom.y) return GLRect(p1: Vec2(ltx,lty), p2: Vec2(rbx,rby)) } public mutating func union(_ rect:GLRect) { let ltx = min(leftTop.x, rect.leftTop.x) let lty = min(leftTop.y, rect.leftTop.y) let rbx = max(rightButtom.x, rect.rightButtom.x) let rby = max(rightButtom.y, rect.rightButtom.y) leftTop.x = ltx leftTop.y = lty rightButtom.x = rbx rightButtom.y = rby _area = (leftTop.x-rightButtom.x)*(leftTop.y-rightButtom.y) } var _area:Float public var area:Float{ get{ return _area } } } public func - (rect1:GLRect,rect2:GLRect)->Float { return rect1.area - rect2.area }
mit
e6591af54524d9270c4eb1495fb416db
25.903614
128
0.581729
3.445988
false
false
false
false
vycasas/language.bindings
swift/code/sources/dotslashzero/swiftlib/SwiftLib.swift
1
16487
fileprivate func callCLibApiFunctionWithStringReturn( _ cLibApiFunction: ( _ pString: UnsafeMutablePointer<CChar>?, _ stringSize: Int, _ pCharsWritten: UnsafeMutablePointer<Int>?) -> DszCLibErrorNum, _ stringResult: inout String) -> DszCLibErrorNum { let stringSize: Int = 128 let pString = UnsafeMutablePointer<CChar>.allocate(capacity: stringSize) pString.assign(repeating: ("\0".utf8CString[0]), count: stringSize) let cLibErrorNum = cLibApiFunction( pString, stringSize, nil) stringResult = String(cString: pString) pString.deallocate() return cLibErrorNum } public struct LibraryError : Error { private(set) var message: String internal init(errorNum: Int) { self.message = "" _ = callCLibApiFunctionWithStringReturn({ (pString, stringSize, pCharsWritten) -> DszCLibErrorNum in DszCLibErrorNumGetMessage(errorNum, pString, stringSize, pCharsWritten) return (0) }, &self.message) } internal init(message: String) { self.message = message } } extension LibraryError : CustomStringConvertible { public var description: String { return message } } fileprivate func callCLibApiAndCheckErrorNum(_ cLibApiFunction: () -> DszCLibErrorNum) throws { let cLibErrorNum = cLibApiFunction() if (cLibErrorNum != 0) { // swift doesn't unwind stack during exception throwing so no information is lost throw (LibraryError(errorNum: cLibErrorNum)) } } public struct Library { private init() { } public static func initialize() throws { try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in DszCLibLibraryInitialize() }) } public static func uninitialize() { DszCLibLibraryUninitialize() } public static func getVersionString() throws -> String { var versionString = String(); try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in callCLibApiFunctionWithStringReturn({ (pString, stringSize, pCharsWritten) -> DszCLibErrorNum in DszCLibLibraryGetVersionString(pString, stringSize, pCharsWritten) }, &versionString) }) return versionString } public static var versionString: String { return (try? getVersionString()) ?? String() } } public final class Address { // https://stackoverflow.com/a/44894681 private var pImpl: UnsafeMutablePointer<DszCLibAddress?>? public init( streetNum: Int, street: String, city: String, province: String, zipCode: String, country: String) throws { self.pImpl = UnsafeMutablePointer<DszCLibAddress?>.allocate(capacity: 1) try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in DszCLibAddressCreate( CInt(truncatingIfNeeded: streetNum), street, city, province, zipCode, country, self.pImpl) // ?? how does this work? }) } internal init(addressImpl: DszCLibAddress?) { self.pImpl = UnsafeMutablePointer<DszCLibAddress?>.allocate(capacity: 1) self.pImpl!.pointee = addressImpl } deinit { if (self.pImpl != nil) { let pAddressImpl = self.pImpl! DszCLibAddressDestroy(pAddressImpl.pointee) pAddressImpl.deallocate() self.pImpl = nil } } internal func getAddressImpl() throws -> DszCLibAddress? { assert(self.pImpl != nil) let pAddressImpl = self.pImpl! return pAddressImpl.pointee } public func getStreetNum() throws -> Int { let addressImpl = try getAddressImpl() let pStreetNum = UnsafeMutablePointer<CInt>.allocate(capacity: 1) try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in DszCLibAddressGetStreetNum(addressImpl, pStreetNum) }) let streetNum = pStreetNum.pointee pStreetNum.deallocate() return Int(streetNum) } public func getStreet() throws -> String { let addressImpl = try getAddressImpl() var street = String(); try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in callCLibApiFunctionWithStringReturn({ (pString, stringSize, pCharsWritten) -> DszCLibErrorNum in DszCLibAddressGetStreet(addressImpl, pString, stringSize, pCharsWritten) }, &street) }) return street } public func getCity() throws -> String { let addressImpl = try getAddressImpl() var city = String(); try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in callCLibApiFunctionWithStringReturn({ (pString, stringSize, pCharsWritten) -> DszCLibErrorNum in DszCLibAddressGetCity(addressImpl, pString, stringSize, pCharsWritten) }, &city) }) return city } public func getProvince() throws -> String { let addressImpl = try getAddressImpl() var province = String(); try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in callCLibApiFunctionWithStringReturn({ (pString, stringSize, pCharsWritten) -> DszCLibErrorNum in DszCLibAddressGetProvince(addressImpl, pString, stringSize, pCharsWritten) }, &province) }) return province } public func getZipCode() throws -> String { let addressImpl = try getAddressImpl() var zipCode = String(); try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in callCLibApiFunctionWithStringReturn({ (pString, stringSize, pCharsWritten) -> DszCLibErrorNum in DszCLibAddressGetZipCode(addressImpl, pString, stringSize, pCharsWritten) }, &zipCode) }) return zipCode } public func getCountry() throws -> String { let addressImpl = try getAddressImpl() var country = String(); try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in callCLibApiFunctionWithStringReturn({ (pString, stringSize, pCharsWritten) -> DszCLibErrorNum in DszCLibAddressGetCountry(addressImpl, pString, stringSize, pCharsWritten) }, &country) }) return country } public var streetNum: Int { return (try? getStreetNum()) ?? Int() } public var street: String { return (try? getStreet()) ?? String() } public var city: String { return (try? getCity()) ?? String() } public var province: String { return (try? getProvince()) ?? String() } public var zipCode: String { return (try? getZipCode()) ?? String() } public var country: String { return (try? getCountry()) ?? String() } public func toString() throws -> String { let addressImpl = try getAddressImpl() var addressString = String(); try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in callCLibApiFunctionWithStringReturn({ (pString, stringSize, pCharsWritten) -> DszCLibErrorNum in DszCLibAddressToString(addressImpl, pString, stringSize, pCharsWritten) }, &addressString) }) return addressString } } extension Address : CustomStringConvertible { public var description: String { return (try? toString()) ?? String() } } public final class Person { private var pImpl: UnsafeMutablePointer<DszCLibPerson?>? public init( lastName: String, firstName: String, age: Int, address: Address) throws { self.pImpl = UnsafeMutablePointer<DszCLibPerson?>.allocate(capacity: 1) let addressImpl = try address.getAddressImpl() try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in DszCLibPersonCreate( lastName, firstName, CInt(truncatingIfNeeded: age), addressImpl, self.pImpl) // ?? how does this work? }) } internal init(personImpl: DszCLibPerson?) { self.pImpl = UnsafeMutablePointer<DszCLibPerson?>.allocate(capacity: 1) self.pImpl!.pointee = personImpl } deinit { if (self.pImpl != nil) { let pPersonImpl = self.pImpl! DszCLibPersonDestroy(pPersonImpl.pointee) pPersonImpl.deallocate() self.pImpl = nil } } internal func getPersonImpl() throws -> DszCLibPerson? { assert(self.pImpl != nil) let pPersonImpl = self.pImpl! return pPersonImpl.pointee } public func getLastName() throws -> String { let personImpl = try getPersonImpl() var lastName = String(); try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in callCLibApiFunctionWithStringReturn({ (pString, stringSize, pCharsWritten) -> DszCLibErrorNum in DszCLibPersonGetLastName(personImpl, pString, stringSize, pCharsWritten) }, &lastName) }) return lastName } public func getFirstName() throws -> String { let personImpl = try getPersonImpl() var firstName = String(); try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in callCLibApiFunctionWithStringReturn({ (pString, stringSize, pCharsWritten) -> DszCLibErrorNum in DszCLibPersonGetFirstName(personImpl, pString, stringSize, pCharsWritten) }, &firstName) }) return firstName } public func getAge() throws -> Int { let personImpl = try getPersonImpl() let pAge = UnsafeMutablePointer<CInt>.allocate(capacity: 1) try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in DszCLibPersonGetAge(personImpl, pAge) }) let age = pAge.pointee pAge.deallocate() return Int(age) } public func getAddress() throws -> Address? { let personImpl = try getPersonImpl() let pAddressImpl = UnsafeMutablePointer<DszCLibAddress?>.allocate(capacity: 1) try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in DszCLibPersonGetAddress(personImpl, pAddressImpl) }) let addressImpl = pAddressImpl.pointee if (addressImpl == nil) { return nil } let address = Address(addressImpl: addressImpl) pAddressImpl.deallocate() return address } public var lastName: String { return (try? getLastName()) ?? String() } public var firstName: String { return (try? getFirstName()) ?? String() } public var age: Int { return (try? getAge()) ?? Int() } public var address: Address? { return try? getAddress() } public func toString() throws -> String { let personImpl = try getPersonImpl() var personString = String(); try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in callCLibApiFunctionWithStringReturn({ (pString, stringSize, pCharsWritten) -> DszCLibErrorNum in DszCLibPersonToString(personImpl, pString, stringSize, pCharsWritten) }, &personString) }) return personString } } extension Person : CustomStringConvertible { public var description: String { return (try? toString()) ?? String() } } public protocol Generator { func generateInt(data: Int) -> Int func generateString(data: Int) -> String } fileprivate func generateIntRedirect( _ data: CInt, _ pInt: UnsafeMutablePointer<CInt>?, _ pUserData: UnsafeMutableRawPointer?) -> DszCLibErrorNum { if (pInt == nil) { return DszCLibErrorNum(-2) } if (pUserData == nil) { return DszCLibErrorNum(-2) } let generator = pUserData!.load(as: Generator.self) let generatedInt = generator.generateInt(data: Int(data)) pInt!.pointee = CInt(truncatingIfNeeded: generatedInt) return DszCLibErrorNum(0) } fileprivate func generateStringRedirect( _ data: CInt, _ pString: UnsafeMutablePointer<CChar>?, _ stringSize: Int, _ pCharsWritten: UnsafeMutablePointer<Int>?, _ pUserData: UnsafeMutableRawPointer?) -> DszCLibErrorNum { if (pUserData == nil) { return DszCLibErrorNum(-2) } let generator = pUserData!.load(as: Generator.self) let generatedString = generator.generateString(data: Int(data)) var numChars = generatedString.utf8.count; if ((pString != nil) && (stringSize > 0)) { numChars = numChars < stringSize ? numChars : stringSize let utf8Array = Array(generatedString.utf8) for i in 1...numChars { pString![i - 1] = CChar(utf8Array[i - 1]) } } if (pCharsWritten != nil) { pCharsWritten!.pointee = numChars } return DszCLibErrorNum(0) } public final class Printer { private var pImpl: UnsafeMutablePointer<DszCLibPrinter?>? private var generator: Generator // needed to keep the closures alive as long as Printer is allive private var fnGenerateInt: DszCLibGenerateIntFunction? private var fnGenerateString: DszCLibGenerateStringFunction? public init(generator: Generator) throws { self.pImpl = UnsafeMutablePointer<DszCLibPerson?>.allocate(capacity: 1) self.generator = generator fnGenerateInt = { (data, pInt, pUserData) -> DszCLibErrorNum in generateIntRedirect(data, pInt, pUserData) } fnGenerateString = { (data, pString, stringSize, pCharsWritten, pUserData) -> DszCLibErrorNum in generateStringRedirect(data, pString, stringSize, pCharsWritten, pUserData) } let pGeneratorImpl = try createGeneratorImpl() if (pGeneratorImpl == nil) { throw LibraryError(message: "Failed to create generator") } try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in DszCLibPrinterCreate( pGeneratorImpl!.pointee, self.pImpl) }) pGeneratorImpl!.deallocate() } deinit { if (self.pImpl != nil) { let pPrinterImpl = self.pImpl! DszCLibPrinterDestroy(pPrinterImpl.pointee) pPrinterImpl.deallocate() self.pImpl = nil } } internal func getPrinterImpl() throws -> DszCLibPrinter? { assert(self.pImpl != nil) let pPrinterImpl = self.pImpl! return pPrinterImpl.pointee } private func createGeneratorImpl() throws -> UnsafeMutablePointer<DszCLibGenerator?>? { let pGeneratorImpl = UnsafeMutablePointer<DszCLibGenerator?>.allocate(capacity: 1) try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in DszCLibGeneratorCreate( fnGenerateInt, fnGenerateString, pGeneratorImpl) }) return pGeneratorImpl } public func printInt() throws { let printerImpl = try getPrinterImpl() try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in DszCLibPrinterPrintIntWithUserData( printerImpl, &self.generator) }) } public func printString() throws { let printerImpl = try getPrinterImpl() try callCLibApiAndCheckErrorNum({ () -> DszCLibErrorNum in DszCLibPrinterPrintStringWithUserData( printerImpl, &self.generator) }) } }
mit
9bec6642971f90d33dc1001b21162e33
28.388592
98
0.595014
4.458356
false
false
false
false
zxpLearnios/MyProject
test_projectDemo1/TVC && NAV/MyCustomTVC.swift
1
9046
// // MyCustomTVC.swift // test_Colsure // // Created by Jingnan Zhang on 16/5/10. // Copyright © 2016年 Jingnan Zhang. All rights reserved. // 1. 自定义TVC, 使用提醒按钮 2. 有判断类型; 3. plusBtn 做动画,从某处到tabbar的指定位置,动画结束后,主动刷新tabbar的子控件,在tabbar里加了判断,移除plusBtn,将此处加自定义的只有图片的tabbarItem即可;实现切屏时的位移问题的处理。 即只要是通过addSubView上到tabbar的估计在横竖屏切换时都会出错,必须是tabbar自带的东西才不会出错的。 import UIKit class MyCustomTVC: UITabBarController, UITabBarControllerDelegate, CAAnimationDelegate { var childVCs = [UIViewController]() var customTabBar = MyTabBar() var plusBtn = MyPlusButton() // 真正的和其他item平均分占了tabbar,如在自定义的tabbar里加plusBtn,则最左边的item的有效范围始终会挡住plusBtn的左半部 var toPoint = CGPoint.zero var isCompleteAnimate = false // MARK: xib\代码 都会调之,但此类型只会调一次 override class func initialize() { self.doInit() } // MARK: 做一些事 class func doInit() { // 所有的字控制器的tabbarItem的 字体属性 let tabbarItem = UITabBarItem.appearance() // 不能用UIBarButtonItem let itemAttributeNormal = [NSFontAttributeName: UIFont.systemFont(ofSize: 10), NSForegroundColorAttributeName: UIColor.red] let itemAttributeHighlight = [NSFontAttributeName: UIFont.systemFont(ofSize: 10), NSForegroundColorAttributeName: UIColor.green] tabbarItem.setTitleTextAttributes(itemAttributeNormal, for: UIControlState()) tabbarItem.setTitleTextAttributes(itemAttributeHighlight, for: .selected) // 用highlight无效 // 此处设置tabbarItem的图片无效(估计纯代码情况下也是无效) // tabBarItem.image = UIImage(named: "Customer_select") // tabBarItem.selectedImage = UIImage(named: "Customer_unselect") } override func viewDidLoad() { super.viewDidLoad() // -1 self.delegate = self // 0. 以便子控制器的view做转场动画时看到白色 self.view.backgroundColor = UIColor.white // 1, 加子控制器 let fistVC = firstChildVC() self.addChildViewControllers(fistVC, title: "第一个", itemImage: UIImage(named: "tabBar_me_icon"), itemSelectedImage: UIImage(named: "tabBar_me_click_icon")) let secondVC = secondChildVC() self.addChildViewControllers(secondVC, title: "第二个", itemImage: UIImage(named: "tabBar_essence_icon"), itemSelectedImage: UIImage(named: "tabBar_essence_click_icon")) let thirdVC = ThirdChildVC() self.addChildViewControllers(thirdVC, title: "第三个", itemImage: UIImage(named: "tabBar_friendTrends_icon"), itemSelectedImage: UIImage(named: "tabBar_friendTrends_click_icon")) // 2。 KVO替换原tabbar self.setValue(customTabBar, forKey: "tabBar") // 4.设置tabbaralpha self.tabBar.alpha = 0.8 let time = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time) { self.addPlusButton() } self.addChildViewControllers(UIViewController(), title: "", itemImage: UIImage(named: "tabBar_publish_icon"), itemSelectedImage: UIImage(named: "tabBar_publish_icon")) // 5. 屏幕旋转通知 kDevice.beginGeneratingDeviceOrientationNotifications() kNotificationCenter.addObserver(self, selector: #selector(orientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // for item in self.tabBar.subviews { // if item.isKindOfClass(UIControl) { // item.removeFromSuperview() // 此时不要 // } // } // MARK: 判断类型 // is 和 item.isKindOfClass 都是判断一个实例是否是某种类型 // print(self.childViewControllers) } // 横屏变竖屏后,会再次调用之,故须做处理, 即不能在此处加加号按钮了,因为横屏变竖屏显示testVC后,就会进入此法,此时加号按钮会显示在testVC底部,且进入TabbarVC后plusBtn的位置也不对, 故在viewDidLoad里加plusBtn但需要延迟等viewDidAppear后才可以加,确保只会执行一次; 此时屏幕还是横着的 override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // 3.添加加号按钮, 必须在视图显示完毕后添加 // addPlusButton() } // MARK: 屏幕旋转了 @objc fileprivate func orientationDidChange(){ if kDevice.orientation == .portrait { } if kDevice.orientation == .landscapeRight || kDevice.orientation == .landscapeLeft { } } // MARK: 添加加号按钮 func addPlusButton(){ // 设置加号按钮 self.tabBar.addSubview(plusBtn) // let width = self.view.width / 4 // customTabBar.buttonW plusBtn.bounds = CGRect(x: 0, y: 0, width: width, height: 50) plusBtn.setImage(UIImage(named: "tabBar_publish_icon"), for: UIControlState()) // plusBtn.setTitle("加号", forState: .Normal) plusBtn.addTarget(self, action: #selector(btnAction), for: .touchUpInside) // 动画 let tabbarCenter = self.view.convert(self.tabBar.center, to: self.tabBar) let ani = CABasicAnimation.init(keyPath: "position") ani.duration = 0.5 ani.fromValue = NSValue.init(cgPoint: CGPoint(x: kwidth * 0.2, y: -kheight * 0.7)) toPoint = CGPoint(x: width * 1.5, y: tabbarCenter.y) ani.toValue = NSValue.init(cgPoint: toPoint) ani.delegate = self let time = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: time) { self.plusBtn.isHidden = false self.plusBtn.layer.add(ani, forKey: "") } } func btnAction(_ plusBtn:MyPlusButton) { plusBtn.isSelected = !plusBtn.isSelected print("点击了加号按钮") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: 添加子控制器 fileprivate func addChildViewControllers(_ viewController:UIViewController, title:String, itemImage:UIImage?, itemSelectedImage:UIImage?){ let newItemSelectdImg = itemSelectedImage?.withRenderingMode(.alwaysOriginal) if self.viewControllers?.count == 3 { // 只有图片的tabbaritem let item = MyCustomTabBarItem.init(image: itemImage, selectedImage: itemSelectedImage) viewController.tabBarItem = item }else{ // 当navigationItem.title != tabBarItem.title 时,必须如此设置:先设置title,在设置navigationItem.title,设置tabBarItem.title已经无用了 // viewController.title = title // viewController.navigationItem.title = "我的账户" viewController.title = title viewController.tabBarItem.image = itemImage viewController.tabBarItem.selectedImage = newItemSelectdImg } let nav = MyCustomNav.init(rootViewController: viewController) self.addChildViewController(nav) } // MARK: UITabBarControllerDelegate func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { let index = self.viewControllers?.index(of: viewController) if index != nil { if index == 3 { self.perform(#selector(btnAction), with: plusBtn, afterDelay: 0) // viewController.tabBarItem.selectedImage = nil // 可以在此处设置点击item时的选中图片,因为点击item选中控制器被禁止了 // self.selectedIndex = 3 // 因为这样会选中并显示控制器 return false }else{ return true } }else{ return false } } func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if flag { plusBtn.center = toPoint isCompleteAnimate = true self.tabBar.layoutSubviews() // 主动刷新 } } }
mit
9db46f4a1c4d9567376377d769cd85f9
34.497778
209
0.623263
4.310308
false
false
false
false
rolson/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Maps/Change map view background/ChangeMapViewBackgroundVC.swift
1
2799
// Copyright 2016 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class ChangeMapViewBackgroundVC: UIViewController, GridSettingsVCDelegate { @IBOutlet var mapView: AGSMapView! @IBOutlet var settingsContainerView: UIView! override func viewDidLoad() { super.viewDidLoad() //add the source code button item to the right of navigation bar (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["ChangeMapViewBackgroundVC", "GridSettingsViewController"] //initialize tiled layer let tiledLayer = AGSArcGISTiledLayer(URL: NSURL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/WorldTimeZones/MapServer")!) //initialize map with tiled layer as basemap let map = AGSMap(basemap: AGSBasemap(baseLayer: tiledLayer)) //set initial viewpoint let center = AGSPoint(x: 3224786.498918, y: 2661231.326777, spatialReference: AGSSpatialReference(WKID: 3857)) map.initialViewpoint = AGSViewpoint(center: center, scale: 236663484.12225574) //assign map to the map view self.mapView.map = map } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: - GridSettingsVCDelegate func gridSettingsViewController(gridSettingsViewController: GridSettingsViewController, didUpdateBackgroundGrid grid: AGSBackgroundGrid) { //update background grid on the map view self.mapView.backgroundGrid = grid } func gridSettingsViewControllerWantsToClose(gridSettingsViewController: GridSettingsViewController) { self.settingsContainerView.hidden = true } //MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "EmbedSegue" { let controller = segue.destinationViewController as! GridSettingsViewController controller.delegate = self } } //MARK: - Actions @IBAction private func changeBackgroundAction() { self.settingsContainerView.hidden = false } }
apache-2.0
9a1a4a7627b7a6c9cc6ce65dcfc38125
36.32
153
0.702036
5.052347
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/StackedImageLabelView.swift
1
2133
import UIKit /// A vertically stacked image/label group that resembles `UITableView`'s swipe actions final class StackedImageLabelView: SetupView { // MARK: - Properties var increaseLabelTopPadding: Bool = false { didSet { labelTopConstraint.constant = increaseLabelTopPadding ? 8 : 2 setNeedsLayout() } } private var imageDimension: CGFloat = 40 private var labelTopConstraint: NSLayoutConstraint = NSLayoutConstraint() // MARK: - UI Elements lazy var label: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.textColor = .white label.numberOfLines = 0 label.textAlignment = .center label.font = UIFont.wmf_scaledSystemFont(forTextStyle: .body, weight: .bold, size: 14, maximumPointSize: 32) label.adjustsFontForContentSizeCategory = true label.adjustsFontSizeToFitWidth = true return label }() lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.tintColor = .white imageView.contentMode = .scaleAspectFit return imageView }() // MARK: - Lifecycle override func setup() { addSubview(imageView) addSubview(label) labelTopConstraint = label.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 2) NSLayoutConstraint.activate([ imageView.bottomAnchor.constraint(equalTo: centerYAnchor, constant: 3), imageView.centerXAnchor.constraint(equalTo: centerXAnchor), imageView.widthAnchor.constraint(equalToConstant: imageDimension), imageView.heightAnchor.constraint(equalToConstant: imageDimension), label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8), label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -8), labelTopConstraint, label.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: -10) ]) } }
mit
0ad0e97cb2023b339f687ececd82d1ca
33.967213
116
0.678387
5.688
false
false
false
false
MA806P/SwiftDemo
Developing_iOS_10_Apps_with_Swift/SwiftDemo/SwiftDemo/FaceIt/FaceView.swift
1
4367
// // FaceView.swift // SwiftDemo // // Created by MA806P on 2017/3/7. // Copyright © 2017年 myz. All rights reserved. // import UIKit @IBDesignable class FaceView: UIView { @IBInspectable var scale: CGFloat = 0.9 { didSet { setNeedsDisplay() } } @IBInspectable var lineWidth: CGFloat = 5.0 { didSet { setNeedsDisplay() } } @IBInspectable var color: UIColor = UIColor.blue { didSet { setNeedsDisplay() } } @IBInspectable var eyesOpen: Bool = true { didSet { setNeedsDisplay() } } @IBInspectable var mouthCurvature: Double = 0.5 { didSet { setNeedsDisplay() } } private var skullCenter: CGPoint { return CGPoint(x: bounds.midX, y: bounds.midY+20) } private var skullRadius: CGFloat { return min(bounds.size.width, bounds.size.height) * 0.5 * scale } private enum Eye { case left case right } private struct Ratios { static let skullRadiusToEyeOffset: CGFloat = 3 static let skullRadiusToEyeRadius: CGFloat = 10 static let skullRadiusToMouthWith: CGFloat = 1 static let skullRadiusToMouthHeight: CGFloat = 3 static let skullRadiusToMouthOffset: CGFloat = 3 } func changeScale(byReactingTo pinchRecognizer: UIPinchGestureRecognizer) { switch pinchRecognizer.state { case .changed, .ended: scale *= pinchRecognizer.scale pinchRecognizer.scale = 1 default: break } } private func pathForSkull() -> UIBezierPath { let path = UIBezierPath(arcCenter: skullCenter, radius: skullRadius, startAngle: 0, endAngle: 2 * CGFloat.pi, clockwise: false) path.lineWidth = lineWidth return path } private func pathForEye(_ eye: Eye) -> UIBezierPath { func centerOfEye(_ eye: Eye) -> CGPoint { let eyeOffset = skullRadius / Ratios.skullRadiusToEyeOffset var eyeCenter = skullCenter eyeCenter.y -= eyeOffset eyeCenter.x += ((eye == .left) ? -1 : 1) * eyeOffset return eyeCenter } let eyeRadius = skullRadius / Ratios.skullRadiusToEyeRadius let eyeCenter = centerOfEye(eye) let path: UIBezierPath if eyesOpen { path = UIBezierPath( arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat.pi * 2.0, clockwise: true ) } else { path = UIBezierPath() path.move(to: CGPoint(x: eyeCenter.x - eyeRadius, y: eyeCenter.y)) path.addLine(to: CGPoint(x: eyeCenter.x + eyeRadius, y: eyeCenter.y)) } path.lineWidth = lineWidth; return path } private func pathForMouth() -> UIBezierPath { let mouthWidth = skullRadius / Ratios.skullRadiusToMouthWith let mouthHeight = skullRadius / Ratios.skullRadiusToMouthHeight let mouthOffset = skullRadius / Ratios.skullRadiusToMouthOffset let mouthRect = CGRect( x: skullCenter.x - mouthWidth * 0.5, y: skullCenter.y + mouthOffset, width: mouthWidth, height: mouthHeight ) let smileOffset = CGFloat(max(-1, min(mouthCurvature, 1))) * mouthHeight let start = CGPoint(x: mouthRect.minX, y: mouthRect.midY) let end = CGPoint(x: mouthRect.maxX, y: mouthRect.midY) let cp1 = CGPoint(x: start.x + mouthRect.width / 3, y: start.y + smileOffset) let cp2 = CGPoint(x: end.x - mouthRect.width / 3, y: start.y + smileOffset) let path = UIBezierPath() path.move(to: start) path.addCurve(to: end, controlPoint1: cp1, controlPoint2: cp2) path.lineWidth = lineWidth return path } override func draw(_ rect: CGRect) { color.set() pathForSkull().stroke() pathForEye(.left).stroke() pathForEye(.right).stroke() pathForMouth().stroke() } }
apache-2.0
7865b045931412cd744e84a1d13d6ff6
25.773006
135
0.558433
4.560084
false
false
false
false
gabek/GitYourFeedback
Example/Pods/GRMustache.swift/Sources/Foundation.swift
2
12615
// The MIT License // // Copyright (c) 2016 Gwendal Roué // // 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 /// GRMustache provides built-in support for rendering `NSObject`. extension NSObject : MustacheBoxable { /// `NSObject` adopts the `MustacheBoxable` protocol so that it can feed /// Mustache templates. /// /// You should not directly call the `mustacheBox` property. /// /// /// NSObject's default implementation handles two general cases: /// /// - Enumerable objects that conform to the `NSFastEnumeration` protocol, /// such as `NSArray` and `NSOrderedSet`. /// - All other objects /// /// GRMustache ships with a few specific classes that escape the general /// cases and provide their own rendering behavior: `NSDictionary`, /// `NSFormatter`, `NSNull`, `NSNumber`, `NSString`, and `NSSet` (see the /// documentation for those classes). /// /// Your own subclasses of NSObject can also override the `mustacheBox` /// method and provide their own custom behavior. /// /// /// ## Arrays /// /// An object is treated as an array if it conforms to `NSFastEnumeration`. /// This is the case of `NSArray` and `NSOrderedSet`, for example. /// `NSDictionary` and `NSSet` have their own custom Mustache rendering: see /// their documentation for more information. /// /// /// ### Rendering /// /// - `{{array}}` renders the concatenation of the renderings of the /// array items. /// /// - `{{#array}}...{{/array}}` renders as many times as there are items in /// `array`, pushing each item on its turn on the top of the /// context stack. /// /// - `{{^array}}...{{/array}}` renders if and only if `array` is empty. /// /// /// ### Keys exposed to templates /// /// An array can be queried for the following keys: /// /// - `count`: number of elements in the array /// - `first`: the first object in the array /// - `last`: the last object in the array /// /// Because 0 (zero) is falsey, `{{#array.count}}...{{/array.count}}` /// renders once, if and only if `array` is not empty. /// /// /// ## Other objects /// /// Other objects fall in the general case. /// /// Their keys are extracted with the `valueForKey:` method, as long as the /// key is a property name, a custom property getter, or the name of a /// `NSManagedObject` attribute. /// /// /// ### Rendering /// /// - `{{object}}` renders the result of the `description` method, /// HTML-escaped. /// /// - `{{{object}}}` renders the result of the `description` method, *not* /// HTML-escaped. /// /// - `{{#object}}...{{/object}}` renders once, pushing `object` on the top /// of the context stack. /// /// - `{{^object}}...{{/object}}` does not render. open var mustacheBox: MustacheBox { if let enumerable = self as? NSFastEnumeration { // Enumerable // Turn enumerable into a Swift array that we know how to box return Box(Array(IteratorSequence(NSFastEnumerationIterator(enumerable)))) } else { // Generic NSObject #if OBJC return MustacheBox( value: self, keyedSubscript: { (key: String) in if GRMustacheKeyAccess.isSafeMustacheKey(key, for: self) { // Use valueForKey: for safe keys return self.value(forKey: key) } else { // Missing key return nil } }) #else return MustacheBox(value: self) #endif } } } /// GRMustache provides built-in support for rendering `NSNull`. extension NSNull { /// `NSNull` adopts the `MustacheBoxable` protocol so that it can feed /// Mustache templates. /// /// You should not directly call the `mustacheBox` property. Always use the /// `Box()` function instead: /// /// NSNull().mustacheBox // Valid, but discouraged /// Box(NSNull()) // Preferred /// /// /// ### Rendering /// /// - `{{null}}` does not render. /// /// - `{{#null}}...{{/null}}` does not render (NSNull is falsey). /// /// - `{{^null}}...{{/null}}` does render (NSNull is falsey). open override var mustacheBox: MustacheBox { return MustacheBox( value: self, boolValue: false, render: { (info: RenderingInfo) in return Rendering("") }) } } /// GRMustache provides built-in support for rendering `NSNumber`. extension NSNumber { /// `NSNumber` adopts the `MustacheBoxable` protocol so that it can feed /// Mustache templates. /// /// You should not directly call the `mustacheBox` property. /// /// /// ### Rendering /// /// NSNumber renders exactly like Swift numbers: depending on its internal /// objCType, an NSNumber is rendered as a Swift Bool, Int, UInt, Int64, /// UInt64, or Double. /// /// - `{{number}}` is rendered with built-in Swift String Interpolation. /// Custom formatting can be explicitly required with NumberFormatter, /// as in `{{format(a)}}` (see `Formatter`). /// /// - `{{#number}}...{{/number}}` renders if and only if `number` is /// not 0 (zero). /// /// - `{{^number}}...{{/number}}` renders if and only if `number` is 0 (zero). /// open override var mustacheBox: MustacheBox { let objCType = String(cString: self.objCType) switch objCType { case "c": return Box(Int(int8Value)) case "C": return Box(UInt(uint8Value)) case "s": return Box(Int(int16Value)) case "S": return Box(UInt(uint16Value)) case "i": return Box(Int(int32Value)) case "I": return Box(UInt(uint32Value)) case "l": return Box(intValue) case "L": return Box(uintValue) case "q": return Box(int64Value) case "Q": return Box(uint64Value) case "f": return Box(floatValue) case "d": return Box(doubleValue) case "B": return Box(boolValue) default: return Box(self) } } } /// GRMustache provides built-in support for rendering `NSString`. extension NSString { /// `NSString` adopts the `MustacheBoxable` protocol so that it can feed /// Mustache templates. /// /// You should not directly call the `mustacheBox` property. /// /// /// ### Rendering /// /// - `{{string}}` renders the string, HTML-escaped. /// /// - `{{{string}}}` renders the string, *not* HTML-escaped. /// /// - `{{#string}}...{{/string}}` renders if and only if `string` is /// not empty. /// /// - `{{^string}}...{{/string}}` renders if and only if `string` is empty. /// /// HTML-escaping of `{{string}}` tags is disabled for Text templates: see /// `Configuration.contentType` for a full discussion of the content type of /// templates. /// /// /// ### Keys exposed to templates /// /// A string can be queried for the following keys: /// /// - `length`: the number of characters in the string (using Swift method). open override var mustacheBox: MustacheBox { return Box(self as String) } } /// GRMustache provides built-in support for rendering `NSSet`. extension NSSet { /// `NSSet` adopts the `MustacheBoxable` protocol so that it can feed /// Mustache templates. /// /// let set: NSSet = [1,2,3] /// /// // Renders "213" /// let template = try! Template(string: "{{#set}}{{.}}{{/set}}") /// try! template.render(Box(["set": Box(set)])) /// /// /// You should not directly call the `mustacheBox` property. /// /// ### Rendering /// /// - `{{set}}` renders the concatenation of the renderings of the set /// items, in any order. /// /// - `{{#set}}...{{/set}}` renders as many times as there are items in /// `set`, pushing each item on its turn on the top of the context stack. /// /// - `{{^set}}...{{/set}}` renders if and only if `set` is empty. /// /// /// ### Keys exposed to templates /// /// A set can be queried for the following keys: /// /// - `count`: number of elements in the set /// - `first`: the first object in the set /// /// Because 0 (zero) is falsey, `{{#set.count}}...{{/set.count}}` renders /// once, if and only if `set` is not empty. open override var mustacheBox: MustacheBox { return Box(Set(IteratorSequence(NSFastEnumerationIterator(self)).flatMap { $0 as? AnyHashable })) } } /// GRMustache provides built-in support for rendering `NSDictionary`. extension NSDictionary { /// `NSDictionary` adopts the `MustacheBoxable` protocol so that it can feed /// Mustache templates. /// /// // Renders "Freddy Mercury" /// let dictionary: NSDictionary = [ /// "firstName": "Freddy", /// "lastName": "Mercury"] /// let template = try! Template(string: "{{firstName}} {{lastName}}") /// let rendering = try! template.render(Box(dictionary)) /// /// /// You should not directly call the `mustacheBox` property. /// /// /// ### Rendering /// /// - `{{dictionary}}` renders the result of the `description` method, /// HTML-escaped. /// /// - `{{{dictionary}}}` renders the result of the `description` method, /// *not* HTML-escaped. /// /// - `{{#dictionary}}...{{/dictionary}}` renders once, pushing `dictionary` /// on the top of the context stack. /// /// - `{{^dictionary}}...{{/dictionary}}` does not render. /// /// /// In order to iterate over the key/value pairs of a dictionary, use the /// `each` filter from the Standard Library: /// /// // Attach StandardLibrary.each to the key "each": /// let template = try! Template(string: "<{{# each(dictionary) }}{{@key}}:{{.}}, {{/}}>") /// template.register(StandardLibrary.each, forKey: "each") /// /// // Renders "<name:Arthur, age:36, >" /// let dictionary = ["name": "Arthur", "age": 36] as NSDictionary /// let rendering = try! template.render(["dictionary": dictionary]) open override var mustacheBox: MustacheBox { return Box(self as? [AnyHashable: Any]) } } /// Support for Mustache rendering of ReferenceConvertible types. extension ReferenceConvertible where Self: MustacheBoxable { /// Returns a MustacheBox that behaves like the equivalent NSObject. /// /// See NSObject.mustacheBox public var mustacheBox: MustacheBox { return (self as! ReferenceType).mustacheBox } } /// Data can feed Mustache templates. extension Data : MustacheBoxable { } /// Date can feed Mustache templates. extension Date : MustacheBoxable { } /// URL can feed Mustache templates. extension URL : MustacheBoxable { } /// UUID can feed Mustache templates. extension UUID : MustacheBoxable { }
mit
bcfc97ebce1f4e92ca2223dad6ba2cd5
33.464481
105
0.577374
4.571946
false
false
false
false
donileo/RMessage
Sources/RMessage/Animators/SlideAnimator.swift
1
12604
// // SlideAnimator.swift // // Created by Adonis Peralta on 8/6/18. // Copyright © 2018 None. All rights reserved. // import Foundation import UIKit private enum Constants { enum KVC { static let safeAreaInsets = "view.safeAreaInsets" } } /// Implements an animator that slides the message from the top to target position or /// bottom to target position. This animator handles the layout of its managed view in the managed /// view's superview. class SlideAnimator: NSObject, RMAnimator { /// Animator delegate. weak var delegate: RMessageAnimatorDelegate? // MARK: - Start the customizable animation properties /// The amount of time to perform the presentation animation in. var presentationDuration = 0.5 /// The amount of time to perform the dismiss animation in. var dismissalDuration = 0.3 /// The alpha value the view should have prior to starting animations. var animationStartAlpha: CGFloat = 0 /// The alpha value the view should have at the end of animations. var animationEndAlpha: CGFloat = 1 /// A custom vertical offset to apply to the animation. positive values move the view upward, /// negative values move it downward. var verticalOffset = CGFloat(0) /// Enables/disables the use animation padding so as to prevent a visual white gap from appearing when /// animating with a spring animation. var disableAnimationPadding = false private let superview: UIView @objc private let view: UIView private let contentView: UIView private let targetPosition: RMessagePosition /** The starting animation constraint for the view */ private var viewStartConstraint: NSLayoutConstraint? /** The ending animation constraint for the view */ private var viewEndConstraint: NSLayoutConstraint? private var contentViewSafeAreaGuideConstraint: NSLayoutConstraint? /** The amount of vertical padding/height to add to RMessage's height so as to perform a spring animation without visually showing an empty gap due to the spring animation overbounce. This value changes dynamically due to iOS changing the overbounce dynamically according to view size. */ private var springAnimationPadding = CGFloat(0) private var springAnimationPaddingCalculated = false private var isPresenting = false private var isDismissing = false private var hasPresented = false private var hasDismissed = true private var kvcContext = 0 init(targetPosition: RMessagePosition, view: UIView, superview: UIView, contentView: UIView) { self.targetPosition = targetPosition self.superview = superview self.contentView = contentView self.view = view super.init() // Sign up to be notified for when the safe area of our view changes addObserver(self, forKeyPath: Constants.KVC.safeAreaInsets, options: [.new], context: &kvcContext) } /// Ask the animator to present the view with animation. This call may or may not succeed depending on whether /// the animator was already previously asked to animate or where in the presentation cycle the animator is. /// In cases when the animator refuses to present this method returns false, otherwise it returns true. /// /// - Note: Your implementation of this method must allow for this method to be called multiple times by ignoring /// subsequent requests. /// - Parameter completion: A completion closure to execute after presentation is complete. /// - Returns: A boolean value indicating if the animator executed your instruction to present. func present(withCompletion completion: (() -> Void)?) -> Bool { // Guard against being called under the following conditions: // 1. If currently presenting or dismissing // 2. If already presented or have not yet dismissed guard !isPresenting && !hasPresented && hasDismissed else { return false } layoutView() setupFinalAnimationConstraints() setupStartingAnimationConstraints() delegate?.animatorWillAnimatePresentation?(self) animatePresentation(withCompletion: completion) return true } /// Ask the animator to dismiss the view with animation. This call may or may not succeed depending on whether /// the animator was already previously asked to animate or where in the presentation cycle the animator is. /// In cases when the animator refuses to dismiss this method returns false, otherwise it returns true. /// /// - Note: Your implementation of this method must allow for this method to be called multiple times by ignoring /// subsequent requests. /// - Parameter completion: A completion closure to execute after presentation is complete. /// - Returns: A boolean value indicating if the animator executed your instruction to dismiss. func dismiss(withCompletion completion: (() -> Void)?) -> Bool { // Guard against being called under the following conditions: // 1. If currently presenting or dismissing // 2. If already dismissed or have not yet presented guard !isDismissing && hasDismissed && hasPresented else { return false } delegate?.animatorWillAnimateDismissal?(self) animateDismissal(withCompletion: completion) return true } private func animatePresentation(withCompletion completion: (() -> Void)?) { guard let viewSuper = view.superview else { assertionFailure("view must have superview by this point") return } guard let viewStartConstraint = viewStartConstraint, let viewEndConstraint = viewEndConstraint else { return } isPresenting = true viewStartConstraint.isActive = true DispatchQueue.main.async { viewSuper.layoutIfNeeded() self.view.alpha = self.animationStartAlpha // For now lets be safe and not call this code inside the animation block. Though there may be some slight timing // issue in notifying exactly when the animator is animating it should be fine. self.delegate?.animatorIsAnimatingPresentation?(self) UIView.animate( withDuration: self.presentationDuration, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [.curveEaseInOut, .beginFromCurrentState, .allowUserInteraction], animations: { viewStartConstraint.isActive = false viewEndConstraint.isActive = true self.contentViewSafeAreaGuideConstraint?.isActive = true self.delegate?.animationBlockForPresentation?(self) self.view.alpha = self.animationEndAlpha viewSuper.layoutIfNeeded() }, completion: { finished in self.isPresenting = false self.hasPresented = true self.delegate?.animatorDidPresent?(self) if finished { completion?() } } ) } } /** Dismiss the view with a completion block */ private func animateDismissal(withCompletion completion: (() -> Void)?) { guard let viewSuper = view.superview else { assertionFailure("view must have superview by this point") return } guard let viewStartConstraint = viewStartConstraint, let viewEndConstraint = viewEndConstraint else { return } isDismissing = true DispatchQueue.main.async { viewSuper.layoutIfNeeded() // For now lets be safe and not call this code inside the animation block. Though there may be some slight timing // issue in notifying exactly when the animator is animating it should be fine. self.delegate?.animatorIsAnimatingDismissal?(self) UIView.animate( withDuration: self.dismissalDuration, animations: { viewEndConstraint.isActive = false self.contentViewSafeAreaGuideConstraint?.isActive = false viewStartConstraint.isActive = true self.delegate?.animationBlockForDismissal?(self) self.view.alpha = self.animationStartAlpha viewSuper.layoutIfNeeded() }, completion: { finished in self.isDismissing = false self.hasPresented = false self.hasDismissed = true self.view.removeFromSuperview() self.delegate?.animatorDidDismiss?(self) if finished { completion?() } } ) } } // MARK: - View notifications override func observeValue( forKeyPath keyPath: String?, of _: Any?, change _: [NSKeyValueChangeKey: Any]?, context _: UnsafeMutableRawPointer? ) { if keyPath == Constants.KVC.safeAreaInsets { safeAreaInsetsDidChange(forView: view) } } private func safeAreaInsetsDidChange(forView view: UIView) { var constant = CGFloat(0) if targetPosition == .bottom { constant = springAnimationPadding + view.safeAreaInsets.bottom } else { constant = -springAnimationPadding - view.safeAreaInsets.top } viewEndConstraint?.constant = constant } // MARK: - Layout /// Lay's out the view in its superview for presentation private func layoutView() { setupContentViewLayoutGuideConstraint() // Add RMessage to superview and prepare the ending constraints if view.superview == nil { superview.addSubview(view) } view.translatesAutoresizingMaskIntoConstraints = false delegate?.animatorDidAddToSuperview?(self) NSLayoutConstraint.activate([ view.centerXAnchor.constraint(equalTo: superview.centerXAnchor), view.leadingAnchor.constraint(equalTo: superview.leadingAnchor), view.trailingAnchor.constraint(equalTo: superview.trailingAnchor) ]) delegate?.animatorDidLayout?(self) calculateSpringAnimationPadding() } private func setupContentViewLayoutGuideConstraint() { // Install a constraint that guarantees the title subtitle container view is properly spaced from the top layout // guide when animating from top or the bottom layout guide when animating from bottom let safeAreaLayoutGuide = superview.safeAreaLayoutGuide switch targetPosition { case .top, .navBarOverlay: contentViewSafeAreaGuideConstraint = contentView.topAnchor.constraint( equalTo: safeAreaLayoutGuide.topAnchor, constant: 10 ) case .bottom: contentViewSafeAreaGuideConstraint = contentView.bottomAnchor.constraint( equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -10 ) } } private func setupStartingAnimationConstraints() { guard let viewSuper = view.superview else { assertionFailure("view must have superview by this point") return } if targetPosition != .bottom { viewStartConstraint = view.bottomAnchor.constraint(equalTo: viewSuper.topAnchor) } else { viewStartConstraint = view.topAnchor.constraint(equalTo: viewSuper.bottomAnchor) } } private func setupFinalAnimationConstraints() { assert(springAnimationPaddingCalculated, "spring animation padding must have been calculated by now!") guard let viewSuper = view.superview else { assertionFailure("view must have superview by this point") return } var viewAttribute: NSLayoutAttribute var layoutGuideAttribute: NSLayoutAttribute var constant = CGFloat(0) view.layoutIfNeeded() if targetPosition == .bottom { viewAttribute = .bottom layoutGuideAttribute = .bottom constant = springAnimationPadding + viewSuper.safeAreaInsets.bottom } else { viewAttribute = .top layoutGuideAttribute = .top constant = -springAnimationPadding - viewSuper.safeAreaInsets.top } viewEndConstraint = NSLayoutConstraint( item: view, attribute: viewAttribute, relatedBy: .equal, toItem: viewSuper.safeAreaLayoutGuide, attribute: layoutGuideAttribute, multiplier: 1, constant: constant ) viewEndConstraint?.constant += verticalOffset } // Calculate the padding after the view has had a chance to perform its own custom layout changes via the delegate // call to animatorWillLayout, animatorDidLayout private func calculateSpringAnimationPadding() { guard !disableAnimationPadding else { springAnimationPadding = CGFloat(0) springAnimationPaddingCalculated = true return } // Tell the view to layout so that we may properly calculate the spring padding view.layoutIfNeeded() // Base the spring animation padding on an estimated height considering we need the spring animation padding itself // to truly calculate the height of the view. springAnimationPadding = (view.bounds.size.height / 120.0).rounded(.up) * 5 springAnimationPaddingCalculated = true } deinit { removeObserver(self, forKeyPath: Constants.KVC.safeAreaInsets) } }
mit
3c85a68da43e01c0565a749a5923e259
36.176991
119
0.723161
5.169401
false
false
false
false
bitjammer/swift
stdlib/public/core/ContiguousArrayBuffer.swift
1
23828
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims /// Class used whose sole instance is used as storage for empty /// arrays. The instance is defined in the runtime and statically /// initialized. See stdlib/runtime/GlobalObjects.cpp for details. /// Because it's statically referenced, it requires non-lazy realization /// by the Objective-C runtime. @_fixed_layout @_versioned @objc_non_lazy_realization internal final class _EmptyArrayStorage : _ContiguousArrayStorageBase { @_inlineable @_versioned init(_doNotCallMe: ()) { _sanityCheckFailure("creating instance of _EmptyArrayStorage") } #if _runtime(_ObjC) @_inlineable @_versioned override func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { return try body(UnsafeBufferPointer(start: nil, count: 0)) } @_inlineable @_versioned override func _getNonVerbatimBridgedCount() -> Int { return 0 } @_inlineable @_versioned override func _getNonVerbatimBridgedHeapBuffer() -> _HeapBuffer<Int, AnyObject> { return _HeapBuffer<Int, AnyObject>( _HeapBufferStorage<Int, AnyObject>.self, 0, 0) } #endif @_inlineable @_versioned override func canStoreElements(ofDynamicType _: Any.Type) -> Bool { return false } /// A type that every element in the array is. @_inlineable @_versioned override var staticElementType: Any.Type { return Void.self } } /// The empty array prototype. We use the same object for all empty /// `[Native]Array<Element>`s. @_inlineable @_versioned internal var _emptyArrayStorage : _EmptyArrayStorage { return Builtin.bridgeFromRawPointer( Builtin.addressof(&_swiftEmptyArrayStorage)) } // The class that implements the storage for a ContiguousArray<Element> @_versioned final class _ContiguousArrayStorage<Element> : _ContiguousArrayStorageBase { deinit { _elementPointer.deinitialize(count: countAndCapacity.count) _fixLifetime(self) } #if _runtime(_ObjC) /// If the `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements and return the result. /// Otherwise, return `nil`. @_inlineable @_versioned final override func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { var result: R? try self._withVerbatimBridgedUnsafeBufferImpl { result = try body($0) } return result } /// If `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements. @_inlineable @_versioned internal final func _withVerbatimBridgedUnsafeBufferImpl( _ body: (UnsafeBufferPointer<AnyObject>) throws -> Void ) rethrows { if _isBridgedVerbatimToObjectiveC(Element.self) { let count = countAndCapacity.count let elements = UnsafeRawPointer(_elementPointer) .assumingMemoryBound(to: AnyObject.self) defer { _fixLifetime(self) } try body(UnsafeBufferPointer(start: elements, count: count)) } } /// Returns the number of elements in the array. /// /// - Precondition: `Element` is bridged non-verbatim. @_inlineable @_versioned override internal func _getNonVerbatimBridgedCount() -> Int { _sanityCheck( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") return countAndCapacity.count } /// Bridge array elements and return a new buffer that owns them. /// /// - Precondition: `Element` is bridged non-verbatim. @_inlineable @_versioned override internal func _getNonVerbatimBridgedHeapBuffer() -> _HeapBuffer<Int, AnyObject> { _sanityCheck( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") let count = countAndCapacity.count let result = _HeapBuffer<Int, AnyObject>( _HeapBufferStorage<Int, AnyObject>.self, count, count) let resultPtr = result.baseAddress let p = _elementPointer for i in 0..<count { (resultPtr + i).initialize(to: _bridgeAnythingToObjectiveC(p[i])) } _fixLifetime(self) return result } #endif /// Returns `true` if the `proposedElementType` is `Element` or a subclass of /// `Element`. We can't store anything else without violating type /// safety; for example, the destructor has static knowledge that /// all of the elements can be destroyed as `Element`. @_inlineable @_versioned override func canStoreElements( ofDynamicType proposedElementType: Any.Type ) -> Bool { #if _runtime(_ObjC) return proposedElementType is Element.Type #else // FIXME: Dynamic casts don't currently work without objc. // rdar://problem/18801510 return false #endif } /// A type that every element in the array is. @_inlineable @_versioned override var staticElementType: Any.Type { return Element.self } @_inlineable @_versioned internal final var _elementPointer : UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self)) } } @_versioned @_fixed_layout internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol { /// Make a buffer with uninitialized elements. After using this /// method, you must either initialize the `count` elements at the /// result's `.firstElementAddress` or set the result's `.count` /// to zero. @_inlineable @_versioned internal init( _uninitializedCount uninitializedCount: Int, minimumCapacity: Int ) { let realMinimumCapacity = Swift.max(uninitializedCount, minimumCapacity) if realMinimumCapacity == 0 { self = _ContiguousArrayBuffer<Element>() } else { _storage = Builtin.allocWithTailElems_1( _ContiguousArrayStorage<Element>.self, realMinimumCapacity._builtinWordValue, Element.self) let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_storage)) let endAddr = storageAddr + _swift_stdlib_malloc_size(storageAddr) let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress _initStorageHeader( count: uninitializedCount, capacity: realCapacity) } } /// Initialize using the given uninitialized `storage`. /// The storage is assumed to be uninitialized. The returned buffer has the /// body part of the storage initialized, but not the elements. /// /// - Warning: The result has uninitialized elements. /// /// - Warning: storage may have been stack-allocated, so it's /// crucial not to call, e.g., `malloc_size` on it. @_inlineable @_versioned internal init(count: Int, storage: _ContiguousArrayStorage<Element>) { _storage = storage _initStorageHeader(count: count, capacity: count) } @_inlineable @_versioned internal init(_ storage: _ContiguousArrayStorageBase) { _storage = storage } /// Initialize the body part of our storage. /// /// - Warning: does not initialize elements @_inlineable @_versioned internal func _initStorageHeader(count: Int, capacity: Int) { #if _runtime(_ObjC) let verbatim = _isBridgedVerbatimToObjectiveC(Element.self) #else let verbatim = false #endif // We can initialize by assignment because _ArrayBody is a trivial type, // i.e. contains no references. _storage.countAndCapacity = _ArrayBody( count: count, capacity: capacity, elementTypeIsBridgedVerbatim: verbatim) } /// True, if the array is native and does not need a deferred type check. @_inlineable @_versioned internal var arrayPropertyIsNativeTypeChecked: Bool { return true } /// A pointer to the first element. @_inlineable @_versioned internal var firstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(_storage, Element.self)) } @_inlineable @_versioned internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return firstElementAddress } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. @_inlineable @_versioned internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. @_inlineable @_versioned internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } //===--- _ArrayBufferProtocol conformance -----------------------------------===// /// Create an empty buffer. @_inlineable @_versioned internal init() { _storage = _emptyArrayStorage } @_inlineable @_versioned internal init(_buffer buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) { _sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") self = buffer } @_inlineable @_versioned internal mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> _ContiguousArrayBuffer<Element>? { if _fastPath(isUniquelyReferenced() && capacity >= minimumCapacity) { return self } return nil } @_inlineable @_versioned internal mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } @_inlineable @_versioned internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool { return isUniquelyReferencedOrPinned() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. @_inlineable @_versioned internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? { return self } @_inlineable @_versioned @inline(__always) internal func getElement(_ i: Int) -> Element { _sanityCheck(i >= 0 && i < count, "Array index out of range") return firstElementAddress[i] } /// Get or set the value of the ith element. @_inlineable @_versioned internal subscript(i: Int) -> Element { @inline(__always) get { return getElement(i) } @inline(__always) nonmutating set { _sanityCheck(i >= 0 && i < count, "Array index out of range") // FIXME: Manually swap because it makes the ARC optimizer happy. See // <rdar://problem/16831852> check retain/release order // firstElementAddress[i] = newValue var nv = newValue let tmp = nv nv = firstElementAddress[i] firstElementAddress[i] = tmp } } /// The number of elements the buffer stores. @_inlineable @_versioned internal var count: Int { get { return _storage.countAndCapacity.count } nonmutating set { _sanityCheck(newValue >= 0) _sanityCheck( newValue <= capacity, "Can't grow an array buffer past its capacity") _storage.countAndCapacity.count = newValue } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @_inlineable @_versioned @inline(__always) func _checkValidSubscript(_ index : Int) { _precondition( (index >= 0) && (index < count), "Index out of range" ) } /// The number of elements the buffer can store without reallocation. @_inlineable @_versioned internal var capacity: Int { return _storage.countAndCapacity.capacity } /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @_inlineable @_versioned @discardableResult internal func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _sanityCheck(bounds.lowerBound >= 0) _sanityCheck(bounds.upperBound >= bounds.lowerBound) _sanityCheck(bounds.upperBound <= count) let initializedCount = bounds.upperBound - bounds.lowerBound target.initialize( from: firstElementAddress + bounds.lowerBound, count: initializedCount) _fixLifetime(owner) return target + initializedCount } /// Returns a `_SliceBuffer` containing the given `bounds` of values /// from this buffer. @_inlineable @_versioned internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get { return _SliceBuffer( owner: _storage, subscriptBaseAddress: subscriptBaseAddress, indices: bounds, hasNativeBuffer: true) } set { fatalError("not implemented") } } /// Returns `true` iff this buffer's storage is uniquely-referenced. /// /// - Note: This does not mean the buffer is mutable. Other factors /// may need to be considered, such as whether the buffer could be /// some immutable Cocoa container. @_inlineable @_versioned internal mutating func isUniquelyReferenced() -> Bool { return _isUnique(&_storage) } /// Returns `true` iff this buffer's storage is either /// uniquely-referenced or pinned. NOTE: this does not mean /// the buffer is mutable; see the comment on isUniquelyReferenced. @_inlineable @_versioned internal mutating func isUniquelyReferencedOrPinned() -> Bool { return _isUniqueOrPinned(&_storage) } #if _runtime(_ObjC) /// Convert to an NSArray. /// /// - Precondition: `Element` is bridged to Objective-C. /// /// - Complexity: O(1). @_inlineable @_versioned internal func _asCocoaArray() -> _NSArrayCore { if count == 0 { return _emptyArrayStorage } if _isBridgedVerbatimToObjectiveC(Element.self) { return _storage } return _SwiftDeferredNSArray(_nativeStorage: _storage) } #endif /// An object that keeps the elements stored in this buffer alive. @_inlineable @_versioned internal var owner: AnyObject { return _storage } /// An object that keeps the elements stored in this buffer alive. @_inlineable @_versioned internal var nativeOwner: AnyObject { return _storage } /// A value that identifies the storage used by the buffer. /// /// Two buffers address the same elements when they have the same /// identity and count. @_inlineable @_versioned internal var identity: UnsafeRawPointer { return UnsafeRawPointer(firstElementAddress) } /// Returns `true` iff we have storage for elements of the given /// `proposedElementType`. If not, we'll be treated as immutable. @_inlineable @_versioned func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool { return _storage.canStoreElements(ofDynamicType: proposedElementType) } /// Returns `true` if the buffer stores only elements of type `U`. /// /// - Precondition: `U` is a class or `@objc` existential. /// /// - Complexity: O(*n*) @_inlineable @_versioned func storesOnlyElementsOfType<U>( _: U.Type ) -> Bool { _sanityCheck(_isClassOrObjCExistential(U.self)) if _fastPath(_storage.staticElementType is U.Type) { // Done in O(1) return true } // Check the elements for x in self { if !(x is U) { return false } } return true } @_versioned internal var _storage: _ContiguousArrayStorageBase } /// Append the elements of `rhs` to `lhs`. @_inlineable @_versioned internal func += <Element, C : Collection>( lhs: inout _ContiguousArrayBuffer<Element>, rhs: C ) where C.Iterator.Element == Element { let oldCount = lhs.count let newCount = oldCount + numericCast(rhs.count) let buf: UnsafeMutableBufferPointer<Element> if _fastPath(newCount <= lhs.capacity) { buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count)) lhs.count = newCount } else { var newLHS = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCount, minimumCapacity: _growArrayCapacity(lhs.capacity)) newLHS.firstElementAddress.moveInitialize( from: lhs.firstElementAddress, count: oldCount) lhs.count = 0 swap(&lhs, &newLHS) buf = UnsafeMutableBufferPointer(start: lhs.firstElementAddress + oldCount, count: numericCast(rhs.count)) } var (remainders,writtenUpTo) = buf.initialize(from: rhs) // ensure that exactly rhs.count elements were written _precondition(remainders.next() == nil, "rhs underreported its count") _precondition(writtenUpTo == buf.endIndex, "rhs overreported its count") } extension _ContiguousArrayBuffer : RandomAccessCollection { /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @_inlineable @_versioned internal var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `index(after:)`. @_inlineable @_versioned internal var endIndex: Int { return count } internal typealias Indices = CountableRange<Int> } extension Sequence { @_inlineable public func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> { return _copySequenceToContiguousArray(self) } } @_inlineable @_versioned internal func _copySequenceToContiguousArray< S : Sequence >(_ source: S) -> ContiguousArray<S.Iterator.Element> { let initialCapacity = source.underestimatedCount var builder = _UnsafePartiallyInitializedContiguousArrayBuffer<S.Iterator.Element>( initialCapacity: initialCapacity) var iterator = source.makeIterator() // FIXME(performance): use _copyContents(initializing:). // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { builder.addWithExistingCapacity(iterator.next()!) } // Add remaining elements, if any. while let element = iterator.next() { builder.add(element) } return builder.finish() } extension Collection { @_inlineable public func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> { return _copyCollectionToContiguousArray(self) } } extension _ContiguousArrayBuffer { @_inlineable @_versioned internal func _copyToContiguousArray() -> ContiguousArray<Element> { return ContiguousArray(_buffer: self) } } /// This is a fast implementation of _copyToContiguousArray() for collections. /// /// It avoids the extra retain, release overhead from storing the /// ContiguousArrayBuffer into /// _UnsafePartiallyInitializedContiguousArrayBuffer. Since we do not support /// ARC loops, the extra retain, release overhead cannot be eliminated which /// makes assigning ranges very slow. Once this has been implemented, this code /// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer. @_inlineable @_versioned internal func _copyCollectionToContiguousArray< C : Collection >(_ source: C) -> ContiguousArray<C.Iterator.Element> { let count: Int = numericCast(source.count) if count == 0 { return ContiguousArray() } let result = _ContiguousArrayBuffer<C.Iterator.Element>( _uninitializedCount: count, minimumCapacity: 0) var p = result.firstElementAddress var i = source.startIndex for _ in 0..<count { // FIXME(performance): use _copyContents(initializing:). p.initialize(to: source[i]) source.formIndex(after: &i) p += 1 } _expectEnd(of: source, is: i) return ContiguousArray(_buffer: result) } /// A "builder" interface for initializing array buffers. /// /// This presents a "builder" interface for initializing an array buffer /// element-by-element. The type is unsafe because it cannot be deinitialized /// until the buffer has been finalized by a call to `finish`. @_versioned @_fixed_layout internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> { @_versioned internal var result: _ContiguousArrayBuffer<Element> @_versioned internal var p: UnsafeMutablePointer<Element> @_versioned internal var remainingCapacity: Int /// Initialize the buffer with an initial size of `initialCapacity` /// elements. @_versioned @inline(__always) // For performance reasons. init(initialCapacity: Int) { if initialCapacity == 0 { result = _ContiguousArrayBuffer() } else { result = _ContiguousArrayBuffer( _uninitializedCount: initialCapacity, minimumCapacity: 0) } p = result.firstElementAddress remainingCapacity = result.capacity } /// Add an element to the buffer, reallocating if necessary. @_versioned @inline(__always) // For performance reasons. mutating func add(_ element: Element) { if remainingCapacity == 0 { // Reallocate. let newCapacity = max(_growArrayCapacity(result.capacity), 1) var newResult = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCapacity, minimumCapacity: 0) p = newResult.firstElementAddress + result.capacity remainingCapacity = newResult.capacity - result.capacity newResult.firstElementAddress.moveInitialize( from: result.firstElementAddress, count: result.capacity) result.count = 0 swap(&result, &newResult) } addWithExistingCapacity(element) } /// Add an element to the buffer, which must have remaining capacity. @_versioned @inline(__always) // For performance reasons. mutating func addWithExistingCapacity(_ element: Element) { _sanityCheck(remainingCapacity > 0, "_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity") remainingCapacity -= 1 p.initialize(to: element) p += 1 } /// Finish initializing the buffer, adjusting its count to the final /// number of elements. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @_versioned @inline(__always) // For performance reasons. mutating func finish() -> ContiguousArray<Element> { // Adjust the initialized count of the buffer. result.count = result.capacity - remainingCapacity return finishWithOriginalCount() } /// Finish initializing the buffer, assuming that the number of elements /// exactly matches the `initialCount` for which the initialization was /// started. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @_versioned @inline(__always) // For performance reasons. mutating func finishWithOriginalCount() -> ContiguousArray<Element> { _sanityCheck(remainingCapacity == result.capacity - result.count, "_UnsafePartiallyInitializedContiguousArrayBuffer has incorrect count") var finalResult = _ContiguousArrayBuffer<Element>() swap(&finalResult, &result) remainingCapacity = 0 return ContiguousArray(_buffer: finalResult) } }
apache-2.0
8467e21832210f1b9cb0a66674a5163c
29.045397
110
0.69315
4.767107
false
false
false
false
simonwhitehouse/SWHGameOfLife
SWHGameOfLife/SWHGameOfLife/LivingView.swift
1
1373
// // LivingView.swift // SWHGameOfLife // // Created by Simon J Whitehouse on 01/10/2015. // Copyright © 2015 co.swhitehouse. All rights reserved. // import Foundation import UIKit enum LivingViewState { case Alive, Dead /// creates a random cell state either alive or dead static func randomCellState() -> LivingViewState { let randomNumber = arc4random_uniform(2) == 1 if randomNumber { return .Alive } else { return .Dead } } } /// Living View - represents a cell that is alive (white) or dead (black) class LivingView: UIView { /// the curent living state of the view var currentLivingViewState: LivingViewState = .Dead { didSet { backgroundColor = currentLivingViewState == .Alive ? UIColor.whiteColor() : UIColor.clearColor() } } /// tap gesture for recognising taps lazy var tapGesture: UITapGestureRecognizer = { var tempTap = UITapGestureRecognizer(target: self, action: "tapped:") return tempTap }() func tapped(tapGesture: UITapGestureRecognizer) { currentLivingViewState = currentLivingViewState == .Dead ? .Alive : .Dead } func configure(startState: LivingViewState) { addGestureRecognizer(tapGesture) currentLivingViewState = startState } }
mit
e4e9f2bb883b7a291965ebfd32f98a65
25.921569
108
0.640671
4.513158
false
false
false
false
apple/swift-lldb
packages/Python/lldbsuite/test/lang/swift/expression/static/main.swift
2
1284
// main.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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // ----------------------------------------------------------------------------- // Class, function class B { class func b (_ i : Int) { var x = i // breakpoint 1 } } // Generic class, function class C<T> { class func c (_ i : T) { var x = i // breakpoint 2 } } // Class, generic function class E { class func e<U> (_ i : U) { var x = i // breakpoint 3 } } // Generic class, generic function class F<T> { class func f<U> (_ i : T, _ j : U) { var x = i var y = j // breakpoint 4 } } struct G { static func g(_ i : Int) { var x = i // breakpoint 5 } } struct H<T> { static func h(_ i : T) { var x = i // breakpoint 6 } } struct K<T> { static func k<U> (_ i: T, _ j : U) { var x = i var y = j // breakpoint 7 } } // Invocations B.b(1) C<Int>.c(2) E.e (3) F<Int>.f (4, 10.1) G.g(5) H<Int>.h(6) K<Int>.k(7,8.0)
apache-2.0
99f57ad61b52ebfbbb9085357d15f01a
12.375
80
0.524143
2.872483
false
false
false
false
ouch1985/IQuery
IQuery/views/DetailWebViewController.swift
1
2531
// // WebViewController.swift // IQuery // // Created by ouchuanyu on 15/12/13. // Copyright © 2015年 ouchuanyu.com. All rights reserved. // import UIKit class DetailWebViewController: UIViewController, UIWebViewDelegate{ var iapp : IApp? init(iapp: IApp?) { self.iapp = iapp super.init(nibName: nil, bundle: nil) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override func viewDidLoad() { super.viewDidLoad() let webWiew = UIWebView(frame: CGRectMake(0, 0, self.view.bounds.width, self.view.bounds.height)) if self.iapp != nil { self.navigationItem.title = iapp!.name // // 加载webview // URLCache.sharedURLCache.get(self.iapp!.url, callback : {(err : String?, path : String?) in // if (err == nil) { // NSLog("加载本地的HTML[%@]", path!) // let contents: String? // do { // contents = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding) // // let h5Bundle = NSBundle.mainBundle().pathForResource("h5", ofType: "bundle") // let base = NSURL(fileURLWithPath: h5Bundle!) //// webWiew.loadHTMLString(contents!, baseURL: base) // webWiew.loadRequest(NSURLRequest(URL: NSURL(string: "http://172.16.4.212/tmp/test.html")!)) // webWiew.delegate = self // } catch _ { // contents = nil // } // } // }) webWiew.loadRequest(NSURLRequest(URL: NSURL(string: "http://172.16.4.212/tmp/test.html")!)) webWiew.delegate = self } self.view.addSubview(webWiew) } //返回按钮点击响应 func backToPrevious(){ self.navigationController?.popViewControllerAnimated(true) } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if(request.URL != nil && request.URL!.scheme == "commands") { JSBridge.sharedInstance.process(webView, iapp : iapp!, url: request.URL!) return false }else{ return true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
896611de70f58d8f98419c579fb4c988
32.756757
137
0.540432
4.382456
false
false
false
false
stephanecopin/ObjectMapper
ObjectMapperTests/BasicTypes.swift
3
7926
// // BasicTypes.swift // ObjectMapper // // Created by Tristan Himmelman on 2015-02-17. // Copyright (c) 2015 hearst. All rights reserved. // import Foundation import ObjectMapper class BasicTypes: Mappable { var bool: Bool = true var boolOptional: Bool? var boolImplicityUnwrapped: Bool! var int: Int = 0 var intOptional: Int? var intImplicityUnwrapped: Int! var double: Double = 1.1 var doubleOptional: Double? var doubleImplicityUnwrapped: Double! var float: Float = 1.11 var floatOptional: Float? var floatImplicityUnwrapped: Float! var string: String = "" var stringOptional: String? var stringImplicityUnwrapped: String! var anyObject: AnyObject = true var anyObjectOptional: AnyObject? var anyObjectImplicitlyUnwrapped: AnyObject! var arrayBool: Array<Bool> = [] var arrayBoolOptional: Array<Bool>? var arrayBoolImplicityUnwrapped: Array<Bool>! var arrayInt: Array<Int> = [] var arrayIntOptional: Array<Int>? var arrayIntImplicityUnwrapped: Array<Int>! var arrayDouble: Array<Double> = [] var arrayDoubleOptional: Array<Double>? var arrayDoubleImplicityUnwrapped: Array<Double>! var arrayFloat: Array<Float> = [] var arrayFloatOptional: Array<Float>? var arrayFloatImplicityUnwrapped: Array<Float>! var arrayString: Array<String> = [] var arrayStringOptional: Array<String>? var arrayStringImplicityUnwrapped: Array<String>! var arrayAnyObject: Array<AnyObject> = [] var arrayAnyObjectOptional: Array<AnyObject>? var arrayAnyObjectImplicitlyUnwrapped: Array<AnyObject>! var dictBool: Dictionary<String,Bool> = [:] var dictBoolOptional: Dictionary<String, Bool>? var dictBoolImplicityUnwrapped: Dictionary<String, Bool>! var dictInt: Dictionary<String,Int> = [:] var dictIntOptional: Dictionary<String,Int>? var dictIntImplicityUnwrapped: Dictionary<String,Int>! var dictDouble: Dictionary<String,Double> = [:] var dictDoubleOptional: Dictionary<String,Double>? var dictDoubleImplicityUnwrapped: Dictionary<String,Double>! var dictFloat: Dictionary<String,Float> = [:] var dictFloatOptional: Dictionary<String,Float>? var dictFloatImplicityUnwrapped: Dictionary<String,Float>! var dictString: Dictionary<String,String> = [:] var dictStringOptional: Dictionary<String,String>? var dictStringImplicityUnwrapped: Dictionary<String,String>! var dictAnyObject: Dictionary<String, AnyObject> = [:] var dictAnyObjectOptional: Dictionary<String, AnyObject>? var dictAnyObjectImplicitlyUnwrapped: Dictionary<String, AnyObject>! enum EnumInt: Int { case Default case Another } var enumInt: EnumInt = .Default var enumIntOptional: EnumInt? var enumIntImplicitlyUnwrapped: EnumInt! enum EnumDouble: Double { case Default case Another } var enumDouble: EnumDouble = .Default var enumDoubleOptional: EnumDouble? var enumDoubleImplicitlyUnwrapped: EnumDouble! enum EnumFloat: Float { case Default case Another } var enumFloat: EnumFloat = .Default var enumFloatOptional: EnumFloat? var enumFloatImplicitlyUnwrapped: EnumFloat! enum EnumString: String { case Default = "Default" case Another = "Another" } var enumString: EnumString = .Default var enumStringOptional: EnumString? var enumStringImplicitlyUnwrapped: EnumString! var arrayEnumInt: [EnumInt] = [] var arrayEnumIntOptional: [EnumInt]? var arrayEnumIntImplicitlyUnwrapped: [EnumInt]! var dictEnumInt: [String: EnumInt] = [:] var dictEnumIntOptional: [String: EnumInt]? var dictEnumIntImplicitlyUnwrapped: [String: EnumInt]! static func newInstance() -> Mappable { return BasicTypes() } func mapping(map: Map) { bool <- map["bool"] boolOptional <- map["boolOpt"] boolImplicityUnwrapped <- map["boolImp"] int <- map["int"] intOptional <- map["intOpt"] intImplicityUnwrapped <- map["intImp"] double <- map["double"] doubleOptional <- map["doubleOpt"] doubleImplicityUnwrapped <- map["doubleImp"] float <- map["float"] floatOptional <- map["floatOpt"] floatImplicityUnwrapped <- map["floatImp"] string <- map["string"] stringOptional <- map["stringOpt"] stringImplicityUnwrapped <- map["stringImp"] anyObject <- map["anyObject"] anyObjectOptional <- map["anyObjectOpt"] anyObjectImplicitlyUnwrapped <- map["anyObjectImp"] arrayBool <- map["arrayBool"] arrayBoolOptional <- map["arrayBoolOpt"] arrayBoolImplicityUnwrapped <- map["arrayBoolImp"] arrayInt <- map["arrayInt"] arrayIntOptional <- map["arrayIntOpt"] arrayIntImplicityUnwrapped <- map["arrayIntImp"] arrayDouble <- map["arrayDouble"] arrayDoubleOptional <- map["arrayDoubleOpt"] arrayDoubleImplicityUnwrapped <- map["arrayDoubleImp"] arrayFloat <- map["arrayFloat"] arrayFloatOptional <- map["arrayFloatOpt"] arrayFloatImplicityUnwrapped <- map["arrayFloatImp"] arrayString <- map["arrayString"] arrayStringOptional <- map["arrayStringOpt"] arrayStringImplicityUnwrapped <- map["arrayStringImp"] arrayAnyObject <- map["arrayAnyObject"] arrayAnyObjectOptional <- map["arrayAnyObjectOpt"] arrayAnyObjectImplicitlyUnwrapped <- map["arratAnyObjectImp"] dictBool <- map["dictBool"] dictBoolOptional <- map["dictBoolOpt"] dictBoolImplicityUnwrapped <- map["dictBoolImp"] dictInt <- map["dictInt"] dictIntOptional <- map["dictIntOpt"] dictIntImplicityUnwrapped <- map["dictIntImp"] dictDouble <- map["dictDouble"] dictDoubleOptional <- map["dictDoubleOpt"] dictDoubleImplicityUnwrapped <- map["dictDoubleImp"] dictFloat <- map["dictFloat"] dictFloatOptional <- map["dictFloatOpt"] dictFloatImplicityUnwrapped <- map["dictFloatImp"] dictString <- map["dictString"] dictStringOptional <- map["dictStringOpt"] dictStringImplicityUnwrapped <- map["dictStringImp"] dictAnyObject <- map["dictAnyObject"] dictAnyObjectOptional <- map["dictAnyObjectOpt"] dictAnyObjectImplicitlyUnwrapped <- map["dictAnyObjectImp"] enumInt <- map["enumInt"] enumIntOptional <- map["enumIntOpt"] enumIntImplicitlyUnwrapped <- map["enumIntImp"] enumDouble <- map["enumDouble"] enumDoubleOptional <- map["enumDoubleOpt"] enumDoubleImplicitlyUnwrapped <- map["enumDoubleImp"] enumFloat <- map["enumFloat"] enumFloatOptional <- map["enumFloatOpt"] enumFloatImplicitlyUnwrapped <- map["enumFloatImp"] enumString <- map["enumString"] enumStringOptional <- map["enumStringOpt"] enumStringImplicitlyUnwrapped <- map["enumStringImp"] arrayEnumInt <- map["arrayEnumInt"] arrayEnumIntOptional <- map["arrayEnumIntOpt"] arrayEnumIntImplicitlyUnwrapped <- map["arrayEnumIntImp"] dictEnumInt <- map["dictEnumInt"] dictEnumIntOptional <- map["dictEnumIntOpt"] dictEnumIntImplicitlyUnwrapped <- map["dictEnumIntImp"] } } class TestCollectionOfPrimitives : Mappable { var dictStringString: [String: String] = [:] var dictStringInt: [String: Int] = [:] var dictStringBool: [String: Bool] = [:] var dictStringDouble: [String: Double] = [:] var dictStringFloat: [String: Float] = [:] var arrayString: [String] = [] var arrayInt: [Int] = [] var arrayBool: [Bool] = [] var arrayDouble: [Double] = [] var arrayFloat: [Float] = [] static func newInstance() -> Mappable { return TestCollectionOfPrimitives() } func mapping(map: Map) { dictStringString <- map["dictStringString"] dictStringBool <- map["dictStringBool"] dictStringInt <- map["dictStringInt"] dictStringDouble <- map["dictStringDouble"] dictStringFloat <- map["dictStringFloat"] arrayString <- map["arrayString"] arrayInt <- map["arrayInt"] arrayBool <- map["arrayBool"] arrayDouble <- map["arrayDouble"] arrayFloat <- map["arrayFloat"] } }
mit
9132c72b6dd4470ad84548a546732751
34.388393
69
0.71297
3.836399
false
false
false
false
Wolox/wolmo-core-ios
WolmoCore/Utilities/Alerts/ConfirmationAlertViewModel.swift
1
2792
// // ConfirmationAlertViewModel.swift // SonicWords // // Created by Francisco Depascuali on 5/18/16. // Copyright © 2016 Wolox. All rights reserved. // import Foundation /** ConfirmationAlertViewModel models a `UIAlertController` that can be confirmed or dismissed. */ public struct ConfirmationAlertViewModel { /// The alert title. public let title: String? /// The alert message. public let message: String? /// The dismiss button title. public let dismissButtonTitle: String /// The confirm button title. public let confirmButtonTitle: String /// The dismiss button action. public let dismissAction: (ConfirmationAlertViewModel) -> Void /// The confirm button action. public let confirmAction: (ConfirmationAlertViewModel) -> Void /** Initialize a new ConfirmationAlertViewModel with the provided parameters. - parameter title: The alert title. - parameter message: The alert message. - parameter dismissButtonTitle: The dismiss button title. - parameter dismissAction: The dismiss button action. - parameter confirmButtonTitle: The confirm button title. - parameter confirmAction: The confirm button action. */ public init( title: String? = "", message: String? = .none, dismissButtonTitle: String = DefaultDismissButtonTitleKey.localized(), dismissAction: @escaping (ConfirmationAlertViewModel) -> Void = { _ in }, confirmButtonTitle: String = DefaultConfirmButtonTitleKey.localized(), confirmAction: @escaping (ConfirmationAlertViewModel) -> Void = { _ in }) { self.title = title self.message = message self.confirmAction = confirmAction self.dismissAction = dismissAction self.dismissButtonTitle = dismissButtonTitle self.confirmButtonTitle = confirmButtonTitle } /** Default title key for confirm button. It will fetch the localized value from the Localizable.strings file in the main bundle. So you'll have to add this key and give it a value in your Localizable.strings file. You can provide a different key by changing this property. - seealso: Localizable.String */ public static var DefaultConfirmButtonTitleKey: String = "confirmation-alert-view.dismiss.title" /** Default title key for dismiss button. It will fetch the localized value from the Localizable.strings file in the main bundle. So you'll have to add this key and give it a value in your Localizable.strings file. You can provide a different key by changing this property. - seealso: Localizable.String */ public static var DefaultDismissButtonTitleKey: String = "confirmation-alert-view.confirm.title" }
mit
2269c6008cb005e23a9956f922f7a5ff
38.309859
110
0.702616
5.111722
false
false
false
false
BruceFight/SparkGame
SparkGame/MainFace/UIKitPart/JBLogResetView.swift
1
3387
// // JBLogResetView.swift // SparkGame // // Created by Bruce Jiang on 2017/5/19. // Copyright © 2017年 Bruce Jiang. All rights reserved. // import UIKit class JBLogResetView: JBLogView,UITextFieldDelegate { //MARK: - parameters var titleLabel = UILabel() var phoneFeild = UITextField() var implementLabel = UILabel() var getModiCodeBtn = UIButton() //MARK: - callback var getModifyCodeHandler : (() -> ())? //MARK: - init override init(frame: CGRect) { super.init(frame: frame) setSuperNode() setResetNode(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setSuperNode() -> () { titleNode.text = "重置密码" leftEmmiterNode.particleBirthRate = 0 rightEmmiterNode.particleBirthRate = 0 } func setResetNode(frame: CGRect) -> () { titleLabel.text = "使用注册/绑定的手机号重置密码" titleLabel.textColor = UIColor.brown titleLabel.textAlignment = .center titleLabel.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight(rawValue: 12)) titleLabel.sizeToFit() titleLabel.frame = CGRect.init(x: (frame.size.width-titleLabel.bounds.size.width)/2, y: JBLogView.realOriginY + 40, width: titleLabel.bounds.size.width, height: titleLabel.bounds.size.height) phoneFeild = UITextField.init(frame: CGRect.init(x: JBLogView.realOriginX+40, y: frame.size.height/2-25 , width: frame.size.width-(2*(JBLogView.realOriginX+40)), height: 50)) phoneFeild.attributedPlaceholder = NSAttributedString.init(string: "请输入手机号", attributes: [NSAttributedString.Key.foregroundColor:UIColor.brown,NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize: 14)]) phoneFeild.tintColor = UIColor.white phoneFeild.delegate = self phoneFeild.backgroundColor = UIColor.yellow implementLabel.text = "忘记或无绑定手机号,请拨打10108899重置密码" implementLabel.textColor = UIColor.brown implementLabel.textAlignment = .center implementLabel.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight(rawValue: 12)) implementLabel.sizeToFit() implementLabel.frame = CGRect.init(x: (frame.size.width-implementLabel.bounds.size.width)/2, y: phoneFeild.frame.maxY+15, width: implementLabel.bounds.size.width, height: implementLabel.bounds.size.height) getModiCodeBtn = UIButton.init(frame: CGRect.init(x: (frame.size.width-150)/2, y: frame.size.height-190, width: 150, height: 50)) getModiCodeBtn.backgroundColor = UIColor.lightGray getModiCodeBtn.setTitle("获取验证码", for: .normal) getModiCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 28, weight: UIFont.Weight(rawValue: 15)) getModiCodeBtn.layer.cornerRadius = 25 getModiCodeBtn.tag = self.hash >> 1 getModiCodeBtn.addTarget(self, action: #selector(getModiCode(btn:)), for: .touchUpInside) self.addSubview(titleLabel) self.addSubview(phoneFeild) self.addSubview(implementLabel) self.addSubview(getModiCodeBtn) } //@ btn clicked @objc func getModiCode(btn:UIButton) -> () { getModifyCodeHandler?() } }
mit
438aef64adba3abeb8b2154519f4bae8
41.230769
214
0.67456
3.861665
false
false
false
false
LeoMobileDeveloper/MDTable
MDTableExample/ExclusiveItemView.swift
1
1972
// // ExclusiveCollectionCell.swift // MDTableExample // // Created by Leo on 2017/7/7. // Copyright © 2017年 Leo Huang. All rights reserved. // import UIKit enum ExclusiveStyle{ case fullScreen case halfScreen } class ExclusiveItemView: UIView{ var avatarImageView: UIImageView! var describeLabel: UILabel! var coverImageView:UIImageView! var discImageView:UIImageView! var style:ExclusiveStyle = .halfScreen override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func commonInit(){ avatarImageView = UIImageView().added(to: self) coverImageView = UIImageView().added(to: self) coverImageView.image = UIImage(named: "cm4_cover_top_mask") describeLabel = UILabel.title().added(to: self) describeLabel.numberOfLines = 2 discImageView = UIImageView().added(to: self) discImageView.image = UIImage(named: "cm4_disc_type_video") } func config(_ exclusive:NMExclusive,style:ExclusiveStyle){ self.avatarImageView.asyncSetImage(exclusive.avatar) self.describeLabel.text = exclusive.describe self.style = style setNeedsLayout() } override func layoutSubviews() { super.layoutSubviews() var aspectRadio:CGFloat = 0.0 switch self.style { case .halfScreen: aspectRadio = 158.0 / 87.0 case .fullScreen: aspectRadio = 320.0 / 115.0 } avatarImageView.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.width / aspectRadio) coverImageView.frame = avatarImageView.frame discImageView.frame = CGRect(x: 4.0, y: 4.0, width: 22.0, height: 22.0) describeLabel.frame = CGRect(x: 4.0, y: coverImageView.maxY + 4.0, width: self.frame.width - 8.0, height: 35.0) } }
mit
4d972dfe81f7a6827ec54be93809fec7
32.372881
119
0.650076
4.05144
false
false
false
false
OnurVar/OVLocationTagger
Example/OVLocationTagger/AppDelegate.swift
1
3089
// // AppDelegate.swift // OVLocationTagger // // Created by Onur Var on 10/02/2017. // Copyright (c) 2017 Onur Var. All rights reserved. // import UIKit import OVLocationTagger import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. //Register Location Tagger OVLocationConfiguration.shared.desiredAccuracy = kCLLocationAccuracyBestForNavigation OVLocationConfiguration.shared.distanceFilter = 20.0 OVLocationConfiguration.shared.requestType = .BackgroundAndSuspended OVLocationTagger.shared.requestPermission() OVLocationTagger.shared.setLocationCompletion { (location) in if let location = location { let stringTest = String.init(format: "%f - %f", (location.coordinate.latitude), (location.coordinate.longitude)) print(stringTest) } } OVLocationTagger.shared.setAuthorizationStatusCompletion { (status) in } OVLocationTagger.shared.setSignalStrengthCompletion { (signal) in } 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
9067c19a405f6dd69f5800ffad23fb6d
43.128571
285
0.717384
5.606171
false
false
false
false
grandiere/box
box/Model/Grid/Algo/Main/MGridAlgoItem.swift
1
5395
import UIKit import CoreLocation class MGridAlgoItem: MGridAlgoItemProtocol, MGridAlgoItemMenuProtocol, MGridAlgoItemRenderProtocol, MGridAlgoItemMapProtocol { let firebaseId:String let location:CLLocation let created:TimeInterval var multipliedHeading:Float private(set) var distance:CLLocationDistance? private(set) var heading:Float private let k180:Double = 180 private let kHour:TimeInterval = 3600 private let k2Hours:TimeInterval = 7200 private let k24Hours:TimeInterval = 86400 private let k48Hours:TimeInterval = 172800 private let kShowDetail:Bool = true private let kShowDownload:Bool = false private let kShowMatch:Bool = false init( firebaseId:String, latitude:Double, longitude:Double, created:TimeInterval) { location = CLLocation(latitude:latitude, longitude:longitude) heading = 0 multipliedHeading = 0 self.firebaseId = firebaseId self.created = created } //MARK: private private func degreesToRadians(degrees:Double) -> Double { return degrees * Double.pi / k180 } private func radiansToDegrees(radians:Double) -> Double { return radians * k180 / Double.pi } private func headingFrom(reference:CLLocationCoordinate2D) -> Float { let referenceLatitude:Double = degreesToRadians( degrees:reference.latitude) let referenceLongitude:Double = degreesToRadians( degrees:reference.longitude) let latitude:Double = degreesToRadians( degrees:location.coordinate.latitude) let longitude:Double = degreesToRadians( degrees:location.coordinate.longitude) let deltaLongitude:Double = longitude - referenceLongitude let sinDeltaLongitude:Double = sin(deltaLongitude) let cosLatitude:Double = cos(latitude) let cosReferenceLatitude:Double = cos(referenceLatitude) let sinLatitude:Double = sin(latitude) let sinReferenceLatitude:Double = sin(referenceLatitude) let cosDeltaLongitude:Double = cos(deltaLongitude) let yPoint:Double = sinDeltaLongitude * cosLatitude let xPoint:Double = cosReferenceLatitude * sinLatitude - sinReferenceLatitude * cosLatitude * cosDeltaLongitude let radiansBearing:Double = atan2(yPoint, xPoint) let degreesBearing:Double = radiansToDegrees( radians:radiansBearing) let floatBearing:Float = Float(degreesBearing) return floatBearing } //MARK: public func distanceTo( location:CLLocation, renderReady:Bool) { distance = self.location.distance(from:location) if renderReady { heading = headingFrom(reference:location.coordinate) } } //MARK: final final func age() -> String { let stringTime:String let timestamp:TimeInterval = Date().timeIntervalSince1970 let deltaTime:TimeInterval = timestamp - created let twoHours:TimeInterval = kHour + kHour if deltaTime < twoHours { stringTime = NSLocalizedString("MGridAlgoItem_justNow", comment:"") } else if deltaTime < k48Hours { let hoursSince:Int = Int(deltaTime / kHour) let hoursSinceNumber:NSNumber = hoursSince as NSNumber stringTime = String( format:NSLocalizedString("MGridAlgoItem_hoursAgo", comment:""), hoursSinceNumber) } else { let daysSince:Int = Int(deltaTime / k24Hours) let daysSinceNumber:NSNumber = daysSince as NSNumber stringTime = String( format:NSLocalizedString("MGridAlgoItem_daysAgo", comment:""), daysSinceNumber) } return stringTime } //MARK: algo protocol var algoTitle:String? { get { return nil } } var firebasePath:String { get { return firebaseId } } var icon:UIImage? { get { return nil } } func detail() -> [MGridVisorDetailProtocol] { return [] } //MARK: menu protocol var showDetail:Bool { get { return kShowDetail } } var showDownload:Bool { get { return kShowDownload } } var showMatch:Bool { get { return kShowMatch } } //MARK: render protocol func textureStandby(textures:MGridVisorRenderTextures) -> MTLTexture? { return nil } func textureTargeted(textures:MGridVisorRenderTextures) -> MTLTexture? { return nil } var overlayColour:UIColor { get { return UIColor.clear } } //MARK: map protocol var annotationImageOn:UIImage? { get { return nil } } var annotationImageOff:UIImage? { get { return nil } } }
mit
be5641e94fe17055b531af3917935f9f
23.301802
119
0.581835
5.104068
false
false
false
false
BrisyIOS/TodayNewsSwift3.0
TodayNews-Swift3.0/TodayNews-Swift3.0/Classes/Home/Model/HomeTopModel.swift
1
1150
// // HomeTopModel.swift // TodayNews-Swift3.0 // // Created by zhangxu on 2016/10/25. // Copyright © 2016年 zhangxu. All rights reserved. // import UIKit class HomeTopModel: NSObject { var category: String?; var concern_id: String?; var default_add: Int?; var flags: Int?; var icon_url: String?; var name: String?; var tip_new: Int?; var type: Int?; var web_url: String?; var isSelected: Bool = false; var index: Int = 0; // 字典转模型 class func modelWidthDic(dic: [String: Any]) -> HomeTopModel { let model = HomeTopModel(); model.category = dic["category"] as? String ?? ""; model.concern_id = dic["concern_id"] as? String ?? ""; model.default_add = dic["default_add"] as? Int ?? 0; model.flags = dic["flags"] as? Int ?? 0; model.icon_url = dic["icon_url"] as? String ?? ""; model.name = dic["name"] as? String ?? ""; model.tip_new = dic["tip_new"] as? Int ?? 0; model.type = dic["type"] as? Int ?? 0; model.web_url = dic["web_url"] as? String ?? ""; return model; } }
apache-2.0
bebfbdf926a120ee7a3969ac489dc4ca
26.731707
66
0.554969
3.414414
false
false
false
false
hilen/TSWeChat
TSWeChat/Classes/Message/View/TSMessageActionFloatView.swift
1
5644
// // TSMessageActionFloatView.swift // TSWeChat // // Created by Hilen on 3/8/16. // Copyright © 2016 Hilen. All rights reserved. // import UIKit import SnapKit import RxSwift import Dollar private let kActionViewWidth: CGFloat = 140 //container view width private let kActionViewHeight: CGFloat = 190 //container view height private let kActionButtonHeight: CGFloat = 44 //button height private let kFirstButtonY: CGFloat = 12 //the first button Y value class TSMessageActionFloatView: UIView { weak var delegate: ActionFloatViewDelegate? let disposeBag = DisposeBag() override init (frame: CGRect) { super.init(frame : frame) self.initContent() } convenience init () { self.init(frame:CGRect.zero) self.initContent() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } fileprivate func initContent() { self.backgroundColor = UIColor.clear let actionImages = [ TSAsset.Contacts_add_newmessage.image, TSAsset.Barbuttonicon_add_cube.image, TSAsset.Contacts_add_scan.image, TSAsset.Receipt_payment_icon.image, ] let actionTitles = [ "发起群聊", "添加朋友", "扫一扫", "收付款", ] //Init containerView let containerView : UIView = UIView() containerView.backgroundColor = UIColor.clear self.addSubview(containerView) containerView.snp.makeConstraints { (make) -> Void in make.top.equalTo(self.snp.top).offset(3) make.right.equalTo(self.snp.right).offset(-5) make.width.equalTo(kActionViewWidth) make.height.equalTo(kActionViewHeight) } //Init bgImageView let stretchInsets = UIEdgeInsets.init(top: 14, left: 6, bottom: 6, right: 34) let bubbleMaskImage = TSAsset.MessageRightTopBg.image.resizableImage(withCapInsets: stretchInsets, resizingMode: .stretch) let bgImageView: UIImageView = UIImageView(image: bubbleMaskImage) containerView.addSubview(bgImageView) bgImageView.snp.makeConstraints { (make) -> Void in make.edges.equalTo(containerView) } //init custom buttons var yValue = kFirstButtonY for index in 0 ..< actionImages.count { let itemButton: UIButton = UIButton(type: .custom) itemButton.backgroundColor = UIColor.clear itemButton.titleLabel!.font = UIFont.systemFont(ofSize: 17) itemButton.setTitleColor(UIColor.white, for: UIControl.State()) itemButton.setTitleColor(UIColor.white, for: .highlighted) let title = Dollar.fetch(actionTitles, index, orElse: "") itemButton.setTitle(title, for: .normal) itemButton.setTitle(title, for: .highlighted) let image = Dollar.fetch(actionImages, index, orElse: nil) itemButton.setImage(image, for: .normal) itemButton.setImage(image, for: .highlighted) itemButton.addTarget(self, action: #selector(TSMessageActionFloatView.buttonTaped(_:)), for: UIControl.Event.touchUpInside) itemButton.contentHorizontalAlignment = .left itemButton.contentEdgeInsets = UIEdgeInsets.init(top: 0, left: 12, bottom: 0, right: 0) itemButton.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 0) itemButton.tag = index containerView.addSubview(itemButton) itemButton.snp.makeConstraints { (make) -> Void in make.top.equalTo(containerView.snp.top).offset(yValue) make.right.equalTo(containerView.snp.right) make.width.equalTo(containerView.snp.width) make.height.equalTo(kActionButtonHeight) } yValue += kActionButtonHeight } //add tap to view let tap = UITapGestureRecognizer() self.addGestureRecognizer(tap) tap.rx.event.subscribe { _ in self.hide(true) }.disposed(by:self.disposeBag) self.isHidden = true } @objc func buttonTaped(_ sender: UIButton!) { guard let delegate = self.delegate else { self.hide(true) return } let type = ActionFloatViewItemType(rawValue:sender.tag)! delegate.floatViewTapItemIndex(type) self.hide(true) } /** Hide the float view - parameter hide: is hide */ func hide(_ hide: Bool) { if hide { self.alpha = 1.0 UIView.animate(withDuration: 0.2 , animations: { self.alpha = 0.0 }, completion: { finish in self.isHidden = true self.alpha = 1.0 }) } else { self.alpha = 1.0 self.isHidden = false } } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ } /** * TSMessageViewController Float view delegate methods */ protocol ActionFloatViewDelegate: class { /** Tap the item with index */ func floatViewTapItemIndex(_ type: ActionFloatViewItemType) } enum ActionFloatViewItemType: Int { case groupChat = 0, addFriend, scan, payment }
mit
b30bf1beb2a7cee3f8df39ede2619573
31.836257
135
0.603562
4.667498
false
false
false
false
nifty-swift/Nifty
Sources/tic_toc.swift
2
4036
/*************************************************************************************************** * tic_toc.swift * * This file provides stopwatch functionality. * * Author: Philip Erickson * Creation Date: 1 May 2016 * * 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. * * Copyright 2016 Philip Erickson **************************************************************************************************/ // TODO: Improvements: // - make this thread safe, allow for multiple stopwatches, etc... e.g. have tic return a key, like // a UUID, which toc could then pass in to retrieve the time ellapsed since particular tic // - do we really want to use formatter here? Seems overkill import Foundation // Time display settings fileprivate var formatSetup = false fileprivate let stopwatchFormat = NumberFormatter() // Start of ellapsed time interval used by tic/toc fileprivate var _stopwatch = Date() /// Restart a stopwatch timer for measuring performance. Ellapsed time since starting the stopwatch /// is measured using the toc() function. /// /// Note: the stopwatch is automatically started at runtime; to accurately time a particular code /// segment, the stopwatch should be reset at the start of the segment using tic(). public func tic() { _stopwatch = Date() if !formatSetup { stopwatchFormat.usesSignificantDigits = true stopwatchFormat.maximumSignificantDigits = 5 } } /// Measure the ellapsed time since the last call to tic() was made and display to the console. /// /// - Parameters: /// - units: units of time to display result in; seconds by default public func toc(_ units: StopwatchUnit = .seconds) { // Calling through to more generic toc function would reduce repeated code but introduce another // function call, reducing the accuracy of the stopwatch. Such a small amount of repeated code // seems worth it in this case. let stop = Date() let ellapsed_secs = Double(stop.timeIntervalSince(_stopwatch)) let ellapsed = ellapsed_secs * units.rawValue let fmt = stopwatchFormat.string(from: NSNumber(value: ellapsed)) ?? "ERROR!" print("Ellapsed time: \(fmt) \(units)") } /// Measure the ellapsed time since the last call to tic() was made and return the result. /// /// - Parameters: /// - returning units: units of time to return measured time in /// - printing: optionally print ellapsed time to console; false by default /// - Returns: ellapsed time in the specified units public func toc(returning units: StopwatchUnit, printing: Bool = false) -> Double { let stop = Date() let ellapsed_secs = Double(stop.timeIntervalSince(_stopwatch)) let ellapsed = ellapsed_secs * units.rawValue if printing { let fmt = stopwatchFormat.string(from: NSNumber(value: ellapsed)) ?? "ERROR!" print("Ellapsed time: \(fmt) \(units)") } return ellapsed } /// Enumerate the units supported by the stopwatch, with a raw value that is the conversion /// factor from seconds to the particular case. /// /// Note: This enum is used instead of Foundation's UnitDuration for two reasons: 1) UnitDuration /// only has hours, minutes, and seconds, and 2) UnitDuration imposes availability constraints /// on Mac. public enum StopwatchUnit: Double { case weeks = 1.6534 case days = 1.1574E-5 case hours = 2.7777E-4 case minutes = 1.6666E-2 case seconds = 1.0 case ms = 1.0E3 case us = 1.0E6 case ns = 1.0E9 }
apache-2.0
54ae23b052386f41321e4b231d1b3948
36.728972
101
0.667245
4.139487
false
false
false
false
lyft/SwiftLint
Source/SwiftLintFramework/Rules/RedundantOptionalInitializationRule.swift
1
5457
import Foundation import SourceKittenFramework public struct RedundantOptionalInitializationRule: ASTRule, CorrectableRule, ConfigurationProviderRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "redundant_optional_initialization", name: "Redundant Optional Initialization", description: "Initializing an optional variable with nil is redundant.", kind: .idiomatic, nonTriggeringExamples: [ "var myVar: Int?\n", "let myVar: Int? = nil\n", "var myVar: Int? = 0\n", "func foo(bar: Int? = 0) { }\n", "var myVar: Optional<Int>\n", "let myVar: Optional<Int> = nil\n", "var myVar: Optional<Int> = 0\n", // properties with body should be ignored "var foo: Int? {\n" + " if bar != nil { }\n" + " return 0\n" + "}\n", // properties with a closure call "var foo: Int? = {\n" + " if bar != nil { }\n" + " return 0\n" + "}()\n", // lazy variables need to be initialized "lazy var test: Int? = nil" ], triggeringExamples: [ "var myVar: Int?↓ = nil\n", "var myVar: Optional<Int>↓ = nil\n", "var myVar: Int?↓=nil\n", "var myVar: Optional<Int>↓=nil\n" ], corrections: [ "var myVar: Int?↓ = nil\n": "var myVar: Int?\n", "var myVar: Optional<Int>↓ = nil\n": "var myVar: Optional<Int>\n", "var myVar: Int?↓=nil\n": "var myVar: Int?\n", "var myVar: Optional<Int>↓=nil\n": "var myVar: Optional<Int>\n", "class C {\n#if true\nvar myVar: Int?↓ = nil\n#endif\n}": "class C {\n#if true\nvar myVar: Int?\n#endif\n}" ] ) private let pattern = "\\s*=\\s*nil\\b" public func validate(file: File, kind: SwiftDeclarationKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { return violationRanges(in: file, kind: kind, dictionary: dictionary).map { StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, characterOffset: $0.location)) } } private func violationRanges(in file: File, kind: SwiftDeclarationKind, dictionary: [String: SourceKitRepresentable]) -> [NSRange] { guard SwiftDeclarationKind.variableKinds.contains(kind), dictionary.setterAccessibility != nil, let type = dictionary.typeName, typeIsOptional(type), !dictionary.enclosedSwiftAttributes.contains(.lazy), let range = range(for: dictionary, file: file), let match = file.match(pattern: pattern, with: [.keyword], range: range).first, match.location == range.location + range.length - match.length else { return [] } return [match] } private func range(for dictionary: [String: SourceKitRepresentable], file: File) -> NSRange? { guard let offset = dictionary.offset, let length = dictionary.length else { return nil } let contents = file.contents.bridge() if let bodyOffset = dictionary.bodyOffset { return contents.byteRangeToNSRange(start: offset, length: bodyOffset - offset) } else { return contents.byteRangeToNSRange(start: offset, length: length) } } private func violationRanges(in file: File, dictionary: [String: SourceKitRepresentable]) -> [NSRange] { let ranges = dictionary.substructure.flatMap { subDict -> [NSRange] in var ranges = violationRanges(in: file, dictionary: subDict) if let kind = subDict.kind.flatMap(SwiftDeclarationKind.init(rawValue:)) { ranges += violationRanges(in: file, kind: kind, dictionary: subDict) } return ranges } return ranges.unique } private func violationRanges(in file: File) -> [NSRange] { return violationRanges(in: file, dictionary: file.structure.dictionary).sorted { lhs, rhs in lhs.location < rhs.location } } public func correct(file: File) -> [Correction] { let violatingRanges = file.ruleEnabled(violatingRanges: violationRanges(in: file), for: self) var correctedContents = file.contents var adjustedLocations = [Int]() for violatingRange in violatingRanges.reversed() { if let indexRange = correctedContents.nsrangeToIndexRange(violatingRange) { correctedContents = correctedContents.replacingCharacters(in: indexRange, with: "") adjustedLocations.insert(violatingRange.location, at: 0) } } file.write(correctedContents) return adjustedLocations.map { Correction(ruleDescription: type(of: self).description, location: Location(file: file, characterOffset: $0)) } } private func typeIsOptional(_ type: String) -> Bool { return type.hasSuffix("?") || type.hasPrefix("Optional<") } }
mit
a02a4aa413e64034d1381a0d84266ac6
38.992647
108
0.578047
4.555276
false
false
false
false
ilyathewhite/Euler
EulerSketch/EulerSketch/Math/Circle.swift
1
5578
// // Circle.swift // EulerSketchOSX // // Created by Ilya Belenkiy on 7/25/16. // Copyright © 2016 Ilya Belenkiy. All rights reserved. // import Foundation /// The Circle protocol. Describes a circle by its center and radius. public protocol Circle: Shape { /// The center. var center: Point { get } /// The radius. var radius: Double { get } } /// Common operations on circles. public extension Circle { /// Returns the circle going through `point1`, `point2`, and `point3`. static func circle(point1 A: Point, point2 B: Point, point3 C: Point) -> HSCircle? { guard (A != B) && (B != C) && (A != C) else { return nil } let AB = HSSegment(vertex1: A, vertex2: B)! let bisectorAB = AB.bisector let BC = HSSegment(vertex1: B, vertex2: C)! let bisectorBC = BC.bisector if let center = bisectorAB.intersect(bisectorBC) { let radius = center.distanceToPoint(A) guard same(center.distanceToPoint(A), radius) else { return nil } guard same(center.distanceToPoint(B), radius) else { return nil } guard same(center.distanceToPoint(C), radius) else { return nil } return HSCircle(center: center, radius: radius) } else { return nil } } /// Returns the circle with a given `center` that goes through `point`. static func circle(center O: Point, point: Point) -> HSCircle { return HSCircle(center: O, radius: O.distanceToPoint(point)) } /// Whether `point` is on the circle. func containsPoint(_ point: Point) -> Bool { return same(center.distanceToPoint(point), radius) } /// Whether the circle is tangent to a given circle. func isTangentTo(circle: Circle) -> Bool { return same(radius + circle.radius, center.distanceToPoint(circle.center)) } /// Returns the points at wchih tangent lines from `point` touch the circle. func tangentPointsFromPoint(point P: Point) -> [HSPoint] { let O = center let distOP = O.distanceToPoint(P) if distOP < radius { return [] } else if distOP == radius { return [ P.basicValue ] } else { let cos = radius / distOP let lineOP = HSLine.line(point1: O, point2: P)! let pointsQ = lineOP.pointsAtDistance(radius * cos, fromPoint:O) let Q = HSSegment(vertex1: O, vertex2: P)!.containsLinePoint(pointsQ[0]) ? pointsQ[0] : pointsQ[1] return lineOP.perpendicularLineFromPoint(Q).intersect(self) } } /// Returns the intersection of the radical axis of the 2 given circles with the line formed by the centers of these circles, /// and the angle of the radical axis from the X axis static func radicalAxis(circle1: Circle, circle2: Circle) -> (point: HSPoint, angleFromXAxis: Double)? { // from Wikipedia on radical axis: let d = circle1.center.distanceToPoint(circle2.center) guard !isZero(d) else { return nil } let x1 = (d + (square(circle1.radius) - square(circle2.radius)) / d) / 2.0 if x1 > 0 { let centersSegment = HSSegment(vertex1: circle1.center, vertex2: circle2.center)! let point = centersSegment.ray.pointAtDistance(x1) let angle = centersSegment.angleFromXAxis() + .pi / 2 return (point, angle) } else { let centersSegment = HSSegment(vertex1: circle2.center, vertex2: circle1.center)! let point = centersSegment.ray.pointAtDistance(d - x1) let angle = centersSegment.angleFromXAxis() + .pi / 2 return (point, angle) } } /// Returns the points of intersection of this circle with `circle`. func intersect(_ circle: Circle) -> [HSPoint] { let O1 = center let r1 = radius let O2 = circle.center let r2 = circle.radius guard O1 != O2 else { return [] } let O1O2 = HSSegment(vertex1: O1, vertex2: O2)! let d = O1O2.length if d > r1 + r2 { return [] } if (d == r1 + r2) { return [O1O2.ray.pointAtDistance(r1)] } let cosVal = (square(r1) + square(d) - square(r2)) / (2 * d * r1) let x = abs(r1 * cosVal) let P = (cosVal >= 0) ? O1O2.ray.pointAtDistance(x) : HSRay(vertex: O1, angle: O1O2.ray.angle + .pi).pointAtDistance(x) return O1O2.line.perpendicularLineFromPoint(P).intersect(self) } // Shape func distanceFromPoint(_ point: Point) -> (Double, Point) { if point == center { return (radius, center.translate(by: (dx: radius, dy: 0))) // any point on the circle is equally likely a good match } let line = HSLine.line(point1: center, point2: point)! let xPoints = line.intersect(self) assert(xPoints.count == 2, "Expected 2 intersection points between a cricle and a line through the circle center.") if point.distanceToPoint(xPoints[0]) < point.distanceToPoint(xPoints[1]) { return xPoints[0].distanceFromPoint(point) } else { return xPoints[1].distanceFromPoint(point) } } static func namePrefix() -> FigureNamePrefix { return .circle } } /// The most basic `Circle` value that can be used for further calculations /// or to construct a drawable circle on the sketch. public struct HSCircle : Circle { private(set) public var center: Point private(set) public var radius: Double public mutating func translateInPlace(by vector: Vector) { center.translateInPlace(by: vector) } }
mit
582783f005e565e3e26b71235071e37c
34.522293
129
0.623991
3.72048
false
false
false
false
GalinaCode/Nutriction-Cal
NutritionCal/Nutrition Cal/CallendarViewController.swift
1
8148
// // CallendarViewController.swift // Nutrition Cal // // Created by Galina Petrova on 03/25/16. // Copyright © 2015 Galina Petrova. All rights reserved. // import UIKit import CoreData import HealthKit import FSCalendar import MaterialDesignColor import BGTableViewRowActionWithImage class CallendarViewController: UIViewController, FSCalendarDelegate, FSCalendarDataSource, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate { @IBOutlet weak var todayBarButtonItem: UIBarButtonItem! @IBOutlet weak var calendarContainerView: UIView! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var noItemsLabel: UILabel! let healthStore = HealthStore.sharedInstance() var allDaysEntries: [DayEntry] = [] private weak var calendar: FSCalendar! override func viewDidLoad() { super.viewDidLoad() do { try daysFetchedResultsController.performFetch() } catch { print("error fetching all days") } fetchAllDays() tableView.delegate = self tableView.dataSource = self daysFetchedResultsController.delegate = self print(daysFetchedResultsController.fetchedObjects?.count) // UI customizations tabBarController?.tabBar.tintColor = MaterialDesignColor.green500 navigationController?.navigationBar.tintColor = MaterialDesignColor.green500 navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: MaterialDesignColor.green500] tabBarController?.tabBar.tintColor = MaterialDesignColor.green500 todayBarButtonItem.enabled = false let calendar = FSCalendar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 250)) calendar.dataSource = self calendar.delegate = self calendarContainerView.addSubview(calendar) self.calendar = calendar calendar.headerTitleColor = UIColor.blackColor() calendar.todayColor = MaterialDesignColor.grey200 calendar.titleTodayColor = MaterialDesignColor.green500 calendar.selectionColor = MaterialDesignColor.green500 calendar.weekdayTextColor = MaterialDesignColor.green500 calendar.selectDate(calendar.today) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) fetchAllDays() } // MARK: - Core Data Convenience // Shared Context from CoreDataStackManager var sharedContext: NSManagedObjectContext { return CoreDataStackManager.sharedInstance().managedObjectContext } // daysFetchedResultsController lazy var daysFetchedResultsController: NSFetchedResultsController = { let fetchRequest = NSFetchRequest(entityName: "DayEntry") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "date", ascending: true)] let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.sharedContext, sectionNameKeyPath: nil, cacheName: nil) return fetchedResultsController }() // MARK: - UITableView delegate & data sourse func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("historyTableViewCell")! let days = daysFetchedResultsController.fetchedObjects as! [DayEntry] cell.textLabel?.text = days[indexPath.row].ndbItemName cell.detailTextLabel?.text = "\(days[indexPath.row].qty) \(days[indexPath.row].measureLabel)" return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if daysFetchedResultsController.fetchedObjects?.count == 0 { tableView.hidden = true noItemsLabel.hidden = false } else { tableView.hidden = false noItemsLabel.hidden = true } return daysFetchedResultsController.fetchedObjects!.count } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.01 } func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let days = daysFetchedResultsController.fetchedObjects as! [DayEntry] let deleteAction = BGTableViewRowActionWithImage.rowActionWithStyle(.Default, title: " ", backgroundColor: MaterialDesignColor.red500, image: UIImage(named: "deleteDayEntryActionIcon"), forCellHeight: 70, handler: { (action, indexPath) -> Void in let alert = UIAlertController(title: "Delete", message: "Delete (\(days[indexPath.row].ndbItemName)) ?", preferredStyle: UIAlertControllerStyle.Alert) let deleteAlertAction = UIAlertAction(title: "Delete", style: UIAlertActionStyle.Default, handler: { (action) -> Void in dispatch_async(dispatch_get_main_queue()) { self.sharedContext.deleteObject(days[indexPath.row]) CoreDataStackManager.sharedInstance().saveContext() self.calendar?.reloadData() } tableView.setEditing(false, animated: true) }) let cancelAlertAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (action) -> Void in self.tableView.setEditing(false, animated: true) }) alert.addAction(deleteAlertAction) alert.addAction(cancelAlertAction) alert.view.tintColor = MaterialDesignColor.green500 dispatch_async(dispatch_get_main_queue()) { self.presentViewController(alert, animated: true, completion: nil) alert.view.tintColor = MaterialDesignColor.green500 } }) return [deleteAction] } // MARK: - daysFetchedResultsController delegate func controllerWillChangeContent(controller: NSFetchedResultsController) { tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: let cell = tableView.cellForRowAtIndexPath(indexPath!)! as UITableViewCell let day = daysFetchedResultsController.objectAtIndexPath(indexPath!) as! DayEntry cell.textLabel?.text = day.ndbItemName cell.detailTextLabel?.text = "\(day.qty) \(day.measureLabel)" case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) } } func controllerDidChangeContent(controller: NSFetchedResultsController) { tableView.endUpdates() } func calendar(calendar: FSCalendar!, imageForDate date: NSDate!) -> UIImage! { for dayEntry in allDaysEntries { if dayEntry.daysSince1970 == date.daysSince1970() { return UIImage(named: "dayLine") } } return UIImage() } // MARK: - FSCalendarDelegate func calendar(calendar: FSCalendar!, didSelectDate date: NSDate!) { if date.isToday() { todayBarButtonItem.enabled = false } else { todayBarButtonItem.enabled = true } getDayEntriesForDate(date) } // MARK: - IBActions @IBAction func todayBarButtonItemTapped(sender: UIBarButtonItem) { calendar.selectDate(NSDate(), scrollToDate: true) todayBarButtonItem.enabled = false getDayEntriesForDate(NSDate()) } @IBAction func addBarButtonItemTapped(sender: UIBarButtonItem) { tabBarController?.selectedIndex = 0 } // CoreData Helpers func fetchAllDays() { let fetchRequest = NSFetchRequest(entityName: "DayEntry") do { allDaysEntries = try self.sharedContext.executeFetchRequest(fetchRequest) as! [DayEntry] } catch { print("Error fetching all days entries") } self.calendar?.reloadData() } func fetchDays() { fetchAllDays() do { try daysFetchedResultsController.performFetch() } catch { print("Error fetching days") } } func getDayEntriesForDate(date: NSDate) { let daysSince1970 = date.daysSince1970() as NSNumber daysFetchedResultsController.fetchRequest.predicate = NSPredicate(format:"daysSince1970 == %@", daysSince1970) fetchDays() tableView.reloadData() } }
apache-2.0
03979f716e1b349c303b251793e69c74
28.625455
251
0.752915
4.523598
false
false
false
false
mrahmiao/ShortcutKit
Demo/AppDelegate.swift
1
1603
// // AppDelegate.swift // Demo // // Created by mrahmiao on 11/13/15. // Copyright © 2015 Code4Blues. All rights reserved. // import Cocoa import ShortcutKit let RedRecorderIdentifier = "RedRecorder" let BlueRecorderIdentifier = "BlueRecorderIdentifier" let ResetRecorderIdentifier = "ResetRecorderIdentifier" @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(aNotification: NSNotification) { // Insert code here to initialize your application SCKHotkeyManager.sharedManager.bindRegisteredControlWithIdentifier(BlueRecorderIdentifier) { self.setColorToBlue(nil) } SCKHotkeyManager.sharedManager.bindRegisteredControlWithIdentifier(RedRecorderIdentifier) { self.setColorToRed(nil) } SCKHotkeyManager.sharedManager.bindRegisteredControlWithIdentifier(ResetRecorderIdentifier) { self.resetColor(nil) } } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } } extension AppDelegate: ColorAlterable { func setColorToBlue(sender: AnyObject?) { if let vc = NSApp.mainWindow?.windowController?.contentViewController as? ColorAlterable { vc.setColorToBlue(sender) } } func setColorToRed(sender: AnyObject?) { if let vc = NSApp.mainWindow?.windowController?.contentViewController as? ColorAlterable { vc.setColorToRed(sender) } } func resetColor(sender: AnyObject?) { if let vc = NSApp.mainWindow?.windowController?.contentViewController as? ColorAlterable { vc.resetColor(sender) } } }
mit
f199442fae3579b3fc6c7977184393d1
29.807692
123
0.768414
4.47486
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/25968-std-function-func-mapsignaturetype.swift
1
2587
// 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 https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck } protocol P{func g:{ } { import n} struct c<T: NSManagedObject { let end = nil let end = nil protocol A{enum S<H for c { } protocol c<T where g<T: Array) { struct c{ class A"\(} class a typealias e: var e:S{ class A : {class A{ } func f A{ protocol A{let:A?typealias e:a class A{ <T. : { <d where f<T where g<T A : Array) { class A? { struct c<T where g: { let s=[]if true{ struct D { class struct S{r let a init(} class a } struct Q{ let func a{ } } } class A?typealias b<H.b:a<T f<T where k.b:A let a { struct Q{ } protocol P{protocol a { } protocol A{ enum S<T where g:a import n} protocol a { typealias e:a{ {func a<T: protocol P{ class A{ class func a struct S{ var A?typealias b{protocol A class a{ let a { struct S<T: a { func f:{let:b{ } protocol a {{ } class A"\(t var _=Void{ } class func f A< T where T: Array) { let s=Void{ for c {let:A? { protocol A? = A{ class A? { class func f A{ var A{ let:a{typealias e let b : NSManagedObject { class { class A : <b<H. : { let a { enum S<T where f<T where k. : b(t } let:A{ } for c { class A{ let b : <T: protocol A{ struct S var e:ExtensibleCollectionType protocol a {let:a{let:a protocol a {r class S<d where H.b struct S<T where g: } <T where g: { protocol P{ protocol A< T where T: NSManagedObject {enum S{ func f A < T where k.b:a{ var _=Void{ var e: d where T:{ struct c<T where f<H : <H:A:a <T where f: { class func b<T. : a { func a=[]if true{class a=Void{struct c<H : { func a{ let end = nil { struct S{let class A{ { let d:a class C<d = A <T where H. : NSManagedObject { class a struct S class C<b(T: protocol A{ struct S protocol A{ {class C<H:e func a<b func a {enum :a=[]if true{protocol A? { struct D { let a init(t var b : a { } } func a=[]if true{ let b { let s=[ var e func a protocol a { func a enum S<d = { protocol A{ } { let d:S<T where f<d = { let { typealias b var e for c { struct Q{r }class a{ let class A{ func a{let } protocol P{class C<T: d where f<T: <d where f: d = { } func f A class { let } class a class A : } var a{ class a{ var _=Void{ class :S<H } var e var b { import n} protocol A{ func a{r class a<T where g:A{let:A{ } let a { protocol P{ let s=[]if true{ } let a {class A"\(} protocol a { struct
apache-2.0
0970438c0f2bec256301173e2d6afc31
12.687831
79
0.652493
2.452133
false
false
false
false
blokadaorg/blokada
ios/App/Repository/Repos.swift
1
2454
// // This file is part of Blokada. // // 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 https://mozilla.org/MPL/2.0/. // // Copyright © 2021 Blocka AB. All rights reserved. // // @author Karol Gusak // import Foundation import Combine // Startable is used for Repos to manually start them (as opposed // to starting with init()) and have better control on when it // happens. It is because we need it in tests. protocol Startable { func start() } var Repos = RepositoriesSingleton() class RepositoriesSingleton { lazy var processingRepo = ProcessingRepo() lazy var stageRepo = StageRepo() lazy var navRepo = NavRepo() lazy var httpRepo = HttpRepo() lazy var accountRepo = AccountRepo() lazy var cloudRepo = CloudRepo() lazy var appRepo = AppRepo() lazy var paymentRepo = PaymentRepo() lazy var activityRepo = ActivityRepo() lazy var statsRepo = StatsRepo() lazy var packRepo = PackRepo() lazy var sheetRepo = SheetRepo() lazy var permsRepo = PermsRepo() lazy var gatewayRepo = GatewayRepo() lazy var leaseRepo = LeaseRepo() lazy var netxRepo = NetxRepo() lazy var plusRepo = PlusRepo() lazy var linkRepo = LinkRepo() } func startAllRepos() { Repos.processingRepo.start() Repos.stageRepo.start() Repos.navRepo.start() Repos.httpRepo.start() Repos.accountRepo.start() Repos.cloudRepo.start() Repos.appRepo.start() Repos.paymentRepo.start() Repos.activityRepo.start() Repos.statsRepo.start() Repos.packRepo.start() Repos.sheetRepo.start() Repos.permsRepo.start() Repos.gatewayRepo.start() Repos.leaseRepo.start() Repos.netxRepo.start() Repos.plusRepo.start() Repos.linkRepo.start() // Also start some services that probably should be repos? Services.netx.start() Services.rate.start() } func resetReposForDebug() { Repos = RepositoriesSingleton() Repos.processingRepo = DebugProcessingRepo() Repos.stageRepo = DebugStageRepo() Repos.accountRepo = DebugAccountRepo() Repos.appRepo = DebugAppRepo() Repos.cloudRepo = DebugCloudRepo() Repos.sheetRepo = DebugSheetRepo() Repos.netxRepo = DebugNetxRepo() } func prepareReposForTesting() { resetReposForDebug() startAllRepos() Logger.w("Repos", "Ready for testing") }
mpl-2.0
64fa84a9931673da6084671b654ac8e9
26.875
71
0.694252
3.750765
false
false
false
false
webim/webim-client-sdk-ios
WebimClientLibrary/Backend/MemoryHistoryStorage.swift
1
9635
// // MemoryHistoryStorage.swift // WebimClientLibrary // // Created by Nikita Lazarev-Zubov on 11.08.17. // Copyright © 2017 Webim. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation /** Class that is responsible for history storage when it is set to memory mode. - author: Nikita Lazarev-Zubov - copyright: 2017 Webim */ final class MemoryHistoryStorage: HistoryStorage { // MARK: - Properties private let majorVersion = Int(InternalUtils.getCurrentTimeInMicrosecond() % Int64(Int.max)) private lazy var historyMessages = [MessageImpl]() private var reachedHistoryEnd = false private var readBeforeTimestamp: Int64 // MARK: - Initialization init() { // Empty initializer introduced because of init(with:) existence. self.readBeforeTimestamp = -1 } init(readBeforeTimestamp: Int64) { self.readBeforeTimestamp = readBeforeTimestamp } // For testing purposes only. init(messagesToAdd: [MessageImpl]) { self.readBeforeTimestamp = -1 for message in messagesToAdd { historyMessages.append(message) } } // MARK: - Methods // MARK: HistoryStorage protocol methods func getMajorVersion() -> Int { return majorVersion } func set(reachedHistoryEnd: Bool) { // No need in this implementation. } func getFullHistory(completion: @escaping ([Message]) -> ()) { completion(historyMessages as [Message]) } func getLatestHistory(byLimit limitOfMessages: Int, completion: @escaping ([Message]) -> ()) { respondTo(messages: historyMessages, limitOfMessages: limitOfMessages, completion: completion) } func getHistoryBefore(id: HistoryID, limitOfMessages: Int, completion: @escaping ([Message]) -> ()) { let sortedMessages = historyMessages.sorted { if let first = $0.getHistoryID() { if let second = $1.getHistoryID() { return first.getTimeInMicrosecond() < second.getTimeInMicrosecond() } return true } return false } guard let firstHistoryID = sortedMessages[0].getHistoryID() else { completion([]) return } guard firstHistoryID.getTimeInMicrosecond() <= id.getTimeInMicrosecond() else { completion([MessageImpl]()) return } for (index, message) in sortedMessages.enumerated() { if message.getHistoryID() == id { respondTo(messages: sortedMessages, limitOfMessages: limitOfMessages, offset: index, completion: completion) break } } } func receiveHistoryBefore(messages: [MessageImpl], hasMoreMessages: Bool) { if !hasMoreMessages { reachedHistoryEnd = true } historyMessages = messages + historyMessages } func receiveHistoryUpdate(withMessages messages: [MessageImpl], idsToDelete: Set<String>, completion: @escaping (_ endOfBatch: Bool, _ messageDeleted: Bool, _ deletedMesageID: String?, _ messageChanged: Bool, _ changedMessage: MessageImpl?, _ messageAdded: Bool, _ addedMessage: MessageImpl?, _ idBeforeAddedMessage: HistoryID?) -> ()) { deleteFromHistory(idsToDelete: idsToDelete, completion: completion) mergeHistoryChanges(messages: messages, completion: completion) completion(true, false, nil, false, nil, false, nil, nil) } func clearHistory() { historyMessages.removeAll() } func updateReadBeforeTimestamp(timestamp: Int64) { self.readBeforeTimestamp = timestamp } // MARK: Private methods private func respondTo(messages: [MessageImpl], limitOfMessages: Int, completion: ([Message]) -> ()) { completion((messages.count == 0) ? messages : ((messages.count <= limitOfMessages) ? messages : Array(messages[(messages.count - limitOfMessages) ..< messages.count]))) } private func respondTo(messages: [MessageImpl], limitOfMessages: Int, offset: Int, completion: ([Message]) -> ()) { let supposedQuantity = offset - limitOfMessages completion(Array(messages[((supposedQuantity > 0) ? supposedQuantity : 0) ..< offset])) } private func deleteFromHistory(idsToDelete: Set<String>, completion: (_ endOfBatch: Bool, _ messageDeleted: Bool, _ deletedMesageID: String?, _ messageChanged: Bool, _ changedMessage: MessageImpl?, _ messageAdded: Bool, _ addedMessage: MessageImpl?, _ idBeforeAddedMessage: HistoryID?) -> ()) { for idToDelete in idsToDelete { for (index, message) in historyMessages.enumerated() { if message.getHistoryID()?.getDBid() == idToDelete { historyMessages.remove(at: index) completion(false, true, message.getHistoryID()?.getDBid(), false, nil, false, nil, nil) break } } } } private func mergeHistoryChanges(messages: [MessageImpl], completion: (_ endOfBatch: Bool, _ messageDeleted: Bool, _ deletedMesageID: String?, _ messageChanged: Bool, _ changedMessage: MessageImpl?, _ messageAdded: Bool, _ addedMessage: MessageImpl?, _ idBeforeAddedMessage: HistoryID?) -> ()) { /* Algorithm merges messages with history messages. Messages before first history message are ignored. Messages with the same time in Microseconds with corresponding history messages are replacing them. Messages after last history message are added in the end. The rest of the messages are merged in the middle of history messages. */ var receivedMessages = messages var result = [MessageImpl]() outerLoop: for historyMessage in historyMessages { while receivedMessages.count > 0 { for message in receivedMessages { if (message.getTimeInMicrosecond() <= readBeforeTimestamp || readBeforeTimestamp == -1) { message.setRead(isRead: true) } if message.getTimeInMicrosecond() < historyMessage.getTimeInMicrosecond() { if !result.isEmpty { result.append(message) completion(false, false, nil, false, nil, true, message, historyMessage.getHistoryID()) receivedMessages.remove(at: 0) continue } else { receivedMessages.remove(at: 0) break } } if message.getTimeInMicrosecond() > historyMessage.getTimeInMicrosecond() { result.append(historyMessage) continue outerLoop } if message.getTimeInMicrosecond() == historyMessage.getTimeInMicrosecond() { result.append(message) completion(false, false, nil, true, message, false, nil, nil) receivedMessages.remove(at: 0) continue outerLoop } } } result.append(historyMessage) } if receivedMessages.count > 0 { for message in receivedMessages { result.append(message) completion(false, false, nil, false, nil, true, message, nil) } } historyMessages = result } }
mit
bf3db0af7bc96ce469009ffec29f599c
38.809917
277
0.561968
5.352222
false
false
false
false
daniel-barros/Comedores-UGR
Comedores UGR/NSUserDefaults+Archiving+DayMenu.swift
1
3335
// // NSUserDefaults+Menu.swift // Comedores UGR // // Created by Daniel Barros López on 3/27/16. /* MIT License Copyright (c) 2016 Daniel Barros 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 UserDefaults { func menu(forKey key: String) -> [DayMenu]? { if let menuData = self.data(forKey: key) { return NSKeyedUnarchiver.unarchiveMenu(with: menuData) } else { return nil } } func setMenu(_ menu: [DayMenu]?, forKey key: String) { if let menu = menu { let menuData = NSKeyedArchiver.archivedMenu(menu) self.set(menuData, forKey: key) } else { self.set(nil, forKey: key) } } } extension NSKeyedUnarchiver { static func unarchiveMenu(with data: Data) -> [DayMenu]? { guard let archivedMenu = NSKeyedUnarchiver.unarchiveObject(with: data) as? [[String: Any]] else { return nil } var ok = true let menu = archivedMenu.map { (dict: [String: Any]) -> DayMenu in if let menu = DayMenu(archivedMenu: dict) { return menu } else { ok = false return DayMenu(date: "", dishes: [], allergens: nil) } } if ok == false { return nil } return menu } } extension NSKeyedArchiver { static func archivedMenu(_ menu: [DayMenu]) -> Data { let archivedMenu = menu.map { $0.archivableVersion } return archivedData(withRootObject: archivedMenu) } } private extension DayMenu { init?(archivedMenu: [String: Any]) { guard let date = archivedMenu["date"] as? String, let dishes = archivedMenu["dishes"] as? [String] else { return nil } self.date = date self.dishes = dishes self.processedDate = DayMenu.date(fromRawString: date) self.allergens = archivedMenu["allergens"] as? String } /// A representation of the menu instance that can be archived using NSKeyedArchiver. var archivableVersion: [String: Any] { if let al = allergens { return ["date": date, "dishes": dishes, "allergens": al] } else { return ["date": date, "dishes": dishes] } } }
mit
8b99d1ed33a7c9b9cc0ca1573ef41f7c
29.87037
105
0.636173
4.35817
false
false
false
false
artsy/eigen
ios/ArtsyTests/View_Controller_Tests/LiveAuctionCurrentLotCTAPositionManagerTests.swift
1
3460
import Quick import Nimble import Interstellar import UIKit @testable import Artsy class LiveAuctionCurrentLotCTAPositionManagerTest: QuickSpec { override func spec() { var scrollView: UIScrollView! var salesPerson: Stub_LiveAuctionsSalesPerson! var subject: LiveAuctionCurrentLotCTAPositionManager! beforeEach { scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) scrollView.contentSize = CGSize(width: 300, height: 100) salesPerson = stub_auctionSalesPerson() subject = LiveAuctionCurrentLotCTAPositionManager(salesPerson: salesPerson, bottomPositionConstraint: NSLayoutConstraint()) subject.currentLotDidChange(to: salesPerson.currentLotSignal.peek()!!) } let currentLotIndex = 1 let halfwayShowing: CGFloat = 47.5 let hidden: CGFloat = 100 let showing: CGFloat = -5 describe("jumping directly to a lot") { it("works when jumping to the current lot") { subject.updateFocusedLotIndex(to: currentLotIndex) expect(subject.bottomPositionConstraint.constant) == hidden } it("works when jumping to a non-current lot") { subject.updateFocusedLotIndex(to: 0) expect(subject.bottomPositionConstraint.constant) == showing } } describe("scrolling to a lot") { it("works when scrolling left to the current lot") { scrollView.contentOffset = CGPoint(x: 50, y: 0) salesPerson.currentFocusedLotIndex.update(currentLotIndex + 1) subject.scrollViewDidScroll(scrollView) expect(subject.bottomPositionConstraint.constant) == halfwayShowing } it("works when scrolling right to the current lot") { scrollView.contentOffset = CGPoint(x: 150, y: 0) salesPerson.currentFocusedLotIndex.update(currentLotIndex - 1) subject.scrollViewDidScroll(scrollView) expect(subject.bottomPositionConstraint.constant) == halfwayShowing } it("works when scrolling left away from the current lot") { scrollView.contentOffset = CGPoint(x: 50, y: 0) salesPerson.currentFocusedLotIndex.update( currentLotIndex) subject.scrollViewDidScroll(scrollView) expect(subject.bottomPositionConstraint.constant) == halfwayShowing } it("works when scrolling right away from the current lot") { scrollView.contentOffset = CGPoint(x: 150, y: 0) salesPerson.currentFocusedLotIndex.update( currentLotIndex) subject.scrollViewDidScroll(scrollView) expect(subject.bottomPositionConstraint.constant) == halfwayShowing } it("does nothing during a jump") { salesPerson.currentFocusedLotIndex.update(0) subject.updateFocusedLotIndex(to: 0) // Sets to showing subject.didStartJump(to: Test_LiveAuctionLotViewModel()) scrollView.contentOffset = CGPoint(x: 150, y: 0) // This should normally trigger something subject.scrollViewDidScroll(scrollView) expect(subject.bottomPositionConstraint.constant) == showing } } } }
mit
a9e6d072108819cdf528aa728923c503
36.608696
135
0.628324
5.282443
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Swift Note/LiveBroadcast/Client/LiveBroadcast/Classes/Room/ChatToolsView.swift
1
2443
// // ChatToolsView.swift // LiveBroadcast // // Created by 朱双泉 on 2018/12/12. // Copyright © 2018 Castie!. All rights reserved. // import UIKit protocol ChatToolsViewDelegate : class { func chatToolsView(toolView : ChatToolsView, message : String) } class ChatToolsView: UIView, NibLoadable { weak var delegate : ChatToolsViewDelegate? fileprivate lazy var emoticonBtn : UIButton = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32)) fileprivate lazy var emoticonView = EmoticonView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: 250)) @IBOutlet weak var inputTextField: UITextField! @IBOutlet weak var sendMsgBtn: UIButton! override func awakeFromNib() { super.awakeFromNib() setupUI() } @IBAction func textFieldDidEdit(_ sender: UITextField) { sendMsgBtn.isEnabled = sender.text!.count != 0 } @IBAction func sendBtnClick(_ sender: UIButton) { let message = inputTextField.text! inputTextField.text = "" sender.isEnabled = false delegate?.chatToolsView(toolView: self, message: message) } } extension ChatToolsView { fileprivate func setupUI() { emoticonBtn.setImage(UIImage(named: "chat_btn_emoji"), for: .normal) emoticonBtn.setImage(UIImage(named: "chat_btn_keyboard"), for: .selected) emoticonBtn.addTarget(self, action: #selector(emoticonBtnClick(_:)), for: .touchUpInside) inputTextField.rightView = emoticonBtn inputTextField.rightViewMode = .always inputTextField.allowsEditingTextAttributes = true emoticonView.emotionClickCallback = { [weak self] emoticon in if emoticon.emoticonName == "delete-n" { self?.inputTextField.deleteBackward() return } guard let range = self?.inputTextField.selectedTextRange else { return } self?.inputTextField.replace(range, withText: emoticon.emoticonName) } } } extension ChatToolsView { @objc fileprivate func emoticonBtnClick(_ btn : UIButton) { btn.isSelected = !btn.isSelected let range = inputTextField.selectedTextRange inputTextField.resignFirstResponder() inputTextField.inputView = inputTextField.inputView == nil ? emoticonView : nil inputTextField.becomeFirstResponder() inputTextField.selectedTextRange = range } }
mit
69837416e87d58ed2a4c2b3723132141
32.833333
109
0.66954
4.842942
false
false
false
false
ruslanskorb/CoreStore
Sources/Value.swift
1
29450
// // Value.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // 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 CoreData import Foundation // MARK: - DynamicObject extension DynamicObject where Self: CoreStoreObject { /** The containing type for value propertiess. `Value` properties support any type that conforms to `ImportableAttributeType`. ``` class Animal: CoreStoreObject { let species = Value.Required<String>("species", initial: "") let nickname = Value.Optional<String>("nickname") let color = Transformable.Optional<UIColor>("color") } ``` - Important: `Value` properties are required to be stored properties. Computed properties will be ignored, including `lazy` and `weak` properties. */ public typealias Value = ValueContainer<Self> } // MARK: - ValueContainer /** The containing type for value properties. Use the `DynamicObject.Value` typealias instead for shorter syntax. ``` class Animal: CoreStoreObject { let species = Value.Required<String>("species", initial: "") let nickname = Value.Optional<String>("nickname") let color = Transformable.Optional<UIColor>("color") } ``` */ public enum ValueContainer<O: CoreStoreObject> { // MARK: - Required /** The containing type for required value properties. Any type that conforms to `ImportableAttributeType` are supported. ``` class Animal: CoreStoreObject { let species = Value.Required<String>("species", initial: "") let nickname = Value.Optional<String>("nickname") let color = Transformable.Optional<UIColor>("color") } ``` - Important: `Value.Required` properties are required to be stored properties. Computed properties will be ignored, including `lazy` and `weak` properties. */ public final class Required<V: ImportableAttributeType>: AttributeKeyPathStringConvertible, AttributeProtocol { /** Initializes the metadata for the property. ``` class Person: CoreStoreObject { let title = Value.Required<String>("title", initial: "Mr.") let name = Value.Required<String>("name", initial: "") let displayName = Value.Required<String>( "displayName", initial: "", isTransient: true, customGetter: Person.getName(_:) ) private static func getName(_ partialObject: PartialObject<Person>) -> String { let cachedDisplayName = partialObject.primitiveValue(for: { $0.displayName }) if !cachedDisplayName.isEmpty { return cachedDisplayName } let title = partialObject.value(for: { $0.title }) let name = partialObject.value(for: { $0.name }) let displayName = "\(title) \(name)" partialObject.setPrimitiveValue(displayName, for: { $0.displayName }) return displayName } } ``` - parameter keyPath: the permanent attribute name for this property. - parameter initial: the initial value for the property when the object is first created - parameter isTransient: `true` if the property is transient, otherwise `false`. Defaults to `false` if not specified. The transient flag specifies whether or not a property's value is ignored when an object is saved to a persistent store. Transient properties are not saved to the persistent store, but are still managed for undo, redo, validation, and so on. - parameter versionHashModifier: used to mark or denote a property as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter customGetter: use this closure as an "override" for the default property getter. The closure receives a `PartialObject<O>`, which acts as a fast, type-safe KVC interface for `CoreStoreObject`. The reason a `CoreStoreObject` instance is not passed directly is because the Core Data runtime is not aware of `CoreStoreObject` properties' static typing, and so loading those info everytime KVO invokes this accessor method incurs a cumulative performance hit (especially in KVO-heavy operations such as `ListMonitor` observing.) When accessing the property value from `PartialObject<O>`, make sure to use `PartialObject<O>.primitiveValue(for:)` instead of `PartialObject<O>.value(for:)`, which would unintentionally execute the same closure again recursively. - parameter customSetter: use this closure as an "override" for the default property setter. The closure receives a `PartialObject<O>`, which acts as a fast, type-safe KVC interface for `CoreStoreObject`. The reason a `CoreStoreObject` instance is not passed directly is because the Core Data runtime is not aware of `CoreStoreObject` properties' static typing, and so loading those info everytime KVO invokes this accessor method incurs a cumulative performance hit (especially in KVO-heavy operations such as `ListMonitor` observing.) When accessing the property value from `PartialObject<O>`, make sure to use `PartialObject<O>.setPrimitiveValue(_:for:)` instead of `PartialObject<O>.setValue(_:for:)`, which would unintentionally execute the same closure again recursively. - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public init( _ keyPath: KeyPathString, initial: @autoclosure @escaping () -> V, isTransient: Bool = false, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, customGetter: ((_ partialObject: PartialObject<O>) -> V)? = nil, customSetter: ((_ partialObject: PartialObject<O>, _ newValue: V) -> Void)? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.keyPath = keyPath self.isTransient = isTransient self.defaultValue = { initial().cs_toQueryableNativeType() } self.versionHashModifier = versionHashModifier self.renamingIdentifier = renamingIdentifier self.customGetter = customGetter self.customSetter = customSetter self.affectedByKeyPaths = affectedByKeyPaths } /** The attribute value */ public var value: ReturnValueType { get { Internals.assert( self.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) return withExtendedLifetime(self.rawObject!) { (object) in Internals.assert( object.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) if let customGetter = self.customGetter { return customGetter(PartialObject<O>(object)) } return V.cs_fromQueryableNativeType( object.value(forKey: self.keyPath)! as! V.QueryableNativeType )! } } set { Internals.assert( self.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) return withExtendedLifetime(self.rawObject!) { (object) in Internals.assert( object.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) Internals.assert( object.isEditableInContext() == true, "Attempted to update a \(Internals.typeName(O.self))'s value from outside a transaction." ) if let customSetter = self.customSetter { return customSetter(PartialObject<O>(object), newValue) } return object.setValue( newValue.cs_toQueryableNativeType(), forKey: self.keyPath ) } } } // MARK: AnyKeyPathStringConvertible public var cs_keyPathString: String { return self.keyPath } // MARK: KeyPathStringConvertible public typealias ObjectType = O public typealias DestinationValueType = V // MARK: AttributeKeyPathStringConvertible public typealias ReturnValueType = DestinationValueType // MARK: PropertyProtocol internal let keyPath: KeyPathString // MARK: AttributeProtocol internal static var attributeType: NSAttributeType { return V.cs_rawAttributeType } internal let isOptional = false internal let isTransient: Bool internal let allowsExternalBinaryDataStorage = false internal let versionHashModifier: () -> String? internal let renamingIdentifier: () -> String? internal let defaultValue: () -> Any? internal let affectedByKeyPaths: () -> Set<String> internal var rawObject: CoreStoreManagedObject? internal private(set) lazy var getter: CoreStoreManagedObject.CustomGetter? = Internals.with { [unowned self] in guard let customGetter = self.customGetter else { return nil } let keyPath = self.keyPath return { (_ id: Any) -> Any? in let rawObject = id as! CoreStoreManagedObject rawObject.willAccessValue(forKey: keyPath) defer { rawObject.didAccessValue(forKey: keyPath) } let value = customGetter(PartialObject<O>(rawObject)) return value.cs_toQueryableNativeType() } } internal private(set) lazy var setter: CoreStoreManagedObject.CustomSetter? = Internals.with { [unowned self] in guard let customSetter = self.customSetter else { return nil } let keyPath = self.keyPath return { (_ id: Any, _ newValue: Any?) -> Void in let rawObject = id as! CoreStoreManagedObject rawObject.willChangeValue(forKey: keyPath) defer { rawObject.didChangeValue(forKey: keyPath) } customSetter( PartialObject<O>(rawObject), V.cs_fromQueryableNativeType(newValue as! V.QueryableNativeType)! ) } } internal var valueForSnapshot: Any { return self.value as Any } // MARK: Private private let customGetter: ((_ partialObject: PartialObject<O>) -> V)? private let customSetter: ((_ partialObject: PartialObject<O>, _ newValue: V) -> Void)? } // MARK: - Optional /** The containing type for optional value properties. Any type that conforms to `ImportableAttributeType` are supported. ``` class Animal: CoreStoreObject { let species = Value.Required<String>("species", initial: "") let nickname = Value.Optional<String>("nickname") let color = Transformable.Optional<UIColor>("color") } ``` - Important: `Value.Optional` properties are required to be stored properties. Computed properties will be ignored, including `lazy` and `weak` properties. */ public final class Optional<V: ImportableAttributeType>: AttributeKeyPathStringConvertible, AttributeProtocol { /** Initializes the metadata for the property. ``` class Person: CoreStoreObject { let title = Value.Optional<String>("title", initial: "Mr.") let name = Value.Optional<String>("name") let displayName = Value.Optional<String>( "displayName", isTransient: true, customGetter: Person.getName(_:) ) private static func getName(_ partialObject: PartialObject<Person>) -> String? { if let cachedDisplayName = partialObject.primitiveValue(for: { $0.displayName }) { return cachedDisplayName } let title = partialObject.value(for: { $0.title }) let name = partialObject.value(for: { $0.name }) let displayName = "\(title) \(name)" partialObject.setPrimitiveValue(displayName, for: { $0.displayName }) return displayName } } ``` - parameter keyPath: the permanent attribute name for this property. - parameter initial: the initial value for the property when the object is first created. Defaults to `nil` if not specified. - parameter isTransient: `true` if the property is transient, otherwise `false`. Defaults to `false` if not specified. The transient flag specifies whether or not a property's value is ignored when an object is saved to a persistent store. Transient properties are not saved to the persistent store, but are still managed for undo, redo, validation, and so on. - parameter versionHashModifier: used to mark or denote a property as being a different "version" than another even if all of the values which affect persistence are equal. (Such a difference is important in cases where the properties are unchanged but the format or content of its data are changed.) - parameter renamingIdentifier: used to resolve naming conflicts between models. When creating an entity mapping between entities in two managed object models, a source entity property and a destination entity property that share the same identifier indicate that a property mapping should be configured to migrate from the source to the destination. If unset, the identifier will be the property's name. - parameter customGetter: use this closure to make final transformations to the property's value before returning from the getter. - parameter self: the `CoreStoreObject` - parameter getValue: the original getter for the property - parameter customSetter: use this closure to make final transformations to the new value before assigning to the property. - parameter setValue: the original setter for the property - parameter finalNewValue: the transformed new value - parameter originalNewValue: the original new value - parameter affectedByKeyPaths: a set of key paths for properties whose values affect the value of the receiver. This is similar to `NSManagedObject.keyPathsForValuesAffectingValue(forKey:)`. */ public init( _ keyPath: KeyPathString, initial: @autoclosure @escaping () -> V? = nil, isTransient: Bool = false, versionHashModifier: @autoclosure @escaping () -> String? = nil, renamingIdentifier: @autoclosure @escaping () -> String? = nil, customGetter: ((_ partialObject: PartialObject<O>) -> V?)? = nil, customSetter: ((_ partialObject: PartialObject<O>, _ newValue: V?) -> Void)? = nil, affectedByKeyPaths: @autoclosure @escaping () -> Set<String> = []) { self.keyPath = keyPath self.isTransient = isTransient self.defaultValue = { initial()?.cs_toQueryableNativeType() } self.versionHashModifier = versionHashModifier self.renamingIdentifier = renamingIdentifier self.customGetter = customGetter self.customSetter = customSetter self.affectedByKeyPaths = affectedByKeyPaths } /** The attribute value */ public var value: ReturnValueType { get { Internals.assert( self.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) return withExtendedLifetime(self.rawObject!) { (object) in Internals.assert( object.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) if let customGetter = self.customGetter { return customGetter(PartialObject<O>(object)) } return (object.value(forKey: self.keyPath) as! V.QueryableNativeType?) .flatMap(V.cs_fromQueryableNativeType) } } set { Internals.assert( self.rawObject != nil, "Attempted to access values from a \(Internals.typeName(O.self)) meta object. Meta objects are only used for querying keyPaths and infering types." ) return withExtendedLifetime(self.rawObject!) { (object) in Internals.assert( object.isRunningInAllowedQueue() == true, "Attempted to access \(Internals.typeName(O.self))'s value outside it's designated queue." ) Internals.assert( object.isEditableInContext() == true, "Attempted to update a \(Internals.typeName(O.self))'s value from outside a transaction." ) if let customSetter = self.customSetter { return customSetter(PartialObject<O>(object), newValue) } object.setValue( newValue?.cs_toQueryableNativeType(), forKey: self.keyPath ) } } } // MARK: AnyKeyPathStringConvertible public var cs_keyPathString: String { return self.keyPath } // MARK: KeyPathStringConvertible public typealias ObjectType = O public typealias DestinationValueType = V // MARK: AttributeKeyPathStringConvertible public typealias ReturnValueType = DestinationValueType? // MARK: PropertyProtocol internal let keyPath: KeyPathString // MARK: AttributeProtocol internal static var attributeType: NSAttributeType { return V.cs_rawAttributeType } internal let isOptional = true internal let isTransient: Bool internal let allowsExternalBinaryDataStorage = false internal let versionHashModifier: () -> String? internal let renamingIdentifier: () -> String? internal let defaultValue: () -> Any? internal let affectedByKeyPaths: () -> Set<String> internal var rawObject: CoreStoreManagedObject? internal private(set) lazy var getter: CoreStoreManagedObject.CustomGetter? = Internals.with { [unowned self] in guard let customGetter = self.customGetter else { return nil } let keyPath = self.keyPath return { (_ id: Any) -> Any? in let rawObject = id as! CoreStoreManagedObject rawObject.willAccessValue(forKey: keyPath) defer { rawObject.didAccessValue(forKey: keyPath) } let value = customGetter(PartialObject<O>(rawObject)) return value?.cs_toQueryableNativeType() } } internal private(set) lazy var setter: CoreStoreManagedObject.CustomSetter? = Internals.with { [unowned self] in guard let customSetter = self.customSetter else { return nil } let keyPath = self.keyPath return { (_ id: Any, _ newValue: Any?) -> Void in let rawObject = id as! CoreStoreManagedObject rawObject.willChangeValue(forKey: keyPath) defer { rawObject.didChangeValue(forKey: keyPath) } customSetter( PartialObject<O>(rawObject), (newValue as! V.QueryableNativeType?).flatMap(V.cs_fromQueryableNativeType) ) } } internal var valueForSnapshot: Any { return self.value as Any } // MARK: Private private let customGetter: ((_ partialObject: PartialObject<O>) -> V?)? private let customSetter: ((_ partialObject: PartialObject<O>, _ newValue: V?) -> Void)? } } // MARK: - Operations infix operator .= : AssignmentPrecedence infix operator .== : ComparisonPrecedence extension ValueContainer.Required { /** Assigns a value to the property. The operation ``` animal.species .= "Swift" ``` is equivalent to ``` animal.species.value = "Swift" ``` */ public static func .= (_ property: ValueContainer<O>.Required<V>, _ newValue: V) { property.value = newValue } /** Assigns a value from another property. The operation ``` animal.species .= anotherAnimal.species ``` is equivalent to ``` animal.species.value = anotherAnimal.species.value ``` */ public static func .= <O2>(_ property: ValueContainer<O>.Required<V>, _ property2: ValueContainer<O2>.Required<V>) { property.value = property2.value } /** Compares equality between a property's value and another value ``` if animal.species .== "Swift" { ... } ``` is equivalent to ``` if animal.species.value == "Swift" { ... } ``` */ public static func .== (_ property: ValueContainer<O>.Required<V>, _ value: V?) -> Bool { return property.value == value } /** Compares equality between a value and a property's value ``` if "Swift" .== animal.species { ... } ``` is equivalent to ``` if "Swift" == animal.species.value { ... } ``` */ public static func .== (_ value: V?, _ property: ValueContainer<O>.Required<V>) -> Bool { return value == property.value } /** Compares equality between a property's value and another property's value ``` if animal.species .== anotherAnimal.species { ... } ``` is equivalent to ``` if animal.species.value == anotherAnimal.species.value { ... } ``` */ public static func .== (_ property: ValueContainer<O>.Required<V>, _ property2: ValueContainer<O>.Required<V>) -> Bool { return property.value == property2.value } /** Compares equality between a property's value and another property's value ``` if animal.species .== anotherAnimal.species { ... } ``` is equivalent to ``` if animal.species.value == anotherAnimal.species.value { ... } ``` */ public static func .== (_ property: ValueContainer<O>.Required<V>, _ property2: ValueContainer<O>.Optional<V>) -> Bool { return property.value == property2.value } } extension ValueContainer.Optional { /** Assigns an optional value to the property. The operation ``` animal.nickname .= "Taylor" ``` is equivalent to ``` animal.nickname.value = "Taylor" ``` */ public static func .= (_ property: ValueContainer<O>.Optional<V>, _ newValue: V?) { property.value = newValue } /** Assigns an optional value from another property. The operation ``` animal.nickname .= anotherAnimal.nickname ``` is equivalent to ``` animal.nickname.value = anotherAnimal.nickname.value ``` */ public static func .= <O2>(_ property: ValueContainer<O>.Optional<V>, _ property2: ValueContainer<O2>.Optional<V>) { property.value = property2.value } /** Assigns a value from another property. The operation ``` animal.nickname .= anotherAnimal.species ``` is equivalent to ``` animal.nickname.value = anotherAnimal.species.value ``` */ public static func .= <O2>(_ property: ValueContainer<O>.Optional<V>, _ property2: ValueContainer<O2>.Required<V>) { property.value = property2.value } /** Compares equality between a property's value and another value ``` if animal.species .== "Swift" { ... } ``` is equivalent to ``` if animal.species.value == "Swift" { ... } ``` */ public static func .== (_ property: ValueContainer<O>.Optional<V>, _ value: V?) -> Bool { return property.value == value } /** Compares equality between a property's value and another property's value ``` if "Swift" .== animal.species { ... } ``` is equivalent to ``` if "Swift" == animal.species.value { ... } ``` */ public static func .== (_ value: V?, _ property: ValueContainer<O>.Optional<V>) -> Bool { return value == property.value } /** Compares equality between a property's value and another property's value ``` if animal.species .== anotherAnimal.species { ... } ``` is equivalent to ``` if animal.species.value == anotherAnimal.species.value { ... } ``` */ public static func .== (_ property: ValueContainer<O>.Optional<V>, _ property2: ValueContainer<O>.Optional<V>) -> Bool { return property.value == property2.value } /** Compares equality between a property's value and another property's value ``` if animal.species .== anotherAnimal.species { ... } ``` is equivalent to ``` if animal.species.value == anotherAnimal.species.value { ... } ``` */ public static func .== (_ property: ValueContainer<O>.Optional<V>, _ property2: ValueContainer<O>.Required<V>) -> Bool { return property.value == property2.value } }
mit
2832d0d6c7380ee7664d9cee65c498b0
40.477465
786
0.591803
5.359236
false
false
false
false
jdarowski/RGSnackBar
Example/RGSnackBar/MutableCollectionType+shuffle.swift
1
839
// // MutableCollectionType+shuffle.swift // RGSnackBar // // Created by Jakub Darowski on 07/09/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import Foundation extension MutableCollection where Index == Int { /// Shuffle the elements of `self` in-place. mutating func shuffleInPlace() { // empty and single-element collections don't shuffle if count < 2 { return } for i in startIndex ..< endIndex - 1 { let j = Int(arc4random_uniform(UInt32(endIndex - i))) + i if i != j { swapAt(i, j) } } } } extension Collection { /// Return a copy of `self` with its elements shuffled. func shuffle() -> [Iterator.Element] { var list = Array(self) list.shuffleInPlace() return list } }
mit
531f9423dee6988025a9aead15f1f05b
24.393939
69
0.583532
4.19
false
false
false
false
bencochran/MinimalJSON
MinimalJSONTests/TestModel.swift
1
1105
// // TestModel.swift // MinimalJSON // // Created by Ben Cochran on 9/1/15. // Copyright © 2015 Ben Cochran. All rights reserved. // import Foundation import CoreLocation @testable import MinimalJSON internal struct Person { internal let id: Int internal let name: String internal let website: NSURL? internal init(id: Int, name: String, website: NSURL? = nil) { self.id = id self.name = name self.website = website } } extension Person: JSONInitializable { internal init(json: JSONValue) throws { self.id = try json["id"].decode() self.name = try json["name"].decode() self.website = try? json["website"].decode() } } extension Person: Equatable { } internal func ==(lhs: Person, rhs: Person) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name && lhs.website == rhs.website } extension CLLocationCoordinate2D: Equatable { } public func ==(lhs: CLLocationCoordinate2D, rhs: CLLocationCoordinate2D) -> Bool { return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude }
bsd-3-clause
d06284a6038066d5402defa0dd65b6f4
23.533333
82
0.645833
3.86014
false
false
false
false
khizkhiz/swift
benchmark/single-source/Array2D.swift
2
858
//===--- Array2D.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 // //===----------------------------------------------------------------------===// @inline(never) public func run_Array2D(N: Int) { var A: [[Int]] = [] for _ in 0 ..< 1024 { var B: [Int] = [] for y in 0 ..< 1024 { B.append(y) } A.append(B) } for _ in 0..<N { for i in 0 ..< 1024 { for y in 0 ..< 1024 { A[i][y] = A[i][y] + 1 A[i][y] = A[i][y] - 1 } } } }
apache-2.0
080f89c15d36e8035c4d746b243c5fd8
26.677419
80
0.472028
3.651064
false
false
false
false
jandro-es/Evergreen
Evergreen/src/Models/Account.swift
1
4139
// // Account.swift // Evergreen // // Created by Alejandro Barros Cuetos on 31/01/2016. // Copyright © 2016 Alejandro Barros Cuetos. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // && and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // import Foundation import Freddy public struct Account: EvergreenObjectable { // MARK: - Private Properties private static let _kBaseNode = "account" private enum _dataKeys: String { case DropletLimit = "droplet_limit" case FloatingIPLimit = "floating_ip_limit" case Email = "email" case UUID = "uuid" case EmailVerified = "email_verified" case Status = "status" case StatusMessage = "status_message" } // MARK: - Public Properties public enum Status: String { case Active = "active" case Warning = "warning" case Locked = "locked" } public let email: String public let uuid: String public let dropletLimit: Int public let emailVerified: Bool public let floatingIPLimit: Int public let accountStatus: Status public let accountStatusMessage: String } // MARK: - JSONDecodable extension Account: JSONDecodable { public init(json: Freddy.JSON) throws { let accountJson = try JSON(json.dictionary(Account._kBaseNode)) uuid = try accountJson.string(_dataKeys.UUID.rawValue) email = try accountJson.string(_dataKeys.Email.rawValue) dropletLimit = try accountJson.int(_dataKeys.DropletLimit.rawValue) emailVerified = try accountJson.bool(_dataKeys.EmailVerified.rawValue) floatingIPLimit = try accountJson.int(_dataKeys.FloatingIPLimit.rawValue) accountStatus = try Status(rawValue: accountJson.string(_dataKeys.Status.rawValue))! accountStatusMessage = try accountJson.string(_dataKeys.StatusMessage.rawValue) } } // MARK: - JSONEncodable extension Account: JSONEncodable { public func toJSON() -> JSON { return .Dictionary([_dataKeys.UUID.rawValue: .String(uuid), _dataKeys.Email.rawValue: .String(email), _dataKeys.DropletLimit.rawValue: .Int(dropletLimit), _dataKeys.EmailVerified.rawValue: .Bool(emailVerified), _dataKeys.FloatingIPLimit.rawValue: .Int(floatingIPLimit), _dataKeys.Status.rawValue: .String(accountStatus.rawValue), _dataKeys.StatusMessage.rawValue: .String(accountStatusMessage)]) } } // MARK: - CustomStringConvertible extension Account: CustomStringConvertible { public var description: String { return "Account:\nemail: \(email)\nuuid: \(uuid)\ndroplet_limit: \(dropletLimit)\nfloating_ip_limit: \(floatingIPLimit)\nstatus: \(accountStatus.rawValue)\nstatus_message: \(accountStatusMessage)\nemail_verified: \(emailVerified)\n" } } public func ==(lhs: Account, rhs: Account) -> Bool { return lhs.email == rhs.email && lhs.uuid == rhs.uuid }
apache-2.0
4036d5686cae364ae096160d0bf31fab
39.980198
403
0.71653
4.332984
false
false
false
false
hyperoslo/AsyncWall
Example/InfiniteScroll/InfiniteScroll/ViewController.swift
1
3352
import UIKit import Wall import Fakery import Sugar class ViewController: WallController { let faker = Faker() override func viewDidLoad() { super.viewDidLoad() title = "Infinite Scroll" Config.thumbnailForAttachment = { (attachment: Attachable, size: CGSize) -> URLStringConvertible? in return String(format: attachment.source.string, Int(size.width), Int(size.height)) } tapDelegate = self scrollDelegate = self posts = generatePosts(1, to: 50) } func generatePosts(from: Int, to: Int) -> [PostConvertible] { var posts = [PostConvertible]() for i in from...to { let user = User( name: faker.name.name(), avatar: Image("http://lorempixel.com/75/75?type=avatar&id=\(i)")) var attachments = [AttachmentConvertible]() var comments = [PostConvertible]() var attachmentCount = 0 var likes = 0 var commentCount = 0 var seen = 0 if i % 4 == 0 { attachmentCount = 4 commentCount = 3 likes = 3 seen = 4 } else if i % 3 == 0 { attachmentCount = 2 commentCount = 1 likes = 1 seen = 2 } else if i % 2 == 0 { attachmentCount = 1 commentCount = 4 likes = 4 seen = 6 } for x in 0..<attachmentCount { attachments.append(Image("http://lorempixel.com/250/250/?type=attachment&id=\(i)\(x)")) } let sencenceCount = Int(arc4random_uniform(8) + 1) let post = Post( text: faker.lorem.sentences(amount: sencenceCount), publishDate: NSDate(timeIntervalSinceNow: -Double(arc4random_uniform(60000))), author: user, attachments: attachments ) post.likeCount = likes post.seenCount = seen post.commentCount = commentCount for x in 0..<commentCount { let commentUser = User( name: faker.name.name(), avatar: Image("http://lorempixel.com/75/75/?type=avatar&id=\(i)\(x)")) let comment = Post( text: faker.lorem.sentences(amount: sencenceCount), publishDate: NSDate(timeIntervalSinceNow: -4), author: commentUser ) comments.append(comment) } post.comments = comments posts.append(post) } return posts } } extension ViewController: WallTapDelegate { func wallPostWasTapped(element: TappedElement, post: Post) { guard let index = posts.indexOf( { $0.wallModel.id == post.id } ), post = posts[index] as? Post else { return } switch element { case .Attachment: let detailView = DetailViewController(post: post) self.navigationController?.pushViewController(detailView, animated: true) case .Text: let detailView = DetailViewController(post: post) self.navigationController?.pushViewController(detailView, animated: true) default: break } } } extension ViewController: WallScrollDelegate { func wallDidScrollToEnd(completion: () -> Void) { let newPosts = generatePosts(0, to: 20) var updatedPosts = self.posts updatedPosts.appendContentsOf(newPosts) self.posts = updatedPosts let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue()) { completion() } } }
mit
a4f1e5b0f0cfcf65e8fad2e10cb5224a
25.816
115
0.622912
4.179551
false
false
false
false
klaus01/Centipede
Centipede/UIKit/CE_UICollectionView.swift
1
20208
// // CE_UICollectionView.swift // Centipede // // Created by kelei on 2016/9/15. // Copyright (c) 2016年 kelei. All rights reserved. // import UIKit extension UICollectionView { private struct Static { static var AssociationKey: UInt8 = 0 } private var _delegate: UICollectionView_Delegate? { get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? UICollectionView_Delegate } set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } private var ce: UICollectionView_Delegate { if let obj = _delegate { return obj } if let obj: AnyObject = self.delegate { if obj is UICollectionView_Delegate { return obj as! UICollectionView_Delegate } } let obj = getDelegateInstance() _delegate = obj return obj } private func rebindingDelegate() { let delegate = ce self.delegate = nil self.delegate = delegate self.dataSource = nil self.dataSource = delegate } internal override func getDelegateInstance() -> UICollectionView_Delegate { return UICollectionView_Delegate() } @discardableResult public func ce_collectionView_numberOfItemsInSection(handle: @escaping (UICollectionView, Int) -> Int) -> Self { ce._collectionView_numberOfItemsInSection = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_cellForItemAt(handle: @escaping (UICollectionView, IndexPath) -> UICollectionViewCell) -> Self { ce._collectionView_cellForItemAt = handle rebindingDelegate() return self } @discardableResult public func ce_numberOfSections_in(handle: @escaping (UICollectionView) -> Int) -> Self { ce._numberOfSections_in = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_viewForSupplementaryElementOfKind(handle: @escaping (UICollectionView, String, IndexPath) -> UICollectionReusableView) -> Self { ce._collectionView_viewForSupplementaryElementOfKind = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_shouldHighlightItemAt(handle: @escaping (UICollectionView, IndexPath) -> Bool) -> Self { ce._collectionView_shouldHighlightItemAt = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_didHighlightItemAt(handle: @escaping (UICollectionView, IndexPath) -> Void) -> Self { ce._collectionView_didHighlightItemAt = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_didUnhighlightItemAt(handle: @escaping (UICollectionView, IndexPath) -> Void) -> Self { ce._collectionView_didUnhighlightItemAt = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_shouldSelectItemAt(handle: @escaping (UICollectionView, IndexPath) -> Bool) -> Self { ce._collectionView_shouldSelectItemAt = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_shouldDeselectItemAt(handle: @escaping (UICollectionView, IndexPath) -> Bool) -> Self { ce._collectionView_shouldDeselectItemAt = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_didSelectItemAt(handle: @escaping (UICollectionView, IndexPath) -> Void) -> Self { ce._collectionView_didSelectItemAt = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_didDeselectItemAt(handle: @escaping (UICollectionView, IndexPath) -> Void) -> Self { ce._collectionView_didDeselectItemAt = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_willDisplay(handle: @escaping (UICollectionView, UICollectionViewCell, IndexPath) -> Void) -> Self { ce._collectionView_willDisplay = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_willDisplaySupplementaryView(handle: @escaping (UICollectionView, UICollectionReusableView, String, IndexPath) -> Void) -> Self { ce._collectionView_willDisplaySupplementaryView = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_didEndDisplaying(handle: @escaping (UICollectionView, UICollectionViewCell, IndexPath) -> Void) -> Self { ce._collectionView_didEndDisplaying = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_didEndDisplayingSupplementaryView(handle: @escaping (UICollectionView, UICollectionReusableView, String, IndexPath) -> Void) -> Self { ce._collectionView_didEndDisplayingSupplementaryView = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_shouldShowMenuForItemAt(handle: @escaping (UICollectionView, IndexPath) -> Bool) -> Self { ce._collectionView_shouldShowMenuForItemAt = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_canPerformAction(handle: @escaping (UICollectionView, Selector, IndexPath, Any?) -> Bool) -> Self { ce._collectionView_canPerformAction = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_performAction(handle: @escaping (UICollectionView, Selector, IndexPath, Any?) -> Void) -> Self { ce._collectionView_performAction = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_transitionLayoutForOldLayout(handle: @escaping (UICollectionView, UICollectionViewLayout, UICollectionViewLayout) -> UICollectionViewTransitionLayout) -> Self { ce._collectionView_transitionLayoutForOldLayout = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_layout(handle: @escaping (UICollectionView, UICollectionViewLayout, IndexPath) -> CGSize) -> Self { ce._collectionView_layout = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_layout_layout(handle: @escaping (UICollectionView, UICollectionViewLayout, Int) -> UIEdgeInsets) -> Self { ce._collectionView_layout_layout = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_layout_layout_layout(handle: @escaping (UICollectionView, UICollectionViewLayout, Int) -> CGFloat) -> Self { ce._collectionView_layout_layout_layout = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_layout_layout_layout_layout(handle: @escaping (UICollectionView, UICollectionViewLayout, Int) -> CGFloat) -> Self { ce._collectionView_layout_layout_layout_layout = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_layout_layout_layout_layout_layout(handle: @escaping (UICollectionView, UICollectionViewLayout, Int) -> CGSize) -> Self { ce._collectionView_layout_layout_layout_layout_layout = handle rebindingDelegate() return self } @discardableResult public func ce_collectionView_layout_layout_layout_layout_layout_layout(handle: @escaping (UICollectionView, UICollectionViewLayout, Int) -> CGSize) -> Self { ce._collectionView_layout_layout_layout_layout_layout_layout = handle rebindingDelegate() return self } } internal class UICollectionView_Delegate: UIScrollView_Delegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { var _collectionView_numberOfItemsInSection: ((UICollectionView, Int) -> Int)? var _collectionView_cellForItemAt: ((UICollectionView, IndexPath) -> UICollectionViewCell)? var _numberOfSections_in: ((UICollectionView) -> Int)? var _collectionView_viewForSupplementaryElementOfKind: ((UICollectionView, String, IndexPath) -> UICollectionReusableView)? var _collectionView_shouldHighlightItemAt: ((UICollectionView, IndexPath) -> Bool)? var _collectionView_didHighlightItemAt: ((UICollectionView, IndexPath) -> Void)? var _collectionView_didUnhighlightItemAt: ((UICollectionView, IndexPath) -> Void)? var _collectionView_shouldSelectItemAt: ((UICollectionView, IndexPath) -> Bool)? var _collectionView_shouldDeselectItemAt: ((UICollectionView, IndexPath) -> Bool)? var _collectionView_didSelectItemAt: ((UICollectionView, IndexPath) -> Void)? var _collectionView_didDeselectItemAt: ((UICollectionView, IndexPath) -> Void)? var _collectionView_willDisplay: ((UICollectionView, UICollectionViewCell, IndexPath) -> Void)? var _collectionView_willDisplaySupplementaryView: ((UICollectionView, UICollectionReusableView, String, IndexPath) -> Void)? var _collectionView_didEndDisplaying: ((UICollectionView, UICollectionViewCell, IndexPath) -> Void)? var _collectionView_didEndDisplayingSupplementaryView: ((UICollectionView, UICollectionReusableView, String, IndexPath) -> Void)? var _collectionView_shouldShowMenuForItemAt: ((UICollectionView, IndexPath) -> Bool)? var _collectionView_canPerformAction: ((UICollectionView, Selector, IndexPath, Any?) -> Bool)? var _collectionView_performAction: ((UICollectionView, Selector, IndexPath, Any?) -> Void)? var _collectionView_transitionLayoutForOldLayout: ((UICollectionView, UICollectionViewLayout, UICollectionViewLayout) -> UICollectionViewTransitionLayout)? var _collectionView_layout: ((UICollectionView, UICollectionViewLayout, IndexPath) -> CGSize)? var _collectionView_layout_layout: ((UICollectionView, UICollectionViewLayout, Int) -> UIEdgeInsets)? var _collectionView_layout_layout_layout: ((UICollectionView, UICollectionViewLayout, Int) -> CGFloat)? var _collectionView_layout_layout_layout_layout: ((UICollectionView, UICollectionViewLayout, Int) -> CGFloat)? var _collectionView_layout_layout_layout_layout_layout: ((UICollectionView, UICollectionViewLayout, Int) -> CGSize)? var _collectionView_layout_layout_layout_layout_layout_layout: ((UICollectionView, UICollectionViewLayout, Int) -> CGSize)? override func responds(to aSelector: Selector!) -> Bool { let funcDic1: [Selector : Any?] = [ #selector(collectionView(_:numberOfItemsInSection:)) : _collectionView_numberOfItemsInSection, #selector(collectionView(_:cellForItemAt:)) : _collectionView_cellForItemAt, #selector(numberOfSections(in:)) : _numberOfSections_in, #selector(collectionView(_:viewForSupplementaryElementOfKind:at:)) : _collectionView_viewForSupplementaryElementOfKind, #selector(collectionView(_:shouldHighlightItemAt:)) : _collectionView_shouldHighlightItemAt, #selector(collectionView(_:didHighlightItemAt:)) : _collectionView_didHighlightItemAt, #selector(collectionView(_:didUnhighlightItemAt:)) : _collectionView_didUnhighlightItemAt, ] if let f = funcDic1[aSelector] { return f != nil } let funcDic2: [Selector : Any?] = [ #selector(collectionView(_:shouldSelectItemAt:)) : _collectionView_shouldSelectItemAt, #selector(collectionView(_:shouldDeselectItemAt:)) : _collectionView_shouldDeselectItemAt, #selector(collectionView(_:didSelectItemAt:)) : _collectionView_didSelectItemAt, #selector(collectionView(_:didDeselectItemAt:)) : _collectionView_didDeselectItemAt, #selector(collectionView(_:willDisplay:forItemAt:)) : _collectionView_willDisplay, #selector(collectionView(_:willDisplaySupplementaryView:forElementKind:at:)) : _collectionView_willDisplaySupplementaryView, #selector(collectionView(_:didEndDisplaying:forItemAt:)) : _collectionView_didEndDisplaying, ] if let f = funcDic2[aSelector] { return f != nil } let funcDic3: [Selector : Any?] = [ #selector(collectionView(_:didEndDisplayingSupplementaryView:forElementOfKind:at:)) : _collectionView_didEndDisplayingSupplementaryView, #selector(collectionView(_:shouldShowMenuForItemAt:)) : _collectionView_shouldShowMenuForItemAt, #selector(collectionView(_:canPerformAction:forItemAt:withSender:)) : _collectionView_canPerformAction, #selector(collectionView(_:performAction:forItemAt:withSender:)) : _collectionView_performAction, #selector(collectionView(_:transitionLayoutForOldLayout:newLayout:)) : _collectionView_transitionLayoutForOldLayout, #selector(collectionView(_:layout:sizeForItemAt:)) : _collectionView_layout, #selector(collectionView(_:layout:insetForSectionAt:)) : _collectionView_layout_layout, ] if let f = funcDic3[aSelector] { return f != nil } let funcDic4: [Selector : Any?] = [ #selector(collectionView(_:layout:minimumLineSpacingForSectionAt:)) : _collectionView_layout_layout_layout, #selector(collectionView(_:layout:minimumInteritemSpacingForSectionAt:)) : _collectionView_layout_layout_layout_layout, #selector(collectionView(_:layout:referenceSizeForHeaderInSection:)) : _collectionView_layout_layout_layout_layout_layout, #selector(collectionView(_:layout:referenceSizeForFooterInSection:)) : _collectionView_layout_layout_layout_layout_layout_layout, ] if let f = funcDic4[aSelector] { return f != nil } return super.responds(to: aSelector) } @objc func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return _collectionView_numberOfItemsInSection!(collectionView, section) } @objc func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { return _collectionView_cellForItemAt!(collectionView, indexPath) } @objc func numberOfSections(in collectionView: UICollectionView) -> Int { return _numberOfSections_in!(collectionView) } @objc func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { return _collectionView_viewForSupplementaryElementOfKind!(collectionView, kind, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return _collectionView_shouldHighlightItemAt!(collectionView, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) { _collectionView_didHighlightItemAt!(collectionView, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) { _collectionView_didUnhighlightItemAt!(collectionView, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return _collectionView_shouldSelectItemAt!(collectionView, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, shouldDeselectItemAt indexPath: IndexPath) -> Bool { return _collectionView_shouldDeselectItemAt!(collectionView, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { _collectionView_didSelectItemAt!(collectionView, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { _collectionView_didDeselectItemAt!(collectionView, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { _collectionView_willDisplay!(collectionView, cell, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) { _collectionView_willDisplaySupplementaryView!(collectionView, view, elementKind, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { _collectionView_didEndDisplaying!(collectionView, cell, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, didEndDisplayingSupplementaryView view: UICollectionReusableView, forElementOfKind elementKind: String, at indexPath: IndexPath) { _collectionView_didEndDisplayingSupplementaryView!(collectionView, view, elementKind, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool { return _collectionView_shouldShowMenuForItemAt!(collectionView, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool { return _collectionView_canPerformAction!(collectionView, action, indexPath, sender) } @objc func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) { _collectionView_performAction!(collectionView, action, indexPath, sender) } @objc func collectionView(_ collectionView: UICollectionView, transitionLayoutForOldLayout fromLayout: UICollectionViewLayout, newLayout toLayout: UICollectionViewLayout) -> UICollectionViewTransitionLayout { return _collectionView_transitionLayoutForOldLayout!(collectionView, fromLayout, toLayout) } @objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return _collectionView_layout!(collectionView, collectionViewLayout, indexPath) } @objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return _collectionView_layout_layout!(collectionView, collectionViewLayout, section) } @objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return _collectionView_layout_layout_layout!(collectionView, collectionViewLayout, section) } @objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return _collectionView_layout_layout_layout_layout!(collectionView, collectionViewLayout, section) } @objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return _collectionView_layout_layout_layout_layout_layout!(collectionView, collectionViewLayout, section) } @objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { return _collectionView_layout_layout_layout_layout_layout_layout!(collectionView, collectionViewLayout, section) } }
mit
b5f6572dd322e0decfca75a7489d6610
55.59944
212
0.728694
5.786369
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.ThreadControlPoint.swift
1
2057
import Foundation public extension AnyCharacteristic { static func threadControlPoint( _ value: Data? = nil, permissions: [CharacteristicPermission] = [.write], description: String? = "Thread Control Point", format: CharacteristicFormat? = .tlv8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.threadControlPoint( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func threadControlPoint( _ value: Data? = nil, permissions: [CharacteristicPermission] = [.write], description: String? = "Thread Control Point", format: CharacteristicFormat? = .tlv8, unit: CharacteristicUnit? = nil, maxLength: Int? = nil, maxValue: Double? = nil, minValue: Double? = nil, minStep: Double? = nil, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Data?> { GenericCharacteristic<Data?>( type: .threadControlPoint, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
3f42abd35032652bcb58824b7b7542a5
32.721311
66
0.580457
5.470745
false
false
false
false
jovito-royeca/CardMagusKit
Example/Pods/Networking/Sources/Response.swift
1
1585
import Foundation public class Response { public var headers: [AnyHashable: Any] { return fullResponse.allHeaderFields } public var statusCode: Int { return fullResponse.statusCode } public let fullResponse: HTTPURLResponse init(response: HTTPURLResponse) { self.fullResponse = response } } public class FailureResponse: Response { public let error: NSError init(response: HTTPURLResponse, error: NSError) { self.error = error super.init(response: response) } } public class JSONResponse: Response { public let json: JSON public var dictionaryBody: [String: Any] { return json.dictionary } public var arrayBody: [[String: Any]] { return json.array } init(json: JSON, response: HTTPURLResponse) { self.json = json super.init(response: response) } } public class SuccessJSONResponse: JSONResponse { } public class FailureJSONResponse: JSONResponse { public let error: NSError init(json: JSON, response: HTTPURLResponse, error: NSError) { self.error = error super.init(json: json, response: response) } } public class SuccessImageResponse: Response { public let image: Image init(image: Image, response: HTTPURLResponse) { self.image = image super.init(response: response) } } public class SuccessDataResponse: Response { public let data: Data init(data: Data, response: HTTPURLResponse) { self.data = data super.init(response: response) } }
mit
2f9a09acd9911a34c9ba2fc17c0207d5
19.584416
65
0.657413
4.477401
false
false
false
false
marinehero/LeetCode-Solutions-in-Swift
Solutions/Solutions/Hard/Hard_023_Merge_K_Sorted_Lists.swift
4
2172
/* https://leetcode.com/problems/merge-k-sorted-lists/ #23 Merge k Sorted Lists Level: hard Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Inspired by @wksora at https://leetcode.com/discuss/9279/a-java-solution-based-on-priority-queue */ import Foundation // O (N x logK), where N is the total number of elements, K is the number of lists class Hard_023_Merge_K_Sorted_Lists { class Node { var value: Int var next: Node? init(value: Int, next: Node?) { self.value = value self.next = next } } class func mergeTwoLists(var l1 l1: Node?, var l2: Node?) -> Node? { if l1 == nil { return l2 } if l2 == nil { return l1 } var curr: Node? = nil var prev: Node? = nil while l1 != nil && l2 != nil { if l1!.value > l2!.value { if prev == nil { prev = l2 } else { prev!.next = l2 } if curr == nil { curr = prev } else { prev = prev!.next } l2 = l2!.next } else { if prev == nil { prev = l1 } else { prev!.next = l1 } if curr == nil { curr = prev } else { prev = prev!.next } l1 = l1!.next } } if l2 != nil { l1 = l2 } prev!.next = l1 return curr } class func mergeKLists(lists: [Node?]) -> Node? { if lists.count == 0 { return nil } else if lists.count == 1 { return lists[0] } else if lists.count == 2 { return mergeTwoLists(l1: lists[0], l2: lists[1]) } else { return mergeTwoLists(l1: mergeKLists(Array(lists[0..<lists.count/2])), l2: mergeKLists(Array(lists[lists.count/2..<lists.count]))) } } }
mit
8ee9f6d5c0d98002433503f9a4aa3a7f
26.1625
142
0.439687
4.037175
false
false
false
false
netcosports/Gnomon
Sources/Decodable/Decoder+XPath.swift
1
2848
// // Created by Vladimir Burdukov on 05/12/2017. // Copyright © 2017 NetcoSports. All rights reserved. // import Foundation public struct Path: CodingKey { public enum Component { case key(String) case index(Int) // swiftlint:disable:next force_try private static let regex = try! NSRegularExpression(pattern: "\\[(\\d)\\]") static func parse(string: String) -> [Component] { do { guard string.hasSuffix("]") else { throw "" } guard let range = string.range(of: "(\\[(\\d)\\])+$", options: .regularExpression) else { throw "" } let matches = regex.matches(in: string, range: NSRange(range, in: string)) var components = [Component]() components.reserveCapacity(matches.count + 1) if range.lowerBound != string.startIndex { components.append(.key(String(string[..<range.lowerBound]))) } for match in matches { guard match.numberOfRanges == 2 else { continue } guard let range = Range(match.range(at: 1), in: string), let index = Int(string[range]) else { continue } components.append(.index(index)) } return components } catch { return [.key(string)] } } } public init?(stringValue: String) { self.init(stringComponents: [stringValue]) } public init(stringComponents: [String]) { self.components = stringComponents.flatMap { Component.parse(string: $0) } } public var stringValue: String { switch components[0] { case let .key(key): return key case let .index(index): return "Index \(index)" } } public var intValue: Int? { switch components[0] { case .key: return nil case let .index(idx): return idx } } public init?(intValue: Int) { return nil } public let components: [Component] public init(components: [Component]) { self.components = components } public var next: Path { var components = self.components _ = components.removeFirst() return Path(components: components) } } public extension Decoder { func decoder(by stringPath: String?) throws -> Decoder { guard let stringPath = stringPath else { return self } return try decoder(by: Path(stringComponents: stringPath.components(separatedBy: "/"))) } func decoder(by path: Path) throws -> Decoder { var decoder: Decoder = self var path = path while path.components.count > 0 { if let index = path.intValue { var container = try decoder.unkeyedContainer() while container.currentIndex < index { _ = try container.superDecoder() } decoder = try container.superDecoder() } else { decoder = try decoder.container(keyedBy: Path.self).superDecoder(forKey: path) } path = path.next } return decoder } }
mit
4f3b8b4ec7ad218e0ebcf23cbde65938
25.607477
115
0.627678
4.242921
false
false
false
false
cforlando/orlando-walking-tours-ios
Orlando Walking Tours/Views/DashboardViewFlowLayout.swift
1
2933
// // DashboardViewFlowLayout.swift // Orlando Walking Tours // // Created by Keli'i Martin on 6/16/16. // Copyright © 2016 Code for Orlando. All rights reserved. // import UIKit protocol DashboardViewLayoutDelegate { func isDeletionModeActiveForCollectionView(collectionView: UICollectionView, layout: UICollectionViewLayout) -> Bool } //////////////////////////////////////////////////////////// class DashboardViewFlowLayout: UICollectionViewFlowLayout { override var itemSize: CGSize { set { } get { let itemWidth = self.collectionView!.frame.width / 2.0 return CGSize(width: itemWidth, height: itemWidth) } } //////////////////////////////////////////////////////////// override class var layoutAttributesClass: AnyClass { get { return DashboardViewLayoutAttributes.self } } //////////////////////////////////////////////////////////// override init() { super.init() setupLayout() } //////////////////////////////////////////////////////////// required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupLayout() } //////////////////////////////////////////////////////////// func setupLayout() { minimumInteritemSpacing = 0 minimumLineSpacing = 0 scrollDirection = .vertical } //////////////////////////////////////////////////////////// func isDeletionModeOn() -> Bool { if let collectionView = self.collectionView, let delegate = collectionView.delegate as? DashboardViewLayoutDelegate { return delegate.isDeletionModeActiveForCollectionView(collectionView: collectionView, layout: self) } return false } //////////////////////////////////////////////////////////// override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if let attributes = super.layoutAttributesForItem(at: indexPath) as? DashboardViewLayoutAttributes { attributes.deleteButtonHidden = isDeletionModeOn() ? false : true return attributes } return nil } //////////////////////////////////////////////////////////// override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { if let attributesArrayInRect = super.layoutAttributesForElements(in: rect) { for attributes in attributesArrayInRect { if let attributes = attributes as? DashboardViewLayoutAttributes { attributes.deleteButtonHidden = isDeletionModeOn() ? false : true } } return attributesArrayInRect } return nil } }
mit
5f2db2ca2f0c4e74b6572c6fa5f0739c
24.946903
120
0.511937
6.530067
false
false
false
false
double-y/ios_swift_practice
ios_swift_practice/SampleTableViewController.swift
1
3756
// // SampleTableViewController.swift // ios_swift_practice // // Created by 安田洋介 on 10/3/15. // Copyright © 2015 安田洋介. All rights reserved. // import UIKit import Foundation import CoreData class SampleTableViewController: UIViewController, UITableViewDataSource{ @IBOutlet weak var tableView: UITableView! var people = [NSManagedObject]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. title = "\"The List\"" tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell") //1 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext //2 let fetchRequest = NSFetchRequest(entityName: "Person") //3 do { let results = try managedContext.executeFetchRequest(fetchRequest) people = results as! [NSManagedObject] } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return people.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") cell!.textLabel!.text = people[indexPath.row].valueForKey("name") as? String return cell! } @IBAction func addName(sender: AnyObject) { let alert = UIAlertController(title: "New Name", message: "Add a new name", preferredStyle: .Alert) let saveAction = UIAlertAction(title: "Save", style: .Default, handler: { (action:UIAlertAction) -> Void in let textField = alert.textFields!.first self.saveName(textField!.text!) self.tableView.reloadData() }) let cancelAction = UIAlertAction(title: "Cancel", style: .Default) { (action: UIAlertAction) -> Void in } alert.addTextFieldWithConfigurationHandler { (textField: UITextField) -> Void in } alert.addAction(saveAction) alert.addAction(cancelAction) presentViewController(alert, animated: true, completion: nil) } func saveName(name: String) { //1 let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate let managedContext = appDelegate.managedObjectContext //2 let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext:managedContext) let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) //3 person.setValue(name, forKey: "name") //4 do { try managedContext.save() //5 people.append(person) } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } } }
mit
42f00d5403db4748d41dd1921b758149
28.92
84
0.564589
5.869702
false
false
false
false
sergeysivak/IconFactory
Example/IconFactory/Classes/SettingsViewController.swift
1
12476
// // SettingsViewController.swift // Demo // // Created by Sergey Sivak on 19/07/16. // // import UIKit import IconFactory class SettingsViewController: UIViewController { @IBOutlet weak var iconsStyleTextField: UITextField! @IBOutlet weak var iconTypeTextField: UITextField! @IBOutlet weak var foregroundColorTextField: UITextField! @IBOutlet weak var backgroundColorTextField: UITextField! @IBOutlet weak var widthTextField: UITextField! @IBOutlet weak var heightTextField: UITextField! private var style: IconsStyle? private var stylePicker: UIPickerView! private var typePicker: UIPickerView! private var foregroundColorPicker: UIPickerView! private var backgroundColorPicker: UIPickerView! @IBOutlet weak var widthStepper: UIStepper! @IBOutlet weak var heightStepper: UIStepper! private var colorHexArray = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"] override func viewDidLoad() { let toolbar = UIToolbar(frame: CGRect(origin: CGPointZero, size: CGSize(width: view.bounds.width, height: 44))) toolbar.barStyle = .Black toolbar.items = [ UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil), UIBarButtonItem(barButtonSystemItem: .Done, target: self, action: #selector(resignKeyboard)), ] stylePicker = createPicker() iconsStyleTextField.inputView = stylePicker iconsStyleTextField.inputAccessoryView = toolbar iconsStyleTextField.delegate = self typePicker = createPicker() iconTypeTextField.inputView = typePicker iconTypeTextField.inputAccessoryView = toolbar iconTypeTextField.delegate = self foregroundColorPicker = createPicker() foregroundColorTextField.inputView = foregroundColorPicker foregroundColorTextField.inputAccessoryView = toolbar foregroundColorTextField.delegate = self backgroundColorPicker = createPicker() backgroundColorTextField.inputView = backgroundColorPicker backgroundColorTextField.inputAccessoryView = toolbar backgroundColorTextField.delegate = self widthTextField.enabled = false heightTextField.enabled = false widthStepper.minimumValue = 1.0 widthStepper.maximumValue = 500.0 heightStepper.minimumValue = 1.0 heightStepper.maximumValue = 500.0 widthStepper.addTarget(self, action: #selector(stepperDidChanged), forControlEvents: .ValueChanged) heightStepper.addTarget(self, action: #selector(stepperDidChanged), forControlEvents: .ValueChanged) setDefaultValues() } func createPicker() -> UIPickerView { let picker = UIPickerView() picker.delegate = self picker.dataSource = self return picker } private func setDefaultValues() { stylePicker.selectRow(0, inComponent: 0, animated: false) typePicker.selectRow(0, inComponent: 0, animated: false) foregroundColorPicker.selectRow(15, inComponent: 1, animated: true) foregroundColorPicker.selectRow(15, inComponent: 2, animated: true) foregroundColorPicker.selectRow(15, inComponent: 3, animated: true) foregroundColorPicker.selectRow(15, inComponent: 4, animated: true) foregroundColorPicker.selectRow(15, inComponent: 5, animated: true) foregroundColorPicker.selectRow(15, inComponent: 6, animated: true) backgroundColorPicker.selectRow(0, inComponent: 1, animated: true) backgroundColorPicker.selectRow(0, inComponent: 2, animated: true) backgroundColorPicker.selectRow(0, inComponent: 3, animated: true) backgroundColorPicker.selectRow(0, inComponent: 4, animated: true) backgroundColorPicker.selectRow(0, inComponent: 5, animated: true) backgroundColorPicker.selectRow(0, inComponent: 6, animated: true) widthStepper.value = 44.0 heightStepper.value = 44.0 stepperDidChanged(widthStepper) stepperDidChanged(heightStepper) iconsStyleTextField.text = IconsStyle.fontAwesome.description style = IconsStyle.fontAwesome iconTypeTextField.text = IconFactory.availableIconTypes.first foregroundColorTextField.text = "#FFFFFF" let fColor = UIColor(hexString: "#FFFFFF") foregroundColorTextField.textColor = fColor.inversedColor() foregroundColorTextField.backgroundColor = fColor backgroundColorTextField.text = "#000000" let bColor = UIColor(hexString: "#000000") backgroundColorTextField.textColor = bColor.inversedColor() backgroundColorTextField.backgroundColor = bColor } @IBAction private func saveBarButtonDidTouchUpInside(sender: UIBarButtonItem) { } private dynamic func resignKeyboard() { for textField in [iconsStyleTextField, iconTypeTextField, backgroundColorTextField, foregroundColorTextField] { textField.resignFirstResponder() } } private dynamic func stepperDidChanged(stepper: UIStepper) { switch stepper { case widthStepper: widthTextField.text = stepper.value.description case heightStepper: heightTextField.text = stepper.value.description default: break } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { guard let viewController = segue.destinationViewController as? DetailViewController, let style = style, let name = iconTypeTextField.text where !name.isEmpty else { return } let width = (widthTextField.text! as NSString).doubleValue let height = (heightTextField.text! as NSString).doubleValue guard width > 0.0 && height > 0.0 else { return } let fColor = UIColor(hexString: foregroundColorTextField.text!) let bColor = UIColor(hexString: backgroundColorTextField.text!) viewController.style = style viewController.name = name viewController.fColor = fColor viewController.size = CGSize(width: width, height: height) viewController.bColor = bColor } } extension UIColor { convenience init(hexString: String) { var cString = hexString if (cString.hasPrefix("#")) { cString = cString.substringFromIndex(cString.startIndex.advancedBy(1)) } guard cString.characters.count == 6 else { self.init( red: 0, green: 0, blue: 0, alpha: 0.0 ) return } var rgbValue: UInt32 = 0 NSScanner(string: cString).scanHexInt(&rgbValue) self.init( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } func inversedColor() -> UIColor { var r:CGFloat = 0.0; var g:CGFloat = 0.0; var b:CGFloat = 0.0; var a:CGFloat = 0.0; if self.getRed(&r, green: &g, blue: &b, alpha: &a) { return UIColor(red: 1.0-r, green: 1.0 - g, blue: 1.0 - b, alpha: a) } return self } } extension SettingsViewController: UIPickerViewDelegate { func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch pickerView { case stylePicker: style = [IconsStyle.fontAwesome][row] iconsStyleTextField.text = [IconsStyle.fontAwesome][row].description case typePicker: iconTypeTextField.text = IconFactory.availableIconTypes[row] case foregroundColorPicker: let colorHexString = "#" + colorHexArray[pickerView.selectedRowInComponent(1)] + colorHexArray[pickerView.selectedRowInComponent(2)] + colorHexArray[pickerView.selectedRowInComponent(3)] + colorHexArray[pickerView.selectedRowInComponent(4)] + colorHexArray[pickerView.selectedRowInComponent(5)] + colorHexArray[pickerView.selectedRowInComponent(6)] let color = UIColor(hexString: colorHexString) foregroundColorTextField.backgroundColor = color foregroundColorTextField.textColor = color.inversedColor() foregroundColorTextField.text = colorHexString case backgroundColorPicker: let colorHexString = "#" + colorHexArray[pickerView.selectedRowInComponent(1)] + colorHexArray[pickerView.selectedRowInComponent(2)] + colorHexArray[pickerView.selectedRowInComponent(3)] + colorHexArray[pickerView.selectedRowInComponent(4)] + colorHexArray[pickerView.selectedRowInComponent(5)] + colorHexArray[pickerView.selectedRowInComponent(6)] let color = UIColor(hexString: colorHexString) backgroundColorTextField.backgroundColor = color backgroundColorTextField.textColor = color.inversedColor() backgroundColorTextField.text = colorHexString default: break } } func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { switch pickerView { case stylePicker: return NSAttributedString(string: [IconsStyle.fontAwesome][row].description) case typePicker: return NSAttributedString(string: IconFactory.availableIconTypes[row]) case foregroundColorPicker, backgroundColorPicker: switch component { case 0: return NSAttributedString(string: "#") case 1, 2: return NSAttributedString(string: colorHexArray[row], attributes: [NSForegroundColorAttributeName: UIColor.redColor()]) case 3, 4: return NSAttributedString(string: colorHexArray[row], attributes: [NSForegroundColorAttributeName: UIColor.greenColor()]) case 5,6: return NSAttributedString(string: colorHexArray[row], attributes: [NSForegroundColorAttributeName: UIColor.blueColor()]) default: return .None } default: return .None } } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { switch pickerView { case stylePicker: return [IconsStyle.fontAwesome][row].description case typePicker: return IconFactory.availableIconTypes[row] case foregroundColorPicker, backgroundColorPicker: if component == 0 { return "#" } else { return colorHexArray[row] } default: return .None } } } extension SettingsViewController: UIPickerViewDataSource { func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { switch pickerView { case stylePicker, typePicker: return 1 case foregroundColorPicker, backgroundColorPicker: return 7 default: return 0 } } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch pickerView { case stylePicker: return [IconsStyle.fontAwesome].count case typePicker: return IconFactory.availableIconTypes.count case foregroundColorPicker, backgroundColorPicker: if component == 0 { return 1 } else { return colorHexArray.count } default: return 0 } } } extension SettingsViewController: UITextFieldDelegate { func textFieldDidBeginEditing(textField: UITextField) { switch textField { case iconsStyleTextField, iconTypeTextField, backgroundColorTextField, foregroundColorTextField: break case widthTextField, heightTextField: break default: break } } }
mit
b9f466282fe330c48f83c35bd2f845bf
37.269939
137
0.645239
5.338468
false
false
false
false
kbelter/SnazzyList
SnazzyList/Classes/src/TableView/Services/Cells/BasicCheckTableCell.swift
1
6143
// // BasicCheckTableCell.swift // Dms // // Created by Kevin on 9/28/18. // Copyright © 2018 DMS. All rights reserved. // /// This cell will fit the cases were you need to show a check with text. /// The behavior of this cell is hardcoded, and what i mean by that, is that when it's selected the font will be bold and when is not, the font will be book, so if it does not fit your needs, then you shouldn't use this cell and you may be interested in BasicCheckAlternativeTableCell. /// Screenshot: https://github.com/datamindedsolutions/noteworth-ios-documentation/blob/master/TableView%20Shared%20Cells/BasicCheckTableCell.png?raw=true final class BasicCheckTableCell: UITableViewCell { let checkImageView = UIImageView(image: UIImage(named: "checkbox_off", in: Bundle.resourceBundle(for: BasicCheckTableCell.self), compatibleWith: nil), contentMode: .scaleAspectFit) let titleLabel = UILabel(font: .systemFont(ofSize: 16.0, weight: .medium), textColor: .black, textAlignment: .left) let scrimView = UIView(backgroundColor: UIColor.white.withAlphaComponent(0.6)) override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() setupConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var configFile: BasicCheckTableCellConfigFile? } extension BasicCheckTableCell: GenericTableCellProtocol { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, with item: Any) { guard let configFile = item as? BasicCheckTableCellConfigFile else { return } self.configFile = configFile configureCheckbox() configureTitle() scrimView.isHidden = configFile.isEditable } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let configFile = self.configFile else { return } guard configFile.isEditable else { return } UISelectionFeedbackGenerator().selectionChanged() configFile.actions?.tapOnCheck(forIdentifier: configFile.identifier) configureCheckbox() configureTitle() } } extension BasicCheckTableCell { private func configureCheckbox() { guard let configFile = self.configFile else { return } let checked = configFile.provider?.getCheckIsChecked(forIdentifier: configFile.identifier) ?? false if checked { checkImageView.image = configFile.checkedIcon ?? UIImage(named: "checkbox_on", in: Bundle.resourceBundle(for: BasicCheckTableCell.self), compatibleWith: nil) } else { checkImageView.image = configFile.uncheckedIcon ?? UIImage(named: "checkbox_off", in: Bundle.resourceBundle(for: BasicCheckTableCell.self), compatibleWith: nil) } } private func configureTitle() { guard let configFile = self.configFile else { return } let checked = configFile.provider?.getCheckIsChecked(forIdentifier: configFile.identifier) ?? false let title = configFile.provider?.getCheckTitle(forIdentifier: configFile.identifier) ?? "" titleLabel.font = checked ? configFile.checkedTitleFont : configFile.uncheckedTitleFont titleLabel.textColor = configFile.titleColor titleLabel.text = title titleLabel.addNormalLineSpacing(lineSpacing: 4.0) } private func setupViews() { setupBackground() setupCheckImageView() setupTitleLabel() setupScrimView() } private func setupCheckImageView() { contentView.addSubview(checkImageView) } private func setupTitleLabel() { titleLabel.numberOfLines = 0 contentView.addSubview(titleLabel) } private func setupScrimView() { contentView.addSubview(scrimView) } private func setupConstraints() { scrimView.bind(withConstant: 0.0, boundType: .full) titleLabel.leftAnchor.constraint(equalTo: checkImageView.rightAnchor, constant: 8.0).isActive = true titleLabel.rightAnchor.constraint(equalTo: contentView.rightAnchor, constant: -16.0).isActive = true titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 9.0).isActive = true titleLabel.heightAnchor.constraint(greaterThanOrEqualTo: checkImageView.heightAnchor).isActive = true titleLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -9.0).isActive = true checkImageView.assignSize(width: 24, height: 24) checkImageView.topAnchor.constraint(equalTo: titleLabel.topAnchor).isActive = true checkImageView.leftAnchor.constraint(equalTo: contentView.leftAnchor, constant: 16.0).isActive = true } } struct BasicCheckTableCellConfigFile { let identifier: Any let isEditable: Bool let checkedTitleFont: UIFont let uncheckedTitleFont: UIFont let checkedIcon: UIImage? let uncheckedIcon: UIImage? let titleColor: UIColor weak var provider: BasicCheckTableProvider? weak var actions: BasicCheckTableActions? init(identifier: Any, isEditable: Bool, checkedTitleFont: UIFont, uncheckedTitleFont: UIFont, titleColor: UIColor, checkedIcon: UIImage?, uncheckedIcon: UIImage?, provider: BasicCheckTableProvider?, actions: BasicCheckTableActions?) { self.identifier = identifier self.isEditable = isEditable self.checkedTitleFont = checkedTitleFont self.uncheckedTitleFont = uncheckedTitleFont self.checkedIcon = checkedIcon self.uncheckedIcon = uncheckedIcon self.titleColor = titleColor self.provider = provider self.actions = actions } } public protocol BasicCheckTableProvider: class { func getCheckIsChecked(forIdentifier identifier: Any) -> Bool func getCheckTitle(forIdentifier identifier: Any) -> String } public protocol BasicCheckTableActions: class { func tapOnCheck(forIdentifier identifier: Any) }
apache-2.0
80f088e6206f2a98f14d5db9d71a36a8
41.951049
285
0.712146
4.953226
false
true
false
false
ivanfoong/IFCacheKit-Swift
Example/Pods/Tests/IFMemoryCacheTests.swift
2
5058
// // IFMemoryCacheTests.swift // IFCacheKit // // Created by Ivan Foong on 7/9/15. // Copyright (c) 2015 CocoaPods. All rights reserved. // import Quick import Nimble import IFCacheKit class IFMemoryCacheSpec: QuickSpec { override func spec() { describe("the memory cache") { it("can put items") { let capacity = 1 var cache = IFMemoryCache<Author, Book>(capacity: capacity) let authors = self.sampleAuthors() let books = self.sampleBooks() cache.put(authors[0], value: books[0]) expect(cache._cache[authors[0]]?.value) == books[0] cache.put(authors[1], value: books[1]) expect(cache._cache[authors[1]]?.value) == books[1] expect(cache._cache[authors[0]]).to(beNil()) // due to overflow } it("can get items") { let capacity = 1 var cache = IFMemoryCache<Author, Book>(capacity: capacity) let authors = self.sampleAuthors() let books = self.sampleBooks() let node = IFMemoryCacheNode<Author, Book>(key: authors[0], value: books[0], expiryDate: nil) cache._cache.updateValue(node, forKey: authors[0]) expect(cache.get(Set([authors[0]]))[authors[0]]) == books[0] let now = NSDate() let expiredNode = IFMemoryCacheNode<Author, Book>(key: authors[0], value: books[0], expiryDate: now) cache._cache.updateValue(expiredNode, forKey: authors[0]) expect(cache.get(Set([authors[0]])).count) == 0 // due to expiry } it("can get all items") { let capacity = 1 var cache = IFMemoryCache<Author, Book>(capacity: capacity) let authors = self.sampleAuthors() let books = self.sampleBooks() let node = IFMemoryCacheNode<Author, Book>(key: authors[0], value: books[0], expiryDate: nil) cache._cache.updateValue(node, forKey: authors[0]) let now = NSDate() let expiredNode = IFMemoryCacheNode<Author, Book>(key: authors[1], value: books[1], expiryDate: now) cache._cache.updateValue(expiredNode, forKey: authors[1]) let result = cache.all() expect(result.count) == 1 expect(result[authors[0]]) == books[0] } it("can get item count") { let capacity = 2 var cache = IFMemoryCache<Author, Book>(capacity: capacity) let authors = self.sampleAuthors() let books = self.sampleBooks() let node = IFMemoryCacheNode<Author, Book>(key: authors[0], value: books[0], expiryDate: nil) cache._cache.updateValue(node, forKey: authors[0]) let now = NSDate() let expiredNode = IFMemoryCacheNode<Author, Book>(key: authors[1], value: books[1], expiryDate: now) cache._cache.updateValue(expiredNode, forKey: authors[1]) expect(cache.size()) == 1 } it("can remove items") { let capacity = 1 var cache = IFMemoryCache<Author, Book>(capacity: capacity) let authors = self.sampleAuthors() let books = self.sampleBooks() let node = IFMemoryCacheNode<Author, Book>(key: authors[0], value: books[0], expiryDate: nil) cache._cache.updateValue(node, forKey: authors[0]) cache.remove(Set([authors[0]])) expect(cache._cache.count) == 0 } it("can clear all items") { let capacity = 2 var cache = IFMemoryCache<Author, Book>(capacity: capacity) let authors = self.sampleAuthors() let books = self.sampleBooks() let node = IFMemoryCacheNode<Author, Book>(key: authors[0], value: books[0], expiryDate: nil) cache._cache.updateValue(node, forKey: authors[0]) let node2 = IFMemoryCacheNode<Author, Book>(key: authors[1], value: books[1], expiryDate: nil) cache._cache.updateValue(node2, forKey: authors[1]) cache.clear() expect(cache._cache.count) == 0 } } } func sampleAuthors() -> [Author] { return [Author(name: "Ivan Foong"), Author(name: "Jon Doe"), Author(name: "John Smith")] } func sampleBooks() -> [Book] { return [Book(title: "Swift Caching"), Book(title: "Gingerbread Man"), Book(title: "Stick Man")] } }
mit
d1ab65a5272c99ba6575a022585c2232
41.864407
116
0.509095
4.661751
false
false
false
false
IvanVorobei/TwitterLaunchAnimation
TwitterLaunchAnimation - project/TwitterLaucnhAnimation/sparrow/ui/views/views/SPGradeWithBlurView.swift
1
2681
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class SPGradeWithBlurView: UIView { private var gradeView: UIView = UIView() private var blurView: UIView = UIView() //private var blurView: SPBlurView = SPBlurView() init(gradeColor: UIColor = UIColor.black, gradeAlphaFactor: CGFloat = 0.1, blurRadius: CGFloat = 3) { super.init(frame: CGRect.zero) if #available(iOS 9, *) { self.blurView = SPBlurView() } self.layer.masksToBounds = true self.addSubview(gradeView) self.addSubview(blurView) self.setGradeColor(gradeColor) self.setGradeAlpha(gradeAlphaFactor, blurRaius: blurRadius) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setGradeColor(_ color: UIColor) { self.gradeView.backgroundColor = UIColor.black } func setGradeAlpha(_ alpha: CGFloat) { self.gradeView.alpha = alpha } func setBlurRadius(_ radius: CGFloat) { if #available(iOS 9, *) { if let blurView = self.blurView as? SPBlurView { blurView.setBlurRadius(radius) } } } func setGradeAlpha(_ alpha: CGFloat, blurRaius: CGFloat) { self.setGradeAlpha(alpha) self.setBlurRadius(blurRaius) } override func layoutSubviews() { super.layoutSubviews() self.gradeView.frame = self.bounds self.blurView.frame = self.bounds } }
mit
c90d54a78a13dbdf1222ab2d33c2e0da
35.216216
105
0.673881
4.415157
false
false
false
false
liyang1217/-
斗鱼/斗鱼/Casses/Main/View/PageTitleView.swift
1
6783
// // PageTitleView.swift // 斗鱼 // // Created by BARCELONA on 16/9/20. // Copyright © 2016年 LY. All rights reserved. // import UIKit //定义协议 //加上class表示这个协议只能被类遵守, 不写的话可能被别的遵守 //点击titleLabel,通知PageContentView发生相应的变化 protocol PageTitleViewDelegate : class { func pageTitleView(titleView: PageTitleView, selectedIndex index: Int) } //定义常量 private let kScrollLineH: CGFloat = 2 private let kNormalColor: (CGFloat, CGFloat, CGFloat) = (85, 85, 85) private let kSelectedColor: (CGFloat, CGFloat, CGFloat) = (255, 128, 0) //定义PageTitleView class PageTitleView: UIView { //定义代理属性 weak var delegate:PageTitleViewDelegate? //定义属性 fileprivate var titles: [NSString] fileprivate var currentIndex : Int = 0 // 懒加载属性 fileprivate lazy var scrollview : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() fileprivate lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() fileprivate lazy var titleLabels : [UILabel] = [UILabel]() //自定义构造函数 init(frame: CGRect, titles: [NSString]) { self.titles = titles super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageTitleView{ fileprivate func setupUI(){ //1. 添加UIscrollView addSubview(scrollview) scrollview.frame = bounds //2. 添加title对应的label setupTitleLabels() //3. 设置底线和滚动的滑块 setupBottonMenuAndScrollLine() } fileprivate func setupBottonMenuAndScrollLine(){ //1. 添加底线 let bottonLine = UIView() bottonLine.backgroundColor = UIColor.lightGray let lineH: CGFloat = 0.5 bottonLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: kScrollLineH) addSubview(bottonLine) //2. 添加scrollLine //2.1 获取第一个label guard let firstLabel = titleLabels.first else { return } firstLabel.textColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2) //2.2 设置属性 scrollview.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.width, height: kScrollLineH + lineH) } fileprivate func setupTitleLabels(){ //设置label的frame值 let labelW: CGFloat = frame.width / CGFloat(titles.count) let labelH: CGFloat = frame.height - kScrollLineH let labelY: CGFloat = 0 for (index, title) in titles.enumerated(){ //1. 创建UIlabel let label = UILabel() titleLabels.append(label) //2. 设置属性 label.text = title as String label.tag = index label.font = UIFont.systemFont(ofSize: 16.0) label.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) label.textAlignment = .center //3. 设置frame let labelX: CGFloat = labelW * CGFloat(index) label.frame = CGRect(x: labelX, y: labelY, width: labelW, height: labelH) //4. label添加到scrollView中 scrollview.addSubview(label) //5. 给label添加手势,响应点击事件 label.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:))) label.addGestureRecognizer(tapGes) } } } //监听label的点击事件 extension PageTitleView{ //事件监听需要加上@objc @objc fileprivate func titleLabelClick(tapGes: UITapGestureRecognizer){ //0. 获取当前label的下标值 guard let currentLabel = tapGes.view as? UILabel else { return } //1. 如果是重复点击同一个title,那么直接返回 if currentLabel.tag == currentIndex { return } //2. 获取之前的label let oldLabel = titleLabels[currentIndex] //3. 切换文字的颜色 currentLabel.textColor = UIColor(r: kSelectedColor.0, g: kSelectedColor.1, b: kSelectedColor.2) oldLabel.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) //4. 保存最新label下标值 currentIndex = currentLabel.tag //5. 滑条位置的变化 let scrollViewX = CGFloat(currentIndex) * scrollLine.frame.width UIView.animate(withDuration: 0.15) { self.scrollLine.frame.origin.x = scrollViewX } //6. 通知代理 delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex) } } //对外暴露的方法 extension PageTitleView{ func setTitleWithProgress(progress: CGFloat, sourceIndex: Int, targetIndex: Int){ //1. 去除sourceLabel/targetLabel let sourceLabel = titleLabels[sourceIndex] let targetLabel = titleLabels[targetIndex] //2. 处理滑块的逻辑 //总共要滑动的距离 let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x //已经滑动的距离 let moveX = moveTotalX * progress scrollLine.frame.origin.x = sourceLabel.frame.origin.x + moveX //3. 颜色的渐变 //3.1 颜色的变化范围 //三中颜色的变化范围,RGB let colorDelta = (kSelectedColor.0 - kNormalColor.0, kSelectedColor.1 - kNormalColor.1, kSelectedColor.2 - kNormalColor.2) //3.2 变化sourceLabel sourceLabel.textColor = UIColor(r: kSelectedColor.0 - colorDelta.0 * progress, g: kSelectedColor.1 - colorDelta.1 * progress, b: kSelectedColor.2 - colorDelta.2 * progress) //3.2 变化targetLabel targetLabel.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1 * progress, b: kNormalColor.2 + colorDelta.2 * progress) //4. 记录最新的index currentIndex = targetIndex } }
mit
ff03584ae5294516fc7aab4b00567467
27.724771
180
0.611626
4.56414
false
false
false
false
venticake/RetricaImglyKit-iOS
RetricaImglyKit/Classes/Frontend/Editor/StickerImageView.swift
1
4058
// This file is part of the PhotoEditor Software Development Kit. // Copyright (C) 2016 9elements GmbH <[email protected]> // All rights reserved. // Redistribution and use in source and binary forms, without // modification, are permitted provided that the following license agreement // is approved and a legal/financial contract was signed by the user. // The license agreement can be found under the following link: // https://www.photoeditorsdk.com/LICENSE.txt import UIKit /** * A `StickerImageView` displays an instance of `Sticker` and provides improved support for accessibility. */ @available(iOS 8, *) @objc(IMGLYStickerImageView) public class StickerImageView: UIImageView { // MARK: - Properties /// The sticker that this image view should display. public let sticker: Sticker /// Called by accessibility to make the image view smaller. public var decrementHandler: (() -> Void)? /// Called by accessibility to make the image view bigger. public var incrementHandler: (() -> Void)? /// Called by accessibility to rotate the image view to the left. public var rotateLeftHandler: (() -> Void)? /// Called by accessibility to rotate the image view to the right. public var rotateRightHandler: (() -> Void)? /// This property holds the normalized center of the view within the image without any crops added. /// It is used to calculate the correct position of the sticker within the preview view. public var normalizedCenterInImage = CGPoint.zero // MARK: - Initializers /** Returns a newly allocated instance of `StickerImageView` with the given sticker. - parameter sticker: The sticker that should be shown in this image view. - returns: An instance of `StickerImageView`. */ public init(sticker: Sticker) { self.sticker = sticker super.init(image: nil) commonInit() } /** :nodoc: */ required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { userInteractionEnabled = true isAccessibilityElement = true accessibilityTraits &= ~UIAccessibilityTraitImage accessibilityTraits |= UIAccessibilityTraitAdjustable accessibilityHint = Localize("Double-tap and hold to move") let rotateLeftAction = UIAccessibilityCustomAction(name: Localize("Rotate left"), target: self, selector: #selector(StickerImageView.rotateLeft)) let rotateRightAction = UIAccessibilityCustomAction(name: Localize("Rotate right"), target: self, selector: #selector(StickerImageView.rotateRight)) accessibilityCustomActions = [rotateLeftAction, rotateRightAction] } @objc internal func flipVertically() { guard let stickerImage = image, cgImage = stickerImage.CGImage else { return } if let flippedOrientation = UIImageOrientation(rawValue: (stickerImage.imageOrientation.rawValue + 4) % 8) { image = UIImage(CGImage: cgImage, scale: stickerImage.scale, orientation: flippedOrientation) transform = CGAffineTransformRotate(transform, CGFloat(M_PI)) } } @objc internal func flipHorizontally() { guard let stickerImage = image, cgImage = stickerImage.CGImage else { return } if let flippedOrientation = UIImageOrientation(rawValue: (stickerImage.imageOrientation.rawValue + 4) % 8) { image = UIImage(CGImage: cgImage, scale: stickerImage.scale, orientation: flippedOrientation) } } /** :nodoc: */ public override func accessibilityDecrement() { decrementHandler?() } /** :nodoc: */ public override func accessibilityIncrement() { incrementHandler?() } @objc private func rotateLeft() -> Bool { rotateLeftHandler?() return true } @objc private func rotateRight() -> Bool { rotateRightHandler?() return true } }
mit
d902cb8b601d6b8ace8050f816ab4c3f
33.683761
156
0.680384
5.040994
false
false
false
false
pyromobile/nubomedia-ouatclient-src
ios/LiveTales/uoat/AccesoriesMgr.swift
2
3059
// // AccesoriesMgr.swift // uoat // // Created by Pyro User on 18/8/16. // Copyright © 2016 Zed. All rights reserved. // import Foundation class AccesoriesMgr { static func getInstance()->AccesoriesMgr { return AccesoriesMgr.instance! } static func create(isHD:Bool) { AccesoriesMgr.instance = AccesoriesMgr( isHD:isHD ) AccesoriesMgr.instance?.load() } func getAll() -> [String:[Complement]] { return self.accesoriesByPack } func getByPack(pack:String) -> [Complement] { return self.accesoriesByPack[pack]! } /*=============================================================*/ /* Private Section */ /*=============================================================*/ private init(isHD:Bool) { self.isHD = isHD self.accesoriesByPack = [String:[Complement]]() } private func load() { //let fm = NSFileManager.defaultManager() let talesPath = NSBundle.mainBundle().pathsForResourcesOfType("", inDirectory: "Res/tales/") for talePath in talesPath { let file = talePath+"/description.json" do { let fileContent = try NSString(contentsOfFile: file, encoding: NSUTF8StringEncoding ) let fc = fileContent as String! self.processComplements( fc ) } catch let error as NSError { print( "Failed to load: \(error.localizedDescription)" ) } } } private func processComplements( description:String ) { let complement:AnyObject = self.getJSON( description )! let id:String = complement["id"] as! String let complements = complement["complements"] as! [String] let resolutionPath = (self.isHD) ? "/" : "/sd/" self.accesoriesByPack[id] = [Complement]() for complementId:String in complements { let imagePath = NSBundle.mainBundle().pathForResource( "\(complementId)", ofType: "png", inDirectory: "Res/tales/\(id)/complements\(resolutionPath)" ) let complement = Complement( id:complementId, imagePath:imagePath!, pack:id ) self.accesoriesByPack[id]?.append( complement ) } } private func getJSON(stringJSON:String)->AnyObject? { let json:AnyObject?; do { let data = stringJSON.dataUsingEncoding( NSUTF8StringEncoding, allowLossyConversion: false ); json = try NSJSONSerialization.JSONObjectWithData( data!, options: .AllowFragments ); } catch let error as NSError { print( "Failed to load: \(error.localizedDescription)" ); json = nil; } return json; } private static var instance:AccesoriesMgr? = nil private var accesoriesByPack:[String:[Complement]] private var isHD:Bool }
apache-2.0
10aebc65d4231debe4216b2210aa2ff9
28.990196
162
0.547744
4.626324
false
false
false
false
tad-iizuka/swift-sdk
Source/DiscoveryV1/Models/Relation.swift
2
6185
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit /** Extracted relationships between the subject, action and object parts of a sentence. */ public struct Relation: JSONDecodable { /// Action public let action: Action? /// Object public let object: RelationObject? /// Entities public let entities: [Entity]? /// Subject public let subject: Subject? /// Sentence of the extracted Subject, Action, Object parts public let sentence: String? /// The raw JSON object used to construct this model. public let json: [String: Any] /// Used internally to initialize a Relation object from JSON. public init(json: JSON) throws { action = try? json.decode(at: "action", type: Action.self) object = try? json.decode(at: "object", type: RelationObject.self) entities = try? json.decodedArray(at: "entities", type: Entity.self) subject = try? json.decode(at: "subject", type: Subject.self) sentence = try? json.getString(at: "sentence") self.json = try json.getDictionaryObject() } /// Used internally to serialize a 'Relation' model to JSON. public func toJSONObject() -> Any { return json } } /** The action as defined by the AlchemyLanguage service. */ public struct Action: JSONDecodable { /// Text the action was extracted from. public let text: String? /// see Verb public let verb: Verb? /// The base or dictionary form of the word. public let lemmatized: String? /// The raw JSON object used to construct this model. public let json: [String: Any] /// Used internally to initialize an Action object from JSON. public init(json: JSON) throws { text = try? json.getString(at: "text") verb = try? json.decode(at: "verb", type: Verb.self) lemmatized = try? json.getString(at: "lemmatized") self.json = try json.getDictionaryObject() } /// Used internally to serialize an 'Action' model to JSON. public func toJSONObject() -> Any { return json } /** A verb as defined by the AlchemyLanguage service. */ public struct Verb: JSONDecodable { /// Text the verb was extracted from. public let text: String? /// The tense of the verb. public let tense: String? /// Used internally to initalize a Verb object. public init(json: JSON) throws { text = try? json.getString(at: "text") tense = try? json.getString(at: "tense") } } } /** Object related to the Subject-Action-Object extraction. */ public struct RelationObject: JSONDecodable { /// keywords found by the SAO extraction public let keywords: [Keyword]? /// see **Entity** public let entities: [Entity]? /// text the relation object was extracted from public let text: String? /// see **Sentiment** public let sentiment: Sentiment? /// see **Sentiment** public let sentimentFromSubject: Sentiment? /// The raw JSON object used to construct this model. public let json: [String: Any] /// Used internally to initialize a RelationObject object from JSON. public init(json: JSON) throws { keywords = try? json.decodedArray(at: "keywords", type: Keyword.self) text = try? json.getString(at: "text") sentiment = try? json.decode(at: "sentiment", type: Sentiment.self) sentimentFromSubject = try? json.decode(at: "sentimentFromSubject", type: Sentiment.self) entities = try? json.decodedArray(at: "entities", type: Entity.self) self.json = try json.getDictionaryObject() } /// Used internally to serialize a 'RelationObject' model to JSON. public func toJSONObject() -> Any { return json } /** A keyword. */ public struct Keyword: JSONDecodable { /// Text of the extracted keyword. public let text: String? /// How keywords are determined. Can be multiple levels deep. /// e.g. /companies/organizations/google finance public let knowledgeGraph: KnowledgeGraph? /// Used internally to initialize a Keyword object. public init(json: JSON) throws { text = try? json.getString(at: "text") knowledgeGraph = try? json.decode(at: "knowledgeGraph", type: KnowledgeGraph.self) } } } /** A subject extracted by the AlchemyLanguage service. */ public struct Subject: JSONDecodable { /// Keywords found by the extraction in the subject. public let keywords: [Keyword]? /// text the subject was extracted from public let text: String? /// see **Sentiment** public let sentiment: Sentiment? /// see **Entity** public let entities: [Entity]? /// The raw JSON object used to construct this model. public let json: [String: Any] /// Used internally to initialize a Subject object from JSON. public init(json: JSON) throws { keywords = try? json.decodedArray(at: "keywords", type: Keyword.self) text = try? json.getString(at: "text") sentiment = try? json.decode(at: "sentiment", type: Sentiment.self) entities = try? json.decodedArray(at: "entities", type: Entity.self) self.json = try json.getDictionaryObject() } /// Used internally to serialize a 'Subject' model to JSON. public func toJSONObject() -> Any { return json } }
apache-2.0
4f09d36cb82fe8a2e7aec98f953157bb
32.252688
97
0.635247
4.468931
false
false
false
false
hrscy/TodayNews
News/News/Classes/Video/View/VideoCell.swift
1
6133
// // VideoCell.swift // News // // Created by 杨蒙 on 2018/1/17. // Copyright © 2018年 hrscy. All rights reserved. // import UIKit import IBAnimatable import Kingfisher class VideoCell: UITableViewCell, RegisterCellFromNib { /// 视频数据 var video = NewsModel() { didSet { titleLabel.text = video.title playCountLabel.text = video.video_detail_info.videoWatchCount + "次播放" avatarButton.kf.setImage(with: URL(string: video.user_info.avatar_url), for: .normal) vImageView.isHidden = !video.user_info.user_verified concernButton.isSelected = video.user_info.follow bgImageButton.kf.setBackgroundImage(with: URL(string: video.video_detail_info.detail_video_large_image.urlString)!, for: .normal) timeLabel.text = video.videoDuration commentButton.setTitle(video.commentCount, for: .normal) commentButton.theme_setTitleColor("colors.black", forState: .normal) commentButton.theme_setImage("images.comment_24x24_", forState: .normal) concernButton.isHidden = video.label_style == .ad commentButton.isHidden = video.label_style == .ad adButton.setTitle((video.ad_button.button_text == "" ? "查看详情" : video.ad_button.button_text), for: .normal) nameLable.text = video.user_info.name if video.label_style == .ad { nameLable.text = video.app_name != "" ? video.app_name : video.ad_button.app_name descriptionLabel.text = video.ad_button.description == "" ? video.sub_title : video.ad_button.description descriptionLabelHeight.constant = 20 layoutIfNeeded() } adButton.isHidden = video.label_style != .ad adLabel.isHidden = video.label_style != .ad } } /// 标题 label @IBOutlet weak var titleLabel: UILabel! /// 广告 @IBOutlet weak var adLabel: AnimatableLabel! /// 播放数量 @IBOutlet weak var playCountLabel: UILabel! /// 时间 label @IBOutlet weak var timeLabel: UILabel! /// 背景图片 @IBOutlet weak var bgImageButton: UIButton! /// 用户头像 @IBOutlet weak var avatarButton: UIButton! @IBOutlet weak var vImageView: UIImageView! /// 用户昵称 @IBOutlet weak var nameLable: UILabel! /// 描述 @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var descriptionLabelHeight: NSLayoutConstraint! /// 分享到 stackView @IBOutlet weak var shareStackView: UIStackView! /// 分享到 @IBOutlet weak var shareLable: UILabel! /// 朋友圈按钮 @IBOutlet weak var pyqButton: UIButton! @IBOutlet weak var pyqButtonWidth: NSLayoutConstraint! /// 微信按钮 @IBOutlet weak var wechatButton: UIButton! /// 关注按钮 @IBOutlet weak var concernButton: UIButton! /// 评论按钮 @IBOutlet weak var commentButton: UIButton! /// 如果是广告,查看详情按钮 @IBOutlet weak var adButton: UIButton! /// 更多按钮 @IBOutlet weak var moreButton: UIButton! override func awakeFromNib() { super.awakeFromNib() theme_backgroundColor = "colors.cellBackgroundColor" bgImageButton.setImage(UIImage(named: "video_play_icon_44x44_"), for: .normal) shareLable.theme_textColor = "colors.black" titleLabel.theme_textColor = "colors.moreLoginTextColor" nameLable.theme_textColor = "colors.black" playCountLabel.theme_textColor = "colors.moreLoginTextColor" concernButton.theme_setImage("images.video_add_24x24_", forState: .normal) concernButton.setImage(nil, for: .selected) concernButton.setTitle("关注", for: .normal) concernButton.setTitle("已关注", for: .selected) concernButton.theme_setTitleColor("colors.black", forState: .normal) concernButton.theme_setTitleColor("colors.grayColor210", forState: .selected) moreButton.theme_setImage("images.More_24x24_", forState: .normal) adButton.theme_setTitleColor("colors.userDetailSendMailTextColor", forState: .normal) adButton.theme_setImage("images.view detail_ad_feed_15x13_", forState: .normal) } /// 关注按点击 @IBAction func concernButtonClicked(_ sender: UIButton) { if sender.isSelected { // 已经关注,点击则取消关注 // 已关注用户,取消关注 NetworkTool.loadRelationUnfollow(userId: video.user_info.user_id, completionHandler: { (_) in sender.isSelected = !sender.isSelected }) } else { // 未关注,点击则关注这个用户 // 点击关注按钮,关注用户 NetworkTool.loadRelationFollow(userId: video.user_info.user_id, completionHandler: { (_) in sender.isSelected = !sender.isSelected }) } } /// 广告按钮点击 @IBAction func adButtonClicked(_ sender: UIButton) { let downloadURL = video.ad_button.download_url != "" ? video.ad_button.download_url : video.download_url print("app 下载地址 - \(downloadURL)") } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } extension VideoCell { /// 视频播放时隐藏 cell 的部分子视图 func hideSubviews() { titleLabel.isHidden = true playCountLabel.isHidden = true timeLabel.isHidden = true vImageView.isHidden = true avatarButton.isHidden = true nameLable.isHidden = true shareStackView.isHidden = false } /// 设置当前 cell 的属性 func showSubviews() { titleLabel.isHidden = false playCountLabel.isHidden = false timeLabel.isHidden = false avatarButton.isHidden = false vImageView.isHidden = !video.user_verified nameLable.isHidden = false shareStackView.isHidden = true } }
mit
742bb665c2e8ec9fa9bc76279f815303
38.22973
141
0.644678
4.294379
false
false
false
false
omnypay/omnypay-sdk-ios
ExampleApp/OmnyPayAPIDemo/OmnyPayAPIDemo/Helpers.swift
1
2908
/** Copyright 2017 OmnyPay Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit import JavaScriptCore struct Helpers { static func getUrl(forType url: String) -> String { let urlString = Constants.hostScheme + "://" + Constants.hostUrl + ":" + String(Constants.hostPort) + url return urlString } static func serialize(urlResponse:URLResponse?, data:Data?, error:Error?) -> Any? { guard error == nil else { return nil } if let urlResponse = urlResponse as? HTTPURLResponse, urlResponse.statusCode == 204 { return NSNull() } guard let validData = data, validData.count > 0 else { return nil } do { let JSON = try JSONSerialization.jsonObject(with: validData as Data, options: .allowFragments) return JSON } catch { return nil } } static func extract(qrString:String)->String?{ var qrString = qrString var index = qrString.range(of: ";", options: .backwards) guard index != nil else{return nil} if index!.upperBound == qrString.range(of: qrString)?.upperBound { qrString = qrString.substring(to: index!.lowerBound) index = qrString.range(of: ";", options: .backwards) guard index != nil else{return nil} } qrString = qrString.substring(to: index!.lowerBound) index = qrString.range(of: ";", options: .backwards) guard index != nil else{return nil} return qrString.substring(from: index!.upperBound) } static func makeButtonEnabled(button: UIButton) { button.isEnabled = true button.setTitleColor(UIColor.black, for: .normal) } static func makeButtonDisabled(button: UIButton) { button.isEnabled = false button.setTitleColor(UIColor.white, for: .normal) } static func getSignatureForAPI(timeStamp: String, correlationId: String, requestMethod: String, relativePath: String, payload: String) -> String { let stringToEncode = Constants.merchantApiKey + timeStamp + correlationId + requestMethod + relativePath + payload let key = Constants.merchantApiSecret if let functionGenSign = jsContext?.objectForKeyedSubscript("generateAPISignature") { if let signed = functionGenSign.call(withArguments: [stringToEncode, key]) { print("stringToEncode:", stringToEncode, " signature: ", signed.toString()) return signed.toString() } } return "" } }
apache-2.0
48acad7292fcc47bd1030ebe7dd2c564
32.813953
148
0.696699
4.406061
false
false
false
false
peigen/iLife
iLife/AppManager.swift
1
1160
// // AppItem.swift // iLife // // Created by Peigen on 6/10/14. // Copyright (c) 2014 Peigen. All rights reserved. // import UIKit class AppManager: NSObject { var apps = AppItem[]() var persistenceHelper: PersistenceHelper = PersistenceHelper() init(){ var tempApps:NSArray = persistenceHelper.list("AppItem") for app:AnyObject in tempApps{ var appItem = AppItem(name:app.valueForKey("name") as String,openURL:app.valueForKey("openURL") as String) apps.append(appItem) } } func addApp(name:String, openURL: String){ var dicApp: Dictionary<String, String> = Dictionary<String,String>() dicApp["name"] = name dicApp["openURL"] = openURL if(persistenceHelper.save("AppItem", parameters: dicApp)){ apps.append(AppItem(name: name, openURL:openURL)) } } func removeTask(index:Int){ var value:String = apps[index].name if(persistenceHelper.remove("AppItem", key: "name", value: value)){ apps.removeAtIndex(index) } } }
gpl-3.0
7a4c367a5aa34869f15cfe1735612271
23.166667
118
0.584483
4.09894
false
false
false
false
giangbvnbgit128/AnViet
AnViet/Class/Helpers/Extensions/UINavigationController.swift
1
2056
// // UINavigationController.swift // TLSafone // // Created by HoaNV-iMac on 3/18/16. // Copyright © 2016 TechLove. All rights reserved. // import UIKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } protocol BackButtonHandlerProtocol { func navigationShouldPopOnBackButton() -> Bool } extension UINavigationController { func rootViewController() -> UIViewController { return viewControllers.first! } func viewController(_ named: String) -> UIViewController? { for vc in viewControllers { if vc.className == named { return vc } } return nil } func viewController(index: Int) -> UIViewController? { if index >= 0 && index < viewControllers.count { return viewControllers[index] } else { return nil } } // func navigationBar(_ navigationBar: UINavigationBar, shouldPopItem item: UINavigationItem) -> Bool { // if viewControllers.count < navigationBar.items?.count { // return true // } // // var shouldPop = true // if let topVC = self.topViewController as? BackButtonHandlerProtocol { // shouldPop = topVC.navigationShouldPopOnBackButton() // } // if shouldPop { // DispatchQueue.main.async { // self.popViewController(animated: true) // } // } else { // for view in navigationBar.subviews { // if view.alpha < 1.0 { // [UIView.animate(withDuration: 0.25, animations: { () -> Void in // view.alpha = 1.0 // })] // } // } // } // return false // } }
apache-2.0
a6c81e6b7875efab13ac0f72f2b6426c
26.039474
106
0.563017
4.409871
false
false
false
false
sschiau/swift
test/refactoring/RefactoringKind/basic.swift
3
12310
func foo() -> Int{ var aaa = 1 + 2 aaa = aaa + 3 if aaa == 3 { aaa = 4 } return aaa } func foo1(a : Int) -> Int { switch a { case 1: return 0 case 2: return 1 default: return a } } func foo8(a : [Int]) { for v in a { if v > 3 { break } if v < 3 { continue } } } protocol P1 { func foo() func foo1() } class C1 : P1 { func foo1() {} } class C2 : P1 { func foo() {} } class C3 : P1 {} protocol P2 { associatedtype T1 associatedtype T2 func foo1() } class C4 : P2 {} class C5 : P2 { typealias T1 = Int func foo1() {} } class C6 : P2 { typealias T1 = Int typealias T2 = Int } class C7 : P2 { typealias T2 = Int func foo1() {} } class C8 : P2 { typealias T1 = Int typealias T2 = Int func foo1() {} } class C9 {} extension C9 : P1 {} extension C9 : P2 {} class C10 {} extension C10 : P1 { func foo() {} func foo1() {} } extension C10 : P2 { typealias T1 = Int typealias T2 = Int func foo1() {} } class C11 {} extension C11 : P1 { func foo() {} } extension C11 : P2 { typealias T1 = Int typealias T2 = Int } class C12 {} extension C12 : P1 { func foo1() {} } extension C12 : P2 { typealias T1 = Int func foo1() {} } class C13 {} extension C13 : P1 { func foo() {} func foo1() {} } extension C13 : P2 { typealias T1 = Int func foo1() {} } class C14 {} extension C14 : P1 { func foo() {} } extension C14 : P2 { typealias T1 = Int typealias T2 = Int func foo1() {} } protocol P3 { func foo3() func foo4() } extension C14: P3 { func foo3() } enum E { case e1 case e2 case e3 } func foo2(_ e : E) -> Int{ switch(e) { case .e1: case .e2: return 0; default: return 1; } } func testInout(_ a : inout Int) { var b = a + 1 + 1 b = b + 1 testInout(&b) } func testBranch1(_ a : Bool) { if a { return } else { return } } func testBranch2(_ a : Bool) { if a { return } } func testBranch3(_ a : Bool) -> Int { if a { return 0 } else { return 1 } } func testBranch4(_ a : Bool) -> Int { if a { return 0 } } func testStringLiteral() -> String { let name = "Jason" print("Hello, \(name)!") return "abc" } func testCollapseNestedIf1() { let a = 3 if a > 2 { if a < 10 {} } } func testCollapseNestedIf2() { let a = 3 if a > 2, a != 4 { if a < 10 {} } } func testCollapseNestedIf3() { let a = 3 if a > 2 { if a < 10 {} let b = 0 } } func testCollapseNestedIf4() { let a = 3 if a > 2 { let b = 0 if a < 10 {} } } func testCollapseNestedIf5() { let a = 3 if a > 2 { if a < 10 {} } else { print("else") } } func testCollapseNestedIf6() { let a = 3 if a > 2 { if a < 10 { print("if") } else if a < 5 { print("else") } } } func testStringInterpolation() -> String { let name = "Jason" let one = "\(1)" let _ = "aaa" + "bbb" let _ = name + "Bourne" let _ = name + one } func testForceTry() { func throwingFunc() throws -> Int { return 3 } let _ = try! throwingFunc() } func testSwitchExpand() { enum AccountType { case savings, checking } let account: AccountType = .savings switch account { } } func testExpandTernaryExpr() { let a = 3 let b = 5 let x = a < 5 ? a : b } func testConvertToTernaryExpr() { let a = 3 let b = 5 let x: Int if a < 5 { x = a } else { x = b } } func testConvertToGuardExpr(idxOpt: Int?) { if let idx = idxOpt { print(idx) } } func testConvertToIfLetExpr(idxOpt: Int?) { guard let idx = idxOpt else { return } print(idx) } // RUN: %refactor -source-filename %s -pos=2:1 -end-pos=5:13 | %FileCheck %s -check-prefix=CHECK1 // RUN: %refactor -source-filename %s -pos=3:1 -end-pos=5:13 | %FileCheck %s -check-prefix=CHECK1 // RUN: %refactor -source-filename %s -pos=4:1 -end-pos=5:13 | %FileCheck %s -check-prefix=CHECK1 // RUN: %refactor -source-filename %s -pos=5:1 -end-pos=5:13 | %FileCheck %s -check-prefix=CHECK1 // RUN: %refactor -source-filename %s -pos=2:1 -end-pos=2:18 | %FileCheck %s -check-prefix=CHECK2 // RUN: %refactor -source-filename %s -pos=2:1 -end-pos=3:16 | %FileCheck %s -check-prefix=CHECK2 // RUN: %refactor -source-filename %s -pos=2:1 -end-pos=4:26 | %FileCheck %s -check-prefix=CHECK2 // RUN: %refactor -source-filename %s -pos=2:13 -end-pos=2:18 | %FileCheck %s -check-prefix=CHECK3 // RUN: %refactor -source-filename %s -pos=10:1 -end-pos=13:13 | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -source-filename %s -pos=12:1 -end-pos=15:13 | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -source-filename %s -pos=21:1 -end-pos=23:6 | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -source-filename %s -pos=24:1 -end-pos=26:6 | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -source-filename %s -pos=21:1 -end-pos=26:6 | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -source-filename %s -pos=34:8 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=37:8 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=40:8 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=47:8 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=48:8 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=52:8 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=56:8 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=60:8 | %FileCheck %s -check-prefix=CHECK-RENAME-ONLY // RUN: %refactor -source-filename %s -pos=66:8 | %FileCheck %s -check-prefix=CHECK-RENAME-ONLY // RUN: %refactor -source-filename %s -pos=67:12 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=68:12 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=69:8 | %FileCheck %s -check-prefix=CHECK-RENAME-ONLY // RUN: %refactor -source-filename %s -pos=70:12 | %FileCheck %s -check-prefix=CHECK-RENAME-ONLY // RUN: %refactor -source-filename %s -pos=74:12 | %FileCheck %s -check-prefix=CHECK-RENAME-ONLY // RUN: %refactor -source-filename %s -pos=79:8 | %FileCheck %s -check-prefix=CHECK-RENAME-ONLY // RUN: %refactor -source-filename %s -pos=80:12 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=83:12 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=87:8 | %FileCheck %s -check-prefix=CHECK-RENAME-ONLY // RUN: %refactor -source-filename %s -pos=88:12 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=91:12 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=95:8 | %FileCheck %s -check-prefix=CHECK-RENAME-ONLY // RUN: %refactor -source-filename %s -pos=96:12 | %FileCheck %s -check-prefix=CHECK-RENAME-ONLY // RUN: %refactor -source-filename %s -pos=100:12 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=104:8 | %FileCheck %s -check-prefix=CHECK-RENAME-ONLY // RUN: %refactor -source-filename %s -pos=105:12 | %FileCheck %s -check-prefix=CHECK-RENAME-ONLY // RUN: %refactor -source-filename %s -pos=108:12 | %FileCheck %s -check-prefix=CHECK-RENAME-ONLY // RUN: %refactor -source-filename %s -pos=117:12 | %FileCheck %s -check-prefix=CHECK-RENAME-STUB // RUN: %refactor -source-filename %s -pos=132:6 | %FileCheck %s -check-prefix=CHECK-EXPAND-DEFAULT // RUN: %refactor -pos=138:11 -end-pos=138:12 -source-filename %s | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -pos=138:11 -end-pos=138:20 -source-filename %s | %FileCheck %s -check-prefix=CHECK3 // RUN: %refactor -pos=139:7 -end-pos=139:8 -source-filename %s | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -pos=139:3 -end-pos=139:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -pos=140:13 -end-pos=140:15 -source-filename %s | %FileCheck %s -check-prefix=CHECK2 // RUN: %refactor -pos=144:1 -end-pos=148:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-EXTRCT-METHOD // RUN: %refactor -pos=158:1 -end-pos=162:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-EXTRCT-METHOD // RUN: %refactor -pos=152:1 -end-pos=154:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -pos=166:1 -end-pos=168:4 -source-filename %s | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -source-filename %s -pos=173:12 | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -source-filename %s -pos=174:12 | %FileCheck %s -check-prefix=CHECK-LOCALIZE-STRING // RUN: %refactor -source-filename %s -pos=173:3 -end-pos=173:27| %FileCheck %s -check-prefix=CHECK-EXTRCT-METHOD // RUN: %refactor -source-filename %s -pos=179:3 | %FileCheck %s -check-prefix=CHECK-COLLAPSE-NESTED-IF // RUN: %refactor -source-filename %s -pos=186:3 | %FileCheck %s -check-prefix=CHECK-COLLAPSE-NESTED-IF // RUN: %refactor -source-filename %s -pos=193:3 | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -source-filename %s -pos=201:3 | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -source-filename %s -pos=209:3 | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -source-filename %s -pos=218:3 | %FileCheck %s -check-prefix=CHECK-NONE // RUN: %refactor -source-filename %s -pos=230:11 -end-pos=230:24 | %FileCheck %s -check-prefix=CHECK-STRINGS-INTERPOLATION // RUN: %refactor -source-filename %s -pos=231:11 -end-pos=231:26 | %FileCheck %s -check-prefix=CHECK-STRINGS-INTERPOLATION // RUN: %refactor -source-filename %s -pos=232:11 -end-pos=232:21 | %FileCheck %s -check-prefix=CHECK-STRINGS-INTERPOLATION // RUN: %refactor -source-filename %s -pos=237:11 | %FileCheck %s -check-prefix=CHECK-TRY-CATCH // RUN: %refactor -source-filename %s -pos=237:12 | %FileCheck %s -check-prefix=CHECK-TRY-CATCH // RUN: %refactor -source-filename %s -pos=237:13 | %FileCheck %s -check-prefix=CHECK-TRY-CATCH // RUN: %refactor -source-filename %s -pos=237:14 | %FileCheck %s -check-prefix=CHECK-TRY-CATCH // RUN: %refactor -source-filename %s -pos=245:3 | %FileCheck %s -check-prefix=CHECK-EXPAND-SWITCH // RUN: %refactor -source-filename %s -pos=251:3 -end-pos=251:24 | %FileCheck %s -check-prefix=CHECK-EXPAND-TERNARY-EXPRESSEXPRESSION // RUN: %refactor -source-filename %s -pos=257:3 -end-pos=262:4 | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-TERNARY-EXPRESSEXPRESSION // RUN: %refactor -source-filename %s -pos=266:3 -end-pos=268:4 | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-GUARD-EXPRESSION // RUN: %refactor -source-filename %s -pos=272:3 -end-pos=275:13 | %FileCheck %s -check-prefix=CHECK-CONVERT-TO-IFLET-EXPRESSION // CHECK1: Action begins // CHECK1-NEXT: Extract Method // CHECK1-NEXT: Action ends // CHECK2: Action begins // CHECK2-NEXT: Action ends // CHECK3: Action begins // CHECK3-NEXT: Extract Expression // CHECK3-NEXT: Extract Method // CHECK3-NEXT: Extract Repeated Expression // CHECK3-NEXT: Action ends // CHECK-NONE: Action begins // CHECK-NONE-NEXT: Action ends // CHECK-RENAME-STUB: Action begins // CHECK-RENAME-STUB-NEXT: Rename // CHECK-RENAME-STUB-NEXT: Add Missing Protocol Requirements // CHECK-RENAME-STUB-NEXT: Action ends // CHECK-RENAME-ONLY: Action begins // CHECK-RENAME-ONLY-NEXT: Rename // CHECK-RENAME-ONLY-NEXT: Action ends // CHECK-EXPAND-DEFAULT: Action begins // CHECK-EXPAND-DEFAULT-NEXT: Expand Default // CHECK-EXPAND-DEFAULT-NEXT: Action ends // CHECK-EXTRCT-METHOD: Action begins // CHECK-EXTRCT-METHOD-NEXT: Extract Method // CHECK-EXTRCT-METHOD-NEXT: Action ends // CHECK-LOCALIZE-STRING: Localize String // CHECK-COLLAPSE-NESTED-IF: Collapse Nested If Statements // CHECK-STRINGS-INTERPOLATION: Convert to String Interpolation // CHECK-TRY-CATCH: Convert To Do/Catch // CHECK-EXPAND-SWITCH: Expand Switch Cases // CHECK-EXPAND-TERNARY-EXPRESSEXPRESSION: Expand Ternary Expression // CHECK-CONVERT-TO-TERNARY-EXPRESSEXPRESSION: Convert To Ternary Expression // CHECK-CONVERT-TO-GUARD-EXPRESSION: Convert To Guard Expression // CHECK-CONVERT-TO-IFLET-EXPRESSION: Convert To IfLet Expression
apache-2.0
98f6f7dbbdb5fc356ac9ef635b3d9e32
27.967059
136
0.663119
2.840332
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/Laundry/Controllers/LaundryTableViewController.swift
1
8706
// // LaundryTableViewController.swift // PennMobile // // Created by Dominic Holmes on 9/30/17. // Copyright © 2017 PennLabs. All rights reserved. // import UIKit class LaundryTableViewController: GenericTableViewController, IndicatorEnabled, ShowsAlert, NotificationRequestable { internal var rooms = [LaundryRoom]() fileprivate let laundryCell = "laundryCell" fileprivate let addLaundryCell = "addLaundry" fileprivate var timer: Timer? internal let allowMachineNotifications = true override func viewDidLoad() { super.viewDidLoad() screenName = "Laundry" tableView.backgroundView = nil tableView.separatorStyle = .none tableView.dataSource = self tableView.allowsSelection = false tableView.backgroundColor = .uiBackground tableView.tableFooterView = getFooterViewForTable() rooms = LaundryRoom.getPreferences() registerHeadersAndCells() prepareRefreshControl() // initialize navigation bar // Start indicator if there are cells that need to be loaded if !rooms.isEmpty { showActivity() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateInfo { self.hideActivity() // Check if laundry is working LaundryAPIService.instance.checkIfWorking { (isWorking) in DispatchQueue.main.async { if let isWorking = isWorking, !isWorking { self.tableView.tableHeaderView = self.getHeaderViewForTable() self.navigationVC?.addPermanentStatusBar(text: .laundryDown) } } } } } fileprivate func getFooterViewForTable() -> UIView { let v = UIView(frame: CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: 30.0)) v.backgroundColor = UIColor.clear return v } fileprivate func getHeaderViewForTable() -> UIView { let v = UIView(frame: CGRect(x: 0.0, y: 0.0, width: self.view.frame.width, height: 70.0)) v.backgroundColor = UIColor.clear return v } override func setupNavBar() { tabBarController?.title = "Laundry" tabBarController?.navigationItem.leftBarButtonItem = nil tabBarController?.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(handleEditPressed)) } } // MARK: - Add/edit selection extension LaundryTableViewController { @objc fileprivate func handleEditPressed() { let roomselectionVC = RoomSelectionViewController() roomselectionVC.delegate = self roomselectionVC.chosenRooms = rooms // provide selected ids here let nvc = UINavigationController(rootViewController: roomselectionVC) showDetailViewController(nvc, sender: nil) } } // MARK: - UIRefreshControl extension LaundryTableViewController { fileprivate func prepareRefreshControl() { refreshControl = UIRefreshControl() // refreshControl?.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl?.addTarget(self, action: #selector(handleRefresh(_:)), for: .valueChanged) } @objc fileprivate func handleRefresh(_ sender: Any) { updateInfo { self.refreshControl?.endRefreshing() } } } // MARK: - Set up table view extension LaundryTableViewController { fileprivate func registerHeadersAndCells() { tableView.register(LaundryCell.self, forCellReuseIdentifier: laundryCell) tableView.register(AddLaundryCell.self, forCellReuseIdentifier: addLaundryCell) } override func numberOfSections(in tableView: UITableView) -> Int { return min(rooms.count + 1, 3) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if self.rooms.count > indexPath.section { let room = rooms[indexPath.section] let cell = tableView.dequeueReusableCell(withIdentifier: laundryCell) as! LaundryCell cell.contentView.isUserInteractionEnabled = false cell.room = room cell.delegate = self return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: addLaundryCell) as! AddLaundryCell cell.contentView.isUserInteractionEnabled = false cell.delegate = self cell.numberOfRoomsSelected = self.rooms.count return cell } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // Use for cards 1/2 the size of the screen // return self.view.layoutMarginsGuide.layoutFrame.height / 2.0 // Use for cards of fixed size if indexPath.section >= rooms.count { return 80.0 } else { return 418.0 } } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section >= rooms.count { return 80.0 } else { return 418.0 } } } // Laundry API Calls extension LaundryTableViewController { func updateInfo(completion: @escaping () -> Void) { timer?.invalidate() LaundryNotificationCenter.shared.updateForExpiredNotifications { if self.rooms.isEmpty { DispatchQueue.main.async { self.tableView.reloadData() completion() } } else { LaundryAPIService.instance.fetchLaundryData(for: self.rooms) { (rooms) in DispatchQueue.main.async { if let rooms = rooms { self.rooms = rooms self.tableView.reloadData() self.resetTimer() } completion() } } } } } } // MARK: - room Selection Delegate extension LaundryTableViewController: RoomSelectionVCDelegate { func saveSelection(for rooms: [LaundryRoom]) { LaundryRoom.setPreferences(for: rooms) self.rooms = rooms self.tableView.reloadData() LaundryAPIService.instance.fetchLaundryData(for: rooms) { (rooms) in DispatchQueue.main.async { if let rooms = rooms { self.rooms = rooms self.tableView.reloadData() self.sendUpdateNotification(for: rooms) } } } } } // MARK: - Laundry Cell Delegate extension LaundryTableViewController: LaundryCellDelegate { internal func deleteLaundryCell(for room: LaundryRoom) { if let index = rooms.firstIndex(of: room) { rooms.remove(at: index) LaundryRoom.setPreferences(for: rooms) UserDBManager.shared.saveLaundryPreferences(for: rooms) tableView.reloadData() sendUpdateNotification(for: rooms) } } } // MARK: - Home Page Notification extension LaundryTableViewController { fileprivate func sendUpdateNotification(for rooms: [LaundryRoom]) { NotificationCenter.default.post(name: Notification.Name(rawValue: "LaundryUpdateNotification"), object: rooms) } } // MARK: - Add Laundry Cell Delegate extension LaundryTableViewController: AddLaundryCellDelegate { internal func addPressed() { handleEditPressed() } } // MARK: - Timer extension LaundryTableViewController { internal func resetTimer() { timer?.invalidate() timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true, block: { (_) in if !self.rooms.containsRunningMachine() { self.timer?.invalidate() return } for room in self.rooms { room.decrementTimeRemaining(by: 1) } LaundryNotificationCenter.shared.updateForExpiredNotifications { DispatchQueue.main.async { self.reloadVisibleMachineCells() } } }) } fileprivate func reloadVisibleMachineCells() { for cell in self.tableView.visibleCells { if let laundryCell = cell as? LaundryCell { laundryCell.reloadData() } } } }
mit
cbd160291fa41624dac109c70ac62bba
32.098859
156
0.619644
5.105572
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/BlockchainNamespace/Sources/BlockchainNamespace/App/FetchResult.swift
1
8074
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Foundation public enum FetchResult { case value(Any, Metadata) case error(FetchResult.Error, Metadata) } extension FetchResult { public enum Error: Swift.Error, LocalizedError { case keyDoesNotExist(Tag.Reference) case decoding(AnyDecoder.Error) case other(Swift.Error) public var errorDescription: String? { switch self { case .keyDoesNotExist(let reference): return "\(reference) does not exist" case .decoding(let error): return error.errorDescription case .other(let error): return String(describing: error) } } } } public struct Metadata { public let ref: Tag.Reference public let source: Source } extension Metadata { public enum Source { case app case undefined case state case remoteConfiguration } } extension FetchResult { public var metadata: Metadata { switch self { case .value(_, let metadata), .error(_, let metadata): return metadata } } public var value: Any? { switch self { case .value(let any, _): return any case .error: return nil } } public var error: FetchResult.Error? { switch self { case .error(let error, _): return error case .value: return nil } } public init(_ any: Any, metadata: Metadata) { self = .value(any, metadata) } public init(_ error: Error, metadata: Metadata) { self = .error(error, metadata) } public init(catching body: () throws -> Any, _ metadata: Metadata) { self.init(.init(catching: body), metadata) } public init<E: Swift.Error>(_ result: Result<Any, E>, _ metadata: Metadata) { switch result { case .success(let value): self = .value(value, metadata) case .failure(let error as FetchResult.Error): self = .error(error, metadata) case .failure(let error as AnyDecoder.Error): self = .error(.decoding(error), metadata) case .failure(let error): self = .error(.other(error), metadata) } } public static func create<E: Swift.Error>( _ metadata: Metadata ) -> ( _ result: Result<Any, E> ) -> FetchResult { { result in FetchResult(result, metadata) } } public static func create( _ metadata: Metadata ) -> ( _ result: Any? ) -> FetchResult { { result in if let any = result { return .value(any, metadata) } else { return .error(.keyDoesNotExist(metadata.ref), metadata) } } } } extension Tag { public func metadata(_ source: Metadata.Source = .undefined) -> Metadata { Metadata(ref: reference, source: source) } } extension Tag.Reference { public func metadata(_ source: Metadata.Source = .undefined) -> Metadata { Metadata(ref: self, source: source) } } public protocol DecodedFetchResult { associatedtype Value: Decodable var identity: FetchResult.Value<Value> { get } static func value(_ value: Value, _ metatata: Metadata) -> Self static func error(_ error: FetchResult.Error, _ metatata: Metadata) -> Self func get() throws -> Value } extension FetchResult { typealias Decoded = DecodedFetchResult public enum Value<T: Decodable>: DecodedFetchResult { case value(T, Metadata) case error(FetchResult.Error, Metadata) } public func decode<T: Decodable>( _ type: T.Type = T.self, using decoder: AnyDecoderProtocol = BlockchainNamespaceDecoder() ) -> Value<T> { do { switch self { case .value(let value, let metadata): return .value(try decoder.decode(T.self, from: value), metadata) case .error(let error, _): throw error } } catch let error as AnyDecoder.Error { return .error(.decoding(error), metadata) } catch let error as FetchResult.Error { return .error(error, metadata) } catch { return .error(.other(error), metadata) } } public var result: Result<Any, FetchResult.Error> { switch self { case .value(let value, _): return .success(value) case .error(let error, _): return .failure(error) } } public func get() throws -> Any { try result.get() } } extension FetchResult.Value { public var identity: FetchResult.Value<T> { self } } extension DecodedFetchResult { public var metadata: Metadata { switch identity { case .value(_, let metadata), .error(_, let metadata): return metadata } } public var value: Value? { switch identity { case .value(let value, _): return value case .error: return nil } } public var error: FetchResult.Error? { switch identity { case .error(let error, _): return error case .value: return nil } } public var result: Result<Value, FetchResult.Error> { switch identity { case .value(let value, _): return .success(value) case .error(let error, _): return .failure(error) } } public func get() throws -> Value { try result.get() } public func map<T>(_ transform: (Value) -> (T)) -> FetchResult.Value<T> { switch identity { case .error(let error, let metadata): return .error(error, metadata) case .value(let value, let metadata): return .value(transform(value), metadata) } } public func flatMap<T>(_ transform: (Value, Metadata) -> (FetchResult.Value<T>)) -> FetchResult.Value<T> { switch identity { case .error(let error, let metadata): return .error(error, metadata) case .value(let value, let metadata): return transform(value, metadata) } } } #if canImport(Combine) import AnyCoding import Combine extension Publisher where Output == FetchResult { public func decode<T>( _: T.Type = T.self, using decoder: AnyDecoderProtocol = BlockchainNamespaceDecoder() ) -> AnyPublisher<FetchResult.Value<T>, Failure> { map { result in result.decode(T.self, using: decoder) } .eraseToAnyPublisher() } } extension Publisher where Output: DecodedFetchResult { public func replaceError( with value: Output.Value ) -> AnyPublisher<Output.Value, Failure> { flatMap { output -> Just<Output.Value> in switch output.result { case .failure: return Just(value) case .success(let value): return Just(value) } } .eraseToAnyPublisher() } } #endif extension Dictionary where Key == Tag { public func decode<T: Decodable>( _ key: L, as type: T.Type = T.self, using decoder: AnyDecoderProtocol = BlockchainNamespaceDecoder() ) throws -> T { try decode(key[], as: T.self, using: decoder) } public func decode<T: Decodable>( _ key: Tag, as type: T.Type = T.self, using decoder: AnyDecoderProtocol = BlockchainNamespaceDecoder() ) throws -> T { try FetchResult.value(self[key] as Any, key.metadata()) .decode(T.self, using: decoder) .get() } } extension Optional { public func decode<T: Decodable>( _ type: T.Type = T.self, using decoder: AnyDecoderProtocol = BlockchainNamespaceDecoder() ) throws -> T { try decoder.decode(T.self, from: self as Any) } }
lgpl-3.0
65e0acc4ad9e155dd69093e4eaa57778
24.547468
110
0.567819
4.445485
false
false
false
false
nathantannar4/Parse-Dashboard-for-iOS-Pro
Pods/Former/Former/Commons/Former.swift
1
43437
// // Former.swift // Former-Demo // // Created by Ryo Aoyama on 7/23/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public final class Former: NSObject { // MARK: Public /** InstantiateType is type of instantiate of Cell or HeaderFooterView. If the cell or HeaderFooterView to instantiate from the nib of mainBudnle , use the case 'Nib(nibName: String)'. Using the '.NibBundle(nibName: String, bundle: NSBundle)' If also using the custom bundle. Or if without xib, use '.Class'. **/ public enum InstantiateType { case Class case Nib(nibName: String) case NibBundle(nibName: String, bundle: Bundle) } /// All SectionFormers. Default is empty. public private(set) var sectionFormers = [SectionFormer]() /// Return all RowFormers. Compute each time of called. public var rowFormers: [RowFormer] { return sectionFormers.flatMap { $0.rowFormers } } /// Number of all sections. public var numberOfSections: Int { return sectionFormers.count } /// Number of all rows. public var numberOfRows: Int { return rowFormers.count } /// Returns the first element of all SectionFormers, or `nil` if `self.sectionFormers` is empty. public var firstSectionFormer: SectionFormer? { return sectionFormers.first } /// Returns the first element of all RowFormers, or `nil` if `self.rowFormers` is empty. public var firstRowFormer: RowFormer? { return rowFormers.first } /// Returns the last element of all SectionFormers, or `nil` if `self.sectionFormers` is empty. public var lastSectionFormer: SectionFormer? { return sectionFormers.last } /// Returns the last element of all RowFormers, or `nil` if `self.rowFormers` is empty. public var lastRowFormer: RowFormer? { return rowFormers.last } public init(tableView: UITableView) { super.init() self.tableView = tableView setupTableView() } deinit { tableView?.delegate = nil tableView?.dataSource = nil NotificationCenter.default.removeObserver(self) } public subscript(index: Int) -> SectionFormer { return sectionFormers[index] } public subscript(range: Range<Int>) -> [SectionFormer] { return Array<SectionFormer>(sectionFormers[range]) } public subscript(range: ClosedRange<Int>) -> [SectionFormer] { return Array<SectionFormer>(sectionFormers[range]) } public subscript(range: CountableRange<Int>) -> [SectionFormer] { return Array<SectionFormer>(sectionFormers[range]) } public subscript(range: CountableClosedRange<Int>) -> [SectionFormer] { return Array<SectionFormer>(sectionFormers[range]) } /// To find RowFormer from indexPath. public func rowFormer(indexPath: IndexPath) -> RowFormer { return self[indexPath.section][indexPath.row] } /// Call when cell has selected. @discardableResult public func onCellSelected(_ handler: @escaping ((IndexPath) -> Void)) -> Self { onCellSelected = handler return self } /// Call when tableView has scrolled. @discardableResult public func onScroll(_ handler: @escaping ((UIScrollView) -> Void)) -> Self { onScroll = handler return self } /// Call when tableView had begin dragging. @discardableResult public func onBeginDragging(_ handler: @escaping ((UIScrollView) -> Void)) -> Self { onBeginDragging = handler return self } /// Call just before cell is deselect. @discardableResult public func willDeselectCell(_ handler: @escaping ((IndexPath) -> IndexPath?)) -> Self { willDeselectCell = handler return self } /// Call just before cell is display. @discardableResult public func willDisplayCell(_ handler: @escaping ((IndexPath) -> Void)) -> Self { willDisplayCell = handler return self } /// Call just before header is display. @discardableResult public func willDisplayHeader(_ handler: @escaping ((/*section:*/Int) -> Void)) -> Self { willDisplayHeader = handler return self } /// Call just before cell is display. @discardableResult public func willDisplayFooter(_ handler: @escaping ((/*section:*/Int) -> Void)) -> Self { willDisplayFooter = handler return self } /// Call when cell has deselect. @discardableResult public func didDeselectCell(_ handler: @escaping ((IndexPath) -> Void)) -> Self { didDeselectCell = handler return self } /// Call when cell has Displayed. @discardableResult public func didEndDisplayingCell(_ handler: @escaping ((IndexPath) -> Void)) -> Self { didEndDisplayingCell = handler return self } /// Call when header has displayed. @discardableResult public func didEndDisplayingHeader(_ handler: @escaping ((/*section:*/Int) -> Void)) -> Self { didEndDisplayingHeader = handler return self } /// Call when footer has displayed. @discardableResult public func didEndDisplayingFooter(_ handler: @escaping ((/*section:*/Int) -> Void)) -> Self { didEndDisplayingFooter = handler return self } /// Call when cell has highlighted. @discardableResult public func didHighlightCell(_ handler: @escaping ((IndexPath) -> Void)) -> Self { didHighlightCell = handler return self } /// Call when cell has unhighlighted. @discardableResult public func didUnHighlightCell(_ handler: @escaping ((IndexPath) -> Void)) -> Self { didUnHighlightCell = handler return self } /// 'true' iff can edit previous row. public func canBecomeEditingPrevious() -> Bool { var section = selectedIndexPath?.section ?? 0 var row = (selectedIndexPath != nil) ? selectedIndexPath!.row - 1 : 0 guard section < sectionFormers.count else { return false } if row < 0 { section -= 1 guard section >= 0 else { return false } row = self[section].rowFormers.count - 1 } guard row < self[section].rowFormers.count else { return false } return self[section][row].canBecomeEditing } /// 'true' iff can edit next row. public func canBecomeEditingNext() -> Bool { var section = selectedIndexPath?.section ?? 0 var row = (selectedIndexPath != nil) ? selectedIndexPath!.row + 1 : 0 guard section < sectionFormers.count else { return false } if row >= self[section].rowFormers.count { section += 1 guard section < sectionFormers.count else { return false } row = 0 } guard row < self[section].rowFormers.count else { return false } return self[section][row].canBecomeEditing } /// Edit previous row iff it can. @discardableResult public func becomeEditingPrevious() -> Self { if let tableView = tableView, canBecomeEditingPrevious() { var section = selectedIndexPath?.section ?? 0 var row = (selectedIndexPath != nil) ? selectedIndexPath!.row - 1 : 0 guard section < sectionFormers.count else { return self } if row < 0 { section -= 1 guard section >= 0 else { return self } row = self[section].rowFormers.count - 1 } guard row < self[section].rowFormers.count else { return self } let indexPath = IndexPath(row: row, section: section) select(indexPath: indexPath, animated: false) let scrollIndexPath = (rowFormer(indexPath: indexPath) is InlineForm) ? IndexPath(row: row + 1, section: section) : indexPath tableView.scrollToRow(at: scrollIndexPath, at: .none, animated: false) } return self } /// Edit next row iff it can. @discardableResult public func becomeEditingNext() -> Self { if let tableView = tableView, canBecomeEditingNext() { var section = selectedIndexPath?.section ?? 0 var row = (selectedIndexPath != nil) ? selectedIndexPath!.row + 1 : 0 guard section < sectionFormers.count else { return self } if row >= self[section].rowFormers.count { section += 1 guard section < sectionFormers.count else { return self } row = 0 } guard row < self[section].rowFormers.count else { return self } let indexPath = IndexPath(row: row, section: section) select(indexPath: indexPath, animated: false) let scrollIndexPath = (rowFormer(indexPath: indexPath) is InlineForm) ? IndexPath(row: row + 1, section: section) : indexPath tableView.scrollToRow(at: scrollIndexPath, at: .none, animated: false) } return self } /// To end editing of tableView. @discardableResult public func endEditing() -> Self { tableView?.endEditing(true) if let selectorRowFormer = selectorRowFormer as? SelectorForm { selectorRowFormer.editingDidEnd() self.selectorRowFormer = nil } return self } /// To select row from indexPath. @discardableResult public func select(indexPath: IndexPath, animated: Bool, scrollPosition: UITableViewScrollPosition = .none) -> Self { if let tableView = tableView { tableView.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition) _ = self.tableView(tableView, willSelectRowAt: indexPath) self.tableView(tableView, didSelectRowAt: indexPath) } return self } /// To select row from instance of RowFormer. @discardableResult public func select(rowFormer: RowFormer, animated: Bool, scrollPosition: UITableViewScrollPosition = .none) -> Self { for (section, sectionFormer) in sectionFormers.enumerated() { if let row = sectionFormer.rowFormers.index(where: { $0 === rowFormer }) { return select(indexPath: IndexPath(row: row, section: section), animated: animated, scrollPosition: scrollPosition) } } return self } /// To deselect current selecting cell. @discardableResult public func deselect(animated: Bool) -> Self { if let indexPath = selectedIndexPath { tableView?.deselectRow(at: indexPath, animated: animated) } return self } /// Reload All cells. @discardableResult public func reload() -> Self { tableView?.reloadData() removeCurrentInlineRowUpdate() return self } /// Reload sections from section indexSet. @discardableResult public func reload(sections: IndexSet, rowAnimation: UITableViewRowAnimation = .none) -> Self { tableView?.reloadSections(sections, with: rowAnimation) return self } /// Reload sections from instance of SectionFormer. @discardableResult public func reload(sectionFormer: SectionFormer, rowAnimation: UITableViewRowAnimation = .none) -> Self { guard let section = sectionFormers.index(where: { $0 === sectionFormer }) else { return self } return reload(sections: IndexSet(integer: section), rowAnimation: rowAnimation) } /// Reload rows from indesPaths. @discardableResult public func reload(indexPaths: [IndexPath], rowAnimation: UITableViewRowAnimation = .none) -> Self { tableView?.reloadRows(at: indexPaths, with: rowAnimation) return self } /// Reload rows from instance of RowFormer. @discardableResult public func reload(rowFormer: RowFormer, rowAnimation: UITableViewRowAnimation = .none) -> Self { for (section, sectionFormer) in sectionFormers.enumerated() { if let row = sectionFormer.rowFormers.index(where: { $0 === rowFormer}) { return reload(indexPaths: [IndexPath(row: row, section: section)], rowAnimation: rowAnimation) } } return self } /// Append SectionFormer to last index. @discardableResult public func append(sectionFormer: SectionFormer...) -> Self { return add(sectionFormers: sectionFormer) } /// Add SectionFormers to last index. @discardableResult public func add(sectionFormers: [SectionFormer]) -> Self { self.sectionFormers += sectionFormers return self } /// Insert SectionFormer to index of section with NO updates. @discardableResult public func insert(sectionFormer: SectionFormer..., toSection: Int) -> Self { return insert(sectionFormers: sectionFormer, toSection: toSection) } /// Insert SectionFormers to index of section with NO updates. @discardableResult public func insert(sectionFormers: [SectionFormer], toSection: Int) -> Self { let count = self.sectionFormers.count if count == 0 || toSection >= count { add(sectionFormers: sectionFormers) return self } else if toSection >= count { self.sectionFormers.insert(contentsOf: sectionFormers, at: 0) return self } self.sectionFormers.insert(contentsOf: sectionFormers, at: toSection) return self } /// Insert SectionFormer to above other SectionFormer with NO updates. @discardableResult public func insert(sectionFormer: SectionFormer..., above: SectionFormer) -> Self { return insert(sectionFormers: sectionFormer, above: above) } /// Insert SectionFormers to above other SectionFormer with NO updates. @discardableResult public func insert(sectionFormers: [SectionFormer], above: SectionFormer) -> Self { for (section, sectionFormer) in self.sectionFormers.enumerated() { if sectionFormer === above { return insert(sectionFormers: sectionFormers, toSection: section - 1) } } return add(sectionFormers: sectionFormers) } /// Insert SectionFormer to below other SectionFormer with NO updates. @discardableResult public func insert(sectionFormer: SectionFormer..., below: SectionFormer) -> Self { for (section, sectionFormer) in self.sectionFormers.enumerated() { if sectionFormer === below { return insert(sectionFormers: sectionFormers, toSection: section + 1) } } add(sectionFormers: sectionFormers) return insert(sectionFormers: sectionFormer, below: below) } /// Insert SectionFormers to below other SectionFormer with NO updates. @discardableResult public func insert(sectionFormers: [SectionFormer], below: SectionFormer) -> Self { for (section, sectionFormer) in self.sectionFormers.enumerated() { if sectionFormer === below { return insert(sectionFormers: sectionFormers, toSection: section + 1) } } return add(sectionFormers: sectionFormers) } /// Insert SectionFormer to index of section with animated updates. @discardableResult public func insertUpdate(sectionFormer: SectionFormer..., toSection: Int, rowAnimation: UITableViewRowAnimation = .none) -> Self { return insertUpdate(sectionFormers: sectionFormer, toSection: toSection, rowAnimation: rowAnimation) } /// Insert SectionFormers to index of section with animated updates. @discardableResult public func insertUpdate(sectionFormers: [SectionFormer], toSection: Int, rowAnimation: UITableViewRowAnimation = .none) -> Self { guard !sectionFormers.isEmpty else { return self } removeCurrentInlineRowUpdate() tableView?.beginUpdates() insert(sectionFormers: sectionFormers, toSection: toSection) tableView?.insertSections(IndexSet(integer: toSection), with: rowAnimation) tableView?.endUpdates() return self } /// Insert SectionFormer to above other SectionFormer with animated updates. @discardableResult public func insertUpdate(sectionFormer: SectionFormer..., above: SectionFormer, rowAnimation: UITableViewRowAnimation = .none) -> Self { return insertUpdate(sectionFormers: sectionFormer, above: above, rowAnimation: rowAnimation) } /// Insert SectionFormers to above other SectionFormer with animated updates. @discardableResult public func insertUpdate(sectionFormers: [SectionFormer], above: SectionFormer, rowAnimation: UITableViewRowAnimation = .none) -> Self { removeCurrentInlineRowUpdate() for (section, sectionFormer) in self.sectionFormers.enumerated() { if sectionFormer === above { let indexSet = IndexSet(integersIn: section..<(section + sectionFormers.count)) tableView?.beginUpdates() insert(sectionFormers: sectionFormers, toSection: section) tableView?.insertSections(indexSet, with: rowAnimation) tableView?.endUpdates() return self } } return self } /// Insert SectionFormer to below other SectionFormer with animated updates. @discardableResult public func insertUpdate(sectionFormer: SectionFormer..., below: SectionFormer, rowAnimation: UITableViewRowAnimation = .none) -> Self { return insertUpdate(sectionFormers: sectionFormer, below: below, rowAnimation: rowAnimation) } /// Insert SectionFormers to below other SectionFormer with animated updates. @discardableResult public func insertUpdate(sectionFormers: [SectionFormer], below: SectionFormer, rowAnimation: UITableViewRowAnimation = .none) -> Self { removeCurrentInlineRowUpdate() for (section, sectionFormer) in self.sectionFormers.enumerated() { if sectionFormer === below { let indexSet = IndexSet(integersIn: (section + 1)..<(section + 1 + sectionFormers.count)) tableView?.beginUpdates() insert(sectionFormers: sectionFormers, toSection: section + 1) tableView?.insertSections(indexSet, with: rowAnimation) tableView?.endUpdates() return self } } return self } /// Insert RowFormer with NO updates. @discardableResult public func insert(rowFormer: RowFormer..., toIndexPath: IndexPath) -> Self { return insert(rowFormers: rowFormer, toIndexPath: toIndexPath) } /// Insert RowFormers with NO updates. @discardableResult public func insert(rowFormers: [RowFormer], toIndexPath: IndexPath) -> Self { self[toIndexPath.section].insert(rowFormers: rowFormers, toIndex: toIndexPath.row) return self } /// Insert RowFormer to above other RowFormer with NO updates. @discardableResult public func insert(rowFormer: RowFormer..., above: RowFormer) -> Self { return insert(rowFormers: rowFormer, above: above) } /// Insert RowFormers to above other RowFormer with NO updates. @discardableResult public func insert(rowFormers: [RowFormer], above: RowFormer) -> Self { guard !rowFormers.isEmpty else { return self } for sectionFormer in self.sectionFormers { for (row, rowFormer) in sectionFormer.rowFormers.enumerated() { if rowFormer === above { sectionFormer.insert(rowFormers: rowFormers, toIndex: row) return self } } } return self } /// Insert RowFormers to below other RowFormer with NO updates. @discardableResult public func insert(rowFormer: RowFormer..., below: RowFormer) -> Self { return insert(rowFormers: rowFormer, below: below) } /// Insert RowFormers to below other RowFormer with NO updates. @discardableResult public func insert(rowFormers: [RowFormer], below: RowFormer) -> Self { guard !rowFormers.isEmpty else { return self } for sectionFormer in self.sectionFormers { for (row, rowFormer) in sectionFormer.rowFormers.enumerated() { if rowFormer === below { sectionFormer.insert(rowFormers: rowFormers, toIndex: row + 1) return self } } } return self } /// Insert RowFormer with animated updates. @discardableResult public func insertUpdate(rowFormer: RowFormer..., toIndexPath: IndexPath, rowAnimation: UITableViewRowAnimation = .none) -> Self { return insertUpdate(rowFormers: rowFormer, toIndexPath: toIndexPath, rowAnimation: rowAnimation) } /// Insert RowFormers with animated updates. @discardableResult public func insertUpdate(rowFormers: [RowFormer], toIndexPath: IndexPath, rowAnimation: UITableViewRowAnimation = .none) -> Self { removeCurrentInlineRowUpdate() guard !rowFormers.isEmpty else { return self } tableView?.beginUpdates() insert(rowFormers: rowFormers, toIndexPath: toIndexPath) let insertIndexPaths = (0..<rowFormers.count).map { IndexPath(row: toIndexPath.row + $0, section: toIndexPath.section) } tableView?.insertRows(at: insertIndexPaths, with: rowAnimation) tableView?.endUpdates() return self } /// Insert RowFormer to above other RowFormer with animated updates. @discardableResult public func insertUpdate(rowFormer: RowFormer..., above: RowFormer, rowAnimation: UITableViewRowAnimation = .none) -> Self { return insertUpdate(rowFormers: rowFormer, above: above, rowAnimation: rowAnimation) } /// Insert RowFormers to above other RowFormer with animated updates. @discardableResult public func insertUpdate(rowFormers: [RowFormer], above: RowFormer, rowAnimation: UITableViewRowAnimation = .none) -> Self { removeCurrentInlineRowUpdate() for (section, sectionFormer) in self.sectionFormers.enumerated() { for (row, rowFormer) in sectionFormer.rowFormers.enumerated() { if rowFormer === above { let indexPaths = (row..<row + rowFormers.count).map { IndexPath(row: $0, section: section) } tableView?.beginUpdates() sectionFormer.insert(rowFormers: rowFormers, toIndex: row) tableView?.insertRows(at: indexPaths, with: rowAnimation) tableView?.endUpdates() return self } } } return self } /// Insert RowFormer to below other RowFormer with animated updates. @discardableResult public func insertUpdate(rowFormer: RowFormer..., below: RowFormer, rowAnimation: UITableViewRowAnimation = .none) -> Self { return insertUpdate(rowFormers: rowFormer, below: below, rowAnimation: rowAnimation) } /// Insert RowFormers to below other RowFormer with animated updates. @discardableResult public func insertUpdate(rowFormers: [RowFormer], below: RowFormer, rowAnimation: UITableViewRowAnimation = .none) -> Self { removeCurrentInlineRowUpdate() for (section, sectionFormer) in self.sectionFormers.enumerated() { for (row, rowFormer) in sectionFormer.rowFormers.enumerated() { if rowFormer === below { let indexPaths = (row + 1..<row + 1 + rowFormers.count).map { IndexPath(row: $0, section: section) } tableView?.beginUpdates() sectionFormer.insert(rowFormers: rowFormers, toIndex: row + 1) tableView?.insertRows(at: indexPaths, with: rowAnimation) tableView?.endUpdates() return self } } } return self } /// Remove All SectionFormers with NO updates. @discardableResult public func removeAll() -> Self { sectionFormers = [] return self } /// Remove All SectionFormers with animated updates. @discardableResult public func removeAllUpdate(rowAnimation: UITableViewRowAnimation = .none) -> Self { let indexSet = IndexSet(integersIn: 0..<sectionFormers.count) sectionFormers = [] guard indexSet.count > 0 else { return self } tableView?.beginUpdates() tableView?.deleteSections(indexSet, with: rowAnimation) tableView?.endUpdates() return self } /// Remove SectionFormers from section index with NO updates. @discardableResult public func remove(section: Int) -> Self { sectionFormers.remove(at: section) return self } /// Remove SectionFormers from instances of SectionFormer with NO updates. @discardableResult public func remove(sectionFormer: SectionFormer...) -> Self { return remove(sectionFormers: sectionFormer) } /// Remove SectionFormers from instances of SectionFormer with NO updates. @discardableResult public func remove(sectionFormers: [SectionFormer]) -> Self { _ = removeSectionFormers(sectionFormers) return self } /// Remove SectionFormers from instances of SectionFormer with animated updates. @discardableResult public func removeUpdate(sectionFormer: SectionFormer..., rowAnimation: UITableViewRowAnimation = .none) -> Self { return removeUpdate(sectionFormers: sectionFormer, rowAnimation: rowAnimation) } /// Remove SectionFormers from instances of SectionFormer with animated updates. @discardableResult public func removeUpdate(sectionFormers: [SectionFormer], rowAnimation: UITableViewRowAnimation = .none) -> Self { guard !sectionFormers.isEmpty else { return self } let indexSet = removeSectionFormers(sectionFormers) guard indexSet.count > 0 else { return self } tableView?.beginUpdates() tableView?.deleteSections(indexSet, with: rowAnimation) tableView?.endUpdates() return self } /// Remove RowFormer with NO updates. @discardableResult public func remove(rowFormer: RowFormer...) -> Self { return remove(rowFormers: rowFormer) } /// Remove RowFormers with NO updates. @discardableResult public func remove(rowFormers: [RowFormer]) -> Self { _ = removeRowFormers(rowFormers) return self } /// Remove RowFormers with animated updates. @discardableResult public func removeUpdate(rowFormer: RowFormer..., rowAnimation: UITableViewRowAnimation = .none) -> Self { return removeUpdate(rowFormers: rowFormer, rowAnimation: rowAnimation) } /// Remove RowFormers with animated updates. @discardableResult public func removeUpdate(rowFormers: [RowFormer], rowAnimation: UITableViewRowAnimation = .none) -> Self { removeCurrentInlineRowUpdate() guard !rowFormers.isEmpty else { return self } tableView?.beginUpdates() let oldIndexPaths = removeRowFormers(rowFormers) tableView?.deleteRows(at: oldIndexPaths, with: rowAnimation) tableView?.endUpdates() return self } // MARK: Private fileprivate var onCellSelected: ((IndexPath) -> Void)? fileprivate var onScroll: ((UIScrollView) -> Void)? fileprivate var onBeginDragging: ((UIScrollView) -> Void)? fileprivate var willDeselectCell: ((IndexPath) -> IndexPath?)? fileprivate var willDisplayCell: ((IndexPath) -> Void)? fileprivate var willDisplayHeader: ((Int) -> Void)? fileprivate var willDisplayFooter: ((Int) -> Void)? fileprivate var didDeselectCell: ((IndexPath) -> Void)? fileprivate var didEndDisplayingCell: ((IndexPath) -> Void)? fileprivate var didEndDisplayingHeader: ((Int) -> Void)? fileprivate var didEndDisplayingFooter: ((Int) -> Void)? fileprivate var didHighlightCell: ((IndexPath) -> Void)? fileprivate var didUnHighlightCell: ((IndexPath) -> Void)? fileprivate weak var tableView: UITableView? fileprivate weak var inlineRowFormer: RowFormer? fileprivate weak var selectorRowFormer: RowFormer? fileprivate var selectedIndexPath: IndexPath? fileprivate var oldBottomContentInset: CGFloat? private func setupTableView() { tableView?.delegate = self tableView?.dataSource = self NotificationCenter.default.addObserver(self, selector: #selector(Former.keyboardWillAppear(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(Former.keyboardWillDisappear(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } fileprivate func removeCurrentInlineRow() -> IndexPath? { var indexPath: IndexPath? = nil if let oldInlineRowFormer = (inlineRowFormer as? InlineForm)?.inlineRowFormer, let removedIndexPath = removeRowFormers([oldInlineRowFormer]).first { indexPath = removedIndexPath (inlineRowFormer as? InlineForm)?.editingDidEnd() inlineRowFormer = nil } return indexPath } fileprivate func removeCurrentInlineRowUpdate() { if let removedIndexPath = removeCurrentInlineRow() { tableView?.beginUpdates() tableView?.deleteRows(at: [removedIndexPath], with: .middle) tableView?.endUpdates() } } fileprivate func removeSectionFormers(_ sectionFormers: [SectionFormer]) -> IndexSet { var removedCount = 0 var indexSet = IndexSet() for (section, sectionFormer) in self.sectionFormers.enumerated() { if sectionFormers.contains(where: { $0 === sectionFormer}) { indexSet.insert(section) remove(section: section) removedCount += 1 if removedCount >= sectionFormers.count { return indexSet } } } return indexSet } fileprivate func removeRowFormers(_ rowFormers: [RowFormer]) -> [IndexPath] { var removedCount = 0 var removeIndexPaths = [IndexPath]() for (section, sectionFormer) in sectionFormers.enumerated() { for (row, rowFormer) in sectionFormer.rowFormers.enumerated() { if rowFormers.contains(where: { $0 === rowFormer }) { removeIndexPaths.append(IndexPath(row: row, section: section)) sectionFormer.remove(rowFormers: [rowFormer]) if let oldInlineRowFormer = (rowFormer as? InlineForm)?.inlineRowFormer, let _ = removeRowFormers([oldInlineRowFormer]).first { removeIndexPaths.append(IndexPath(row: row + 1, section: section)) (inlineRowFormer as? InlineForm)?.editingDidEnd() inlineRowFormer = nil } removedCount += 1 if removedCount >= rowFormers.count { return removeIndexPaths } } } } return removeIndexPaths } private func findFirstResponder(_ view: UIView?) -> UIView? { if view?.isFirstResponder ?? false { return view } for subView in view?.subviews ?? [] { if let firstResponder = findFirstResponder(subView) { return firstResponder } } return nil } private func findCellWithSubView(_ view: UIView?) -> UITableViewCell? { if let view = view { if let cell = view as? UITableViewCell { return cell } return findCellWithSubView(view.superview) } return nil } @objc private dynamic func keyboardWillAppear(notification: NSNotification) { guard let keyboardInfo = notification.userInfo else { return } if case let (tableView?, cell?) = (tableView, findCellWithSubView(findFirstResponder(tableView))) { let frame = (keyboardInfo[UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue let keyboardFrame = tableView.window!.convert(frame!, to: tableView.superview!) let bottomInset = tableView.frame.minY + tableView.frame.height - keyboardFrame.minY guard bottomInset > 0 else { return } if oldBottomContentInset == nil { oldBottomContentInset = tableView.contentInset.bottom } let duration = (keyboardInfo[UIKeyboardAnimationDurationUserInfoKey]! as AnyObject).doubleValue! let curve = (keyboardInfo[UIKeyboardAnimationCurveUserInfoKey]! as AnyObject).integerValue! guard let indexPath = tableView.indexPath(for: cell) else { return } UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(duration) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!) tableView.contentInset.bottom = bottomInset tableView.scrollIndicatorInsets.bottom = bottomInset tableView.scrollToRow(at: indexPath, at: .none, animated: false) UIView.commitAnimations() } } @objc private dynamic func keyboardWillDisappear(notification: NSNotification) { guard let keyboardInfo = notification.userInfo else { return } if case let (tableView?, inset?) = (tableView, oldBottomContentInset) { let duration = (keyboardInfo[UIKeyboardAnimationDurationUserInfoKey]! as AnyObject).doubleValue! let curve = (keyboardInfo[UIKeyboardAnimationCurveUserInfoKey]! as AnyObject).integerValue! UIView.beginAnimations(nil, context: nil) UIView.setAnimationDuration(duration) UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!) tableView.contentInset.bottom = inset tableView.scrollIndicatorInsets.bottom = inset UIView.commitAnimations() oldBottomContentInset = nil } } } extension Former: UITableViewDelegate, UITableViewDataSource { public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { endEditing() onBeginDragging?(scrollView) } public func scrollViewDidScroll(_ scrollView: UIScrollView) { onScroll?(scrollView) } public func tableView(_ tableView: UITableView, willDeselectRowAt indexPath: IndexPath) -> IndexPath? { return willDeselectCell?(indexPath) ?? indexPath } public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { willDisplayCell?(indexPath) } public func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { willDisplayHeader?(section) } public func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { willDisplayFooter?(section) } public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) { didDeselectCell?(indexPath) } public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { didEndDisplayingCell?(indexPath) } public func tableView(_ tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) { didEndDisplayingHeader?(section) } public func tableView(_ tableView: UITableView, didEndDisplayingFooterView view: UIView, forSection section: Int) { didEndDisplayingFooter?(section) } public func tableView(_ tableView: UITableView, didHighlightRowAt indexPath: IndexPath) { didHighlightCell?(indexPath) } public func tableView(_ tableView: UITableView, didUnhighlightRowAt indexPath: IndexPath) { didUnHighlightCell?(indexPath) } public func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { endEditing() deselect(animated: false) selectedIndexPath = indexPath return indexPath } public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let rowFormer = self.rowFormer(indexPath: indexPath) guard rowFormer.enabled else { return } rowFormer.cellSelected(indexPath: indexPath) onCellSelected?(indexPath) // InlineRow if let oldInlineRowFormer = (inlineRowFormer as? InlineForm)?.inlineRowFormer { if let currentInlineRowFormer = (rowFormer as? InlineForm)?.inlineRowFormer, rowFormer !== inlineRowFormer { self.tableView?.beginUpdates() if let removedIndexPath = removeRowFormers([oldInlineRowFormer]).first { let insertIndexPath = (removedIndexPath.section == indexPath.section && removedIndexPath.row < indexPath.row) ? indexPath : IndexPath(row: indexPath.row + 1, section: indexPath.section) insert(rowFormers: [currentInlineRowFormer], toIndexPath: insertIndexPath) self.tableView?.deleteRows(at: [removedIndexPath], with: .middle) self.tableView?.insertRows(at: [insertIndexPath], with: .middle) } self.tableView?.endUpdates() (inlineRowFormer as? InlineForm)?.editingDidEnd() (rowFormer as? InlineForm)?.editingDidBegin() inlineRowFormer = rowFormer } else { removeCurrentInlineRowUpdate() } } else if let inlineRowFormer = (rowFormer as? InlineForm)?.inlineRowFormer { let inlineIndexPath = IndexPath(row: indexPath.row + 1, section: indexPath.section) insertUpdate(rowFormers: [inlineRowFormer], toIndexPath: inlineIndexPath, rowAnimation: .middle) (rowFormer as? InlineForm)?.editingDidBegin() self.inlineRowFormer = rowFormer } // SelectorRow if let selectorRow = rowFormer as? SelectorForm { if let selectorRowFormer = selectorRowFormer { if !(selectorRowFormer === rowFormer) { selectorRow.editingDidBegin() } } else { selectorRow.editingDidBegin() } selectorRowFormer = rowFormer rowFormer.cellInstance.becomeFirstResponder() } } public func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return false } public func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return false } // for Cell public func numberOfSections(in tableView: UITableView) -> Int { return numberOfSections } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self[section].numberOfRows } public func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { let rowFormer = self.rowFormer(indexPath: indexPath) if let dynamicRowHeight = rowFormer.dynamicRowHeight { rowFormer.rowHeight = dynamicRowHeight(tableView, indexPath) } return rowFormer.rowHeight } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let rowFormer = self.rowFormer(indexPath: indexPath) if let dynamicRowHeight = rowFormer.dynamicRowHeight { rowFormer.rowHeight = dynamicRowHeight(tableView, indexPath) } return rowFormer.rowHeight } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let rowFormer = self.rowFormer(indexPath: indexPath) if rowFormer.former == nil { rowFormer.former = self } rowFormer.update() return rowFormer.cellInstance } // for HeaderFooterView // Not implemented for iOS8 estimatedHeight bug // public func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat { // let headerViewFormer = self[section].headerViewFormer // if let dynamicViewHeight = headerViewFormer?.dynamicViewHeight { // headerViewFormer?.viewHeight = dynamicViewHeight(tableView, section) // } // return headerViewFormer?.viewHeight ?? 0 // } public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let headerViewFormer = self[section].headerViewFormer if let dynamicViewHeight = headerViewFormer?.dynamicViewHeight { headerViewFormer?.viewHeight = dynamicViewHeight(tableView, section) } return headerViewFormer?.viewHeight ?? 0 } // Not implemented for iOS8 estimatedHeight bug // public func tableView(_ tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat { // let footerViewFormer = self[section].footerViewFormer // if let dynamicViewHeight = footerViewFormer?.dynamicViewHeight { // footerViewFormer?.viewHeight = dynamicViewHeight(tableView, section) // } // return footerViewFormer?.viewHeight ?? 0 // } public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { let footerViewFormer = self[section].footerViewFormer if let dynamicViewHeight = footerViewFormer?.dynamicViewHeight { footerViewFormer?.viewHeight = dynamicViewHeight(tableView, section) } return footerViewFormer?.viewHeight ?? 0 } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let viewFormer = self[section].headerViewFormer else { return nil } viewFormer.update() return viewFormer.viewInstance } public func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { guard let viewFormer = self[section].footerViewFormer else { return nil } viewFormer.update() return viewFormer.viewInstance } }
mit
cf2d31733b27be0dfa9bff65de06ece6
39.938737
177
0.641357
5.545257
false
false
false
false
CoderFeiSu/FFCategoryHUD
FFCategoryHUD/UIColor+FFExtension.swift
1
757
// // UIColor+Extension.swift // FFCategoryHUDExample // // Created by Freedom on 2017/4/20. // Copyright © 2017年 Freedom. All rights reserved. // import UIKit extension UIColor { static var random: UIColor { let redRandom = CGFloat(arc4random_uniform(UInt32(256))) / 255.0 let greenRandom = CGFloat(arc4random_uniform(UInt32(256))) / 255.0 let blueRandom = CGFloat(arc4random_uniform(UInt32(256))) / 255.0 return UIColor(red: redRandom, green: greenRandom, blue: blueRandom, alpha: 1.0) } var rgbValue: (CGFloat, CGFloat, CGFloat) { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: nil) return (r,g,b) } }
mit
58ca396c76e866829b9b84890550ff74
25.928571
87
0.62069
3.396396
false
false
false
false
conopsys/COSTouchVisualizer
ExampleSwift/TouchVisualizer/AppDelegate.swift
1
1830
// // AppDelegate.swift // TouchVisualizer // // Created by Joseph Blau on 5/18/15. // Copyright (c) 2015 Conopsys. All rights reserved. // import UIKit import COSTouchVisualizer @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, COSTouchVisualizerWindowDelegate { internal var window: UIWindow? = { let customWindow = COSTouchVisualizerWindow(frame: UIScreen.main.bounds) customWindow.fillColor = UIColor.purple customWindow.strokeColor = UIColor.blue customWindow.touchAlpha = 0.4; customWindow.rippleFillColor = UIColor.purple customWindow.rippleStrokeColor = UIColor.blue customWindow.touchAlpha = 0.1; return customWindow }() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { guard let window = window as? COSTouchVisualizerWindow else { return false } window.touchVisualizerWindowDelegate = self return true } // MARK: - COSTouchVisualizerWindowDelegate func touchVisualizerWindowShouldAlwaysShowFingertip(_ window: COSTouchVisualizerWindow!) -> Bool { // Return YES to make the fingertip always display even if there's no any mirrored screen. // Return NO or don't implement this method if you want to keep the fingertip display only when // the device is connected to a mirrored screen. return true } func touchVisualizerWindowShouldShowFingertip(_ window: COSTouchVisualizerWindow!) -> Bool { // Return YES or don't implement this method to make this window show fingertip when necessary. // Return NO to make this window not to show fingertip. return true } }
mit
915788aa8296d6ce63b5a0514fff3f0f
34.882353
144
0.696721
4.765625
false
false
false
false
Jnosh/swift
test/SILOptimizer/access_enforcement_noescape.swift
3
26407
// RUN: %target-swift-frontend -enforce-exclusivity=checked -Onone -emit-sil -parse-as-library %s | %FileCheck %s // REQUIRES: asserts // This tests SILGen and AccessEnforcementSelection as a single set of tests. // (Some static/dynamic enforcement selection is done in SILGen, and some is // deferred. That may change over time but we want the outcome to be the same). // // Each FIXME line is a case that the current implementation misses. // The model is currently being refined, so this isn't set in stone. // // TODO: Move all static cases (search for // Error:) into // a set of -verify tests (noescape_static_diagnostics.swift). // and a set of separate SILGen-only tests to check [unknown] markers. // // TODO: Ensure that each dynamic case is covered by // Interpreter/enforce_exclusive_access.swift. // Helper func doOne(_ f: () -> ()) { f() } // Helper func doTwo(_: ()->(), _: ()->()) {} // Helper func doOneInout(_: ()->(), _: inout Int) {} // FIXME: statically prohibit a call to a non-escaping closure // parameter using another non-escaping closure parameter as an argument. func reentrantNoescape(fn: (() -> ()) -> ()) { fn { fn {} } } // Error: Cannot capture nonescaping closure. // func reentrantCapturedNoescape(fn: (() -> ()) -> ()) { // let c = { fn {} } // fn(c) // } // Helper struct Frob { mutating func outerMut() { doOne { innerMut() } } mutating func innerMut() {} } // Allow nested mutable access via closures. func nestedNoEscape(f: inout Frob) { doOne { f.outerMut() } } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape14nestedNoEscapeyAA4FrobVz1f_tF : $@convention(thin) (@inout Frob) -> () { // CHECK-NOT: begin_access // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14nestedNoEscapeyAA4FrobVz1f_tF' // closure #1 in nestedNoEscape(f:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape14nestedNoEscapeyAA4FrobVz1f_tFyycfU_ : $@convention(thin) (@inout_aliasable Frob) -> () { // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Frob // CHECK: [[ACCESS:%.*]] = begin_access [modify] // CHECK: %{{.*}} = apply %{{.*}}([[ACCESS]]) : $@convention(method) (@inout Frob) -> () // CHECK: end_access [[ACCESS]] : $*Frob // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14nestedNoEscapeyAA4FrobVz1f_tFyycfU_' // Allow aliased noescape reads. func readRead() { var x = 3 // Around the call: [read] [static] // Inside each closure: [read] [static] doTwo({ _ = x }, { _ = x }) x = 42 } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape8readReadyyF : $@convention(thin) () -> () { // CHECK: [[ALLOC:%.*]] = alloc_stack $Int, var, name "x" // CHECK-NOT: begin_access [read] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [static] [[ALLOC]] : $*Int // CHECK-NOT: begin_access [read] [dynamic] // CHECK: apply // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape8readReadyyF' // closure #1 in readRead() // CHECK-LABEL: sil private @_T027access_enforcement_noescape8readReadyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [read] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape8readReadyyFyycfU_' // closure #2 in readRead() // CHECK-LABEL: sil private @_T027access_enforcement_noescape8readReadyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [read] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape8readReadyyFyycfU0_' // Allow aliased noescape reads of an `inout` arg. func inoutReadRead(x: inout Int) { // Around the call: [read] [static] // Inside each closure: [read] [static] doTwo({ _ = x }, { _ = x }) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape09inoutReadE0ySiz1x_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape09inoutReadE0ySiz1x_tF' // closure #1 in inoutReadRead(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape09inoutReadE0ySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [read] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape09inoutReadE0ySiz1x_tFyycfU_' // closure #2 in inoutReadRead(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape09inoutReadE0ySiz1x_tFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [read] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape09inoutReadE0ySiz1x_tFyycfU0_' // Allow aliased noescape read + boxed read. func readBoxRead() { var x = 3 let c = { _ = x } // Inside may-escape closure `c`: [read] [dynamic] // Inside never-escape closure: [read] [dynamic] doTwo(c, { _ = x }) x = 42 } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape11readBoxReadyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape11readBoxReadyyF' // closure #1 in readBoxRead() // CHECK-LABEL: sil private @_T027access_enforcement_noescape11readBoxReadyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape11readBoxReadyyFyycfU_' // closure #2 in readBoxRead() // CHECK-LABEL: sil private @_T027access_enforcement_noescape11readBoxReadyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // FIXME-CHECK-LABEL: sil private @_T027access_enforcement_noescape11readBoxReadyyFyycfU0_ : $@convention(thin) (@owned { var Int }) -> () { // FIXME-CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape11readBoxReadyyFyycfU0_' // Error: cannout capture inout. // // func inoutReadReadBox(x: inout Int) { // let c = { _ = x } // doTwo({ _ = x }, c) // } // Allow aliased noescape read + write. func readWrite() { var x = 3 // Around the call: [modify] [static] // Inside closure 1: [read] [static] // Inside closure 2: [modify] [static] doTwo({ _ = x }, { x = 42 }) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape9readWriteyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape9readWriteyyF' // closure #1 in readWrite() // CHECK-LABEL: sil private @_T027access_enforcement_noescape9readWriteyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [read] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape9readWriteyyFyycfU_' // closure #2 in readWrite() // CHECK-LABEL: sil private @_T027access_enforcement_noescape9readWriteyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape9readWriteyyFyycfU0_' // Allow aliased noescape read + write of an `inout` arg. func inoutReadWrite(x: inout Int) { // Around the call: [modify] [static] // Inside closure 1: [read] [static] // Inside closure 2: [modify] [static] doTwo({ _ = x }, { x = 3 }) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape14inoutReadWriteySiz1x_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14inoutReadWriteySiz1x_tF' // closure #1 in inoutReadWrite(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape14inoutReadWriteySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [read] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14inoutReadWriteySiz1x_tFyycfU_' // closure #2 in inoutReadWrite(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape14inoutReadWriteySiz1x_tFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14inoutReadWriteySiz1x_tFyycfU0_' // FIXME: Trap on aliased boxed read + noescape write. // // Note: There's no actual exclusivity danger here, because `c` is // passed to a noescape argument and is never itself // captured. However, SILGen conservatively assumes that the // assignment `let c =` captures the closure. Later we could refine // the rules to recognize obviously nonescpaping closures. func readBoxWrite() { var x = 3 let c = { _ = x } // Inside may-escape closure `c`: [read] [dynamic] // Inside never-escape closure: [modify] [dynamic] doTwo(c, { x = 42 }) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape12readBoxWriteyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape12readBoxWriteyyF' // closure #1 in readBoxWrite() // CHECK-LABEL: sil private @_T027access_enforcement_noescape12readBoxWriteyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape12readBoxWriteyyFyycfU_' // closure #2 in readBoxWrite() // CHECK-LABEL: sil private @_T027access_enforcement_noescape12readBoxWriteyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // FIXME-CHECK-LABEL: sil private @_T027access_enforcement_noescape12readBoxWriteyyFyycfU0_ : $@convention(thin) (@owned { var Int }) -> () { // FIXME-CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape12readBoxWriteyyFyycfU0_' // Error: cannout capture inout. // func inoutReadBoxWrite(x: inout Int) { // let c = { _ = x } // doTwo({ x = 42 }, c) // } // FIXME: Trap on aliased noescape read + boxed write. // // See the note above. func readWriteBox() { var x = 3 let c = { x = 42 } // Inside may-escape closure `c`: [modify] [dynamic] // Inside never-escape closure: [read] [dynamic] doTwo({ _ = x }, c) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape12readWriteBoxyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // CHECK-NOT: begin_access // CHECK: apply %{{.*}}([[PA2]], [[PA1]]) // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape12readWriteBoxyyF' // closure #1 in readWriteBox() // CHECK-LABEL: sil private @_T027access_enforcement_noescape12readWriteBoxyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape12readWriteBoxyyFyycfU_' // closure #2 in readWriteBox() // CHECK-LABEL: sil private @_T027access_enforcement_noescape12readWriteBoxyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // FIXME-CHECK-LABEL: sil private @_T027access_enforcement_noescape12readWriteBoxyyFyycfU0_ : $@convention(thin) ((@owned { var Int }) -> () { // FIXME-CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape12readWriteBoxyyFyycfU0_' // Error: cannout capture inout. // func inoutReadWriteBox(x: inout Int) { // let c = { x = 42 } // doTwo({ _ = x }, c) // } // Error: noescape read + write inout. func readWriteInout() { var x = 3 // Around the call: [read] [static] // Around the call: [modify] [static] // Error // Inside closure: [modify] [static] doOneInout({ _ = x }, &x) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape14readWriteInoutyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // FIXME-CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: apply %{{.*}}([[PA1]], [[ACCESS2]]) // FIXME-CHECK: end_access [[ACCESS2]] // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14readWriteInoutyyF' // closure #1 in readWriteInout() // CHECK-LABEL: sil private @_T027access_enforcement_noescape14readWriteInoutyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [read] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape14readWriteInoutyyFyycfU_' // Error: noescape read + write inout of an inout. func inoutReadWriteInout(x: inout Int) { // Around the call: [read] [static] // Around the call: [modify] [static] // Error // Inside closure: [modify] [static] doOneInout({ _ = x }, &x) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape19inoutReadWriteInoutySiz1x_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // FIXME-CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: apply %{{.*}}([[PA1]], [[ACCESS2]]) // FIXME-CHECK: end_access [[ACCESS2]] // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape19inoutReadWriteInoutySiz1x_tF' // closure #1 in inoutReadWriteInout(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape19inoutReadWriteInoutySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [read] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [read] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape19inoutReadWriteInoutySiz1x_tFyycfU_' // Trap on boxed read + write inout. // FIXME: Passing a captured var as inout needs dynamic enforcement. func readBoxWriteInout() { var x = 3 let c = { _ = x } // Around the call: [modify] [dynamic] // Inside closure: [read] [dynamic] doOneInout(c, &x) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape17readBoxWriteInoutyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %0 : $*Int // FIXME-CHECK: apply %{{.*}}([[PA1]], [[ACCESS]]) // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape17readBoxWriteInoutyyF' // closure #1 in readBoxWriteInout() // CHECK-LABEL: sil private @_T027access_enforcement_noescape17readBoxWriteInoutyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape17readBoxWriteInoutyyFyycfU_' // Error: inout cannot be captured. // func inoutReadBoxWriteInout(x: inout Int) { // let c = { _ = x } // doOneInout(c, &x) // } // Allow aliased noescape write + write. func writeWrite() { var x = 3 // Around the call: [modify] [static] // Inside closure 1: [modify] [static] // Inside closure 2: [modify] [static] doTwo({ x = 42 }, { x = 87 }) _ = x } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape10writeWriteyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape10writeWriteyyF' // closure #1 in writeWrite() // CHECK-LABEL: sil private @_T027access_enforcement_noescape10writeWriteyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape10writeWriteyyFyycfU_' // closure #2 in writeWrite() // CHECK-LABEL: sil private @_T027access_enforcement_noescape10writeWriteyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape10writeWriteyyFyycfU0_' // Allow aliased noescape write + write of an `inout` arg. func inoutWriteWrite(x: inout Int) { // Around the call: [modify] [static] // Inside closure 1: [modify] [static] // Inside closure 2: [modify] [static] doTwo({ x = 42}, { x = 87 }) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tF' // closure #1 in inoutWriteWrite(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tFyycfU_' // closure #2 in inoutWriteWrite(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE0ySiz1x_tFyycfU0_' // FIXME: Trap on aliased boxed write + noescape write. // // See the note above. func writeWriteBox() { var x = 3 let c = { x = 87 } // Inside may-escape closure `c`: [modify] [dynamic] // Inside never-escape closure: [modify] [dynamic] doTwo({ x = 42 }, c) _ = x } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape13writeWriteBoxyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // CHECK: [[PA2:%.*]] = partial_apply // FIXME-CHECK-NOT: begin_access // FIXME-CHECK: apply %{{.*}}([[PA1]], [[PA2]]) // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape13writeWriteBoxyyF' // closure #1 in writeWriteBox() // CHECK-LABEL: sil private @_T027access_enforcement_noescape13writeWriteBoxyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape13writeWriteBoxyyFyycfU_' // closure #2 in writeWriteBox() // CHECK-LABEL: sil private @_T027access_enforcement_noescape13writeWriteBoxyyFyycfU0_ : $@convention(thin) (@inout_aliasable Int) -> () { // FIXME-CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape13writeWriteBoxyyFyycfU0_' // Error: inout cannot be captured. // func inoutWriteWriteBox(x: inout Int) { // let c = { x = 87 } // doTwo({ x = 42 }, c) // } // Error: on noescape write + write inout. func writeWriteInout() { var x = 3 // Around the call: [modify] [static] // Around the call: [modify] [static] // Error // Inside closure: [modify] [static] doOneInout({ x = 42 }, &x) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape15writeWriteInoutyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // FIXME-CHECK: [[ACCESS1:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: apply %{{.*}}([[PA1]], [[ACCESS2]]) // FIXME-CHECK: end_access [[ACCESS2]] // FIXME-CHECK: end_access [[ACCESS1]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape15writeWriteInoutyyF' // closure #1 in writeWriteInout() // CHECK-LABEL: sil private @_T027access_enforcement_noescape15writeWriteInoutyyFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape15writeWriteInoutyyFyycfU_' // Error: on noescape write + write inout. func inoutWriteWriteInout(x: inout Int) { // Around the call: [modify] [static] // Around the call: [modify] [static] // Error // Inside closure: [modify] [static] doOneInout({ x = 42 }, &x) } // inoutWriteWriteInout(x:) // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape010inoutWriteE5InoutySiz1x_tF : $@convention(thin) (@inout Int) -> () { // CHECK: [[PA1:%.*]] = partial_apply // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: [[ACCESS2:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: apply %{{.*}}([[PA1]], [[ACCESS2]]) // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: // end sil function '_T027access_enforcement_noescape010inoutWriteE5InoutySiz1x_tF' // closure #1 in inoutWriteWriteInout(x:) // CHECK-LABEL: sil private @_T027access_enforcement_noescape010inoutWriteE5InoutySiz1x_tFyycfU_ : $@convention(thin) (@inout_aliasable Int) -> () { // CHECK-NOT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [static] %0 : $*Int // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape010inoutWriteE5InoutySiz1x_tFyycfU_' // Trap on boxed write + write inout. // FIXME: Passing a captured var as inout needs dynamic enforcement. func writeBoxWriteInout() { var x = 3 let c = { x = 42 } // Around the call: [modify] [dynamic] // Inside closure: [modify] [dynamic] doOneInout(c, &x) } // CHECK-LABEL: sil hidden @_T027access_enforcement_noescape18writeBoxWriteInoutyyF : $@convention(thin) () -> () { // CHECK: [[PA1:%.*]] = partial_apply // FIXME-CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] %0 : $*Int // FIXME-CHECK: apply %{{.*}}([[PA1]], [[ACCESS]]) // FIXME-CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape18writeBoxWriteInoutyyF' // closure #1 in writeBoxWriteInout() // CHECK-LABEL: sil private @_T027access_enforcement_noescape18writeBoxWriteInoutyyFyycfU_ : $@convention(thin) (@owned { var Int }) -> () { // CHECK: [[ADDR:%.*]] = project_box %0 : ${ var Int }, 0 // CHECK: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // CHECK: end_access [[ACCESS]] // CHECK-LABEL: } // end sil function '_T027access_enforcement_noescape18writeBoxWriteInoutyyFyycfU_' // Error: Cannot capture inout // func inoutWriteBoxWriteInout(x: inout Int) { // let c = { x = 42 } // doOneInout(c, &x) // }
apache-2.0
1acd77f716ec63faf67a79e5852aae0b
46.239714
151
0.658159
3.270622
false
false
false
false
nirmankarta/eddystone
tools/ios-eddystone-scanner-sample/EddystoneScannerSampleSwift/Eddystone.swift
2
8345
// Copyright 2015-2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import CoreBluetooth /// /// BeaconID /// /// Uniquely identifies an Eddystone compliant beacon. /// class BeaconID : NSObject { enum BeaconType { case Eddystone // 10 bytes namespace + 6 bytes instance = 16 byte ID case EddystoneEID // 8 byte ID } let beaconType: BeaconType /// /// The raw beaconID data. This is typically printed out in hex format. /// let beaconID: [UInt8] private init(beaconType: BeaconType!, beaconID: [UInt8]) { self.beaconID = beaconID self.beaconType = beaconType } override var description: String { if self.beaconType == BeaconType.Eddystone || self.beaconType == BeaconType.EddystoneEID { let hexid = hexBeaconID(self.beaconID) return "BeaconID beacon: \(hexid)" } else { return "BeaconID with invalid type (\(beaconType))" } } private func hexBeaconID(beaconID: [UInt8]) -> String { var retval = "" for byte in beaconID { var s = String(byte, radix:16, uppercase: false) if s.characters.count == 1 { s = "0" + s } retval += s } return retval } } func ==(lhs: BeaconID, rhs: BeaconID) -> Bool { if lhs == rhs { return true; } else if lhs.beaconType == rhs.beaconType && rhs.beaconID == rhs.beaconID { return true; } return false; } /// /// BeaconInfo /// /// Contains information fully describing a beacon, including its beaconID, transmission power, /// RSSI, and possibly telemetry information. /// class BeaconInfo : NSObject { static let EddystoneUIDFrameTypeID: UInt8 = 0x00 static let EddystoneURLFrameTypeID: UInt8 = 0x10 static let EddystoneTLMFrameTypeID: UInt8 = 0x20 static let EddystoneEIDFrameTypeID: UInt8 = 0x30 enum EddystoneFrameType { case UnknownFrameType case UIDFrameType case URLFrameType case TelemetryFrameType case EIDFrameType var description: String { switch self { case .UnknownFrameType: return "Unknown Frame Type" case .UIDFrameType: return "UID Frame" case .URLFrameType: return "URL Frame" case .TelemetryFrameType: return "TLM Frame" case .EIDFrameType: return "EID Frame" } } } let beaconID: BeaconID let txPower: Int let RSSI: Int let telemetry: NSData? private init(beaconID: BeaconID, txPower: Int, RSSI: Int, telemetry: NSData?) { self.beaconID = beaconID self.txPower = txPower self.RSSI = RSSI self.telemetry = telemetry } class func frameTypeForFrame(advertisementFrameList: [NSObject : AnyObject]) -> EddystoneFrameType { let uuid = CBUUID(string: "FEAA") if let frameData = advertisementFrameList[uuid] as? NSData { if frameData.length > 1 { let count = frameData.length var frameBytes = [UInt8](count: count, repeatedValue: 0) frameData.getBytes(&frameBytes, length: count) if frameBytes[0] == EddystoneUIDFrameTypeID { return EddystoneFrameType.UIDFrameType } else if frameBytes[0] == EddystoneTLMFrameTypeID { return EddystoneFrameType.TelemetryFrameType } else if frameBytes[0] == EddystoneEIDFrameTypeID { return EddystoneFrameType.EIDFrameType } else if frameBytes[0] == EddystoneURLFrameTypeID { return EddystoneFrameType.URLFrameType } } } return EddystoneFrameType.UnknownFrameType } class func telemetryDataForFrame(advertisementFrameList: [NSObject : AnyObject]!) -> NSData? { return advertisementFrameList[CBUUID(string: "FEAA")] as? NSData } /// /// Unfortunately, this can't be a failable convenience initialiser just yet because of a "bug" /// in the Swift compiler — it can't tear-down partially initialised objects, so we'll have to /// wait until this gets fixed. For now, class method will do. /// class func beaconInfoForUIDFrameData(frameData: NSData, telemetry: NSData?, RSSI: Int) -> BeaconInfo? { if frameData.length > 1 { let count = frameData.length var frameBytes = [UInt8](count: count, repeatedValue: 0) frameData.getBytes(&frameBytes, length: count) if frameBytes[0] != EddystoneUIDFrameTypeID { NSLog("Unexpected non UID Frame passed to BeaconInfoForUIDFrameData.") return nil } else if frameBytes.count < 18 { NSLog("Frame Data for UID Frame unexpectedly truncated in BeaconInfoForUIDFrameData.") } let txPower = Int(Int8(bitPattern:frameBytes[1])) let beaconID: [UInt8] = Array(frameBytes[2..<18]) let bid = BeaconID(beaconType: BeaconID.BeaconType.Eddystone, beaconID: beaconID) return BeaconInfo(beaconID: bid, txPower: txPower, RSSI: RSSI, telemetry: telemetry) } return nil } class func beaconInfoForEIDFrameData(frameData: NSData, telemetry: NSData?, RSSI: Int) -> BeaconInfo? { if frameData.length > 1 { let count = frameData.length var frameBytes = [UInt8](count: count, repeatedValue: 0) frameData.getBytes(&frameBytes, length: count) if frameBytes[0] != EddystoneEIDFrameTypeID { NSLog("Unexpected non EID Frame passed to BeaconInfoForEIDFrameData.") return nil } else if frameBytes.count < 10 { NSLog("Frame Data for EID Frame unexpectedly truncated in BeaconInfoForEIDFrameData.") } let txPower = Int(Int8(bitPattern:frameBytes[1])) let beaconID: [UInt8] = Array(frameBytes[2..<10]) let bid = BeaconID(beaconType: BeaconID.BeaconType.EddystoneEID, beaconID: beaconID) return BeaconInfo(beaconID: bid, txPower: txPower, RSSI: RSSI, telemetry: telemetry) } return nil } class func parseURLFromFrame(frameData: NSData) -> NSURL? { if frameData.length > 0 { let count = frameData.length var frameBytes = [UInt8](count: count, repeatedValue: 0) frameData.getBytes(&frameBytes, length: count) if let URLPrefix = URLPrefixFromByte(frameBytes[2]) { var output = URLPrefix for i in 3..<frameBytes.count { if let encoded = encodedStringFromByte(frameBytes[i]) { output.appendContentsOf(encoded) } } return NSURL(string: output) } } return nil } override var description: String { switch self.beaconID.beaconType { case .Eddystone: return "Eddystone \(self.beaconID), txPower: \(self.txPower), RSSI: \(self.RSSI)" case .EddystoneEID: return "Eddystone EID \(self.beaconID), txPower: \(self.txPower), RSSI: \(self.RSSI)" } } class func URLPrefixFromByte(schemeID: UInt8) -> String? { switch schemeID { case 0x00: return "http://www." case 0x01: return "https://www." case 0x02: return "http://" case 0x03: return "https://" default: return nil } } class func encodedStringFromByte(charVal: UInt8) -> String? { switch charVal { case 0x00: return ".com/" case 0x01: return ".org/" case 0x02: return ".edu/" case 0x03: return ".net/" case 0x04: return ".info/" case 0x05: return ".biz/" case 0x06: return ".gov/" case 0x07: return ".com" case 0x08: return ".org" case 0x09: return ".edu" case 0x0a: return ".net" case 0x0b: return ".info" case 0x0c: return ".biz" case 0x0d: return ".gov" default: return String(data: NSData(bytes: [ charVal ] as [UInt8], length: 1), encoding: NSUTF8StringEncoding) } } }
apache-2.0
bd9337105877e9d3fb69330ac9cdc3c3
28.273684
97
0.644972
4.140447
false
false
false
false
revealapp/Revert
Shared/Sources/RevertItems.swift
1
1834
// // Copyright © 2015 Itty Bitty Apps. All rights reserved. import Foundation enum RevertItems: String { case capitalCities = "CountriesCapitals" case alert = "AlertItems" case home = "HomeItems" case control = "ControlItems" case mapLocations = "MapLocations" case layerProperties = "LayerPropertiesItems" case view = "ViewItems" case whatsNew = "NewItems" func data<T: Decodable>() -> T { do { let data = try Data(contentsOf: self.URL) let decoder = PropertyListDecoder() let decodedData = try decoder.decode(T.self, from: data) return decodedData } catch { fatalError(self.invalidContentError) } } // MARK: Private private static let fileExtension = "plist" private static let subfolder = "Data" private var invalidContentError: String { return "Invalid content: \(self.rawValue).\(type(of: self).fileExtension)" } private var invalidFileError: String { return "Invalid file: No common or platform-specific \(self.rawValue) files exist" } private var URL: Foundation.URL { var URL: Foundation.URL? { let commonPath = "\(type(of: self).subfolder)/\(self.rawValue)" let platformPath = "\(commonPath)\(type(of: self).platformSuffix)" if let platformURL = Bundle.main.url(forResource: platformPath, withExtension: type(of: self).fileExtension) { return platformURL } else { let commonURL = Bundle.main.url(forResource: commonPath, withExtension: type(of: self).fileExtension) return commonURL } } guard let fileURL = URL else { fatalError(self.invalidFileError) } return fileURL } } extension RevertItems { #if os(iOS) private static let platformSuffix = "_iOS" #endif #if os(tvOS) private static let platformSuffix = "_tvOS" #endif }
bsd-3-clause
f79b3a1d6ea44abc726e5eadc09529c4
25.565217
116
0.675396
4.100671
false
false
false
false
kimar/himbo
himbo/SphereMenu.swift
1
8217
// // SphereMenu.swift // Sphere Menu // // Created by Camilo Morales on 10/21/14. // Copyright (c) 2014 Camilo Morales. All rights reserved. // import Foundation import UIKit @objc protocol SphereMenuDelegate{ func sphereDidSelected(index:Int) @objc optional func sphereDidOpen() @objc optional func sphereDidClose() } // fixme: make this a struct class SphereMenu:UIView, UICollisionBehaviorDelegate{ let kItemInitTag:Int = 1001 let kAngleOffset:CGFloat = CGFloat(Double.pi / 2) / 2.0 let kSphereLength:CGFloat = 80 let kSphereDamping:Float = 1.0 var delegate:SphereMenuDelegate? var count:Int = 0 var images:Array<UIImage>? var items:Array<UIImageView>? var positions:Array<NSValue>? // animator and behaviors var animator:UIDynamicAnimator? var collision:UICollisionBehavior? var itemBehavior:UIDynamicItemBehavior? var snaps:Array<UISnapBehavior>? var bumper:UIDynamicItem? var expanded:Bool? required init(startPoint:CGPoint, submenuImages:Array<UIImage>){ self.init() self.images = submenuImages; self.count = self.images!.count; self.center = startPoint; } required init?(coder aDecoder: NSCoder) { self.count = 0; self.images = Array() self.init() } required override init(frame: CGRect) { self.count = 0; self.images = Array() super.init(frame: frame) } override func didMoveToSuperview() { self.commonSetup() } func commonSetup() { self.items = Array() self.positions = Array() self.snaps = Array() guard let images = images else { return } var i = 0 // setup the items for image in images { let item = UIImageView(image: image) item.tag = kItemInitTag + i; item.isUserInteractionEnabled = true; self.superview?.addSubview(item) let position = self.centerForSphereAtIndex(index: i) item.center = self.center; self.positions?.append(NSValue(cgPoint: position)) let tap = UITapGestureRecognizer(target: self, action: #selector(SphereMenu.tapped(gesture:))) item.addGestureRecognizer(tap) // let pan = UIPanGestureRecognizer(target: self, action: "panned:") // item.addGestureRecognizer(pan) item.alpha = 0.0 self.items?.append(item) i += 1 } self.superview?.bringSubview(toFront: self) // setup animator and behavior self.animator = UIDynamicAnimator(referenceView: self.superview!) self.collision = UICollisionBehavior(items: self.items!) self.collision?.translatesReferenceBoundsIntoBoundary = true; self.collision?.collisionDelegate = self; guard let items = items else { return } for item in items { let snap = UISnapBehavior(item: item, snapTo: self.center) snap.damping = CGFloat(kSphereDamping) self.snaps?.append(snap) } self.itemBehavior = UIDynamicItemBehavior(items: self.items!) self.itemBehavior?.allowsRotation = false; self.itemBehavior?.elasticity = 0.25; self.itemBehavior?.density = 0.5; self.itemBehavior?.angularResistance = 4; self.itemBehavior?.resistance = 10; self.itemBehavior?.elasticity = 0.8; self.itemBehavior?.friction = 0.5; } func centerForSphereAtIndex(index:Int) -> CGPoint{ let firstAngle:CGFloat = CGFloat(Double.pi) /*+ (CGFloat(M_PI_2) - kAngleOffset)*/ + CGFloat(index) * kAngleOffset let startPoint = self.center let x = startPoint.x + cos(firstAngle) * kSphereLength; let y = startPoint.y + sin(firstAngle) * kSphereLength; let position = CGPoint(x: x, y: y); return position; } func startTapped(gesture:UITapGestureRecognizer){ self.animator?.removeBehavior(self.collision!) self.animator?.removeBehavior(self.itemBehavior!) toggle() } func toggle() { if (self.expanded == true) { self.shrinkSubmenu() self.delegate?.sphereDidClose?() } else { self.expandSubmenu() self.delegate?.sphereDidOpen?() } } @objc func tapped(gesture:UITapGestureRecognizer) { var tag = gesture.view?.tag tag? -= Int(kItemInitTag) self.delegate?.sphereDidSelected(index: tag!) self.shrinkSubmenu() } func panned(gesture:UIPanGestureRecognizer) { let touchedView = gesture.view; if (gesture.state == UIGestureRecognizerState.began) { self.animator?.removeBehavior(self.itemBehavior!) self.animator?.removeBehavior(self.collision!) self.removeSnapBehaviors() } else if (gesture.state == UIGestureRecognizerState.changed) { touchedView?.center = gesture.location(in: self.superview) } else if (gesture.state == UIGestureRecognizerState.ended) { self.bumper = touchedView; self.animator?.addBehavior(self.collision!) let index = self.indexOfItemInArray(dataArray: self.items!, item: touchedView!) if (index >= 0) { self.snapToPostionsWithIndex(index: index) } } } func indexOfItemInArray(dataArray:Array<UIImageView>, item:AnyObject) -> Int{ var index = -1 var i = 0 for thing in dataArray { if thing === item { index = i break } i += 1 } return index } func shrinkSubmenu(){ self.animator?.removeBehavior(self.collision!) for index in 0..<self.count { self.snapToStartWithIndex(index: index) } self.expanded = false; } func expandSubmenu(){ for index in 0..<self.count { self.snapToPostionsWithIndex(index: index) } self.expanded = true; } func snapToStartWithIndex(index:Int) { let item = self.items![index] UIView.animate(withDuration: 0.3, animations: { () -> Void in item.alpha = 0.0 }) let snap = UISnapBehavior(item: item, snapTo: self.center) snap.damping = CGFloat(kSphereDamping) let snapToRemove = self.snaps![index]; self.snaps![index] = snap; self.animator?.removeBehavior(snapToRemove) self.animator?.addBehavior(snap) } func snapToPostionsWithIndex(index:Int) { let positionValue:AnyObject = self.positions![index]; let position = positionValue.cgPointValue let item = self.items![index] UIView.animate(withDuration: 0.3, animations: { () -> Void in item.alpha = 1.0 }) let snap = UISnapBehavior(item: item, snapTo: position!) snap.damping = CGFloat(kSphereDamping) let snapToRemove = self.snaps![index]; self.snaps![index] = snap; self.animator?.removeBehavior(snapToRemove) self.animator?.addBehavior(snap) } func removeSnapBehaviors() { for index in 0...self.snaps!.count { self.animator?.removeBehavior(self.snaps![index]) } } func collisionBehavior(_ behavior: UICollisionBehavior, endedContactFor item1: UIDynamicItem, with item2: UIDynamicItem) { self.animator?.addBehavior(self.itemBehavior!) if (item1 !== self.bumper){ let index = self.indexOfItemInArray(dataArray: self.items!, item: item1) if (index >= 0) { self.snapToPostionsWithIndex(index: index) } } if (item2 !== self.bumper){ let index = self.indexOfItemInArray(dataArray: self.items!, item: item2) if (index >= 0) { self.snapToPostionsWithIndex(index: index) } } } }
mit
9b6ceb62187e5dc4802314f8224fa85a
30.362595
126
0.592674
4.453659
false
false
false
false
evermeer/PassportScanner
Pods/EVGPUImage2/framework/Source/iOS/PictureInput.swift
1
8199
import OpenGLES import UIKit public class PictureInput: ImageSource { public let targets = TargetContainer() var imageFramebuffer:Framebuffer! var hasProcessedImage:Bool = false public init(image:CGImage, smoothlyScaleOutput:Bool = false, orientation:ImageOrientation = .portrait) { // TODO: Dispatch this whole thing asynchronously to move image loading off main thread let widthOfImage = GLint(image.width) let heightOfImage = GLint(image.height) // If passed an empty image reference, CGContextDrawImage will fail in future versions of the SDK. guard((widthOfImage > 0) && (heightOfImage > 0)) else { fatalError("Tried to pass in a zero-sized image") } var widthToUseForTexture = widthOfImage var heightToUseForTexture = heightOfImage var shouldRedrawUsingCoreGraphics = false // For now, deal with images larger than the maximum texture size by resizing to be within that limit let scaledImageSizeToFitOnGPU = GLSize(sharedImageProcessingContext.sizeThatFitsWithinATextureForSize(Size(width:Float(widthOfImage), height:Float(heightOfImage)))) if ((scaledImageSizeToFitOnGPU.width != widthOfImage) && (scaledImageSizeToFitOnGPU.height != heightOfImage)) { widthToUseForTexture = scaledImageSizeToFitOnGPU.width heightToUseForTexture = scaledImageSizeToFitOnGPU.height shouldRedrawUsingCoreGraphics = true } if (smoothlyScaleOutput) { // In order to use mipmaps, you need to provide power-of-two textures, so convert to the next largest power of two and stretch to fill let powerClosestToWidth = ceil(log2(Float(widthToUseForTexture))) let powerClosestToHeight = ceil(log2(Float(heightToUseForTexture))) widthToUseForTexture = GLint(round(pow(2.0, powerClosestToWidth))) heightToUseForTexture = GLint(round(pow(2.0, powerClosestToHeight))) shouldRedrawUsingCoreGraphics = true } var imageData:UnsafeMutablePointer<GLubyte>! var dataFromImageDataProvider:CFData! var format = GL_BGRA if (!shouldRedrawUsingCoreGraphics) { /* Check that the memory layout is compatible with GL, as we cannot use glPixelStore to * tell GL about the memory layout with GLES. */ if ((image.bytesPerRow != image.width * 4) || (image.bitsPerPixel != 32) || (image.bitsPerComponent != 8)) { shouldRedrawUsingCoreGraphics = true } else { /* Check that the bitmap pixel format is compatible with GL */ let bitmapInfo = image.bitmapInfo if (bitmapInfo.contains(.floatComponents)) { /* We don't support float components for use directly in GL */ shouldRedrawUsingCoreGraphics = true } else { let alphaInfo = CGImageAlphaInfo(rawValue:bitmapInfo.rawValue & CGBitmapInfo.alphaInfoMask.rawValue) if (bitmapInfo.contains(.byteOrder32Little)) { /* Little endian, for alpha-first we can use this bitmap directly in GL */ if ((alphaInfo != CGImageAlphaInfo.premultipliedFirst) && (alphaInfo != CGImageAlphaInfo.first) && (alphaInfo != CGImageAlphaInfo.noneSkipFirst)) { shouldRedrawUsingCoreGraphics = true } } else if ((bitmapInfo.contains(CGBitmapInfo())) || (bitmapInfo.contains(.byteOrder32Big))) { /* Big endian, for alpha-last we can use this bitmap directly in GL */ if ((alphaInfo != CGImageAlphaInfo.premultipliedLast) && (alphaInfo != CGImageAlphaInfo.last) && (alphaInfo != CGImageAlphaInfo.noneSkipLast)) { shouldRedrawUsingCoreGraphics = true } else { /* Can access directly using GL_RGBA pixel format */ format = GL_RGBA } } } } } // CFAbsoluteTime elapsedTime, startTime = CFAbsoluteTimeGetCurrent(); if (shouldRedrawUsingCoreGraphics) { // For resized or incompatible image: redraw imageData = UnsafeMutablePointer<GLubyte>.allocate(capacity:Int(widthToUseForTexture * heightToUseForTexture) * 4) let genericRGBColorspace = CGColorSpaceCreateDeviceRGB() let imageContext = CGContext(data: imageData, width: Int(widthToUseForTexture), height: Int(heightToUseForTexture), bitsPerComponent: 8, bytesPerRow: Int(widthToUseForTexture) * 4, space: genericRGBColorspace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue) // CGContextSetBlendMode(imageContext, kCGBlendModeCopy); // From Technical Q&A QA1708: http://developer.apple.com/library/ios/#qa/qa1708/_index.html imageContext?.draw(image, in:CGRect(x:0.0, y:0.0, width:CGFloat(widthToUseForTexture), height:CGFloat(heightToUseForTexture))) } else { // Access the raw image bytes directly dataFromImageDataProvider = image.dataProvider?.data imageData = UnsafeMutablePointer<GLubyte>(mutating:CFDataGetBytePtr(dataFromImageDataProvider)) } sharedImageProcessingContext.runOperationSynchronously{ do { // TODO: Alter orientation based on metadata from photo self.imageFramebuffer = try Framebuffer(context:sharedImageProcessingContext, orientation:orientation, size:GLSize(width:widthToUseForTexture, height:heightToUseForTexture), textureOnly:true) } catch { fatalError("ERROR: Unable to initialize framebuffer of size (\(widthToUseForTexture), \(heightToUseForTexture)) with error: \(error)") } glBindTexture(GLenum(GL_TEXTURE_2D), self.imageFramebuffer.texture) if (smoothlyScaleOutput) { glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR_MIPMAP_LINEAR) } glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, widthToUseForTexture, heightToUseForTexture, 0, GLenum(format), GLenum(GL_UNSIGNED_BYTE), imageData) if (smoothlyScaleOutput) { glGenerateMipmap(GLenum(GL_TEXTURE_2D)) } glBindTexture(GLenum(GL_TEXTURE_2D), 0) } if (shouldRedrawUsingCoreGraphics) { imageData.deallocate() } } public convenience init(image:UIImage, smoothlyScaleOutput:Bool = false, orientation:ImageOrientation = .portrait) { self.init(image:image.cgImage!, smoothlyScaleOutput:smoothlyScaleOutput, orientation:orientation) } public convenience init(imageName:String, smoothlyScaleOutput:Bool = false, orientation:ImageOrientation = .portrait) { guard let image = UIImage(named:imageName) else { fatalError("No such image named: \(imageName) in your application bundle") } self.init(image:image.cgImage!, smoothlyScaleOutput:smoothlyScaleOutput, orientation:orientation) } public func processImage(synchronously:Bool = false) { if synchronously { sharedImageProcessingContext.runOperationSynchronously{ self.updateTargetsWithFramebuffer(self.imageFramebuffer) self.hasProcessedImage = true } } else { sharedImageProcessingContext.runOperationAsynchronously{ self.updateTargetsWithFramebuffer(self.imageFramebuffer) self.hasProcessedImage = true } } } public func transmitPreviousImage(to target:ImageConsumer, atIndex:UInt) { if hasProcessedImage { imageFramebuffer.lock() target.newFramebufferAvailable(imageFramebuffer, fromSourceIndex:atIndex) } } }
bsd-3-clause
c9df805d35857179a296e276a0148e7b
54.398649
322
0.643493
5.225621
false
false
false
false
YoungGary/DYTV
DouyuTV/DouyuTV/Class/First(首页)/View/CycleView.swift
1
3181
// // CycleView.swift // DouyuTV // // Created by YOUNG on 2017/3/17. // Copyright © 2017年 Young. All rights reserved. // 推荐页的最上方轮播图 import UIKit let kcycleCellID = "cycle" class CycleView: UIView , UICollectionViewDataSource ,UICollectionViewDelegate{ @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var pageControl: UIPageControl! var timer : Timer? //model var modelArr : [CycleModel]?{ didSet{ collectionView.reloadData() pageControl.numberOfPages = modelArr?.count ?? 0 } } class func loadViewWithNib() -> CycleView{ return (Bundle.main.loadNibNamed("CycleView", owner: nil, options: nil)?.first) as! CycleView } override func awakeFromNib() { super.awakeFromNib() self.autoresizingMask = UIViewAutoresizing() collectionView.dataSource = self collectionView.delegate = self collectionView.register(UINib(nibName: "CycleCollectionViewCell",bundle: nil), forCellWithReuseIdentifier: kcycleCellID) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true //timer addTimer() } override func layoutSubviews() { super.layoutSubviews() let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = self.bounds.size layout.scrollDirection = .horizontal layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 } } extension CycleView{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return( modelArr?.count ?? 0) * 10000 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kcycleCellID, for: indexPath) as! CycleCollectionViewCell guard let models = modelArr else { return cell } cell.setmodel = models[indexPath.item%(modelArr?.count ?? 1)] return cell } func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { pageControl.currentPage = Int(scrollView.contentOffset.x/scrollView.frame.size.width)%(modelArr?.count ?? 1) } } extension CycleView{ func addTimer(){ timer = Timer.scheduledTimer(timeInterval: 4.0, target: self, selector: #selector(self.scroll), userInfo: nil , repeats: true) RunLoop.current.add(timer!, forMode: RunLoopMode.commonModes) } func removeTimer(){ timer?.invalidate() timer = nil } func scroll() -> () { let offset = collectionView.contentOffset.x let current = offset + collectionView.bounds.width collectionView.setContentOffset(CGPoint(x:current ,y:0) , animated: true) pageControl.currentPage = Int(collectionView.contentOffset.x/collectionView.frame.size.width)%(modelArr?.count ?? 1) } }
mit
e833370a9c1008a1f578fe19f58db50e
27.45045
134
0.655478
5.143322
false
false
false
false