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
Macostik/StreamView
Source/StreamView.swift
1
12578
// // StreamView.swift // StreamView // // Created by Yura Granchenko on 4/11/17. // Copyright © 2017 Yura Granchenko. All rights reserved. // import Foundation import UIKit public enum ScrollDirection { case Unknown, Up, Down } public enum PositionScroll { case top, middle, bottom } var StreamViewCommonLocksChanged: String = "StreamViewCommonLocksChanged" public protocol StreamViewDataSource: class { func numberOfSections() -> Int func numberOfItemsIn(section: Int) -> Int func metricsAt(position: StreamPosition) -> [StreamMetricsProtocol] func didLayoutItem(item: StreamItem) func entryBlockForItem(item: StreamItem) -> ((StreamItem) -> Any?)? func didChangeContentSize(oldContentSize: CGSize) func didLayout() func headerMetricsIn(section: Int) -> [StreamMetricsProtocol] func footerMetricsIn(section: Int) -> [StreamMetricsProtocol] } public extension StreamViewDataSource { func numberOfSections() -> Int { return 1 } func didLayoutItem(item: StreamItem) { } func entryBlockForItem(item: StreamItem) -> ((StreamItem) -> Any?)? { return nil } func didChangeContentSize(oldContentSize: CGSize) { } func didLayout() { } func headerMetricsIn(section: Int) -> [StreamMetricsProtocol] { return [] } func footerMetricsIn(section: Int) -> [StreamMetricsProtocol] { return [] } } public class StreamViewLayer: CALayer { public var didChangeBounds: (() -> Void)? override public var bounds: CGRect { didSet { didChangeBounds?() } } } public class StreamView: UIScrollView { override public class var layerClass: AnyClass { return StreamViewLayer.self } public var layout: StreamLayout = StreamLayout() private var reloadAfterUnlock = false public var locked = false public var forceShowPlaceholder = false static public var locked = false private var items = [StreamItem]() public weak var dataSource: StreamViewDataSource? public weak var placeholderView: PlaceholderView? { willSet { newValue?.isHidden = isHidden } } override public var isHidden: Bool { didSet { placeholderView?.isHidden = isHidden } } public var placeholderViewBlock: (() -> PlaceholderView)? override public var contentInset: UIEdgeInsets { didSet { if oldValue != contentInset && items.count == 1 && layout.finalized { reload() } } } deinit { delegate = nil NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: StreamViewCommonLocksChanged), object: nil) } private func setup() { (layer as! StreamViewLayer).didChangeBounds = { [unowned self] in self.didChangeBounds() } NotificationCenter.default.addObserver(self, selector: #selector(StreamView.locksChanged), name: NSNotification.Name(rawValue: StreamViewCommonLocksChanged), object: nil) } public var scrollDirectionChanged: ((_ isUp: Bool) -> Void)? public var directionHelper: ((_ isUp: Bool) -> Void)? public var trackScrollDirection = false public var direction: ScrollDirection = .Unknown { didSet { if direction != oldValue { scrollDirectionChanged?(direction == .Up) } } } public func didChangeBounds() { if trackScrollDirection && isTracking && (contentSize.height > height || direction == .Up) { direction = panGestureRecognizer.translation(in: self).y > 0 ? .Down : .Up directionHelper?(direction == .Up) } if layout.finalized { updateVisibility() } } override public init(frame: CGRect) { super.init(frame: frame) setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func clear() { placeholderView?.removeFromSuperview() for item in items { if let view = item.view { view.isHidden = true item.metrics.enqueueView(view: view) } } items.removeAll() } static public func lock() { locked = true } static public func unlock() { if locked { locked = false NotificationCenter.default.post(name: NSNotification.Name(rawValue: StreamViewCommonLocksChanged), object: nil) } } @objc public func locksChanged() { if !locked && !StreamView.locked && reloadAfterUnlock { reloadAfterUnlock = false reload() } } public func lock() { locked = true } public func unlock() { if locked { locked = false locksChanged() } } public func reload() { if locked || StreamView.locked { reloadAfterUnlock = true return } clear() layout.prepareLayout(streamView: self) addItems() if let item = items.last { changeContentSize(newContentSize: layout.contentSize(item: item, streamView: self)) } else { if layout.horizontal { changeContentSize(newContentSize: CGSize.init(width: 0, height: height)) } else { changeContentSize(newContentSize: CGSize.init(width: width, height: 0)) } } layout.finalizeLayout() _layoutSize = layoutSize(rect: layer.bounds) dataSource?.didLayout() updateVisibility() } private func changeContentSize(newContentSize: CGSize) { let oldContentSize = contentSize if newContentSize != oldContentSize { contentSize = newContentSize dataSource?.didChangeContentSize(oldContentSize: oldContentSize) } } private func addItems() { guard let dataSource = dataSource else { return } let layout = self.layout for section in 0..<dataSource.numberOfSections() { let position = StreamPosition(section: section, index: 0) for header in dataSource.headerMetricsIn(section: section) { _ = addItem(metrics: header, position: position) } for i in 0..<dataSource.numberOfItemsIn(section: section) { let position = StreamPosition(section: section, index: i) for metrics in dataSource.metricsAt(position: position) { if let item = addItem(dataSource: dataSource, metrics: metrics, position: position) { dataSource.didLayoutItem(item: item) } } } for footer in dataSource.footerMetricsIn(section: section) { _ = addItem(metrics: footer, position: position) } layout.prepareForNextSection() } if items.isEmpty || forceShowPlaceholder, let placeholder = placeholderViewBlock { let placeholderView = placeholder() self.placeholderView = placeholderView } } private func addItem(dataSource: StreamViewDataSource? = nil, metrics: StreamMetricsProtocol, position: StreamPosition) -> StreamItem? { let item = StreamItem(metrics: metrics, position: position) item.entryBlock = dataSource?.entryBlockForItem(item: item) metrics.modifyItem?(item) guard !item.hidden else { return nil } if let currentItem = items.last { item.previous = currentItem currentItem.next = item } layout.layoutItem(item: item, streamView: self) items.append(item) return item } private func updateVisibility() { updateVisibility(withRect: layer.bounds) } private var _layoutSize: CGFloat = 0 private func layoutSize(rect: CGRect) -> CGFloat { return layout.horizontal ? rect.height : rect.width } private func reloadIfNeeded(rect: CGRect) -> Bool { let size = layoutSize(rect: rect) if abs(_layoutSize - size) >= 1 { reload() return true } else { return false } } private func updateVisibility(withRect rect: CGRect) { guard !reloadIfNeeded(rect: rect) else { return } for item in items { let visible = item.frame.intersects(rect) if item.visible != visible { item.visible = visible if visible { let view = item.metrics.dequeueViewWithItem(item: item) if view.superview != self { insertSubview(view, at: 0) } view.isHidden = false } else if let view = item.view { item.metrics.enqueueView(view: view) view.isHidden = true item.view = nil } } } } // MARK: - User Actions public func visibleItems() -> [StreamItem] { return itemsPassingTest { $0.visible } } public func selectedItems() -> [StreamItem] { return itemsPassingTest { $0.selected && $0.entry != nil } } public var selectedItem: StreamItem? { return itemPassingTest { $0.selected } } public func itemPassingTest(test: (StreamItem) -> Bool) -> StreamItem? { for item in items where test(item) { return item } return nil } @discardableResult public func itemsPassingTest(test: (StreamItem) -> Bool) -> [StreamItem] { return items.filter(test) } public func selectSingleItem(item: StreamItem) { _ = items.map({ $0.selected = $0.position.index == item.position.index && !item.selected }) } @discardableResult public func scrollToItemPassingTest( test: (StreamItem) -> Bool, positionScroll: PositionScroll = .middle, animated: Bool) -> StreamItem? { let item = itemPassingTest(test: test) scrollToItem(item: item, positionScroll: positionScroll, animated: animated) return item } public func scrollToItem(item: StreamItem?, positionScroll: PositionScroll = .middle, animated: Bool) { guard let item = item else { return } let minOffset = minimumContentOffset let maxOffset = maximumContentOffset if layout.horizontal { var offset: CGFloat = 0 switch positionScroll { case .top: offset = item.frame.origin.x - contentInset.right case .middle: offset = (item.frame.origin.x - contentInset.right) - fittingContentWidth / 2 + item.frame.size.width / 2 case .bottom: offset = (item.frame.origin.x - contentInset.right) - fittingContentWidth + item.frame.size.width } if offset < minOffset.x { setContentOffset(minOffset, animated: animated) } else if offset > maxOffset.x { setContentOffset(maxOffset, animated: animated) } else { setContentOffset(CGPoint.init(x: offset, y: 0), animated: animated) } } else { var offset: CGFloat = 0 switch positionScroll { case .top: offset = item.frame.origin.y - contentInset.top case .middle: offset = (item.frame.origin.y - contentInset.top) - fittingContentHeight / 2 + item.frame.size.height / 2 case .bottom: offset = (item.frame.origin.y - contentInset.top) - fittingContentHeight + item.frame.size.height } if offset < minOffset.y { setContentOffset(minOffset, animated: animated) } else if offset > maxOffset.y { setContentOffset(maxOffset, animated: animated) } else { setContentOffset(CGPoint.init(x: 0, y: offset), animated: animated) } } } override public func touchesShouldCancel(in view: UIView) -> Bool { return true } }
mit
415dbf6763fb684e5ff1c9eab3dd132b
31.33162
178
0.57955
4.994837
false
false
false
false
banxi1988/BXAppKit
BXModel/UIModels.swift
1
1461
// // UIModels.swift // Pods // // Created by Haizhen Lee on 15/11/10. // // import Foundation public protocol BXBindable{ associatedtype ModelType func bind(_ item: ModelType,indexPath:IndexPath) } extension IndexPath{ public static let zero = IndexPath(item:0, section:0) } public protocol BXNibable{ associatedtype CustomViewClass static var hasNib:Bool{ get } static func nib() -> UINib static func instantiate() -> CustomViewClass } extension UIView:BXNibable{ public typealias CustomViewClass = UIView public static var hasNib:Bool{ let name = simpleClassName(self) let bundle = Bundle(for: self) let path = bundle.path(forResource: name, ofType: "nib") return path != nil } public static func nib() -> UINib{ let name = simpleClassName(self) return UINib(nibName: name, bundle: Bundle(for: self)) } public static func instantiate() -> CustomViewClass{ return nib().instantiate(withOwner: self, options: nil).first as! CustomViewClass } } open class StaticTableViewCell:UITableViewCell { open var staticHeight:CGFloat = 44 open var removeSeparator:Bool = false open var removeSeparatorInset:Bool = false open var shouldHighlight:Bool = true } extension StaticTableViewCell{ // public override var bx_height: CGFloat{ return staticHeight } //public override var bx_shouldHighlight: Bool{ return shouldHighlight } }
mit
03756b69fbe7fd1397304bac5ea8851a
22.564516
89
0.700205
4.234783
false
false
false
false
HabitRPG/habitrpg-ios
HabitRPG/Views/AdventureGuidePromoView.swift
1
4748
// // AdventureGuidePromoView.swift // Habitica // // Created by Phillip Thelen on 23.06.20. // Copyright © 2020 HabitRPG Inc. All rights reserved. // import Foundation class AdventureGuideBannerView: UIView, Themeable { var onTapped: (() -> Void)? private let container: UIView = { let view = UIView() view.cornerRadius = 8 return view }() private let titleLabel: UILabel = { let label = UILabel() label.font = .systemFont(ofSize: 17, weight: .semibold) label.text = L10n.onboardingTasks return label }() private let completeLabel: UILabel = { let label = UILabel() label.font = .systemFont(ofSize: 12) return label }() private let progressLabel: UILabel = { let label = UILabel() label.font = .systemFont(ofSize: 17, weight: .semibold) label.textColor = .yellow10 return label }() private let progressView: UIProgressView = { let progressView = UIProgressView() let transform = CGAffineTransform(scaleX: 1, y: 2) progressView.transform = transform progressView.cornerRadius = 2 return progressView }() private let leftImage = UIImageView(image: Asset.onboardingGoldLeft.image) private let rightImage = UIImageView(image: Asset.onboardingGoldRight.image) private let rightIndicator: UIImageView = { let view = UIImageView() view.contentMode = .center view.image = Asset.caretRight.image return view }() override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder: NSCoder) { super.init(coder: coder) setupView() } private func setupView() { addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewTapped))) addSubview(leftImage) leftImage.contentMode = .bottom addSubview(rightImage) rightImage.contentMode = .bottom addSubview(container) container.addSubview(titleLabel) container.addSubview(completeLabel) container.addSubview(progressLabel) container.addSubview(progressView) container.addSubview(rightIndicator) ThemeService.shared.addThemeable(themable: self) } func applyTheme(theme: Theme) { titleLabel.textColor = theme.primaryTextColor let attrString = NSMutableAttributedString(string: L10n.completeToEarnGold) attrString.addAttribute(NSAttributedString.Key.foregroundColor, value: theme.primaryTextColor, range: NSRange(location: 0, length: attrString.length)) attrString.addAttributesToSubstring(string: L10n.hundredGold, attributes: [ NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12, weight: .bold), NSAttributedString.Key.foregroundColor: UIColor.yellow10 ]) completeLabel.attributedText = attrString backgroundColor = theme.navbarHiddenColor if (theme.isDark) { container.backgroundColor = theme.windowBackgroundColor rightIndicator.backgroundColor = theme.offsetBackgroundColor } else { container.backgroundColor = theme.contentBackgroundColor rightIndicator.backgroundColor = theme.windowBackgroundColor } progressView.backgroundColor = theme.offsetBackgroundColor progressView.tintColor = .yellow50 } override func layoutSubviews() { super.layoutSubviews() layout() } private func layout() { leftImage.pin.start().top().bottom().width(73) rightImage.pin.end().top().bottom().width(75) container.pin.all(12) rightIndicator.pin.top().bottom().right().width(29) titleLabel.pin.top(8).start(16).end(16).sizeToFit(.width) progressLabel.pin.below(of: titleLabel).before(of: rightIndicator).marginRight(16).sizeToFit() completeLabel.pin.below(of: titleLabel).marginTop(4).start(16).end(16).sizeToFit() progressView.pin.start(16).before(of: rightIndicator).marginRight(16).bottom(16).height(4) } func setProgress(earned: Int, total: Int) { progressLabel.text = "\(earned) / \(total)" progressView.setProgress(Float(earned) / Float(total), animated: false) setNeedsLayout() } override var intrinsicContentSize: CGSize { return CGSize(width: 100, height: 81) } override func sizeThatFits(_ size: CGSize) -> CGSize { return CGSize(width: size.width, height: 81) } @objc private func viewTapped() { onTapped?() } }
gpl-3.0
2578b6d033f8802f5919c2fb6742897f
33.151079
158
0.644618
4.848825
false
false
false
false
jmgc/swift
test/decl/circularity.swift
1
2983
// RUN: %target-typecheck-verify-swift // N.B. Validating the pattern binding initializer for `pickMe` used to cause // recursive validation of the VarDecl. Check that we don't regress now that // this isn't the case. public struct Cyclic { static func pickMe(please: Bool) -> Int { return 42 } public static let pickMe = Cyclic.pickMe(please: true) } struct Node {} struct Parameterized<Value, Format> { func please<NewValue>(_ transform: @escaping (_ otherValue: NewValue) -> Value) -> Parameterized<NewValue, Format> { fatalError() } } extension Parameterized where Value == [Node], Format == String { static var pickMe: Parameterized { fatalError() } } extension Parameterized where Value == Node, Format == String { static let pickMe = Parameterized<[Node], String>.pickMe.please { [$0] } } enum Loop: Circle { struct DeLoop { } } protocol Circle { typealias DeLoop = Loop.DeLoop } class Base { static func foo(_ x: Int) {} } class Sub: Base { var foo = { () -> Int in let x = 42 // FIXME: Bogus diagnostic return foo(1) // expected-error {{cannot convert return expression of type '()' to return type 'Int'}} }() } extension Float { static let pickMe: Float = 1 } extension SIMD3 { init(_ scalar: Scalar) { self.init(repeating: scalar) } } extension SIMD3 where SIMD3.Scalar == Float { static let pickMe = SIMD3(.pickMe) } // Test case with circular overrides protocol P { associatedtype A // expected-note@-1 {{protocol requires nested type 'A'; do you want to add it?}} // expected-note@-2 {{through reference here}} func run(a: A) } class C1 { func run(a: Int) {} } class C2: C1, P { override func run(a: A) {} // expected-error@-1 {{circular reference}} // expected-note@-2 {{while resolving type 'A'}} // expected-note@-3 2{{through reference here}} } // Another crash to the above open class G1<A> { open func run(a: A) {} } class C3: G1<A>, P { // expected-error@-1 {{type 'C3' does not conform to protocol 'P'}} // expected-error@-2 {{cannot find type 'A' in scope}} override func run(a: A) {} // expected-error@-1 {{method does not override any method from its superclass}} } // Another case that triggers circular override checking. protocol P1 { associatedtype X = Int // expected-note {{through reference here}} init(x: X) } class C4 { required init(x: Int) {} } class D4 : C4, P1 { // expected-note 2 {{through reference here}} required init(x: X) { // expected-error {{circular reference}} // expected-note@-1 {{while resolving type 'X'}} // expected-note@-2 2{{through reference here}} super.init(x: x) } } // SR-12236 // N.B. This used to compile in 5.1. protocol SR12236 { } class SR12236_A { // expected-note {{through reference here}} typealias Nest = SR12236 // expected-error {{circular reference}} expected-note {{through reference here}} } extension SR12236_A: SR12236_A.Nest { }
apache-2.0
a864edbcb83a0a5da9478cfc2221b90e
24.93913
118
0.655716
3.538553
false
false
false
false
milseman/swift
test/Reflection/typeref_decoding.swift
9
24321
// REQUIRES: no_asan // RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ConcreteTypes.swift %S/Inputs/GenericTypes.swift %S/Inputs/Protocols.swift %S/Inputs/Extensions.swift %S/Inputs/Closures.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/libTypesToReflect.%target-dylib-extension // RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect.%target-dylib-extension | %FileCheck %s // CHECK: FIELDS: // CHECK: ======= // CHECK: TypesToReflect.Box // CHECK: ------------------ // CHECK: item: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: TypesToReflect.C // CHECK: ---------------- // CHECK: aClass: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: aStruct: TypesToReflect.S // CHECK: (struct TypesToReflect.S) // CHECK: anEnum: TypesToReflect.E // CHECK: (enum TypesToReflect.E) // CHECK: aTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int)) // CHECK: aTupleWithLabels: (a: TypesToReflect.C, s: TypesToReflect.S, e: TypesToReflect.E) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E)) // CHECK: aMetatype: TypesToReflect.C.Type // CHECK: (metatype // CHECK: (class TypesToReflect.C)) // CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int // CHECK: (function // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int) // CHECK: (struct Swift.Int)) // CHECK: aFunctionWithVarArgs: (TypesToReflect.C, TypesToReflect.S...) -> () // CHECK: (function // CHECK: (class TypesToReflect.C) // CHECK: (bound_generic_struct Swift.Array // CHECK: (struct TypesToReflect.S)) // CHECK: (tuple)) // CHECK: TypesToReflect.S.NestedS // CHECK: ------------------------ // CHECK: aField: Swift.Int // CHECK: (struct Swift.Int) // CHECK: TypesToReflect.S // CHECK: ---------------- // CHECK: aClass: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (struct TypesToReflect.S)) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (enum TypesToReflect.E)) // CHECK: aTuple: (TypesToReflect.C, TypesToReflect.Box<TypesToReflect.S>, TypesToReflect.Box<TypesToReflect.E>, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (struct TypesToReflect.S)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (enum TypesToReflect.E)) // CHECK: (struct Swift.Int)) // CHECK: aMetatype: TypesToReflect.C.Type // CHECK: (metatype // CHECK: (class TypesToReflect.C)) // CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int // CHECK: (function // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int) // CHECK: (struct Swift.Int)) // CHECK: aFunctionWithThinRepresentation: @convention(thin) () -> () // CHECK: (function convention=thin // CHECK: (tuple)) // CHECK: aFunctionWithCRepresentation: @convention(c) () -> () // CHECK: (function convention=c // CHECK: (tuple)) // CHECK: TypesToReflect.E // CHECK: ---------------- // CHECK: Class: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: Struct: TypesToReflect.S // CHECK: (struct TypesToReflect.S) // CHECK: Enum: TypesToReflect.E // CHECK: (enum TypesToReflect.E) // CHECK: Function: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> () // CHECK: (function // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int) // CHECK: (tuple)) // CHECK: Tuple: (TypesToReflect.C, TypesToReflect.S, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (struct Swift.Int)) // CHECK: IndirectTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int)) // CHECK: NestedStruct: TypesToReflect.S.NestedS // CHECK: (struct TypesToReflect.S.NestedS // CHECK: (struct TypesToReflect.S)) // CHECK: Metatype // CHECK: EmptyCase // CHECK: TypesToReflect.References // CHECK: ------------------------- // CHECK: strongRef: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: weakRef: weak Swift.Optional<TypesToReflect.C> // CHECK: (weak_storage // CHECK: (bound_generic_enum Swift.Optional // CHECK: (class TypesToReflect.C))) // CHECK: unownedRef: unowned TypesToReflect.C // CHECK: (unowned_storage // CHECK: (class TypesToReflect.C)) // CHECK: unownedUnsafeRef: unowned(unsafe) TypesToReflect.C // CHECK: (unmanaged_storage // CHECK: (class TypesToReflect.C)) // CHECK: TypesToReflect.C1 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.S1<A> // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: anEnum: TypesToReflect.E1<A> // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int // CHECK: (function // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (function // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (function // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, TypesToReflect.E1<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: dependentMember: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: TypesToReflect.C2 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.S1<A> // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: anEnum: TypesToReflect.E1<A> // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int // CHECK: (function // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (function // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (function // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, TypesToReflect.E2<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.Inner // CHECK: (dependent_member // CHECK: (protocol TypesToReflect.P1) // CHECK: (generic_type_parameter depth=0 index=0) member=Inner) // CHECK: TypesToReflect.C3 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C3<A> // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.S3<A> // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: anEnum: TypesToReflect.E3<A> // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int // CHECK: (function // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (function // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (function // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, TypesToReflect.E3<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.Outer // CHECK: (dependent_member // CHECK: (protocol TypesToReflect.P2) // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) // CHECK: dependentMember2: A.Outer.Inner // CHECK: (dependent_member // CHECK: (protocol TypesToReflect.P1) // CHECK: (dependent_member // CHECK: (protocol TypesToReflect.P2) // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner) // CHECK: TypesToReflect.C4 // CHECK: ----------------- // CHECK: TypesToReflect.S1 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S1<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E1<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int // CHECK: (function // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (function // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (function // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.Box<TypesToReflect.S1<A>>, TypesToReflect.Box<TypesToReflect.E1<A>>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: TypesToReflect.S2 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C2<A> // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S2<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E2<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: function: (TypesToReflect.C2<A>) -> (TypesToReflect.S2<A>) -> (TypesToReflect.E2<A>) -> Swift.Int // CHECK: (function // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (function // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (function // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.Box<TypesToReflect.S2<A>>, TypesToReflect.Box<TypesToReflect.E2<A>>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.Inner // CHECK: (dependent_member // CHECK: (protocol TypesToReflect.P1) // CHECK: (generic_type_parameter depth=0 index=0) member=Inner) // CHECK: TypesToReflect.S3 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C3<A> // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S3<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E3<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int // CHECK: (function // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (function // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (function // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.Box<TypesToReflect.S3<A>>, TypesToReflect.Box<TypesToReflect.E3<A>>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.Outer // CHECK: (dependent_member // CHECK: (protocol TypesToReflect.P2) // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) // CHECK: dependentMember2: A.Outer.Inner // CHECK: (dependent_member // CHECK: (protocol TypesToReflect.P1) // CHECK: (dependent_member // CHECK: (protocol TypesToReflect.P2) // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner) // CHECK: TypesToReflect.S4 // CHECK: ----------------- // CHECK: TypesToReflect.E1 // CHECK: ----------------- // CHECK: Class: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Struct: TypesToReflect.S1<A> // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Enum: TypesToReflect.E1<A> // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Int: Swift.Int // CHECK: (struct Swift.Int) // CHECK: Function: (A) -> TypesToReflect.E1<A> // CHECK: (function // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: Tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: Primary: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: Metatype: A.Type // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: TypesToReflect.E2 // CHECK: ----------------- // CHECK: Class: TypesToReflect.C2<A> // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Struct: TypesToReflect.S2<A> // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Enum: TypesToReflect.E2<A> // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Function: (A.Type) -> TypesToReflect.E1<A> // CHECK: (function // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: Tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: Primary: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: DependentMemberInner: A.Inner // CHECK: (dependent_member // CHECK: (protocol TypesToReflect.P1) // CHECK: (generic_type_parameter depth=0 index=0) member=Inner) // CHECK: ExistentialMetatype: A.Type // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: TypesToReflect.E3 // CHECK: ----------------- // CHECK: Class: TypesToReflect.C3<A> // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Struct: TypesToReflect.S3<A> // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Enum: TypesToReflect.E3<A> // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Function: (A.Type.Type) -> TypesToReflect.E1<A> // CHECK: (function // CHECK: (metatype // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: Tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: Primary: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: DependentMemberOuter: A.Outer // CHECK: (dependent_member // CHECK: (protocol TypesToReflect.P2) // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) // CHECK: DependentMemberInner: A.Outer.Inner // CHECK: (dependent_member // CHECK: (protocol TypesToReflect.P1) // CHECK: (dependent_member // CHECK: (protocol TypesToReflect.P2) // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner) // CHECK: TypesToReflect.E4 // CHECK: ----------------- // CHECK: TypesToReflect.P1 // CHECK: ----------------- // CHECK: TypesToReflect.P2 // CHECK: ----------------- // CHECK: TypesToReflect.P3 // CHECK: ----------------- // CHECK: TypesToReflect.P4 // CHECK: ----------------- // CHECK: TypesToReflect.ClassBoundP // CHECK: -------------------------- // CHECK: TypesToReflect.(FileprivateProtocol in _{{[0-9A-F]+}}) // CHECK: ------------------------------------------------------------------------- // CHECK: TypesToReflect.HasFileprivateProtocol // CHECK: ------------------------------------- // CHECK: x: TypesToReflect.(FileprivateProtocol in _{{[0-9A-F]+}}) // CHECK: (protocol TypesToReflect.(FileprivateProtocol in _{{[0-9A-F]+}})) // CHECK: ASSOCIATED TYPES: // CHECK: ================= // CHECK: - TypesToReflect.C1 : TypesToReflect.ClassBoundP // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.C4 : TypesToReflect.P1 // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.C4 : TypesToReflect.P2 // CHECK: typealias Outer = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.S4 : TypesToReflect.P1 // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.S4 : TypesToReflect.P2 // CHECK: typealias Outer = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.E4 : TypesToReflect.P1 // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.E4 : TypesToReflect.P2 // CHECK: typealias Outer = B // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: - TypesToReflect.E4 : TypesToReflect.P3 // CHECK: typealias First = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: typealias Second = B // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: - TypesToReflect.S : TypesToReflect.P4 // CHECK: typealias Result = Swift.Int // CHECK: (struct Swift.Int) // CHECK: BUILTIN TYPES: // CHECK: ============== // CHECK: CAPTURE DESCRIPTORS: // CHECK: ==================== // CHECK: - Capture types: // CHECK: (sil_box // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: - Metadata sources: // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: (closure_binding index=0) // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: (closure_binding index=1) // CHECK: - Capture types: // CHECK: (struct Swift.Int) // CHECK: - Metadata sources: // CHECK: - Capture types: // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=1)) // CHECK: - Metadata sources: // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: (closure_binding index=0) // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: (generic_argument index=0 // CHECK: (reference_capture index=0))
apache-2.0
1ce703b4bbdbcc30da50340b1b96261a
35.962006
285
0.678837
3.336672
false
false
false
false
billdonner/sheetcheats9
sc9/Recents.swift
1
3363
// // Recents.swift // sheetcheats // // Created by william donner on 7/21/14. // Copyright (c) 2014 william donner. All rights reserved. // import Foundation public final class Recents : SpecialList, Singleton { public struct Configuration { public static let maxSize = 500 public static let displayCount = 5 public static let label = "recents" } var gRecents:RecentList = [] // one list to rule them all public class var shared: Recents { struct Singleton { static let sharedAppConfiguration = Recents() } return Singleton.sharedAppConfiguration } override public var description : String { return Recents.Configuration.label + ": \(gRecents.count) \(gRecents)" } private func pathForSaveFile()-> String { return FS.shared.RecentsPlist } func add(_ t:RecentListEntry) { t.listNamed = "Recents" addToList(&gRecents, maxSize: Recents.Configuration.maxSize , t: t) //save() - saves in Incorporator } func sortedalpha(_ limit:Int) -> [RecentListEntry] { return alphaSorted(&gRecents,limit:limit) } //brutally check all the recents for everything we have shown so as to get the hintID func hintFromRecents(_ title:Title)->ID { for eachRecent:RecentListEntry in gRecents { if eachRecent.title == title { return eachRecent.hint } } return "" } func exportAll(){ var obuf:String func writecsvline( _ s:String,kind:String ) { //write lines obuf += "\(s),,,,\(kind)\n" } // starts here /// recreate export directory FS.shared.createDir(FS.shared.ExportDirectory) obuf = "" // nothing let title = "Recents - \(Date())" obuf += ("= Exporting: \(title) Generated by CheatSheets9 - name,key,bpm,comment,pref\n") /// write out the title and the type of the hint /// this is the best we can do in a general way for eachRecent:RecentListEntry in gRecents { let raw = "\"" + eachRecent.title + "\"" let clean = raw //raw.replacingOccurrences(of: ",", with: "\,") let idex = eachRecent.hint.components(separatedBy: ".") if idex.count > 1 { let kind = idex[1] writecsvline( clean,kind:kind ) } else { // no hint, oh well writecsvline( clean,kind:"") } } // write whatever we have to the export directory let type = "csv" let dpath = FS.shared.ExportDirectory + "/" + title + "." + type let tourl = URL(fileURLWithPath: dpath, isDirectory: false) do { try obuf.write(to: tourl, atomically: true, encoding:.utf8) } catch { print("could not write csv to \(tourl) \(error)") } } public override func save(){ gsave( g:self.gRecents,path:self.pathForSaveFile(),label: Recents.Configuration.label) } public override func restore(){ grestore( &self.gRecents,path:self.pathForSaveFile(),label: Recents.Configuration.label) } }
apache-2.0
47c079beb91a306d1ee1fc63bc5be84e
29.853211
99
0.561404
4.339355
false
true
false
false
XiongJoJo/OFO
App/OFO/OFO/PasscodeController.swift
1
4172
// // PasscodeController.swift // OFO // // Created by JoJo on 2017/6/8. // Copyright © 2017年 JoJo. All rights reserved. // import UIKit import SwiftyTimer import SwiftySound class PasscodeController: UIViewController { @IBOutlet weak var label1st: MyPreviewLabel! @IBOutlet weak var label2nd: MyPreviewLabel! @IBOutlet weak var label3rd: MyPreviewLabel! @IBOutlet weak var label4th: MyPreviewLabel! @IBOutlet weak var showInfo: UILabel! //[8,4,5,6] var passArray : [String] = [] var bikeID = "" let defaults = UserDefaults.standard @IBOutlet weak var countDownLabel: UILabel! // var remindSeconds = 121 var remindSeconds = 21 var isTorchOn = false var isVoiceOn = true @IBOutlet weak var voiceBtn: UIButton! @IBAction func voiceBtnTap(_ sender: UIButton) { if isVoiceOn { voiceBtn.setImage(#imageLiteral(resourceName: "voiceclose"), for: .normal) } else { voiceBtn.setImage(#imageLiteral(resourceName: "voiceopen"), for: .normal) } isVoiceOn = !isVoiceOn } @IBAction func torchBtnTap(_ sender: UIButton) { turnTorch() if isTorchOn { torchBtn.setImage(#imageLiteral(resourceName: "lightopen"), for: .normal) defaults.set(true, forKey: "isVoiceOn") } else { torchBtn.setImage(#imageLiteral(resourceName: "lightclose"), for: .normal) defaults.set(false, forKey: "isVoiceOn") } isTorchOn = !isTorchOn } @IBOutlet weak var torchBtn: UIButton! override func viewDidLoad() { super.viewDidLoad() self.title = "车辆解锁" self.navigationItem.hidesBackButton = true //隐藏返回按钮 Sound.play(file: "您的解锁码为_D.m4a") DispatchQueue.main.asyncAfter(deadline: .now()+1) { Sound.play(file: "\(self.passArray[0])_D.m4a") } DispatchQueue.main.asyncAfter(deadline: .now()+2) { Sound.play(file: "\(self.passArray[1])_D.m4a") } DispatchQueue.main.asyncAfter(deadline: .now()+3) { Sound.play(file: "\(self.passArray[2])_D.m4a") } DispatchQueue.main.asyncAfter(deadline: .now()+4) { Sound.play(file: "\(self.passArray[3])_D.m4a") } DispatchQueue.main.asyncAfter(deadline: .now()+5) { Sound.play(file: "上车前_LH.m4a") } Timer.every(1) { (timer: Timer) in self.remindSeconds -= 1 self.countDownLabel.text = self.remindSeconds.description + "秒" if self.remindSeconds == 0 { timer.invalidate() //时间结束跳转计时页面 self.performSegue(withIdentifier: "toTimePage", sender: self) // Sound.play(file:"骑行结束_LH.m4a")//这里我们时间现实结束之后播放 } } voiceBtnStatus(voiceBtn: voiceBtn) self.label1st.text = passArray[0] self.label2nd.text = passArray[1] self.label3rd.text = passArray[2] self.label4th.text = passArray[3] // let bikeID = passArray.joined(separator: "")//数组转字符串 showInfo.text = "车牌号" + bikeID + "的解锁码" } @IBAction func reportBtnTap(_ sender: UIButton) { dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
d0e35c2bb5af0b3b79345d30e76b43e8
26.910345
107
0.573264
4.112805
false
false
false
false
jterhorst/SwiftParseDemo
SwiftParseExample/AppDelegate.swift
1
7959
// // AppDelegate.swift // SwiftParseExample // // Created by Jason Terhorst on 7/14/14. // Copyright (c) 2014 Jason Terhorst. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.endIndex-1] as UINavigationController splitViewController.delegate = navigationController.topViewController as DetailViewController let dataParser = DataParser() dataParser.managedObjectContext = self.managedObjectContext dataParser.parseFromFile() let masterNavigationController = splitViewController.viewControllers[0] as UINavigationController let controller = masterNavigationController.topViewController as MasterViewController controller.managedObjectContext = self.managedObjectContext 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } func saveContext () { var error: NSError? = nil let managedObjectContext = self.managedObjectContext if managedObjectContext.hasChanges && !managedObjectContext.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //println("Unresolved error \(error), \(error.userInfo)") abort() } } // #pragma mark - Core Data stack // Returns the managed object context for the application. // If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application. var managedObjectContext: NSManagedObjectContext { if _managedObjectContext == nil { _managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) _managedObjectContext!.parentContext = self.diskMOC } return _managedObjectContext! } var _managedObjectContext: NSManagedObjectContext? = nil var diskMOC: NSManagedObjectContext { if _diskMOC == nil { if let coordinator = self.persistentStoreCoordinator { _diskMOC = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) _diskMOC!.persistentStoreCoordinator = coordinator } } return _diskMOC! } var _diskMOC: NSManagedObjectContext? = nil // Returns the managed object model for the application. // If the model doesn't already exist, it is created from the application's model. var managedObjectModel: NSManagedObjectModel { if _managedObjectModel == nil { let modelURL = NSBundle.mainBundle().URLForResource("SwiftParseExample", withExtension: "momd") _managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL!) } return _managedObjectModel! } var _managedObjectModel: NSManagedObjectModel? = nil // Returns the persistent store coordinator for the application. // If the coordinator doesn't already exist, it is created and the application's store added to it. var persistentStoreCoordinator: NSPersistentStoreCoordinator? { if (_persistentStoreCoordinator == nil) { let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SwiftParseExample.sqlite") var error: NSError? = nil _persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil { /* Replace this implementation with code to handle the error appropriately. abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. Typical reasons for an error here include: * The persistent store is not accessible; * The schema for the persistent store is incompatible with current managed object model. Check the error message to determine what the actual problem was. If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory. If you encounter schema incompatibility errors during development, you can reduce their frequency by: * Simply deleting the existing store: NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil) * Performing automatic lightweight migration by passing the following dictionary as the options parameter: [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true} Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details. */ //println("Unresolved error \(error), \(error.userInfo)") abort() } } return _persistentStoreCoordinator! } var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil // #pragma mark - Application's Documents directory // Returns the URL to the application's Documents directory. var applicationDocumentsDirectory: NSURL { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.endIndex-1] as NSURL } }
mit
0ab18ec6c627c8b3b23aa321e9e2cc12
51.019608
285
0.725594
6.052471
false
false
false
false
vector-im/vector-ios
RiotSwiftUI/Modules/Spaces/SpaceCreation/SpaceCreationEmailInvites/ViewModel/SpaceCreationEmailInvitesViewModel.swift
1
4679
// File created from SimpleUserProfileExample // $ createScreen.sh Spaces/SpaceCreation/SpaceCreationEmailInvites SpaceCreationEmailInvites // // Copyright 2021 New Vector Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import SwiftUI import Combine @available(iOS 14, *) typealias SpaceCreationEmailInvitesViewModelType = StateStoreViewModel<SpaceCreationEmailInvitesViewState, SpaceCreationEmailInvitesStateAction, SpaceCreationEmailInvitesViewAction> @available(iOS 14, *) class SpaceCreationEmailInvitesViewModel: SpaceCreationEmailInvitesViewModelType, SpaceCreationEmailInvitesViewModelProtocol { // MARK: - Properties // MARK: Private private let creationParameters: SpaceCreationParameters private let service: SpaceCreationEmailInvitesServiceProtocol // MARK: Public var completion: ((SpaceCreationEmailInvitesViewModelResult) -> Void)? // MARK: - Setup init(creationParameters: SpaceCreationParameters, service: SpaceCreationEmailInvitesServiceProtocol) { self.creationParameters = creationParameters self.service = service super.init(initialViewState: SpaceCreationEmailInvitesViewModel.defaultState(creationParameters: creationParameters, service: service)) } private func setupServiceObserving() { let publisher = service.isLoadingSubject .map(SpaceCreationEmailInvitesStateAction.updateLoading) .eraseToAnyPublisher() dispatch(actionPublisher: publisher) } private static func defaultState(creationParameters: SpaceCreationParameters, service: SpaceCreationEmailInvitesServiceProtocol) -> SpaceCreationEmailInvitesViewState { let emailValidation = service.validate(creationParameters.emailInvites) let bindings = SpaceCreationEmailInvitesViewModelBindings(emailInvites: creationParameters.emailInvites) return SpaceCreationEmailInvitesViewState( title: creationParameters.isPublic ? VectorL10n.spacesCreationPublicSpaceTitle : VectorL10n.spacesCreationPrivateSpaceTitle, emailAddressesValid: emailValidation, loading: service.isLoadingSubject.value, bindings: bindings ) } // MARK: - Public override func process(viewAction: SpaceCreationEmailInvitesViewAction) { switch viewAction { case .cancel: cancel() case .back: back() case .done: done() case .inviteByUsername: inviteByUsername() } } override class func reducer(state: inout SpaceCreationEmailInvitesViewState, action: SpaceCreationEmailInvitesStateAction) { switch action { case .updateEmailValidity(let emailValidity): state.emailAddressesValid = emailValidity case .updateLoading(let isLoading): state.loading = isLoading } } private func done() { self.creationParameters.emailInvites = self.context.emailInvites self.creationParameters.inviteType = .email let emailAddressesValidity = service.validate(self.context.emailInvites) dispatch(action: .updateEmailValidity(emailAddressesValidity)) if self.context.emailInvites.reduce(true, { $0 && $1.isEmpty }) { completion?(.done) } else if emailAddressesValidity.reduce(true, { $0 && $1}) { if service.isIdentityServiceReady { completion?(.done) } else { service.prepareIdentityService { [weak self] baseURL, accessToken in self?.completion?(.needIdentityServiceTerms(baseURL, accessToken)) } failure: { [weak self] error in self?.completion?(.identityServiceFailure(error)) } } } } private func cancel() { completion?(.cancel) } private func back() { completion?(.back) } private func inviteByUsername() { completion?(.inviteByUsername) } }
apache-2.0
459985764ff5f4c00a1d1e0ccca21808
37.352459
172
0.68006
5.678398
false
false
false
false
dehesa/Metal
samples/tessellation/Sources/Common/TessellationPipeline.swift
1
10964
import Foundation import Metal import MetalKit final class TessellationPipeline: NSObject, MTKViewDelegate { /// The type of tessellation patch being rendered. var patchType: MTLPatchType = .triangle /// Indicates whether only the wireframe or the whole patch will be displayed. var wireframe: Bool = true /// Tessellation factors to be applied on the following renders. var factors: (edge: Float, inside: Float) = (2, 2) /// Basic Metal entities to interface with the assignated GPU. private let _metal: (device: MTLDevice, queue: MTLCommandQueue, library: MTLLibrary) /// Compute pipelines for tessellation triangles and quads. private let _computePipelines: (triangle: MTLComputePipelineState, quad: MTLComputePipelineState) /// Render pipelines for this project. private let _renderPipelines: (triangle: MTLRenderPipelineState, quad: MTLRenderPipelineState) /// Buffer needed to feed the compute/render pipelines. private let _buffers: (tessellationFactors: MTLBuffer, triangleControlPoints: MTLBuffer, quadControlPoints: MTLBuffer) /// Designated initializer requiring passing the MetalKit view that will be driven by this pipeline. /// - parameter view: MetalKit view driven by the created pipeline. init(view: MTKView) { self._metal = TessellationPipeline._setupMetal() self._computePipelines = TessellationPipeline._setupComputePipelines(device: _metal.device, library: _metal.library) self._renderPipelines = TessellationPipeline._setupRenderPipelines(device: _metal.device, library: _metal.library, view: view) self._buffers = TessellationPipeline._setupBuffers(device: _metal.device) super.init() view.device = self._metal.device view.delegate = self } func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {} func draw(in view: MTKView) { autoreleasepool { guard let buffer = self._metal.queue.makeCommandBuffer() else { return } buffer.label = "Tessellation Pass" if self._computeTessellationFactors(on: buffer), self._tessellateAndRender(view: view, on: buffer), let drawable = view.currentDrawable { buffer.present(drawable) } buffer.commit() } } } private extension TessellationPipeline { /// Creates the basic *non-trasient* Metal objects needed for this project. /// - returns: A metal device, a metal command queue, and the default library (hopefully hosting the tessellation compute and vertex/fragment functions). static func _setupMetal() -> (device: MTLDevice, queue: MTLCommandQueue, library: MTLLibrary) { guard let device = MTLCreateSystemDefaultDevice() else { fatalError("Metal is not supported on this device.") } guard device.supportsFeatureSet(_minTessellationFeatureSet) else { fatalError("Tessellation is not supported on this device.") } guard let queue = device.makeCommandQueue() else { fatalError("A Metal command queue couldn't be created.") } guard let library = device.makeDefaultLibrary() else { fatalError("The default Metal library couldn't be found or couldn't be created.") } return (device, queue, library) } /// Creates the two compute pipelines (one for triangles, one for quads). /// - parameter device: Metal device needed to create pipeline state objects. /// - parameter library: Compile Metal code hosting the kernel functions driving the compute pipelines. static func _setupComputePipelines(device: MTLDevice, library: MTLLibrary) -> (triangle: MTLComputePipelineState, quad: MTLComputePipelineState) { guard let triangleFunction = library.makeFunction(name: "kernel_triangle"), let quadFunction = library.makeFunction(name: "kernel_quad") else { fatalError("The kernel functions calculating the tessellation factors couldn't be found/created.") } guard let trianglePipeline = try? device.makeComputePipelineState(function: triangleFunction), let quadPipeline = try? device.makeComputePipelineState(function: quadFunction) else { fatalError("The compute pipelines couldn't be created.") } return (trianglePipeline, quadPipeline) } static func _setupRenderPipelines(device: MTLDevice, library: MTLLibrary, view: MTKView) -> (triangle: MTLRenderPipelineState, quad: MTLRenderPipelineState) { guard let triangleFunction = library.makeFunction(name: "vertex_triangle"), let quadFunction = library.makeFunction(name: "vertex_quad"), let fragmentFunction = library.makeFunction(name: "fragment_both") else { fatalError("The render functions couldn't be found/created.") } let pipelineDescriptor = MTLRenderPipelineDescriptor().set { (pipeline) in // Vertex descriptor for the control point data. // This describes the inputs to the post-tessellation vertex function, delcared with the `stage_in` qualifier. pipeline.vertexDescriptor = MTLVertexDescriptor().set { (vertex) in vertex.attributes[0].setUp { $0.format = .float4 $0.offset = 0 $0.bufferIndex = 0 } vertex.layouts[0].setUp { $0.stepFunction = .perPatchControlPoint $0.stepRate = 1 $0.stride = 4 * MemoryLayout<Float>.size } } // Configure common render properties pipeline.sampleCount = view.sampleCount pipeline.colorAttachments[0].pixelFormat = view.colorPixelFormat pipeline.fragmentFunction = fragmentFunction // Configure common tessellation properties pipeline.isTessellationFactorScaleEnabled = false pipeline.tessellationFactorFormat = .half pipeline.tessellationControlPointIndexType = .none pipeline.tessellationFactorStepFunction = .constant pipeline.tessellationOutputWindingOrder = .clockwise pipeline.tessellationPartitionMode = .fractionalEven pipeline.maxTessellationFactor = _maxTessellationFactor } guard let pipelines: [MTLRenderPipelineState] = try? [triangleFunction, quadFunction].map({ pipelineDescriptor.vertexFunction = $0 return try device.makeRenderPipelineState(descriptor: pipelineDescriptor) }) else { fatalError("The post-tessellation vertex pipelines couldn't be created.") } return (pipelines[0], pipelines[1]) } static func _setupBuffers(device: MTLDevice) -> (tessellationFactors: MTLBuffer, triangleControlPoints: MTLBuffer, quadControlPoints: MTLBuffer) { let triangleControlPointPositions: [Float] = [ -0.8, -0.8, 0.0, 1.0, // lower-left 0.0, 0.8, 0.0, 1.0, // upper-middle 0.8, -0.8, 0.0, 1.0, // lower-right ] let quadControlPointPositions: [Float] = [ -0.8, 0.8, 0.0, 1.0, // upper-left 0.8, 0.8, 0.0, 1.0, // upper-right 0.8, -0.8, 0.0, 1.0, // lower-right -0.8, -0.8, 0.0, 1.0, // lower-left ] let triangleControlPointLength = triangleControlPointPositions.count * MemoryLayout<Float>.size let quadControlPointLength = quadControlPointPositions.count * MemoryLayout<Float>.size // Allocate memory for the tessellation factors, triangle control points, and quad control points. guard let factorsBuffer = device.makeBuffer(length: 256, options: .storageModePrivate), let triangleBuffer = device.makeBuffer(bytes: triangleControlPointPositions, length: triangleControlPointLength, options: _bufferStorageMode), let quadBuffer = device.makeBuffer(bytes: quadControlPointPositions, length: quadControlPointLength, options: _bufferStorageMode) else { fatalError("The Metal buffers couldn't be created.") } // More sophisticated tessellation passes might have additional buffers for per-patch user data. return (factorsBuffer.set { $0.label = "Tessellation Factors" }, triangleBuffer.set { $0.label = "Control Points Triangle" }, quadBuffer.set { $0.label = "Control Points Quad" }) } /// The minimum OSes supporting Tessellation. static var _minTessellationFeatureSet: MTLFeatureSet { #if os(macOS) .macOS_GPUFamily1_v2 #elseif os(iOS) .iOS_GPUFamily3_v2 #endif } /// The maximum Tessellation factor for the given OS. static var _maxTessellationFactor: Int { #if os(macOS) 64 #elseif os(iOS) 16 #endif } // OS Buffer storage mode static var _bufferStorageMode: MTLResourceOptions { #if arch(arm64) .storageModeShared #else .storageModeManaged #endif } func _computeTessellationFactors(on commandBuffer: MTLCommandBuffer) -> Bool { guard let encoder = commandBuffer.makeComputeCommandEncoder() else { return false } encoder.label = "Compute Command Encoder" encoder.pushDebugGroup("Compute Tessellation Factors") // Set the correct pipeline. encoder.setComputePipelineState((self.patchType == .triangle) ? self._computePipelines.triangle : self._computePipelines.quad) // Bind the buffers (user selection & tessellation factor) encoder.setBytes(&factors.edge, length: MemoryLayout.size(ofValue: factors.edge), index: 0) encoder.setBytes(&factors.inside, length: MemoryLayout.size(ofValue: factors.inside), index: 1) encoder.setBuffer(self._buffers.tessellationFactors, offset: 0, index: 2) // Dispatch threadgroups encoder.dispatchThreadgroups(MTLSize(width: 1, height: 1, depth: 1), threadsPerThreadgroup: MTLSize(width: 1, height: 1, depth: 1)) encoder.popDebugGroup() encoder.endEncoding() return true } func _tessellateAndRender(view: MTKView, on commandBuffer: MTLCommandBuffer) -> Bool { guard let renderPassDescriptor = view.currentRenderPassDescriptor, let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor) else { return false } encoder.label = "Render Command Encoder" encoder.pushDebugGroup("Tessellate and Render") let numControlPoints: Int // Set the correct render pipeline and bind the correct control points buffer. if case .triangle = self.patchType { numControlPoints = 3 encoder.setRenderPipelineState(self._renderPipelines.triangle) encoder.setVertexBuffer(self._buffers.triangleControlPoints, offset: 0, index: 0) } else { numControlPoints = 4 encoder.setRenderPipelineState(self._renderPipelines.quad) encoder.setVertexBuffer(self._buffers.quadControlPoints, offset: 0, index: 0) } // Enable/Disable wireframe mode. encoder.setTriangleFillMode((self.wireframe) ? .lines : .fill) // Encode tessellation-specific commands. encoder.setTessellationFactorBuffer(self._buffers.tessellationFactors, offset: 0, instanceStride: 0) encoder.drawPatches(numberOfPatchControlPoints: numControlPoints, patchStart: 0, patchCount: 1, patchIndexBuffer: nil, patchIndexBufferOffset: 0, instanceCount: 1, baseInstance: 0) encoder.popDebugGroup() encoder.endEncoding() return true } }
mit
a2c646a9be96b45edd061f42c4e83393
44.683333
184
0.720084
4.3856
false
false
false
false
DaSens/StartupDisk
Pods/ProgressKit/InDeterminate/Rainbow.swift
2
3503
// // Rainbow.swift // ProgressKit // // Created by Kauntey Suryawanshi on 09/07/15. // Copyright (c) 2015 Kauntey Suryawanshi. All rights reserved. // import Foundation import Cocoa @IBDesignable open class Rainbow: MaterialProgress { @IBInspectable open var onLightOffDark: Bool = false override func configureLayers() { super.configureLayers() self.background = NSColor.clear } override open func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { super.animationDidStop(anim, finished: flag) if onLightOffDark { progressLayer.strokeColor = lightColorList[Int(arc4random()) % lightColorList.count].cgColor } else { progressLayer.strokeColor = darkColorList[Int(arc4random()) % darkColorList.count].cgColor } } } var randomColor: NSColor { let red = CGFloat(Double(arc4random()).truncatingRemainder(dividingBy: 256.0) / 256.0) let green = CGFloat(Double(arc4random()).truncatingRemainder(dividingBy: 256.0) / 256.0) let blue = CGFloat(Double(arc4random()).truncatingRemainder(dividingBy: 256.0) / 256.0) return NSColor(calibratedRed: red, green: green, blue: blue, alpha: 1.0) } private let lightColorList:[NSColor] = [ NSColor(red: 0.9461, green: 0.6699, blue: 0.6243, alpha: 1.0), NSColor(red: 0.8625, green: 0.7766, blue: 0.8767, alpha: 1.0), NSColor(red: 0.6676, green: 0.6871, blue: 0.8313, alpha: 1.0), NSColor(red: 0.7263, green: 0.6189, blue: 0.8379, alpha: 1.0), NSColor(red: 0.8912, green: 0.9505, blue: 0.9971, alpha: 1.0), NSColor(red: 0.7697, green: 0.9356, blue: 0.9692, alpha: 1.0), NSColor(red: 0.3859, green: 0.7533, blue: 0.9477, alpha: 1.0), NSColor(red: 0.6435, green: 0.8554, blue: 0.8145, alpha: 1.0), NSColor(red: 0.8002, green: 0.936, blue: 0.7639, alpha: 1.0), NSColor(red: 0.5362, green: 0.8703, blue: 0.8345, alpha: 1.0), NSColor(red: 0.9785, green: 0.8055, blue: 0.4049, alpha: 1.0), NSColor(red: 1.0, green: 0.8667, blue: 0.6453, alpha: 1.0), NSColor(red: 0.9681, green: 0.677, blue: 0.2837, alpha: 1.0), NSColor(red: 0.9898, green: 0.7132, blue: 0.1746, alpha: 1.0), NSColor(red: 0.8238, green: 0.84, blue: 0.8276, alpha: 1.0), NSColor(red: 0.8532, green: 0.8763, blue: 0.883, alpha: 1.0), ] let darkColorList: [NSColor] = [ NSColor(red: 0.9472, green: 0.2496, blue: 0.0488, alpha: 1.0), NSColor(red: 0.8098, green: 0.1695, blue: 0.0467, alpha: 1.0), NSColor(red: 0.853, green: 0.2302, blue: 0.3607, alpha: 1.0), NSColor(red: 0.8152, green: 0.3868, blue: 0.5021, alpha: 1.0), NSColor(red: 0.96, green: 0.277, blue: 0.3515, alpha: 1.0), NSColor(red: 0.3686, green: 0.3069, blue: 0.6077, alpha: 1.0), NSColor(red: 0.5529, green: 0.3198, blue: 0.5409, alpha: 1.0), NSColor(red: 0.2132, green: 0.4714, blue: 0.7104, alpha: 1.0), NSColor(red: 0.1706, green: 0.2432, blue: 0.3106, alpha: 1.0), NSColor(red: 0.195, green: 0.2982, blue: 0.3709, alpha: 1.0), NSColor(red: 0.0, green: 0.3091, blue: 0.5859, alpha: 1.0), NSColor(red: 0.2261, green: 0.6065, blue: 0.3403, alpha: 1.0), NSColor(red: 0.1101, green: 0.5694, blue: 0.4522, alpha: 1.0), NSColor(red: 0.1716, green: 0.4786, blue: 0.2877, alpha: 1.0), NSColor(red: 0.8289, green: 0.33, blue: 0.0, alpha: 1.0), NSColor(red: 0.4183, green: 0.4842, blue: 0.5372, alpha: 1.0), NSColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0), ]
apache-2.0
f1a7169cc3b67171428eb7fe7a5d4684
45.092105
104
0.633457
2.665906
false
false
false
false
zapdroid/RXWeather
Pods/Nimble/Sources/Nimble/Matchers/ThrowError.swift
1
2059
import Foundation /// A Nimble matcher that succeeds when the actual expression throws an /// error of the specified type or from the specified case. /// /// Errors are tried to be compared by their implementation of Equatable, /// otherwise they fallback to comparision by _domain and _code. /// /// Alternatively, you can pass a closure to do any arbitrary custom matching /// to the thrown error. The closure only gets called when an error was thrown. /// /// nil arguments indicates that the matcher should not attempt to match against /// that parameter. public func throwError<T: Error>( _ error: T? = nil, errorType: T.Type? = nil, closure: ((T) -> Void)? = nil) -> MatcherFunc<Any> { return MatcherFunc { actualExpression, failureMessage in var actualError: Error? do { _ = try actualExpression.evaluate() } catch let catchedError { actualError = catchedError } setFailureMessageForError(failureMessage, actualError: actualError, error: error, errorType: errorType, closure: closure) return errorMatchesNonNilFieldsOrClosure(actualError, error: error, errorType: errorType, closure: closure) } } /// A Nimble matcher that succeeds when the actual expression throws any /// error or when the passed closures' arbitrary custom matching succeeds. /// /// This duplication to it's generic adequate is required to allow to receive /// values of the existential type `Error` in the closure. /// /// The closure only gets called when an error was thrown. public func throwError( closure: ((Error) -> Void)? = nil) -> MatcherFunc<Any> { return MatcherFunc { actualExpression, failureMessage in var actualError: Error? do { _ = try actualExpression.evaluate() } catch let catchedError { actualError = catchedError } setFailureMessageForError(failureMessage, actualError: actualError, closure: closure) return errorMatchesNonNilFieldsOrClosure(actualError, closure: closure) } }
mit
7045f7b2d09704dc75c645ae7fe3450e
37.849057
129
0.697912
4.844706
false
false
false
false
STShenZhaoliang/STKitSwift
STKitSwiftDemo/STKitSwiftDemo/STTimerButtonController.swift
1
4189
// // STTimerButtonController.swift // STKitSwiftDemo // // Created by mac on 2019/7/5. // Copyright © 2019 沈兆良. All rights reserved. // import UIKit import STKitSwift import SnapKit class STTimerButtonController: UIViewController { // MARK: 1.lift cycle override func viewDidLoad() { super.viewDidLoad() buttonCode.snp.makeConstraints { (maker) in maker.height.equalTo(44) maker.width.equalTo(150) maker.center.equalToSuperview() } buttonTime.snp.makeConstraints { (maker) in maker.height.equalTo(44) maker.width.equalTo(240) maker.centerX.equalToSuperview() maker.top.equalTo(buttonCode.snp.bottom).offset(20) } actionTime() } deinit { buttonCode.invalidate() buttonTime.invalidate() print("--------- STTimerButtonController deinit ---------") } // MARK: 2.private methods /// 秒数转换为时间格式 - 00:00:00 func secondsToStr(second: Int) -> String{ let hour = second / 3600 let minu = (second - hour * 3600) / 60 let sec = second - hour * 3600 - minu * 60 let Hstr = String(format: "%02d", hour) let MStr = String(format: "%02d", minu) let SStr = String(format: "%02d", sec) return Hstr + ":" + MStr + ":" + SStr } // MARK: 3.event response @objc func actionCode(){ buttonCode.startCountDown(duration: 10) { (button, type, time) in print("button = \(button) type = \(type) time = \(time)") switch type { case .start: button.isEnabled = false button.setTitle(time.description + "s", for: .normal) button.backgroundColor = .gray case .ongoing: button.isEnabled = false button.setTitle(time.description + "s", for: .normal) button.backgroundColor = .gray case .finish: button.isEnabled = true button.setTitle("重新发送", for: .normal) button.backgroundColor = .red default: button.isEnabled = true } } } @objc func actionTime(){ switch buttonTime.type { case .none: buttonTime.startTime(startTime: 22222) { [weak self] (button, type, time) in print("button = \(button) type = \(type) time = \(time)") switch type { case .start: button.setTitle(self?.secondsToStr(second: time), for: .normal) case .ongoing: button.setTitle(self?.secondsToStr(second: time), for: .normal) case .pause: button.setTitle("⏸", for: .normal) case .finish: button.isEnabled = true default: button.isEnabled = true } } case .ongoing: buttonTime.pause() case .pause: buttonTime.resume() default: buttonTime.isEnabled = true } } // MARK: 4.interface // MARK: 5.getter private lazy var buttonCode: STTimerButton = { let buttonCode = STTimerButton() buttonCode.addTarget(self, action: #selector(actionCode), for: .touchUpInside) buttonCode.setTitle("发送验证码", for: .normal) buttonCode.layer.cornerRadius = 22 buttonCode.layer.masksToBounds = true buttonCode.backgroundColor = .blue view.addSubview(buttonCode) return buttonCode }() private lazy var buttonTime: STTimerButton = { let buttonTime = STTimerButton() buttonTime.addTarget(self, action: #selector(actionTime), for: .touchUpInside) buttonTime.setTitle(secondsToStr(second: 22222), for: .normal) buttonTime.layer.cornerRadius = 22 buttonTime.layer.masksToBounds = true buttonTime.backgroundColor = .blue view.addSubview(buttonTime) return buttonTime }() }
mit
66f64941b3216ab0f79d9d6bf12aed88
31.375
88
0.547539
4.42735
false
false
false
false
dn-m/PitchSpellingTools
PitchSpellingTools/SpelledPitchSet.swift
1
1214
// // SpelledPitchSet.swift // PitchSpellingTools // // Created by James Bean on 5/28/16. // // import Pitch /// Unordered set of unique `SpelledPitch` values. /// /// - TODO: Conform to `AnySequenceWrapping`. public struct SpelledPitchSet { fileprivate let pitches: Set<SpelledPitch> // MARK: - Initializers /// Create a `SpelledPitchSet` with an array of `SpelledPitch` values. public init<S: Sequence>(_ pitches: S) where S.Iterator.Element == SpelledPitch { self.pitches = Set(pitches) } } extension SpelledPitchSet: ExpressibleByArrayLiteral { public typealias Element = SpelledPitch public init(arrayLiteral elements: Element...) { self.pitches = Set(elements) } } extension SpelledPitchSet: Sequence { // MARK: - SequenceType /// Generate `Pitches` for iteration. public func makeIterator() -> AnyIterator<SpelledPitch> { var generator = pitches.makeIterator() return AnyIterator { return generator.next() } } } extension SpelledPitchSet: Equatable { public static func == (lhs: SpelledPitchSet, rhs: SpelledPitchSet) -> Bool { return lhs.pitches == rhs.pitches } }
mit
d954780ec616a0fbfe85e18c30c52775
22.346154
85
0.659802
4.320285
false
false
false
false
ashare80/ASTextInputAccessoryView
Example/ASTextInputAccessoryView/CustomComponents/PhotosComponentView.swift
1
8641
// // PhotosComponentView.swift // ASTextViewController // // Created by Adam J Share on 4/13/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import Photos import ASTextInputAccessoryView class PhotosComponentView: UIView { @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var selectButton: UIButton! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var searchBar: UISearchBar! @IBAction func selectButton(sender: UIButton) { sender.selected = !sender.selected if !sender.selected { reset() } else { collectionView.allowsMultipleSelection = true closeButton.setTitle("Done", forState: .Normal) UIView.animateWithDuration(0.2, animations: { self.layoutIfNeeded() }) } } var assets: PHFetchResult? var selectedAssets: [PHAsset] = [] override func awakeFromNib() { super.awakeFromNib() collectionView.registerClass(ImageCell.self, forCellWithReuseIdentifier: "Cell") collectionView.dataSource = self collectionView.delegate = self collectionView.layer.shadowOffset = CGSize(width: 0, height: 2) collectionView.layer.shadowColor = UIColor.blackColor().CGColor collectionView.layer.shadowOpacity = 0.2 collectionView.layer.shadowRadius = 2 } } extension PhotosComponentView: ASComponent { var contentHeight: CGFloat { return 200 } var textInputView: UITextInputTraits? { return searchBar } func animatedLayout(newheight: CGFloat) { collectionView.collectionViewLayout.invalidateLayout() collectionView.reloadData() } func postAnimationLayout(newheight: CGFloat) { collectionView.collectionViewLayout.invalidateLayout() } } extension PhotosComponentView { func reset() { selectButton.selected = false selectedAssets = [] collectionView.allowsMultipleSelection = false closeButton.setTitle("X", forState: .Normal) UIView.animateWithDuration(0.2, animations: { self.layoutIfNeeded() }) } @IBAction func close(sender: AnyObject) { var shouldBecomeFirstResponder = false if selectedAssets.count > 0 { for asset in selectedAssets { let options = PHImageRequestOptions() options.synchronous = true options.deliveryMode = .HighQualityFormat let m = PHImageManager.defaultManager() m.requestImageForAsset( asset, targetSize: UIScreen.mainScreen().bounds.size, contentMode: .Default, options: options ) { [weak self] (image, info) in guard let image = image else { return } if let view = self?.parentView?.components.first as? ASTextComponentView { view.textView.insertImages([image]) } } } shouldBecomeFirstResponder = true } let component = parentView?.components.first parentView?.selectedComponent = component reset() collectionView.contentOffset = CGPointZero if shouldBecomeFirstResponder { (component?.textInputView as? UIView)?.becomeFirstResponder() } } } // MARK: Photo library extension PhotosComponentView { func getPhotoLibrary() { let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] self.assets = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions) self.collectionView.reloadData() } } extension PhotosComponentView: UICollectionViewDataSource { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let assets = assets else { return 0 } return assets.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! ImageCell cell.asset = assets?[indexPath.item] as? PHAsset cell.selected = selectedAssets.contains(cell.asset!) return cell } } class ImageCell: UICollectionViewCell { override var selected: Bool { didSet { if selected { imageView.layer.borderColor = tintColor.CGColor imageView.layer.borderWidth = 4 } else { imageView.layer.borderWidth = 0 } } } var requestID: PHImageRequestID = 0 var asset: PHAsset? { didSet { imageView.image = nil if let asset = asset { let manager = PHImageManager.defaultManager() cancelRequest() requestID = manager.requestImageForAsset( asset, targetSize: frame.size, contentMode: .Default, options: nil ) { [weak self] (image, info) in guard let id = info?[PHImageResultRequestIDKey] as? NSNumber where PHImageRequestID(id.integerValue) == self?.requestID || self?.requestID == 0 else { return } self?.imageView.image = image } } } } func cancelRequest() { if requestID != 0 { PHImageManager.defaultManager().cancelImageRequest(requestID) requestID = 0 } } let imageView: UIImageView = UIImageView() override init(frame: CGRect) { super.init(frame: frame) setupViews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupViews() } func setupViews() { contentView.addSubview(imageView) imageView.autoLayoutToSuperview() imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true imageView.backgroundColor = UIColor.whiteColor() } } extension PhotosComponentView: UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let asset = assets![indexPath.item] as! PHAsset if selectButton.selected { selectedAssets.append(asset) return } let options = PHImageRequestOptions() options.synchronous = true options.deliveryMode = .HighQualityFormat let m = PHImageManager.defaultManager() m.requestImageForAsset( asset, targetSize: UIScreen.mainScreen().bounds.size, contentMode: .Default, options: options ) { [weak self] (image, info) in guard let image = image else { return } if let view = self?.parentView?.components.first as? ASTextComponentView { view.textView.insertImages([image]) self?.close(self!.closeButton) } } } func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { if let asset = assets![indexPath.item] as? PHAsset, let index = selectedAssets.indexOf(asset) { selectedAssets.removeAtIndex(index) } } } extension PhotosComponentView: UICollectionViewDelegateFlowLayout { override func layoutSubviews() { super.layoutSubviews() collectionView.collectionViewLayout.invalidateLayout() } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: collectionView.frame.size.height, height: collectionView.frame.size.height) } }
mit
9a114ca7ff2a771f8de6d183b12cbe1f
29.75089
169
0.594097
5.962733
false
false
false
false
michals92/iOS_skautIS
skautIS/MySTS.swift
1
6590
// // STS.swift // skautIS // // Copyright (c) 2015, Michal Simik // All rights reserved. // import UIKit import SWXMLHash class MySTS: UITableViewController, UITableViewDelegate, UITableViewDataSource { var stringData = "" var userName = NSString() var isNumberSTS = NSString() var storage = Storage() var xmlNumbers = SWXMLHash.parse("") /* Sets title when this view is showed. */ override func viewDidAppear(animated: Bool) { super.viewDidAppear(false) self.navigationController?.visibleViewController.title = "Moje STS" } /** Initial method. */ override func viewDidLoad() { super.viewDidLoad() if !loadNumbers() { performSegueWithIdentifier("nonSTS", sender: nil) } tableView.contentInset = UIEdgeInsetsMake(0, 0, 49, 0); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /** Gets name of logged user to display on screen. */ func getDisplayName() { var storage = Storage() var login = storage.loader("login") var app = storage.loader("app") var urlString = "http://test-is.skaut.cz/JunakWebservice/UserManagement.asmx" var userDetail = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" + "<soap:Body>" + "<UserDetail xmlns=\"https://is.skaut.cz/\">" + "<userDetailInput>" + "<ID_Login>\(login)</ID_Login>" + "</userDetailInput></UserDetail></soap:Body></soap:Envelope>" var request: Request = Request(request: userDetail,urlString: urlString) var result = request.getAnswer(self) var xml = SWXMLHash.parse(result) userName = xml["soap:Envelope"]["soap:Body"]["UserDetailResponse"]["UserDetailResult"]["UserName"].element!.text! } /** Loads id of person from UserDetail web service. @return string of logged user id */ func getDisplayNameFromUserDetail() -> String{ var login = storage.loader("login") var urlString = "http://test-is.skaut.cz/JunakWebservice/UserManagement.asmx" var userDetail = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><UserDetail xmlns=\"https://is.skaut.cz/\"><userDetailInput><ID_Login>\(login)</ID_Login></userDetailInput></UserDetail></soap:Body></soap:Envelope>" var request: Request = Request(request: userDetail,urlString: urlString) var result = request.getAnswer(self) var xml = SWXMLHash.parse(result) var displayName = "" if (xml["soap:Envelope"]["soap:Body"]["UserDetailResponse"]["UserDetailResult"]["ID_Person"].element?.text != nil) { displayName = xml["soap:Envelope"]["soap:Body"]["UserDetailResponse"]["UserDetailResult"]["ID_Person"].element!.text! } return displayName } /* Gets STS number of user. @return if number is presented */ func loadNumbers () -> Bool{ var login = storage.loader("login") var urlString = "http://test-is.skaut.cz/JunakWebservice/Telephony.asmx" var name = getDisplayNameFromUserDetail() var enrollNumberAll = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body><EnrollNumberAllPerson xmlns=\"https://is.skaut.cz/\"><enrollNumberAllPersonInput> <ID_Login>\(login)</ID_Login><ID_Person>\(name)</ID_Person></enrollNumberAllPersonInput></EnrollNumberAllPerson></soap:Body></soap:Envelope>" var request: Request = Request(request: enrollNumberAll,urlString: urlString) var result = request.getAnswer(self) xmlNumbers = SWXMLHash.parse(result) if xmlNumbers["soap:Envelope"]["soap:Body"]["EnrollNumberAllPersonResponse"]["EnrollNumberAllPersonResult"]["EnrollNumberAllPersonOutput"][0].element != nil { return true } else { return false } } /** Table view methods to add STS number of user. */ override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return xmlNumbers["soap:Envelope"]["soap:Body"]["EnrollNumberAllPersonResponse"]["EnrollNumberAllPersonResult"]["EnrollNumberAllPersonOutput"].all.count } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: MySTSCell = tableView.dequeueReusableCellWithIdentifier("MySTSCell", forIndexPath: indexPath) as! MySTSCell var MySTS = self.xmlNumbers["soap:Envelope"]["soap:Body"]["EnrollNumberAllPersonResponse"]["EnrollNumberAllPersonResult"]["EnrollNumberAllPersonOutput"] var holder = "držitel: " if (MySTS[indexPath.row]["HolderName"]) { holder += MySTS[indexPath.row]["HolderName"].element!.text! } var tariff = "tarif: " if (MySTS[indexPath.row]["Tariff"]) { tariff += MySTS[indexPath.row]["Tariff"].element!.text! } var tariffData = "data: " if (MySTS[indexPath.row]["TariffData"]) { tariffData += MySTS[indexPath.row]["TariffData"].element!.text! } var state = "stav: " if (MySTS[indexPath.row]["EnrollNumberState"]) { state += MySTS[indexPath.row]["EnrollNumberState"].element!.text! } //var tariff = "tarif: " + MySTS[indexPath.row]["Tariff"].element!.text! cell.setCell(MySTS[indexPath.row]["DisplayName"].element!.text!, holderLabel: holder, tariffLabel: tariff,dataTariffLabel: tariffData, stateLabel: state) return cell } }
bsd-3-clause
9c4d2726801c9b0404c23721610a60b8
39.429448
490
0.615723
4.337722
false
false
false
false
Verchen/Swift-Project
JinRong/JinRong/Classes/Bill(账单)/Controller/BillController.swift
1
5664
// // BillController.swift // JinRong // // Created by 乔伟成 on 2017/7/12. // Copyright © 2017年 乔伟成. All rights reserved. // import UIKit import Alamofire import ObjectMapper class BillController: BaseController, UITableViewDelegate, UITableViewDataSource { var billModel: BillModel? lazy var segmentView: UISegmentedControl = { var segment = UISegmentedControl(items: ["应还款", "已还款"]) segment.tintColor = UIColor.white segment.selectedSegmentIndex = 0 segment.setWidth(120, forSegmentAt: 0) segment.setWidth(120, forSegmentAt: 1) segment.addTarget(self, action: #selector(BillController.segmentChange(segment:)), for: .valueChanged) return segment }() //应还列表 lazy var repayView: UITableView = { var table = UITableView(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 64 - 49), style: .grouped) table.delegate = self table.dataSource = self table.separatorStyle = .none return table }() //已还列表 lazy var repaidView: UITableView = { var table = UITableView(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 64 - 49), style: .plain) table.delegate = self table.dataSource = self table.isHidden = true return table }() deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() setupConfig() navigationItem.titleView = segmentView view.addSubview(repayView) view.addSubview(repaidView) requestBillList() } func setupConfig() -> Void { NotificationCenter.default.addObserver(self, selector: #selector(BillController.requestBillList), name: NSNotification.Name(rawValue: LoginSuccessNotification), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(BillController.requestBillList), name: NSNotification.Name(rawValue: LogoutSuccessNotification), object: nil) } //MARK: - 网络请求方法 func requestBillList() -> Void { let param: Parameters = [ "userId":UserDefaults.standard.object(forKey: MemberIdKey) ?? "", "access_token":UserDefaults.standard.object(forKey: TokenKey) ?? "", "timestamp":Date.timeIntervalBetween1970AndReferenceDate ] Alamofire.request(URL_Bill, method: .post, parameters: param).responseJSON { (response) in guard let jsonDic = response.value as? NSDictionary else { return } if jsonDic["code"] as? Int == 200 { self.billModel = BillModel(JSON: jsonDic["data"] as! [String : Any]) self.repayView.reloadData() } } } //MARK: - tableview代理方法 func numberOfSections(in tableView: UITableView) -> Int { if tableView.isEqual(repayView) { return 2 }else{ return 1 } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView.isEqual(repayView) { if section == 0 { return 1 }else{ guard (billModel != nil) else { return 0 } return (billModel?.notYetList?.count)! } }else{ return 10 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if tableView.isEqual(repayView) { if indexPath.section == 0 { var cell = tableView.dequeueReusableCell(withIdentifier: "SumCell") as? SumCell if cell == nil { cell = SumCell(style: .default, reuseIdentifier: "SumCell") } cell?.model = billModel return cell! } var cell = tableView.dequeueReusableCell(withIdentifier: "BillCell") if cell == nil { cell = BillCell(style: .default, reuseIdentifier: "BillCell") } return cell! }else{ var cell = tableView.dequeueReusableCell(withIdentifier: "RepaidCell") if cell == nil { cell = RepaidCell(style: .default, reuseIdentifier: "RepaidCell") } return cell! } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if tableView.isEqual(repayView) { switch indexPath.section { case 0: return 85 default: return 195 + 40 } }else{ return 65 } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if tableView.isEqual(repayView) { return 20 }else{ return 0.001 } } //MARK: - 事件方法 func segmentChange(segment: UISegmentedControl) -> Void { if segment.selectedSegmentIndex == 0 { repayView.isHidden = false repaidView.isHidden = true }else{ repayView.isHidden = true repaidView.isHidden = false } } }
mit
89d49d9aca92eaf402bd12043a2129fa
32.692771
182
0.58019
4.800858
false
false
false
false
jonreiling/Rockbox-Framework-Swift
Source/Model/RBArtist.swift
1
1248
// // RBArtist.swift // AKQARockboxController // // Created by Jon Reiling on 9/7/14. // Copyright (c) 2014 AKQA. All rights reserved. // import Foundation import SwiftyJSON public class RBArtist : RBBase { public var artistArtworkURL:String? public var artistArtworkThumbnailURL:String? public var albums:[RBAlbum]? init( json: JSON ) { super.init() type = "artist" populateFromJSON(json) } override public func populateFromJSON( json : JSON ) { super.populateFromJSON(json) if let jsonArtworkURI = json["images"][0]["url"].string { self.artistArtworkURL = jsonArtworkURI } if let jsonArtistThumbnailURI = json["images"][2]["url"].string { self.artistArtworkThumbnailURL = jsonArtistThumbnailURI } if let jsonAlbums = json["items"].array { var albums:[RBAlbum] = [] for jsonAlbum in jsonAlbums { let album:RBAlbum = RBAlbum(json:jsonAlbum); albums.append(album) } self.albums = albums } } }
mit
28f31f1c3ef52f612b3c4c870e537f38
22.566038
73
0.536859
4.674157
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL/Vec2.swift
1
6199
// // Vec2.swift // SwiftGL // // Created by Scott Bennett on 2014-06-08. // Copyright (c) 2014 Scott Bennett. All rights reserved. // import Darwin import CoreGraphics public struct Vec2 { public var x, y: Float public init() { self.x = 0 self.y = 0 } // Explicit initializers public init(s: Float) { self.x = s self.y = s } public init(x: Float) { self.x = x self.y = 0 } public init(x: Int, y:Int) { self.x = Float(x) self.y = Float(y) } public init(x: Float, y: Float) { self.x = x self.y = y } // Implicit initializers public init(_ x: Float) { self.x = x self.y = 0 } public init(point:CGPoint) { self.x = Float(point.x) self.y = Float(point.y) } public init(cgVector:CGVector) { self.x = Float(cgVector.dx) self.y = Float(cgVector.dy) } public init(_ x: Float, _ y: Float) { self.x = x self.y = y } public var length2: Float { get { return x * x + y * y } } public var length: Float { get { return sqrt(self.length2) } set { self = length * normalize(self) } } public var unit:Vec2 { get{ return normalize(self) } } // Swizzle (Vec2) Properties public var xx: Vec2 {get {return Vec2(x: x, y: x)}} public var yx: Vec2 {get {return Vec2(x: y, y: x)} set(v) {self.y = v.x; self.x = v.y}} public var xy: Vec2 {get {return Vec2(x: x, y: y)} set(v) {self.x = v.x; self.y = v.y}} public var yy: Vec2 {get {return Vec2(x: y, y: y)}} // Swizzle (Vec3) Properties public var xxx: Vec3 {get {return Vec3(x: x, y: x, z: x)}} public var yxx: Vec3 {get {return Vec3(x: y, y: x, z: x)}} public var xyx: Vec3 {get {return Vec3(x: x, y: y, z: x)}} public var yyx: Vec3 {get {return Vec3(x: y, y: y, z: x)}} public var xxy: Vec3 {get {return Vec3(x: x, y: x, z: y)}} public var yxy: Vec3 {get {return Vec3(x: y, y: x, z: y)}} public var xyy: Vec3 {get {return Vec3(x: x, y: y, z: y)}} public var yyy: Vec3 {get {return Vec3(x: y, y: y, z: y)}} // Swizzle (Vec4) Properties public var xxxx: Vec4 {get {return Vec4(x: x, y: x, z: x, w: x)}} public var yxxx: Vec4 {get {return Vec4(x: y, y: x, z: x, w: x)}} public var xyxx: Vec4 {get {return Vec4(x: x, y: y, z: x, w: x)}} public var yyxx: Vec4 {get {return Vec4(x: y, y: y, z: x, w: x)}} public var xxyx: Vec4 {get {return Vec4(x: x, y: x, z: y, w: x)}} public var yxyx: Vec4 {get {return Vec4(x: y, y: x, z: y, w: x)}} public var xyyx: Vec4 {get {return Vec4(x: x, y: y, z: y, w: x)}} public var yyyx: Vec4 {get {return Vec4(x: y, y: y, z: y, w: x)}} public var xxxy: Vec4 {get {return Vec4(x: x, y: x, z: x, w: y)}} public var yxxy: Vec4 {get {return Vec4(x: y, y: x, z: x, w: y)}} public var xyxy: Vec4 {get {return Vec4(x: x, y: y, z: x, w: y)}} public var yyxy: Vec4 {get {return Vec4(x: y, y: y, z: x, w: y)}} public var xxyy: Vec4 {get {return Vec4(x: x, y: x, z: y, w: y)}} public var yxyy: Vec4 {get {return Vec4(x: y, y: x, z: y, w: y)}} public var xyyy: Vec4 {get {return Vec4(x: x, y: y, z: y, w: y)}} public var yyyy: Vec4 {get {return Vec4(x: y, y: y, z: y, w: y)}} } // Make it easier to interpret Vec2 as a string extension Vec2: CustomStringConvertible, CustomDebugStringConvertible { public var description: String {get {return "(\(x), \(y))"}} public var debugDescription: String {get {return "Vec2(x: \(x), y: \(y))"}} } extension Vec2{ public var tojson:String{get{return "{\"x\":\(x),\"y\":\(y)}"}} } // Vec2 Prefix Operators public prefix func - (v: Vec2) -> Vec2 {return Vec2(x: -v.x, y: -v.y)} // Vec2 Infix Operators public func + (a: Vec2, b: Vec2) -> Vec2 {return Vec2(x: a.x + b.x, y: a.y + b.y)} public func - (a: Vec2, b: Vec2) -> Vec2 {return Vec2(x: a.x - b.x, y: a.y - b.y)} public func * (a: Vec2, b: Vec2) -> Vec2 {return Vec2(x: a.x * b.x, y: a.y * b.y)} public func / (a: Vec2, b: Vec2) -> Vec2 {return Vec2(x: a.x / b.x, y: a.y / b.y)} // Vec2 Scalar Operators public func * (s: Float, v: Vec2) -> Vec2 {return Vec2(x: s * v.x, y: s * v.y)} public func * (v: Vec2, s: Float) -> Vec2 {return Vec2(x: v.x * s, y: v.y * s)} public func / (v: Vec2, s: Float) -> Vec2 {return Vec2(x: v.x / s, y: v.y / s)} // Vec2 Assignment Operators public func += (a: inout Vec2, b: Vec2) {a = a + b} public func -= (a: inout Vec2, b: Vec2) {a = a - b} public func *= (a: inout Vec2, b: Vec2) {a = a * b} public func /= (a: inout Vec2, b: Vec2) {a = a / b} public func *= (a: inout Vec2, b: Float) {a = a * b} public func /= (a: inout Vec2, b: Float) {a = a / b} public func < (a:Vec2,b:Vec2)->Bool { return (a.x < b.x && a.y < b.y) } public func <= (a:Vec2,b:Vec2)->Bool { return (a.x <= b.x && a.y <= b.y) } public func >= (a:Vec2,b:Vec2)->Bool { return (a.x >= b.x && a.y >= b.y) } public func > (a:Vec2,b:Vec2)->Bool { return (a.x > b.x && a.y > b.y) } // Functions which operate on Vec2 public func length(_ v: Vec2) -> Float {return v.length} public func length2(_ v: Vec2) -> Float {return v.length2} public func normalize(_ v: Vec2) -> Vec2 {return v / v.length} public func dot(_ a: Vec2, b: Vec2) -> Float {return a.x * b.x + a.y * b.y} public func clamp(_ value: Vec2, min: Float, max: Float) -> Vec2 {return Vec2(clamp(value.x, min: min, max: max), clamp(value.y, min: min, max: max))} public func mix(_ a: Vec2, b: Vec2, t: Float) -> Vec2 {return a + (b - a) * t} public func smoothstep(_ a: Vec2, b: Vec2, t: Float) -> Vec2 {return mix(a, b: b, t: t * t * (3 - 2 * t))} public func clamp(_ value: Vec2, min: Vec2, max: Vec2) -> Vec2 {return Vec2(clamp(value.x, min: min.x, max: max.x), clamp(value.y, min: min.y, max: max.y))} public func mix(_ a: Vec2, b: Vec2, t: Vec2) -> Vec2 {return a + (b - a) * t} public func smoothstep(_ a: Vec2, b: Vec2, t: Vec2) -> Vec2 {return mix(a, b: b, t: t * t * (Vec2(s: 3) - 2 * t))}
mit
1f752ff430719e5b6fb717789ef00c96
34.022599
156
0.542184
2.586149
false
false
false
false
rain2540/RGAppTools
Sources/AppCommons/UISingleton.swift
1
624
// // UISingleton.swift // RGAppTools // // Created by RAIN on 2020/1/21. // Copyright © 2020 Smartech. All rights reserved. // import UIKit /// Application public let SharedApplication = UIApplication.shared /// AppDelegate public let SharedAppDelegate = UIApplication.shared.delegate /// Main Window public let AppMainWindow = UIApplication.shared.delegate?.window /// Root View Controller public let RootViewController = UIApplication.shared.delegate?.window??.rootViewController /// Key Window public let AppKeyWindow = UIApplication.shared.keyWindow /// Main Screen public let AppMainScreen = UIScreen.main
mpl-2.0
ea29256632b402430b7a8ecd3eaa2bd1
22.074074
90
0.770465
4.356643
false
false
false
false
drewcrawford/DCAKit
DCAKit/UIKit Additions/AutoLayout/UIView+AutolayoutPushPop.swift
1
2781
// // UIView+AutolayoutPop.swift // DCAKit // // Created by Drew Crawford on 8/24/14. // Copyright (c) 2015 DrewCrawfordApps. // This file is part of DCAKit. It is subject to the license terms in the LICENSE // file found in the top level of this distribution and at // https://github.com/drewcrawford/DCAKit/blob/master/LICENSE. // No part of DCAKit, including this file, may be copied, modified, // propagated, or distributed except according to the terms contained // in the LICENSE file. import UIKit private var constraintStack = Dictionary<UIView,[[NSLayoutConstraint]]>() extension NSLayoutConstraint { public func DCACopy() -> NSLayoutConstraint { //it's either NSLayoutConstraint, or some private subclass if object_getClassName(self)=="NSLayoutConstraint" { //if it's (exactly) NSLayoutConstraint, then we can copy it return NSLayoutConstraint(item: self.firstItem, attribute: self.firstAttribute, relatedBy: self.relation, toItem: self.secondItem, attribute: self.secondAttribute, multiplier: self.multiplier, constant: self.constant) } else { //otherwise, we can't safely copy it. Let's just return it. return self } } /** Returns a dictionary that can be tested for value equality.*/ public func DCAEqualityBag() -> Dictionary<String,AnyObject!> { //overriding the actual isEqual here fucks up UIAlertView of all things //the absurd NSNumber casting is a workaround for rdar://18116576 var maybeItem : AnyObject = self.secondItem ?? (NSNull() as AnyObject) //fatal error: attempt to bridge an implicitly unwrapped optional containing nil return ["fi":self.firstItem,"fa":NSNumber(integer:self.firstAttribute.rawValue),"re":NSNumber(integer:self.relation.rawValue),"si":maybeItem,"sa":NSNumber(integer:self.secondAttribute.rawValue),"mu":NSNumber(float:Float(self.multiplier)),"co":NSNumber(float:Float(self.constant))] } } extension UIView { /**Push (saves) the constraints onto the stack */ public func pushConstraints() { var viewStack = constraintStack[self] if viewStack==nil { viewStack = [] } let arr:[NSLayoutConstraint] = (self.constraints() as! [NSLayoutConstraint]).map({x in x.DCACopy()}) println(arr) println(self.constraints()) viewStack!.append(arr) constraintStack[self] = viewStack! } /** Pops (restores) the constraints from the stack */ public func popConstraints() { var viewStack = constraintStack[self]! let newConstraints = viewStack.last viewStack.removeLast() constraintStack[self] = viewStack self.removeConstraints(self.constraints()) self.addConstraints(newConstraints!) } }
mit
994c160ddfe7019b47ac229660efb0c3
43.870968
284
0.697591
4.365777
false
false
false
false
natecook1000/swift
test/Interpreter/collection_casts.swift
3
3128
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -o %t/main // RUN: %target-build-swift %s -o %t/main-optimized // RUN: %target-codesign %t/main // RUN: %target-codesign %t/main-optimized // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-run %t/main-optimized | %FileCheck %s // REQUIRES: executable_test protocol Preening { func preen() } struct A : Preening, Hashable, Equatable { private var value: Int init(_ value: Int) { self.value = value } func preen() { print("A\(value)") } static func ==(lhs: A, rhs: A) -> Bool { return lhs.value == rhs.value } var hashValue: Int { return value.hashValue } } do { print("Arrays.") // CHECK: Arrays. let a_array = [ A(5), A(10), A(20) ] a_array.forEach { $0.preen() } // CHECK-NEXT: A5 // CHECK-NEXT: A10 // CHECK-NEXT: A20 let preening_array_1 = a_array as [Preening] preening_array_1.forEach { $0.preen() } // CHECK-NEXT: A5 // CHECK-NEXT: A10 // CHECK-NEXT: A20 let any_array_1 = preening_array_1 as [Any] print(any_array_1.count) // CHECK-NEXT: 3 let preening_array_2 = any_array_1 as! [Preening] preening_array_2.forEach { $0.preen() } // CHECK-NEXT: A5 // CHECK-NEXT: A10 // CHECK-NEXT: A20 let preening_array_3 = any_array_1 as? [Preening] preening_array_3?.forEach { $0.preen() } // CHECK-NEXT: A5 // CHECK-NEXT: A10 // CHECK-NEXT: A20 let a_array_2 = any_array_1 as! [A] a_array_2.forEach { $0.preen() } // CHECK-NEXT: A5 // CHECK-NEXT: A10 // CHECK-NEXT: A20 let a_array_3 = any_array_1 as? [Preening] a_array_3?.forEach { $0.preen() } // CHECK-NEXT: A5 // CHECK-NEXT: A10 // CHECK-NEXT: A20 } do { print("Dictionaries.") // CHECK-NEXT: Dictionaries. let a_dict = ["one" : A(1), "two" : A(2), "three" : A(3)] print("begin") a_dict.forEach { $0.1.preen() } print("end") // CHECK-NEXT: begin // CHECK-DAG: A1 // CHECK-DAG: A2 // CHECK-DAG: A3 // CHECK-NEXT: end let preening_dict_1 = a_dict as [String: Preening] print("begin") preening_dict_1.forEach { $0.1.preen() } print("end") // CHECK-NEXT: begin // CHECK-DAG: A1 // CHECK-DAG: A2 // CHECK-DAG: A3 // CHECK-NEXT: end let any_dict_1 = preening_dict_1 as [String: Any] print(any_dict_1.count) // CHECK-NEXT: 3 let preening_dict_2 = any_dict_1 as! [String: Preening] print("begin") preening_dict_2.forEach { $0.1.preen() } print("end") // CHECK-NEXT: begin // CHECK-DAG: A1 // CHECK-DAG: A2 // CHECK-DAG: A3 // CHECK-NEXT: end let preening_dict_3 = any_dict_1 as? [String: Preening] print("begin") preening_dict_3?.forEach { $0.1.preen() } print("end") // CHECK-NEXT: begin // CHECK-DAG: A1 // CHECK-DAG: A2 // CHECK-DAG: A3 // CHECK-NEXT: end let a_dict_2 = any_dict_1 as! [String: A] print("begin") a_dict_2.forEach { $0.1.preen() } print("end") // CHECK-NEXT: begin // CHECK-DAG: A1 // CHECK-DAG: A2 // CHECK-DAG: A3 // CHECK-NEXT: end let a_dict_3 = any_dict_1 as? [String: A] print("begin") a_dict_3?.forEach { $0.1.preen() } print("end") // CHECK-NEXT: begin // CHECK-DAG: A1 // CHECK-DAG: A2 // CHECK-DAG: A3 // CHECK-NEXT: end } // TODO: I can't think of any way to do this for sets and dictionary // keys that doesn't involve bridging.
apache-2.0
62bbfad3d0d4f5dc7ef17bf9c63f5b9f
19.853333
68
0.634271
2.472727
false
false
false
false
superk589/DereGuide
DereGuide/Card/View/SpreadImageView.swift
2
3285
// // SpreadImageView.swift // DereGuide // // Created by zzk on 16/7/7. // Copyright © 2016 zzk. All rights reserved. // import UIKit import SDWebImage import SnapKit import ImageViewer class SpreadImageView: UIImageView, UIGestureRecognizerDelegate { let progressIndicator = UIProgressView() var url: URL? override init(frame: CGRect) { super.init(frame: frame) contentMode = .scaleAspectFit clipsToBounds = true backgroundColor = .black addSubview(progressIndicator) progressIndicator.snp.makeConstraints { (make) in make.bottom.left.right.equalToSuperview() make.height.equalTo(2) } isUserInteractionEnabled = true let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap(_:))) doubleTap.numberOfTapsRequired = 2 addGestureRecognizer(doubleTap) doubleTap.delegate = self } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { return otherGestureRecognizer is UITapGestureRecognizer } @objc func handleDoubleTap(_ tap: UITapGestureRecognizer) { if let url = self.url { if let key = SDWebImageManager.shared.cacheKey(for: url) { SDImageCache.shared.removeImage(forKey: key, withCompletion: { self.setImage(with: url) }) } } } convenience init() { self.init(frame: .zero) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func hideIndicator() { progressIndicator.isHidden = true } private func showIndicator() { progressIndicator.isHidden = false } override var intrinsicContentSize: CGSize { return image?.size ?? .zero } func setImage(with url: URL, shouldShowIndicator: Bool = true) { self.url = url guard let key = SDWebImageManager.shared.cacheKey(for: url) else { return } SDImageCache.shared.diskImageExists(withKey: key) { [weak self] (isInCache) in if !UserDefaults.standard.shouldCacheFullImage && !isInCache && CGSSGlobal.isMobileNet() { return } else { if shouldShowIndicator { self?.showIndicator() } else { self?.hideIndicator() } self?.sd_setImage(with: url, placeholderImage: nil, options: [.retryFailed, .progressiveLoad], progress: { (current, total, url) in DispatchQueue.main.async { self?.progressIndicator.progress = Float(current) / Float(total) } }) { (image, error, cacheType, url) in DispatchQueue.main.async { self?.progressIndicator.progress = 1 self?.hideIndicator() self?.invalidateIntrinsicContentSize() } } } } } }
mit
85b6d32aa3cb9ce02a9e79615e554322
30.576923
148
0.5743
5.491639
false
false
false
false
danwey/INSPhotoGallery
INSPhotoGallery/INSPhotosInteractionAnimator.swift
1
6966
// // INSInteractionAnimator.swift // INSPhotoViewer // // Created by Michal Zaborowski on 28.02.2016. // Copyright © 2016 Inspace Labs Sp z o. o. Spółka Komandytowa. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this library 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 class INSPhotosInteractionAnimator: NSObject, UIViewControllerInteractiveTransitioning { var animator: UIViewControllerAnimatedTransitioning? var viewToHideWhenBeginningTransition: UIView? var shouldAnimateUsingAnimator: Bool = false private var transitionContext: UIViewControllerContextTransitioning? func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) { viewToHideWhenBeginningTransition?.alpha = 0.0 self.transitionContext = transitionContext } func handlePanWithPanGestureRecognizer(gestureRecognizer: UIPanGestureRecognizer, viewToPan: UIView, anchorPoint: CGPoint) { guard let fromView = transitionContext?.viewForKey(UITransitionContextFromViewKey) else { return } let translatedPanGesturePoint = gestureRecognizer.translationInView(fromView) let newCenterPoint = CGPoint(x: anchorPoint.x, y: anchorPoint.y + translatedPanGesturePoint.y) viewToPan.center = newCenterPoint let verticalDelta = newCenterPoint.y - anchorPoint.y let backgroundAlpha = backgroundAlphaForPanningWithVerticalDelta(verticalDelta) fromView.backgroundColor = fromView.backgroundColor?.colorWithAlphaComponent(backgroundAlpha) if gestureRecognizer.state == .Ended { finishPanWithPanGestureRecognizer(gestureRecognizer, verticalDelta: verticalDelta,viewToPan: viewToPan, anchorPoint: anchorPoint) } } func finishPanWithPanGestureRecognizer(gestureRecognizer: UIPanGestureRecognizer, verticalDelta: CGFloat, viewToPan: UIView, anchorPoint: CGPoint) { guard let fromView = transitionContext?.viewForKey(UITransitionContextFromViewKey) else { return } let returnToCenterVelocityAnimationRatio = 0.00007 let panDismissDistanceRatio = 50.0 / 667.0 // distance over iPhone 6 height let panDismissMaximumDuration = 0.45 let velocityY = gestureRecognizer.velocityInView(gestureRecognizer.view).y var animationDuration = (Double(abs(velocityY)) * returnToCenterVelocityAnimationRatio) + 0.2 var animationCurve: UIViewAnimationOptions = .CurveEaseOut var finalPageViewCenterPoint = anchorPoint var finalBackgroundAlpha = 1.0 let dismissDistance = panDismissDistanceRatio * Double(fromView.bounds.height) let isDismissing = Double(abs(verticalDelta)) > dismissDistance var didAnimateUsingAnimator = false if isDismissing { if let animator = self.animator, let transitionContext = transitionContext where shouldAnimateUsingAnimator { animator.animateTransition(transitionContext) didAnimateUsingAnimator = true } else { let isPositiveDelta = verticalDelta >= 0 let modifier: CGFloat = isPositiveDelta ? 1 : -1 let finalCenterY = fromView.bounds.midY + modifier * fromView.bounds.height finalPageViewCenterPoint = CGPoint(x: fromView.center.x, y: finalCenterY) animationDuration = Double(abs(finalPageViewCenterPoint.y - viewToPan.center.y) / abs(velocityY)) animationDuration = min(animationDuration, panDismissMaximumDuration) animationCurve = .CurveEaseOut finalBackgroundAlpha = 0.0 } } if didAnimateUsingAnimator { self.transitionContext = nil } else { UIView.animateWithDuration(animationDuration, delay: 0, options: animationCurve, animations: { () -> Void in viewToPan.center = finalPageViewCenterPoint fromView.backgroundColor = fromView.backgroundColor?.colorWithAlphaComponent(CGFloat(finalBackgroundAlpha)) }, completion: { finished in if isDismissing { self.transitionContext?.finishInteractiveTransition() } else { self.transitionContext?.cancelInteractiveTransition() if !self.isRadar20070670Fixed() { self.fixCancellationStatusBarAppearanceBug() } } self.viewToHideWhenBeginningTransition?.alpha = 1.0 self.transitionContext?.completeTransition(isDismissing && !(self.transitionContext?.transitionWasCancelled() ?? false)) self.transitionContext = nil }) } } private func fixCancellationStatusBarAppearanceBug() { guard let toViewController = self.transitionContext?.viewControllerForKey(UITransitionContextToViewControllerKey), let fromViewController = self.transitionContext?.viewControllerForKey(UITransitionContextFromViewControllerKey) else { return } let statusBarViewControllerSelector = Selector("_setPresentedSta" + "tusBarViewController:") if toViewController.respondsToSelector(statusBarViewControllerSelector) && fromViewController.modalPresentationCapturesStatusBarAppearance { toViewController.performSelector(statusBarViewControllerSelector, withObject: fromViewController) } } private func isRadar20070670Fixed() -> Bool { return NSProcessInfo.processInfo().isOperatingSystemAtLeastVersion(NSOperatingSystemVersion.init(majorVersion: 8, minorVersion: 3, patchVersion: 0)) } private func backgroundAlphaForPanningWithVerticalDelta(delta: CGFloat) -> CGFloat { guard let fromView = transitionContext?.viewForKey(UITransitionContextFromViewKey) else { return 0.0 } let startingAlpha: CGFloat = 1.0 let finalAlpha: CGFloat = 0.1 let totalAvailableAlpha = startingAlpha - finalAlpha let maximumDelta = CGFloat(fromView.bounds.height / 2.0) let deltaAsPercentageOfMaximum = min(abs(delta) / maximumDelta, 1.0) return startingAlpha - (deltaAsPercentageOfMaximum * totalAvailableAlpha) } }
apache-2.0
c00f588302eb2c899d9a45c407c1fdae
48.042254
156
0.688784
5.817043
false
false
false
false
russbishop/swift
test/IRGen/swift3-metadata-coff.swift
1
995
// RUN: %swift -target thumbv7--windows-itanium -parse-stdlib -parse-as-library -module-name Swift -O -emit-ir %s -o - | FileCheck %s public enum Optional<Wrapped> { case none case some(Wrapped) } public protocol P { associatedtype T } public struct S : P { public typealias T = Optional<S> } public func f(s : S) -> (() -> ()) { return { _ = s } } // CHECK-DAG: @"\01l__swift3_capture_descriptor" = private constant {{.*}}, section ".sw3cptr" // CHECK-DAG: @{{[0-9]+}} = private constant [3 x i8] c"Sq\00", section ".sw3tyrf" // CHECK-DAG: @{{[0-9]+}} = private constant [5 x i8] c"none\00", section ".sw3rfst" // CHECK-DAG: @{{[0-9]+}} = private constant [5 x i8] c"some\00", section ".sw3rfst" // CHECK-DAG: @"\01l__swift3_reflection_metadata" = private constant {{.*}}, section ".sw3flmd" // CHECK-DAG: @"\01l__swift3_assocty_metadata" = private constant {{.*}}, section ".sw3asty" // CHECK-DAG: @"\01l__swift3_builtin_metadata" = private constant {{.*}}, section ".sw3bltn"
apache-2.0
00d4b1833ce1d9d260d1791e0a3b1e18
35.851852
133
0.631156
2.987988
false
false
false
false
koba-uy/chivia-app-ios
src/Pods/LGButton/LGButton/Classes/SwiftIconFont/FontLoader.swift
3
1494
// // FontLoader.swift // SwiftIconFont // // Created by Sedat Ciftci on 18/03/16. // Copyright © 2016 Sedat Gokbek Ciftci. All rights reserved. // import UIKit import Foundation import CoreText class FontLoader: NSObject { class func loadFont(_ fontName: String) { let bundle = Bundle(for: FontLoader.self) var fontURL = URL(string: "") for filePath : String in bundle.paths(forResourcesOfType: "ttf", inDirectory: nil) { let filename = NSURL(fileURLWithPath: filePath).lastPathComponent! if filename.lowercased().range(of: fontName.lowercased()) != nil { fontURL = NSURL(fileURLWithPath: filePath) as URL } } do { let data = try Data(contentsOf: fontURL!) let provider = CGDataProvider(data: data as CFData) let font = CGFont.init(provider!) var error: Unmanaged<CFError>? if !CTFontManagerRegisterGraphicsFont(font!, &error) { let errorDescription: CFString = CFErrorCopyDescription(error!.takeUnretainedValue()) let nsError = error!.takeUnretainedValue() as AnyObject as! NSError NSException(name: NSExceptionName.internalInconsistencyException, reason: errorDescription as String, userInfo: [NSUnderlyingErrorKey: nsError]).raise() } } catch { } } }
lgpl-3.0
3ae72858dcb0ae3110c67d0c071434b8
32.177778
168
0.594106
5.202091
false
false
false
false
GraphQLSwift/GraphQL
Sources/GraphQL/GraphQLRequest.swift
1
1799
import Foundation /// A GraphQL request object, containing `query`, `operationName`, and `variables` fields public struct GraphQLRequest: Equatable, Codable { public var query: String public var operationName: String? public var variables: [String: Map] public init(query: String, operationName: String? = nil, variables: [String: Map] = [:]) { self.query = query self.operationName = operationName self.variables = variables } // To handle decoding with a default of variables = [] public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) query = try container.decode(String.self, forKey: .query) operationName = try container.decodeIfPresent(String.self, forKey: .operationName) variables = try container.decodeIfPresent([String: Map].self, forKey: .variables) ?? [:] } /// Boolean indicating if the GraphQL request is a subscription operation. /// This operation performs an entire AST parse on the GraphQL request, so consider /// performance when calling multiple times. /// /// - Returns: True if request is a subscription, false if it is an atomic operation (like `query` or `mutation`) public func isSubscription() throws -> Bool { let documentAST = try GraphQL.parse( instrumentation: NoOpInstrumentation, source: Source(body: query, name: "GraphQL request") ) let firstOperation = documentAST.definitions.compactMap { $0 as? OperationDefinition }.first guard let operationType = firstOperation?.operation else { throw GraphQLError(message: "GraphQL operation type could not be determined") } return operationType == .subscription } }
mit
ed7e899a70d23eab00fd8e3626087949
45.128205
117
0.682046
4.942308
false
false
false
false
playbasis/native-sdk-ios
PlaybasisSDK/Classes/PBModel/PBReward.swift
1
1094
// // PBReward.swift // Playbook // // Created by Nuttapol Thitaweera on 6/20/2559 BE. // Copyright © 2559 smartsoftasia. All rights reserved. // import UIKit import ObjectMapper public enum RewardType:String { case Goods = "GOODS" case Badge = "BADGE" } public class PBReward: PBModel { public var value:String? public var type:RewardType = .Goods public var rewardId:String? public var rewardData:PBRewardData? public override init() { super.init() } required public init?(_ map: Map) { super.init(map) } override public func mapping(map: Map) { super.mapping(map) value <- map["reward_value"] type <- (map["reward_type"], EnumTransform<RewardType>()) rewardId <- map["reward_id"] rewardData <- map["reward_data"] } class func pbRewardFromGoodsApiResponse(apiResponse:PBApiResponse) -> [PBReward] { var goods:[PBReward] = [] goods = Mapper<PBReward>().mapArray(apiResponse.parsedJson!["goods"])! return goods } }
mit
c39a039ecc77ef811a6e78da62233f37
20.431373
86
0.614822
3.903571
false
false
false
false
materik/stubborn
Stubborn/Stub/Delay.swift
1
1185
extension Stubborn { public struct Delay { public fileprivate(set) var rawValue: TimeInterval public init(_ rawValue: TimeInterval = 0) { self.rawValue = rawValue } func asyncAfter(_ fire: @escaping () -> ()) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + self.rawValue, execute: fire ) } } } extension Stubborn.Delay: CustomStringConvertible { public var description: String { return "Delay(\(self.rawValue))" } } extension Stubborn.Delay: ExpressibleByFloatLiteral { public typealias FloatLiteralType = TimeInterval public init(floatLiteral value: TimeInterval) { self.rawValue = value } } extension Stubborn.Delay: ExpressibleByIntegerLiteral { public typealias IntegerLiteralType = TimeInterval public init(integerLiteral value: TimeInterval) { self.rawValue = value } } public func + (lhs: Stubborn.Delay, rhs: Stubborn.Delay) -> Stubborn.Delay { return Stubborn.Delay(lhs.rawValue + rhs.rawValue) }
mit
2db027ddf09aa348b8705a4d78a14c12
21.358491
76
0.603376
5.107759
false
false
false
false
wordpress-mobile/WordPress-Aztec-iOS
AztecTests/Formatters/PreFormaterTests.swift
2
2096
import XCTest @testable import Aztec // MARK: - PreFormatterTests Tests // class PreFormatterTests: XCTestCase { /// Verifies that the PreFormatter is not interacting with NSTextAttachment Attributes, that are unrelated /// to the formatter's behavior. /// func testPreFormatterDoesNotLooseAttachmentAttribuesOnRemove() { let placeholderAttributes: [NSAttributedString.Key: Any] = [ .font: "Value", .paragraphStyle: NSParagraphStyle() ] let stringAttributes: [NSAttributedString.Key: Any] = [ .attachment: NSTextAttachment(), ] let formatter = PreFormatter(placeholderAttributes: placeholderAttributes) let updated = formatter.remove(from: stringAttributes) let expectedValue = stringAttributes[.attachment] as! NSTextAttachment let updatedValue = updated[.attachment] as! NSTextAttachment XCTAssert(updatedValue == expectedValue) } /// Tests that the Pre formatter doesn't drop the inherited ParagraphStyle. /// /// Issue: /// https://github.com/wordpress-mobile/AztecEditor-iOS/issues/993 /// func testPreFormatterDoesNotDropInheritedParagraphStyle(){ let placeholderAttributes: [NSAttributedString.Key: Any] = [ .font: "Value", .paragraphStyle: NSParagraphStyle() ] let div = HTMLDiv(with: nil) let paragraphStyle = ParagraphStyle() paragraphStyle.appendProperty(div) let previousAttributes: [NSAttributedString.Key: Any] = [.paragraphStyle: paragraphStyle] let formatter = PreFormatter(placeholderAttributes: placeholderAttributes) let newAttributes = formatter.apply(to: previousAttributes, andStore: nil) guard let newParagraphStyle = newAttributes[.paragraphStyle] as? ParagraphStyle else { XCTFail() return } XCTAssert(newParagraphStyle.hasProperty(where: { property -> Bool in return property === div })) } }
gpl-2.0
a7a09ac9773f3efda5721bc48f988aec
33.360656
110
0.653149
5.515789
false
true
false
false
csujedihy/Flicks
MoviesViewer/MoviesViewController.swift
1
10662
// // MoviesViewController.swift // MoviesViewer // // Created by YiHuang on 1/22/16. // Copyright © 2016 c2fun. All rights reserved. // import UIKit import AFNetworking import PKHUD import MJRefresh class MoviesViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIGestureRecognizerDelegate, UISearchBarDelegate { let gradientLayer = CAGradientLayer() var movies: [NSDictionary]? var filteredMovies: [NSDictionary]? var header: MJRefreshNormalHeader? = nil var endpoint: String! var kbHide: Int = 0 @IBOutlet weak var networkProblemView: UIView! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var searchBar: UISearchBar! func handleTap(gestureRecognizer: UIGestureRecognizer) { self.view.endEditing(true) } @IBAction func onTapNetworkView(sender: AnyObject) { networkProblemView.hidden = true fetchMoivesData(true) } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { // a little trick to distinguish imageView from other views if (searchBar.isFirstResponder()) { return true } else { return false } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // print(sender?.description) if segue.identifier == "gotoMovieDetail" { let destinationView:detailMoviePageController = segue.destinationViewController as! detailMoviePageController destinationView.movieId = (sender as! MovieCollectoinCell).movieId } } func headerRefresh(){ fetchMoivesData(true) } func fetchMoivesData(pullFlag: Bool) { let apiKey = "a07e22bc18f5cb106bfe4cc1f83ad8ed" let url = NSURL(string: "https://api.themoviedb.org/3/movie/\(self.endpoint)?api_key=\(apiKey)") let request = NSURLRequest(URL: url!) let session = NSURLSession( configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: NSOperationQueue.mainQueue() ) let task: NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: { (dataOrNil, response, error) in if let _ = error { if pullFlag == true { self.collectionView.mj_header.endRefreshing() self.networkProblemView.hidden = false } else { self.networkProblemView.hidden = false } self.collectionView.reloadData() return } if let data = dataOrNil { if let responseDictionary = try! NSJSONSerialization.JSONObjectWithData( data, options:[]) as? NSDictionary { self.movies = responseDictionary["results"] as? [NSDictionary] if pullFlag == true { self.collectionView.mj_header.endRefreshing() } else { PKHUD.sharedHUD.hide() } self.filteredMovies = self.movies self.collectionView.reloadData() } } }) task.resume() } override func preferredStatusBarStyle() -> UIStatusBarStyle { //LightContent return UIStatusBarStyle.Default //Default //return UIStatusBarStyle.Default } override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self searchBar.delegate = self networkProblemView.hidden = true let onTapGesture: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("handleTap:")) onTapGesture.delegate = self self.view.addGestureRecognizer(onTapGesture) PKHUD.sharedHUD.contentView = PKHUDProgressView() PKHUD.sharedHUD.show() header = MJRefreshNormalHeader() if let hdr = header { hdr.setTitle("Pull down to refresh", forState: MJRefreshState.Idle) hdr.setTitle("Release to refresh", forState: MJRefreshState.Pulling) hdr.setTitle("Loading...", forState: MJRefreshState.Refreshing) hdr.setRefreshingTarget(self, refreshingAction: Selector("headerRefresh")) hdr.stateLabel?.hidden = true } self.collectionView.mj_header = header // true => fetching triggered by pull gesture, false => fetching at starting fetchMoivesData(false) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // This method updates filteredData based on the text in the Search Box func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if searchText.isEmpty { filteredMovies = movies } else { filteredMovies = searchText.isEmpty ? movies : movies!.filter({(dataItem: NSDictionary) -> Bool in // If dataItem matches the searchText, return true to include it if (dataItem["title"] as! String).rangeOfString(searchText, options: .CaseInsensitiveSearch) != nil { return true } else { return false } }) } collectionView.reloadData() } func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { let cell:MovieCollectoinCell = collectionView.cellForItemAtIndexPath(indexPath) as! MovieCollectoinCell cell.layer.cornerRadius = 10.0 cell.layer.borderColor = UIColor.whiteColor().CGColor cell.layer.borderWidth = 3.0 return true } func collectionView(collectionView: UICollectionView, didUnhighlightItemAtIndexPath indexPath: NSIndexPath) { if collectionView == self.collectionView { let cell:MovieCollectoinCell = collectionView.cellForItemAtIndexPath(indexPath) as! MovieCollectoinCell UIView.animateWithDuration(0.2, animations: { () -> Void in }, completion: { (sucess) -> Void in cell.layer.borderWidth = 0 }) } } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let movies = filteredMovies { return movies.count } else { return -1 } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MovieCollectoinCell", forIndexPath: indexPath) as! MovieCollectoinCell let movie = filteredMovies![indexPath.row] if let posterPath = movie["poster_path"] as? String { let posterBaseUrl = "http://image.tmdb.org/t/p/w45" let posterUrl = NSURL(string: posterBaseUrl + posterPath) let imageRequest = NSURLRequest(URL: posterUrl!) let largeImageBaseUrl = "http://image.tmdb.org/t/p/original" let largePosterUrl = NSURL(string: largeImageBaseUrl + posterPath) let fullImageRequest = NSURLRequest(URL: largePosterUrl!) cell.movieId = movie["id"] as! Int cell.posterViewInCollectionCell.setImageWithURLRequest( imageRequest, placeholderImage: nil, success: { (imageRequest, imageResponse, image) -> Void in cell.posterViewInCollectionCell.alpha = 0.0 cell.posterViewInCollectionCell.image = image UIView.animateWithDuration(0.3, animations: { () -> Void in cell.posterViewInCollectionCell.alpha = 1.0 }, completion: { (sucess) -> Void in // The AFNetworking ImageView Category only allows one request to be sent at a time cell.posterViewInCollectionCell.setImageWithURLRequest( fullImageRequest, placeholderImage: image, success: { (largeImageRequest, largeImageResponse, largeImage) -> Void in cell.posterViewInCollectionCell.image = largeImage; }, failure: { (request, response, error) -> Void in }) }) cell.posterViewInCollectionCell.setImageWithURLRequest(fullImageRequest, placeholderImage: nil, success: { (fullImageRequest, newimageResponse, newimage) -> Void in cell.posterViewInCollectionCell.image = newimage }, failure: { (fullImageRequest, newimageResponse, error) -> Void in // do something for the failure condition }) }, failure: { (imageRequest, imageResponse, error) -> Void in // do something for the failure condition }) } else { // No poster image. Can either set to nil (no image) or a default movie poster image // that you include as an asset cell.posterViewInCollectionCell.image = nil } return cell } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
gpl-3.0
e531104830bc654b611342f1ddd26801
39.846743
188
0.580715
5.916204
false
false
false
false
airalex/Servus
Servus/Internals/Advertiser.swift
1
899
// // Advertiser.swift // Servus // // Created by Alexander Juda on 27/12/15. // Copyright © 2015 Alexander Juda. All rights reserved. // import Foundation class Advertiser { let identifier: String let netServiceType: String let netServiceDomain: String var announcingService: NetService? init(identifier: String, netServiceType: String, netServiceDomain: String) { self.identifier = identifier self.netServiceType = netServiceType self.netServiceDomain = netServiceDomain } func start() { stop() announcingService = NetService(domain: netServiceDomain, type: netServiceType, name: identifier, port: 55855) announcingService?.includesPeerToPeer = true announcingService?.publish() } func stop() { announcingService?.stop() announcingService = nil } }
mit
42c9acd5add7694df819382bf654bf4b
23.944444
117
0.658129
4.338164
false
false
false
false
BeezleLabs/HackerTracker-iOS
hackertracker/ConferenceCell.swift
1
1386
// // ConferenceCell.swift // hackertracker // // Created by Seth Law on 7/9/18. // Copyright © 2018 Beezle Labs. All rights reserved. // import UIKit class ConferenceCell: UITableViewCell { @IBOutlet private var name: UILabel! @IBOutlet private var dates: UILabel! @IBOutlet private var color: UIView! var conference: ConferenceModel? override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) accessoryType = isSelected ? .checkmark : .none color.isHidden = !isSelected } func selectCell(_ select: Bool) { if select == true { accessoryType = .checkmark color.isHidden = false } else { accessoryType = .none color.isHidden = true } } func setConference(conference: ConferenceModel) { self.conference = conference self.name.text = self.conference?.name let dfu = DateFormatterUtility.shared if let startDate = dfu.yearMonthDayFormatter.date(from: (conference.startDate)), let endDate = dfu.yearMonthDayFormatter.date(from: (conference.endDate)) { let start = dfu.monthDayYearFormatter.string(from: startDate) let end = dfu.monthDayYearFormatter.string(from: endDate) self.dates.text = "\(start) - \(end)" } } }
gpl-2.0
304814e131f2cc3f2ae9c2c169f66144
29.777778
163
0.639711
4.511401
false
false
false
false
zning1994/practice
Swift学习/code4xcode6/ch19/19.1.1获得NSNumber实例.playground/section-1.swift
1
662
// 本书网站:http://www.51work6.com/swift.php // 智捷iOS课堂在线课堂:http://v.51work6.com // 智捷iOS课堂新浪微博:http://weibo.com/u/3215753973 // 智捷iOS课堂微信公共账号:智捷iOS课堂 // 作者微博:http://weibo.com/516inc // 官方csdn博客:http://blog.csdn.net/tonny_guan // Swift语言QQ讨论群:362298485 联系QQ:1575716557 邮箱:[email protected] import Foundation var intSwift = 80 var intNumber1 = NSNumber(integer: intSwift) var intNumber2 = NSNumber(int: CInt(intSwift)) var floatNumber1 = NSNumber(double: 80.00) let myint = intNumber1.intValue let myfloat = floatNumber1.floatValue
gpl-2.0
5e7bf0eafa9103a314ae782c2d310f0d
24.809524
62
0.749077
2.669951
false
false
false
false
dangquochoi2007/cleancodeswift
CleanStore/CleanStore/AppDelegate.swift
1
8758
// // AppDelegate.swift // CleanStore // // Created by hoi on 3/5/17. // Copyright © 2017 hoi. All rights reserved. // import UIKit import CoreData import CoreLocation import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var locationManager:CLLocationManager? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let screen = UIScreen.main self.window = UIWindow(frame: screen.bounds) self.window?.makeKeyAndVisible() // let revealController = SWRevealViewController(rearViewController: SVMenuViewController(), frontViewController: CustomTabbarController()) // self.window?.rootViewController = iBeaconReceiveViewController() application.statusBarStyle = .lightContent // let beaconUUID:UUID = UUID(uuidString: iBeaconViewModel.FetchPromotion.Request.uuid)! // let beaconRegion:CLBeaconRegion = CLBeaconRegion(proximityUUID: beaconUUID, identifier: iBeaconViewModel.FetchPromotion.Request.beaconIdentifier) // // locationManager = CLLocationManager() // if (CLLocationManager.responds(to: #selector(CLLocationManager.requestAlwaysAuthorization))) { // // locationManager?.requestWhenInUseAuthorization() // } // locationManager?.delegate = self // locationManager?.pausesLocationUpdatesAutomatically = false // // 20 beacons at a given time. // locationManager?.startMonitoring(for: beaconRegion) // // locationManager?.startRangingBeacons(in: beaconRegion) // //https://spin.atomicobject.com/2017/01/31/ibeacon-in-swift/ // // Apple will reject it // // locationManager?.startUpdatingLocation() if #available(iOS 10.0, *) { let center = UNUserNotificationCenter.current() center.delegate = self center.requestAuthorization(options: [UNAuthorizationOptions.sound], completionHandler: { (granted, error) in if error == nil { UIApplication.shared.registerForRemoteNotifications() } }) } else { // Lower version > 7.0 let settings = UIUserNotificationSettings(types: [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound], categories: nil) UIApplication.shared.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() } 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 invalidate graphics rendering callbacks. 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 active 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "CleanStore") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } } extension AppDelegate: UNUserNotificationCenterDelegate { @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { print("User info notification") completionHandler([ UNNotificationPresentationOptions.sound, UNNotificationPresentationOptions.alert, UNNotificationPresentationOptions.badge ]) } @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { print("user received notification") completionHandler() } } extension AppDelegate: CLLocationManagerDelegate { func sendLocalNotificationWithMessage(message: String, playSound: Bool) { } func locationManager(_ manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], in region: CLBeaconRegion) { let knowBeacons = beacons.filter{ $0.proximity != CLProximity.unknown } if (knowBeacons.count > 0) { } } func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) { guard region is CLBeaconRegion else { return } } func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) { guard region is CLBeaconRegion else { return } } func tet() { let view1 = UIView() view1.alpha = 0.3 } }
mit
91daa9c480ee1d51a9add6224215a950
39.541667
285
0.658673
6.047652
false
false
false
false
lynnx4869/LYAutoPhotoPickers
LYAutoPhotoPickers/LYAutoPhotoPickers/ViewController.swift
1
2033
// // ViewController.swift // LYAutoPhotoPickers // // Created by xianing on 2017/6/15. // Copyright © 2017年 lyning. All rights reserved. // import UIKit import LYAutoUtils class ViewController: UIViewController { @IBOutlet weak var displayImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. navigationItem.title = "主页" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func pickImage(_ sender: UIButton) { LYAutoAlert.show(title: "", btns: ["相机", "相册", "扫描二维码"], viewController: self) { (title) in var type = LYAutoPhotoType.camera if title == "相机" { type = .camera } else if title == "相册" { type = .album } else { type = .qrcode } self.showPickers(type: type, callback: { [weak self] photos in if let photos = photos, let photo = photos.first { self?.displayImage.image = photo.image DispatchQueue.global().async { let path = NSHomeDirectory() + "/Documents/\(Date().description).png" let fileManager = FileManager.default fileManager.createFile(atPath: path, contents: photo.image.pngData(), attributes: nil) } } else { debugPrint("photo picker cancel...") } }, qr: { url in if let u = url { debugPrint(u) } }) } } }
mit
1358b0e2436e69a6df7a687e8052bae6
28.850746
93
0.47
5.390836
false
false
false
false
darkFunction/Gloss
GlossTests/OperatorTests.swift
1
20119
// // OperatorTests.swift // GlossExample // // Copyright (c) 2015 Harlan Kellaway // // 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 Gloss import UIKit import XCTest class OperatorTests: XCTestCase { var testJSON: JSON? = [:] var testNestedModel1: TestNestedModel? = nil var testNestedModel2: TestNestedModel? = nil override func setUp() { super.setUp() let testJSONPath: NSString = NSBundle(forClass: self.dynamicType).pathForResource("TestModel", ofType: "json")! let testJSONData: NSData = NSData(contentsOfFile: testJSONPath as String)! do { try testJSON = NSJSONSerialization.JSONObjectWithData(testJSONData, options: NSJSONReadingOptions(rawValue: 0)) as? JSON } catch { print(error) } testNestedModel1 = TestNestedModel(json: [ "id" : 1, "name" : "nestedModel1" ]) testNestedModel2 = TestNestedModel(json: ["id" : 2, "name" : "nestedModel2"]) } override func tearDown() { testJSON = nil testNestedModel1 = nil testNestedModel2 = nil super.tearDown() } // MARK: - Operator <~~ func testDecodeOperatorForInvalidReturnsDecoderDecode() { let resultInvalid: String? = "invalid" <~~ testJSON! let decoderResultInvalid: String? = Decoder.decode("invalid")(testJSON!) XCTAssertTrue((resultInvalid == decoderResultInvalid), "<~~ for invalid value should return same as Decoder.decode") } func testDecodeOperatorGenericReturnsDecoderDecodeForBool() { let resultBool: Bool? = "bool" <~~ testJSON! let decoderResultBool: Bool? = Decoder.decode("bool")(testJSON!) XCTAssertTrue((resultBool == decoderResultBool), "<~~ for generic value should return same as Decoder.decode for Bool") } func testDecodeOperatorGenericReturnsDecoderDecodeForBoolArray() { let resultBoolArray: [Bool]? = "boolArray" <~~ testJSON! let decoderResultBoolArray: [Bool]? = Decoder.decode("boolArray")(testJSON!) XCTAssertTrue((resultBoolArray! == decoderResultBoolArray!), "<~~ for generic value should return same as Decoder.decode for Bool array") } func testDecodeOperatorGenericReturnsDecoderDecodeForInt() { let resultInt: Int? = "integer" <~~ testJSON! let decoderResultInt: Int? = Decoder.decode("integer")(testJSON!) XCTAssertTrue((resultInt == decoderResultInt), "<~~ for generic value should return same as Decoder.decode for Int") } func testDecodeOperatorGenericReturnsDecoderDecodeForIntArray() { let resultIntArray: [Int]? = "integerArray" <~~ testJSON! let decoderResultIntArray: [Int]? = Decoder.decode("integerArray")(testJSON!) XCTAssertTrue((resultIntArray! == decoderResultIntArray!), "<~~ for generic value should return same as Decoder.decode for Int array") } func testDecodeOperatorGenericReturnsDecoderDecodeForFloat() { let resultFloat: Float? = "float" <~~ testJSON! let decoderResultFloat: Float? = Decoder.decode("float")(testJSON!) XCTAssertTrue((resultFloat == decoderResultFloat), "<~~ for generic value should return same as Decoder.decode for Float") } func testDecodeOperatorGenericReturnsDecoderDecodeForFloatArray() { let resultFloatArray: [Float]? = "floatArray" <~~ testJSON! let decoderResultFloatArray: [Float]? = Decoder.decode("floatArray")(testJSON!) XCTAssertTrue((resultFloatArray! == decoderResultFloatArray!), "<~~ for generic value should return same as Decoder.decode for Float array") } func testDecodeOperatorGenericReturnsDecoderDecodeForDouble() { let resultDouble: Double? = "double" <~~ testJSON! let decoderResultDouble: Double? = Decoder.decode("double")(testJSON!) XCTAssertTrue((resultDouble == decoderResultDouble), "<~~ for generic value should return same as Decoder.decode for Double") } func testDecodeOperatorGenericReturnsDecoderDecodeForDoubleArray() { let resultDoubleArray: [Double]? = "doubleArray" <~~ testJSON! let decoderResultDoubleArray: [Double]? = Decoder.decode("doubleArray")(testJSON!) XCTAssertTrue((resultDoubleArray! == decoderResultDoubleArray!), "<~~ for generic value should return same as Decoder.decode for Double array") } func testDecodeOperatorGenericReturnsDecoderDecodableDictionary() { let resultDictionary: [String : TestNestedModel]? = "dictionary" <~~ testJSON! let decoderDictionary: [String : TestNestedModel]? = Decoder.decodeDecodableDictionary("dictionary")(testJSON!) XCTAssertTrue(resultDictionary!["otherModel"]! == decoderDictionary!["otherModel"]!, "<~~ for generic value should result same as Decoder.decodeDecodableDictionary for dictionary") } func testDecodeOperatorGenericReturnsDecoderDecodeForString() { let resultString: String? = "string" <~~ testJSON! let decoderResultString: String? = Decoder.decode("string")(testJSON!) XCTAssertTrue((resultString == decoderResultString), "<~~ for generic value should return same as Decoder.decode for String") } func testDecodeOperatorGenericReturnsDecoderDecodeForStringArray() { let resultStringArray: [String]? = "stringArray" <~~ testJSON! let decoderResultStringArray: [String]? = Decoder.decode("stringArray")(testJSON!) XCTAssertTrue((resultStringArray! == decoderResultStringArray!), "<~~ for generic value should return same as Decoder.decode for String array") } func testDecodeOperatorDecodableReturnsDecoderDecode() { let resultNestedModel: TestNestedModel? = "nestedModel" <~~ testJSON! let decoderResultNestedModel: TestNestedModel? = Decoder.decodeDecodable("nestedModel")(testJSON!) XCTAssertTrue((resultNestedModel!.id == decoderResultNestedModel!.id), "<~~ for Decodable models should return same as Decoder.decode") XCTAssertTrue((resultNestedModel!.name == decoderResultNestedModel!.name), "<~~ for Decodable models should return same as Decoder.decode") } func testDecodeOperatorDecodableArrayReturnsDecoderDecodeArray() { let result: [TestNestedModel]? = "nestedModelArray" <~~ testJSON! let resultElement1: TestNestedModel = result![0] let resultElement2: TestNestedModel = result![1] let decoderResult: [TestNestedModel]? = Decoder.decodeDecodableArray("nestedModelArray")(testJSON!) let decoderResultElement1: TestNestedModel = decoderResult![0] let decoderResultElement2: TestNestedModel = decoderResult![1] XCTAssertTrue((resultElement1.id == decoderResultElement1.id), "<~~ for Decodable models array should return same as Decoder.decodeArray") XCTAssertTrue((resultElement1.name == decoderResultElement1.name), "<~~ for Decodable models array should return same as Decoder.decodeArray") XCTAssertTrue((resultElement2.id == decoderResultElement2.id), "<~~ for Decodable models array should return same as Decoder.decodeArray") XCTAssertTrue((resultElement2.name == decoderResultElement2.name), "<~~ for Decodable models array should return same as Decoder.decodeArray") } func testDecodeOperatorEnumValueReturnsDecoderDecodeEnum() { let result: TestModel.EnumValue? = "enumValue" <~~ testJSON! let decoderResult: TestModel.EnumValue? = Decoder.decodeEnum("enumValue")(testJSON!) XCTAssertTrue((result == decoderResult), "<~~ for enum value should return same as Decoder.decodeEnum") } func testDecodeOperatorEnumArrayReturnsDecoderDecodeArray() { let result: [TestModel.EnumValue]? = "enumValueArray" <~~ testJSON! let resultElement1: TestModel.EnumValue = result![0] let resultElement2: TestModel.EnumValue = result![1] let resultElement3: TestModel.EnumValue = result![2] let decoderResult: [TestModel.EnumValue]? = Decoder.decodeEnumArray("enumValueArray")(testJSON!) let decoderResultElement1: TestModel.EnumValue = decoderResult![0] let decoderResultElement2: TestModel.EnumValue = decoderResult![1] let decoderResultElement3: TestModel.EnumValue = decoderResult![2] XCTAssertTrue((resultElement1 == decoderResultElement1), "<~~ for enum value array should return same as Decoder.decodeArray") XCTAssertTrue((resultElement2 == decoderResultElement2), "<~~ for enum value array should return same as Decoder.decodeArray") XCTAssertTrue((resultElement3 == decoderResultElement3), "<~~ for enum value array should return same as Decoder.decodeArray") } func testDecodeOperatorURLReturnsDecoderDecodeURL() { let result: NSURL? = "url" <~~ testJSON! let decoderResult: NSURL? = Decoder.decodeURL("url")(testJSON!) XCTAssertTrue((result == decoderResult), "<~~ for url should return same as Decoder.decodeURL") } func testDecodeOperatorURLArrayReturnsDecoderDecodeURLArray() { let result: [NSURL]? = "urlArray" <~~ testJSON! let decoderResult: [NSURL]? = Decoder.decodeURLArray("urlArray")(testJSON!) XCTAssertTrue((result! == decoderResult!), "<~~ for url array should return same as Decoder.decodeURLArray") } // MARK: - Operator ~~> func testEncodeOperatorGenericReturnsEncoderEncodeForBool() { let bool: Bool? = true let resultBool: JSON? = "bool" ~~> bool let encoderResultBool: JSON? = Encoder.encode("bool")(bool) XCTAssertTrue(((resultBool!["bool"] as! Bool) == (encoderResultBool!["bool"] as! Bool)), "~~> for generic value should return same as Encoder.encode for Bool") } func testEncodeOperatorGenericReturnsEncoderEncodeForBoolArray() { let boolArray: [Bool]? = [true, false, true] let resultBoolArray: JSON? = "boolArray" ~~> boolArray let encoderResultBoolArray: JSON? = Encoder.encode("boolArray")(boolArray) XCTAssertTrue(((resultBoolArray!["boolArray"] as! [Bool]) == (encoderResultBoolArray!["boolArray"] as! [Bool])), "~~> for generic value should return same as Encoder.encode for Bool array") } func testEncodeOperatorGenericReturnsEncoderEncodeForInt() { let integer: Int? = 1 let resultInteger: JSON? = "integer" ~~> integer let encoderResultInteger: JSON? = Encoder.encode("integer")(integer) XCTAssertTrue(((resultInteger!["integer"] as! Int) == (encoderResultInteger!["integer"] as! Int)), "~~> for generic value should return same as Encoder.encode for Int array") } func testEncodeOperatorGenericReturnsEncoderEncodeForIntArray() { let integerArray: [Int]? = [1, 2, 3] let resultIntegerArray: JSON? = "integerArray" ~~> integerArray let encoderResultIntegerArray: JSON? = Encoder.encode("integerArray")(integerArray) XCTAssertTrue(((resultIntegerArray!["integerArray"] as! [Int]) == (encoderResultIntegerArray!["integerArray"] as! [Int])), "~~> for generic value should return same as Encoder.encode for Int") } func testEncodeOperatorGenericReturnsEncoderEncodeForFloat() { let float: Float? = 1.0 let resultFloat: JSON? = "float" ~~> float let encoderResultFloat: JSON? = Encoder.encode("float")(float) XCTAssertTrue(((resultFloat!["float"] as! Float) == (encoderResultFloat!["float"] as! Float)), "~~> for generic value should return same as Encoder.encode for Float") } func testEncodeOperatorGenericReturnsEncoderEncodeForFloatArray() { let floatArray: [Float]? = [1.0, 2.0, 3.0] let resultFloatArray: JSON? = "floatArray" ~~> floatArray let encoderResultFloatArray: JSON? = Encoder.encode("floatArray")(floatArray) XCTAssertTrue(((resultFloatArray!["floatArray"] as! [Float]) == (encoderResultFloatArray!["floatArray"] as! [Float])), "~~> for generic value should return same as Encoder.encode for Float array") } func testEncodeOperatorGenericReturnsEncoderEncodeForDouble() { let double: Double? = 1.0 let resultDouble: JSON? = "double" ~~> double let encoderResultDouble: JSON? = Encoder.encode("double")(double) XCTAssertTrue(((resultDouble!["double"] as! Double) == (encoderResultDouble!["double"] as! Double)), "~~> for generic value should return same as Encoder.encode for Double") } func testEncodeOperatorGenericReturnsEncoderEncodeForDoubleArray() { let doubleArray: [Double]? = [1.0, 2.0, 3.0] let resultDoubleArray: JSON? = "doubleArray" ~~> doubleArray let encoderResultDoubleArray: JSON? = Encoder.encode("doubleArray")(doubleArray) XCTAssertTrue(((resultDoubleArray!["doubleArray"] as! [Double]) == (encoderResultDoubleArray!["doubleArray"] as! [Double])), "~~> for generic value should return same as Encoder.encode for Double array") } func testEncodeOperatorGenericReturnsEncoderEncodeEncodableDictionary() { let dictionary: [String : TestNestedModel]? = ["otherModel" : testNestedModel1!] let result: JSON? = "dictionary" ~~> dictionary let encoderResult: JSON? = Encoder.encodeEncodableDictionary("dictionary")(dictionary) let dict = (result!["dictionary"] as! JSON)["otherModel"] as! JSON let encDict = (encoderResult!["dictionary"] as! JSON)["otherModel"] as! JSON XCTAssertTrue(dict["id"] as! Int == encDict["id"] as! Int, "~~> for [String:Encodable] value should return same as Encoder.encodeEncodableDictionary for dictionary") XCTAssertTrue(dict["name"] as! String == encDict["name"] as! String, "~~> for [String:Encodable] value should return same as Encoder.encodeEncodableDictionary for dictionary") } func testEncodeOperatorGenericReturnsEncoderEncodeForString() { let string: String? = "abc" let resultString: JSON? = "string" ~~> string let encoderResultString: JSON? = Encoder.encode("string")(string) XCTAssertTrue(((resultString!["string"] as! String) == (encoderResultString!["string"] as! String)), "~~> for generic value should return same as Encoder.encode for String") } func testEncodeOperatorGenericReturnsEncoderEncodeForStringArray() { let stringArray: [String]? = ["def", "ghi", "jkl"] let resultStringArray: JSON? = "stringArray" ~~> stringArray let encoderResultStringArray: JSON? = Encoder.encode("stringArray")(stringArray) XCTAssertTrue(((resultStringArray!["stringArray"] as! [String]) == (encoderResultStringArray!["stringArray"] as! [String])), "~~> for generic value should return same as Encoder.encode for String array") } func testEncodeOperatorEncodableReturnsEncoderEncode() { let result: JSON? = "nestedModel" ~~> testNestedModel1 let modelJSON: JSON = result!["nestedModel"] as! JSON let encoderResult: JSON? = Encoder.encodeEncodable("nestedModel")(testNestedModel1) let encoderModelJSON: JSON = encoderResult!["nestedModel"] as! JSON XCTAssertTrue((modelJSON["id"] as! Int == encoderModelJSON["id"] as! Int), "~~> for nested model should return same as Encoder.encode") XCTAssertTrue((modelJSON["name"] as! String == encoderModelJSON["name"] as! String), "~~> for nested model should return same as Encoder.encode") } func testEncodeOperatorEncodableArrayReturnsEncoderEncodeArray() { let model1: TestNestedModel = testNestedModel1! let model2: TestNestedModel = testNestedModel2! let result: JSON? = "nestedModelArray" ~~> ([model1, model2]) let modelsJSON: [JSON] = result!["nestedModelArray"] as! [JSON] let model1JSON: JSON = modelsJSON[0] let model2JSON: JSON = modelsJSON[1] let encoderResult: JSON? = Encoder.encodeEncodableArray("nestedModelArray")([model1, model2]) let encoderModelsJSON: [JSON] = encoderResult!["nestedModelArray"] as! [JSON] let encoderModel1JSON: JSON = encoderModelsJSON[0] let encoderModel2JSON: JSON = encoderModelsJSON[1] XCTAssertTrue((model1JSON["id"] as! Int == encoderModel1JSON["id"] as! Int), "~~> for nested model array should return same as Encoder.encodeArray") XCTAssertTrue((model1JSON["name"] as! String == encoderModel1JSON["name"] as! String), "~~> for nested model array should return same as Encoder.encodeArray") XCTAssertTrue((model2JSON["id"] as! Int == encoderModel2JSON["id"] as! Int), "~~> for nested model array should return same as Encoder.encodeArray") XCTAssertTrue((model2JSON["name"] as! String == encoderModel2JSON["name"] as! String), "~~> for nested model array should return same as Encoder.encodeArray") } func testEncodeOperatorEnumValueReturnsEncoderEncode() { let enumValue: TestModel.EnumValue? = TestModel.EnumValue.A let result: JSON? = "enumValue" ~~> enumValue let encoderResult: JSON? = Encoder.encodeEnum("enumValue")(enumValue) XCTAssertTrue(((result!["enumValue"] as! TestModel.EnumValue.RawValue) == (encoderResult!["enumValue"] as! TestModel.EnumValue.RawValue)), "~~> for enum value should return same as Encoder.encodeEnum") } func testEncodeOperatorEnumArrayReturnsEncoderEncodeArray() { let enumArray: [TestModel.EnumValue]? = [TestModel.EnumValue.A, TestModel.EnumValue.B, TestModel.EnumValue.C] let result: JSON? = "enumValueArray" ~~> enumArray let encoderResult: JSON? = Encoder.encodeEnumArray("enumValueArray")(enumArray) XCTAssertTrue(((result!["enumValueArray"] as! [TestModel.EnumValue.RawValue]) == (encoderResult!["enumValueArray"] as! [TestModel.EnumValue.RawValue])), "~~> for enum value array should return same as Encoder.encodeArray") } func testEncodeOperatorURLReturnsEncoderEncodeURL() { let url: NSURL? = NSURL(string: "http://github.com") let result: JSON? = "url" ~~> url let encoderResult: JSON? = Encoder.encodeURL("url")(url) XCTAssertTrue(((result!["url"] as! String) == (encoderResult!["url"] as! String)), "~~> for url should return same as Encoder.encodeURL") } func testEncodeOperatorURLArrayReturnsEncoderEncodeURLArray() { let urls: [NSURL]? = [NSURL(string: "http://github.com")!, NSURL(string: "http://github.com")!] let result: JSON? = "urlArray" ~~> urls let encoderResult: JSON? = Encoder.encodeArray("urlArray")(urls) XCTAssertTrue(((result!["urlArray"] as! [NSURL]) == (encoderResult!["urlArray"] as! [NSURL])), "~~> for url array should return same as Encoder.encodeArray") } }
mit
971a8d769f79dd9c8e4e401072239621
55.198324
230
0.684378
4.802817
false
true
false
false
Egibide-DAM/swift
02_ejemplos/06_tipos_personalizados/03_propiedades/07_observers.playground/Contents.swift
1
430
class StepCounter { var totalSteps: Int = 0 { willSet(newTotalSteps) { print("About to set totalSteps to \(newTotalSteps)") } didSet { if totalSteps > oldValue { print("Added \(totalSteps - oldValue) steps") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 stepCounter.totalSteps = 360 stepCounter.totalSteps = 896
apache-2.0
0cdf779952d12d4def9f537be7da57c4
22.888889
64
0.57907
4.479167
false
false
false
false
dabainihao/MapProject
MapProject/MapProject/LO_HomeController.swift
1
9546
// // LO_LoginViewController.swift // MapProject // // Created by 杨少锋 on 16/4/17. // Copyright © 2016年 杨少锋. All rights reserved. // 个人中心 import UIKit class LO_HomeController: UIViewController,UITableViewDelegate,UITableViewDataSource,updateInformationDelegate { weak var loginButton : UIButton? weak var tableView : UITableView? var headImageView : UIImageView? override func viewDidLoad() { super.viewDidLoad() self.title = "用户中心" } override func viewWillAppear(animated: Bool) { self.navigationController?.navigationBar.translucent = false super.viewWillAppear(animated) if (LO_loginHelper().isLogin()) { //登录时 self.showLoingView() } else { self.showLoginOutView() } } // 显示登录时的界面 func showLoingView() { if self.loginButton != nil { self.loginButton?.removeFromSuperview() } if self.tableView != nil { self.tableView?.removeFromSuperview() self.tableView?.delegate = nil self.tableView?.dataSource = nil } if self.headImageView != nil { self.headImageView?.removeFromSuperview() } let table = UITableView(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)) self.view .addSubview(table) self.tableView = table self.tableView?.delegate = self; self.tableView?.dataSource = self; } // 显示未登录时候的界面 func showLoginOutView() { if self.loginButton != nil { self.loginButton?.removeFromSuperview() } if self.tableView != nil { self.tableView?.removeFromSuperview() self.tableView?.delegate = nil self.tableView?.dataSource = nil } let button = UIButton(type: UIButtonType.System) button.frame = CGRectMake(80, 100, 220, 50); button .setTitle("登陆", forState: UIControlState.Normal) button.backgroundColor = UIColor.whiteColor() button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) button.layer.borderColor = UIColor.blackColor().CGColor button.layer.borderWidth = 1 button.addTarget(self, action: "loginOrRegist", forControlEvents: UIControlEvents.TouchUpInside) self.view .addSubview(button) self.loginButton = button; self.headImageView = UIImageView(frame: CGRectMake(155, 20, 60, 60)) self.headImageView?.layer.cornerRadius = 30; self.headImageView?.layer.masksToBounds = true self.headImageView?.layer.borderColor = UIColor.grayColor().CGColor self.headImageView?.layer.borderWidth = 1 self.view .addSubview(self.headImageView!) self.headImageView?.image = UIImage(named: "person_all") } // 注册或者登陆 func loginOrRegist() { let nav : UINavigationController = UINavigationController(rootViewController: LO_LoginController()) self.presentViewController(nav, animated: true) { () -> Void in } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell : UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "1") cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator switch indexPath.row { case 0 : cell.textLabel?.text = "用户名" cell.detailTextLabel?.text = LO_loginHelper().getUserName(); case 1 : cell.textLabel?.text = "电话" cell.detailTextLabel?.text = LO_loginHelper().getPhone(); case 2 : cell.textLabel?.text = "email" cell.detailTextLabel?.text = LO_loginHelper().getEmail(); case 3 : cell.textLabel?.text = "退出登录" cell.accessoryType = UITableViewCellAccessoryType.None default : print("未知") } cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let updateVC : UpdateInformation = UpdateInformation() updateVC.delegate = self switch indexPath.row { case 3 : updateVC.delegate = nil LO_loginHelper().loginOut() self .showLoginOutView() return case 0 : updateVC.navTitle = "用户名" updateVC.textFieldString = LO_loginHelper().getUserName() case 1 : updateVC.navTitle = "电话" updateVC.textFieldString = LO_loginHelper().getPhone(); case 2 : updateVC.navTitle = "email" updateVC.textFieldString = LO_loginHelper().getEmail(); default : print("未知") } //self.presentViewController(updateVC, animated: true, completion: nil) self.navigationController?.pushViewController(updateVC, animated: true) } } //暂时没有使用 修改数据回调使用, 但是AVUser提供了一种类似NSUsrDefalut一样的工程 @objc protocol updateInformationDelegate { optional func sendInforMation(infor: AnyObject)->Void } // 修改用户名邮箱等 class UpdateInformation:UIViewController { var delegate: updateInformationDelegate? = nil var navTitle : String? var textFieldString : String? var nameTextField : UITextField? var saveButton : UIButton? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() self.title = self.navTitle self.nameTextField = UITextField(frame: CGRectMake(50, 100, self.view.bounds.size.width - 100,50)) self.nameTextField?.text = textFieldString self.nameTextField?.borderStyle = UITextBorderStyle.Bezel NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldChang", name: UITextFieldTextDidChangeNotification, object: nil) self.view.addSubview(self.nameTextField!) self.saveButton = UIButton(type: UIButtonType.System) self.saveButton?.enabled = false self.saveButton?.layer.borderColor = UIColor.grayColor().CGColor self.saveButton?.layer.borderWidth = 1 self.saveButton?.frame = CGRectMake(50, 170, self.view.bounds.size.width - 100,50) self.saveButton?.setTitle("保存", forState: UIControlState.Normal) self.saveButton?.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(self.saveButton!) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } // func textFieldChang() { if (self.nameTextField?.text != self.textFieldString) { self.saveButton?.enabled = true } else { self.saveButton?.enabled = false } } // 保存 func save() { weak var wealself : UpdateInformation! = self if self.navTitle == "用户名" { AVUser.currentUser().setObject(self.nameTextField?.text, forKey: "username") AVUser.currentUser().saveInBackgroundWithBlock({ (sucess, Err) -> Void in if (Err != nil) { let alter = UIAlertView(title: "温馨提示", message: "暂时无法修改用户名.本地修改替代", delegate: nil, cancelButtonTitle: "取消", otherButtonTitles: "确定") alter .show() } if sucess { wealself.navigationController?.popToRootViewControllerAnimated(true) } // }) } if self.navTitle == "email" { AVUser.currentUser().setObject(self.nameTextField?.text, forKey: "email") AVUser.currentUser().saveInBackgroundWithBlock({ (sucess, Err) -> Void in if (Err != nil) { print("err = \(Err)") let alter = UIAlertView(title: "温馨提示", message: "暂时无法修改绑定邮箱.本地修改替代", delegate: nil, cancelButtonTitle: "取消", otherButtonTitles: "确定") alter .show() } if sucess { print("绑定成功"); wealself.navigationController?.popToRootViewControllerAnimated(true) } }) } if self.navTitle == "电话" { AVUser.currentUser().setObject(self.nameTextField?.text, forKey: "mobilePhoneNumber") AVUser.currentUser().saveInBackgroundWithBlock({ (sucess, Err) -> Void in if (Err != nil) { print("err = %@",Err) let alter = UIAlertView(title: "温馨提示", message: "暂时无法修改绑定电话.本地修改替代", delegate: nil, cancelButtonTitle: "取消", otherButtonTitles: "确定") alter .show() } if sucess { wealself.navigationController?.popToRootViewControllerAnimated(true) } }) } } } class LO_Infor: NSObject { var index : NSIndexPath? var usrDate : String? }
apache-2.0
68fa7c7f0fe7c8dbbb026d1b52ff0b9f
36.17004
153
0.612787
4.827024
false
false
false
false
Awalz/ark-ios-monitor
ArkMonitor/AppDelegate.swift
1
2773
// Copyright (c) 2016 Ark // // 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 UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate { var window: UIWindow? public let center = UNUserNotificationCenter.current() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UIApplication.shared.statusBarStyle = .lightContent window = UIWindow(frame: UIScreen.main.bounds) let homeVC = ArkTabViewController() window!.rootViewController = homeVC window?.makeKeyAndVisible() center.delegate = self center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in if let aError = error { print(aError) } } UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum) return true } func applicationDidBecomeActive(_ application: UIApplication) { ArkDataManager.startupOperations() } func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { ArkBackgroundDownloadManager.shared.updateNewData() completionHandler(.newData) } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { print(notification.request.content.userInfo) completionHandler(.alert) } }
mit
699bdd777bf32de84eea073ceff5c305
46.810345
207
0.736387
5.753112
false
false
false
false
3drobotics/SwiftIO
Sources/Retrier.swift
2
4087
// // Retrier.swift // SwiftIO // // Created by Jonathan Wight on 1/25/16. // Copyright © 2016 schwa.io. All rights reserved. // import SwiftUtilities /// Helper to retry closures ('retryClosure') with truncated exponential backoff. See: https://en.wikipedia.org/wiki/Exponential_backoff public class Retrier { // MARK: Public Properties /// Configuration options for Retrier. Bundled into struct to add reuse. public struct Options { public var delay: NSTimeInterval = 0.25 public var multiplier: Double = 2 public var maximumDelay: NSTimeInterval = 8 public var maximumAttempts: Int? = nil public init() { } } public let options: Options /// Pass in a Result describing success or failure. Return true if `Retrier` will retry. public typealias RetryStatus = Result <Void> -> Bool /// This is the action closure that is called repeated until it succeeds or a (optional) maximum attempts is exceeded. This closure is passed a `RetryStatus` closure that is used to pass success or failure back to `Retrier`. public let retryClosure: RetryStatus -> Void // MARK: Internal/Private Properties private let queue = dispatch_queue_create("retrier", DISPATCH_QUEUE_SERIAL) private var attempts = Atomic(0) private var running = Atomic(false) // MARK: Public methods /// Initialisation. `Retrier` is created in an un-resumed state, you should call `resume()`. public init(options: Options, retryClosure: RetryStatus -> Void) { self.options = options self.retryClosure = retryClosure } /// Resume a `Retrier` public func resume() { running.with() { (inout running: Bool) in if running == false { running = true attempt() } } } /// Cancel a `retrier`. This will not cancel `retryClosure` already running, but will prevent subsequent retry attempts. public func cancel() { running.with() { (inout running: Bool) in if running == true { running = false } } } // Computer the next delay before retrying `retryClosure`. public func delayForAttempt(attempt: Int) -> NSTimeInterval { let expotentialDelay = options.delay * pow(NSTimeInterval(options.multiplier), NSTimeInterval(attempt)) let truncatedDelay = min(expotentialDelay, options.maximumDelay) return truncatedDelay } // MARK: Internal/Private Methods private func attempt() { dispatch_async(queue) { [weak self] in guard let strong_self = self else { return } log?.debug("Retrying: Attempt \(strong_self.attempts.value)") if strong_self.running.value == true { strong_self.attempts.value += 1 strong_self.retryClosure(strong_self.callback) } } } private func retry() { let delay = delayForAttempt(attempts.value - 1) log?.debug("Retrying: Sleeping for \(delay)") let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * NSTimeInterval(NSEC_PER_SEC))) dispatch_after(time, queue) { self.attempt() } } private func callback(result: Result <Void>) -> Bool { if case .Failure = result { if let maximumAttempts = options.maximumAttempts where attempts.value > maximumAttempts { return false } retry() } return true } } extension Retrier { convenience init(delay: NSTimeInterval = 0.25, multiplier: Double = 2.0, maximumDelay: NSTimeInterval = 8, maximumAttempts: Int? = nil, retryClosure: RetryStatus -> Void) { var options = Options() options.delay = delay options.multiplier = multiplier options.maximumDelay = maximumDelay options.maximumAttempts = maximumAttempts self.init(options: options, retryClosure: retryClosure) } }
mit
46c38b201b6b74c5ec3d8469a371ee98
31.951613
228
0.622614
4.712803
false
false
false
false
Tsiems/WirelessNetwork
NetworkSimulation/NetworkSimulation/Edge.swift
1
412
// // Edge.swift // NetworkSimulation // // Created by Travis Siems on 2/28/17. // Copyright © 2017 Travis Siems. All rights reserved. // import UIKit class Edge: NSObject { var node1:Node var node2:Node var color: UIColor = UIColor.red init(node1:Node,node2:Node,color:UIColor = UIColor.red) { self.node1 = node1 self.node2 = node2 self.color = color } }
mit
43863b9d0388f9d19e12f5913d31af4b
18.571429
61
0.625304
3.261905
false
false
false
false
adrfer/swift
test/IRGen/clang_inline.swift
20
2941
// RUN: rm -rf %t && mkdir -p %t // RUN: %target-swift-frontend -sdk %S/Inputs -primary-file %s -emit-ir | FileCheck %s // RUN: mkdir -p %t/Empty.framework/Modules/Empty.swiftmodule // RUN: %target-swift-frontend -emit-module-path %t/Empty.framework/Modules/Empty.swiftmodule/%target-swiftmodule-name %S/../Inputs/empty.swift -module-name Empty // RUN: %target-swift-frontend -sdk %S/Inputs -primary-file %s -F %t -DIMPORT_EMPTY -emit-ir > %t.ll // RUN: FileCheck %s < %t.ll // RUN: FileCheck -check-prefix=NEGATIVE %s < %t.ll // REQUIRES: CPU=i386_or_x86_64 // XFAIL: linux #if IMPORT_EMPTY import Empty #endif import gizmo // CHECK-LABEL: define hidden i64 @_TFC12clang_inline16CallStaticInline10ReturnZerofT_Vs5Int64(%C12clang_inline16CallStaticInline*) {{.*}} { class CallStaticInline { func ReturnZero() -> Int64 { return Int64(zero()) } } // CHECK-LABEL: define internal i32 @zero() // CHECK: [[INLINEHINT_SSP_UWTABLE:#[0-9]+]] { // CHECK-LABEL: define hidden i64 @_TFC12clang_inline17CallStaticInline210ReturnZerofT_Vs5Int64(%C12clang_inline17CallStaticInline2*) {{.*}} { class CallStaticInline2 { func ReturnZero() -> Int64 { return Int64(wrappedZero()) } } // CHECK-LABEL: define internal i32 @wrappedZero() // CHECK: [[INLINEHINT_SSP_UWTABLE:#[0-9]+]] { // CHECK-LABEL: define hidden i32 @_TF12clang_inline10testExternFT_Vs5Int32() {{.*}} { func testExtern() -> CInt { return wrappedGetInt() } // CHECK-LABEL: define internal i32 @wrappedGetInt() // CHECK: [[INLINEHINT_SSP_UWTABLE:#[0-9]+]] { // CHECK-LABEL: define hidden i32 @_TF12clang_inline16testAlwaysInlineFT_Vs5Int32() // CHECK: [[SSP:#[0-9]+]] { // NEGATIVE-NOT: @alwaysInlineNumber // CHECK: ret i32 17 func testAlwaysInline() -> CInt { return alwaysInlineNumber() } // CHECK-LABEL: define hidden i32 @_TF12clang_inline20testInlineRedeclaredFT_Vs5Int32() {{.*}} { func testInlineRedeclared() -> CInt { return zeroRedeclared() } // CHECK-LABEL: define internal i32 @zeroRedeclared() #{{[0-9]+}} { // CHECK-LABEL: define hidden i32 @_TF12clang_inline27testInlineRedeclaredWrappedFT_Vs5Int32() {{.*}} { func testInlineRedeclaredWrapped() -> CInt { return wrappedZeroRedeclared() } // CHECK-LABEL: define internal i32 @wrappedZeroRedeclared() #{{[0-9]+}} { // CHECK-LABEL: define hidden i32 @_TF12clang_inline22testStaticButNotInlineFT_Vs5Int32() {{.*}} { func testStaticButNotInline() -> CInt { return staticButNotInline() } // CHECK-LABEL: define internal i32 @staticButNotInline() #{{[0-9]+}} { // CHECK-LABEL: define internal i32 @innerZero() // CHECK: [[INNER_ZERO_ATTR:#[0-9]+]] { // CHECK-LABEL: declare i32 @getInt() // CHECK: [[GET_INT_ATTR:#[0-9]+]] // CHECK: attributes [[INLINEHINT_SSP_UWTABLE]] = { inlinehint ssp {{.*}}} // CHECK: attributes [[SSP]] = { ssp {{.*}} } // CHECK: attributes [[INNER_ZERO_ATTR]] = { inlinehint nounwind ssp // CHECK: attributes [[GET_INT_ATTR]] = {
apache-2.0
bf609e3e6da93c8175c2b895b69eb713
35.7625
162
0.684461
3.148822
false
true
false
false
mountainvat/google-maps-ios-utils
samples/SwiftDemoApp/SwiftDemoApp/GeoJSONViewController.swift
1
1323
/* Copyright (c) 2017 Google 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 GoogleMaps import UIKit class GeoJSONViewController: UIViewController { private var mapView: GMSMapView! private var renderer: GMUGeometryRenderer! private var geoJsonParser: GMUGeoJSONParser! override func loadView() { let camera = GMSCameraPosition.camera(withLatitude: -28, longitude: 137, zoom: 4) mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) self.view = mapView let path = Bundle.main.path(forResource: "GeoJSON_sample", ofType: "json") let url = URL(fileURLWithPath: path!) geoJsonParser = GMUGeoJSONParser(url: url) geoJsonParser.parse() renderer = GMUGeometryRenderer(map: mapView, geometries: geoJsonParser.features) renderer.render() } }
apache-2.0
293ef9c79018f0723ca0aaa3ef140deb
33.815789
85
0.739229
4.2
false
false
false
false
simplicitylab/electronics-experiments
Eddy and his stones/mobile apps/SimpleIOSEddystone/SimpleIOSEddystone/ViewController.swift
1
1855
// // ViewController.swift // SimpleIOSEddystone // // Created by Glenn De Backer on 23/01/16. // Copyright © 2016 Glenn De Backer. All rights reserved. // import UIKit import Eddystone class ViewController: UIViewController, Eddystone.ScannerDelegate { // labels @IBOutlet weak var lblEddystoneUUID: UILabel! @IBOutlet weak var lblEddystoneStrength: UILabel! @IBOutlet weak var lblEddystoneUrl: UILabel! // button @IBOutlet weak var btnSearch: UIButton! var urls = Eddystone.Scanner.nearbyUrls override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /** * process eddystone info **/ func processEddystoneInfo() { // check if urls has been found if(urls.count > 0){ // update identifier lblEddystoneUUID.text = urls[0].identifier // update url lblEddystoneUrl.text = urls[0].url.absoluteString // update strength //urls[0].signalStrength lblEddystoneStrength.text = String( urls[0].signalStrength) } // disable search button btnSearch.setTitle("Beacon found", forState: UIControlState.Normal) btnSearch.enabled = false // start scanning Eddystone.Scanner.start(self) } /** * Search button clicked **/ @IBAction func searchButtonClicked(sender: AnyObject) { // start scanning Eddystone.Scanner.start(self) } func eddystoneNearbyDidChange() { print("eddystone") // store scanned urls self.urls = Eddystone.Scanner.nearbyUrls // process urls self.processEddystoneInfo() } }
gpl-2.0
d3ed922dd2a7979265f4ab636e7be6c6
23.394737
75
0.602481
4.957219
false
false
false
false
ericvergnaud/antlr4
runtime/Swift/Sources/Antlr4/atn/LexerIndexedCustomAction.swift
7
3553
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// /// /// This implementation of _org.antlr.v4.runtime.atn.LexerAction_ is used for tracking input offsets /// for position-dependent actions within a _org.antlr.v4.runtime.atn.LexerActionExecutor_. /// /// This action is not serialized as part of the ATN, and is only required for /// position-dependent lexer actions which appear at a location other than the /// end of a rule. For more information about DFA optimizations employed for /// lexer actions, see _org.antlr.v4.runtime.atn.LexerActionExecutor#append_ and /// _org.antlr.v4.runtime.atn.LexerActionExecutor#fixOffsetBeforeMatch_. /// /// - Sam Harwell /// - 4.2 /// public final class LexerIndexedCustomAction: LexerAction { fileprivate let offset: Int fileprivate let action: LexerAction /// /// Constructs a new indexed custom action by associating a character offset /// with a _org.antlr.v4.runtime.atn.LexerAction_. /// /// Note: This class is only required for lexer actions for which /// _org.antlr.v4.runtime.atn.LexerAction#isPositionDependent_ returns `true`. /// /// - parameter offset: The offset into the input _org.antlr.v4.runtime.CharStream_, relative to /// the token start index, at which the specified lexer action should be /// executed. /// - parameter action: The lexer action to execute at a particular offset in the /// input _org.antlr.v4.runtime.CharStream_. /// public init(_ offset: Int, _ action: LexerAction) { self.offset = offset self.action = action } /// /// Gets the location in the input _org.antlr.v4.runtime.CharStream_ at which the lexer /// action should be executed. The value is interpreted as an offset relative /// to the token start index. /// /// - returns: The location in the input _org.antlr.v4.runtime.CharStream_ at which the lexer /// action should be executed. /// public func getOffset() -> Int { return offset } /// /// Gets the lexer action to execute. /// /// - returns: A _org.antlr.v4.runtime.atn.LexerAction_ object which executes the lexer action. /// public func getAction() -> LexerAction { return action } /// /// /// /// - returns: This method returns the result of calling _#getActionType_ /// on the _org.antlr.v4.runtime.atn.LexerAction_ returned by _#getAction_. /// public override func getActionType() -> LexerActionType { return action.getActionType() } /// /// /// - returns: This method returns `true`. /// public override func isPositionDependent() -> Bool { return true } /// /// /// /// This method calls _#execute_ on the result of _#getAction_ /// using the provided `lexer`. /// public override func execute(_ lexer: Lexer) throws { // assume the input stream position was properly set by the calling code try action.execute(lexer) } public override func hash(into hasher: inout Hasher) { hasher.combine(offset) hasher.combine(action) } } public func ==(lhs: LexerIndexedCustomAction, rhs: LexerIndexedCustomAction) -> Bool { if lhs === rhs { return true } return lhs.offset == rhs.offset && lhs.action == rhs.action }
bsd-3-clause
8d29b06596fc9f89ea2d93dd7aa913fa
30.723214
100
0.645933
4.165299
false
false
false
false
sivu22/AnyTracker
AnyTracker/Utils.swift
1
13177
// // Utils.swift // AnyTracker // // Created by Cristian Sava on 14/02/16. // Copyright © 2016 Cristian Sava. All rights reserved. // import Foundation import UIKit typealias JSONObject = AnyObject typealias JSONDictionary = [String: JSONObject] typealias JSONArray = [JSONObject] struct Utils { static fileprivate(set) var documentsPath: String = { let fileManager = FileManager.default let URLs = fileManager.urls(for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask) Utils.debugLog("documentsPath = " + URLs[0].path) return URLs[0].path }() static func debugLog(_ text: String, functionName: String = #function, lineNumber: Int = #line) { #if DEBUG print("\(functionName):\(lineNumber) \(text)") #endif } static func validString(_ string: String?) -> Bool { if (string ?? "").isEmpty { return false } return true } static func errorInfo(_ error: NSError?) -> String { guard error != nil else { return "" } guard error!.userInfo[NSUnderlyingErrorKey] != nil else { return error!.localizedDescription } // Much more useful return (error!.userInfo[NSUnderlyingErrorKey]! as AnyObject).localizedDescription } static func currentTime() -> String { return timeFromDate(Date()) } static func timeFromDate(_ date: Date) -> String { return String(Int64(date.timeIntervalSince1970)) } static func dateFromTime(_ timeIntervalSince1970: String?) -> Date? { guard let timeString = timeIntervalSince1970 else { return nil } guard let time = Double(timeString) else { return nil } return Date(timeIntervalSince1970: time) } static func stringFrom(date: Date?, startDate: Bool, longFormat: Bool) -> String { if startDate { return "From " + stringFrom(date: date, longFormat: longFormat) } else { return "To " + stringFrom(date: date, longFormat: longFormat) } } static func stringFrom(date: Date?, longFormat: Bool) -> String { guard let date = date else { return "" } let dateFormatter = DateFormatter() if longFormat { dateFormatter.dateStyle = DateFormatter.Style.long } else { dateFormatter.dateStyle = DateFormatter.Style.short } return dateFormatter.string(from: date) } // MARK: - Files static func fileExists(atPath path: String?) -> Bool { guard validString(path) else { debugLog("Invalid path") return false } let fileManager = FileManager.default return fileManager.fileExists(atPath: path!); } fileprivate static func createFile(atPath path: String?, withContent content: String?, overwriteExisting overwrite: Bool = false) -> Bool { guard validString(path) else { debugLog("Invalid path") return false } let fileManager = FileManager.default if !overwrite && fileManager.fileExists(atPath: path!) { debugLog("File \(String(describing: path)) already exists") return false } if !fileManager.createFile(atPath: path!, contents: nil, attributes: nil) { debugLog("Failed to create file \(String(describing: path))") return false } if validString(content) { do { try content!.write(toFile: path!, atomically: true, encoding: String.Encoding.utf8) } catch let error as NSError { debugLog("Couldn't write to \(String(describing: path))! error " + errorInfo(error)) return false } } return true } static func createFile(withName fileName: String?, withContent content: String?, overwriteExisting overwrite: Bool = false) -> Bool { guard validString(fileName) else { debugLog("Invalid filename") return false } return createFile(atPath: documentsPath + "/" + fileName!, withContent: content, overwriteExisting: overwrite) } static func readFile(withName fileName: String?) -> String? { guard validString(fileName) else { debugLog("Invalid filename") return nil } let filePath = documentsPath + "/" + fileName! let content: String? do { content = try String(contentsOfFile: filePath, encoding: String.Encoding.utf8) } catch let error as NSError { debugLog("Failed to load content of \(filePath)! error " + errorInfo(error)) return nil } return content } static func deleteFile(atPath path: String?) -> Bool { guard fileExists(atPath: path) else { debugLog("File \(String(describing: path)) doesn't exist") return false } let fileManager = FileManager.default do { try fileManager.removeItem(atPath: path!) } catch let error as NSError { debugLog("Failed to delete file \(String(describing: path))! error " + errorInfo(error)) return false } return true } // MARK: - JSON static func getDictionaryFromJSON(_ input: String?) -> JSONDictionary? { guard validString(input) else { debugLog("Bad input") return nil } guard let data = input!.data(using: String.Encoding.utf8) else { debugLog("Failed to convert input to byte data") return nil } let jsonDict: JSONDictionary? do { jsonDict = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? JSONDictionary } catch let error as NSError { debugLog("Failed to deserialize JSON into a dictionary! error " + errorInfo(error)) return nil } return jsonDict } static func getArrayFromJSON(_ input: String?) ->JSONArray? { guard validString(input) else { debugLog("Bad input") return nil } guard let data = input!.data(using: String.Encoding.utf8) else { debugLog("Failed to convert input to byte data") return nil } let jsonArray: JSONArray? do { jsonArray = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? JSONArray } catch let error as NSError { debugLog("Failed to deserialize JSON into an array! error " + errorInfo(error)) return nil } return jsonArray } static func getJSONFromObject(_ input: JSONObject?) -> String? { guard input != nil else { debugLog("Bad input") return nil } let jsonString: String? do { let jsonData = try JSONSerialization.data(withJSONObject: input! as AnyObject, options: JSONSerialization.WritingOptions()) jsonString = String(data: jsonData, encoding: String.Encoding.utf8) } catch let error as NSError { debugLog("Failed to serialize JSON from array! error " + errorInfo(error)) return nil } return jsonString } // MARK: - Views static func snapshotFromView(_ view: UIView) -> UIView { UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0.0) view.layer.render(in: UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() let snapshot: UIView = UIImageView(image: image) snapshot.layer.masksToBounds = false snapshot.layer.cornerRadius = 0.0 snapshot.layer.shadowOffset = CGSize(width: -5.0, height: 0.0) snapshot.layer.shadowRadius = 0.0 snapshot.layer.shadowOpacity = 0.4 return snapshot } static func addDoneButton(toTextField textField: UITextField, forTarget target: Any?, negativeTarget: AnyObject?, negativeSelector: Selector) { let keyboardToolbar = UIToolbar() keyboardToolbar.backgroundColor = UIColor.white keyboardToolbar.sizeToFit() let negativeBarButton = UIBarButtonItem(title: "+/-", style: .plain, target: negativeTarget, action: negativeSelector) let flexBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: target, action: #selector(UIView.endEditing(_:))) keyboardToolbar.items = [negativeBarButton, flexBarButton, doneBarButton] textField.inputAccessoryView = keyboardToolbar } static func addDoneButton(toDateTextField textField: UITextField, forTarget target: Any?, doneSelector selector: Selector? = nil) { let keyboardToolbar = UIToolbar() keyboardToolbar.backgroundColor = UIColor.white keyboardToolbar.sizeToFit() let flexBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: target, action: selector == nil ? #selector(UIView.endEditing(_:)) : selector) keyboardToolbar.items = [flexBarButton, doneBarButton] textField.inputAccessoryView = keyboardToolbar } static func addDoneButton(toTextView textView: UITextView, forTarget target: Any?, doneSelector selector: Selector? = nil) { let keyboardToolbar = UIToolbar() keyboardToolbar.backgroundColor = UIColor.white keyboardToolbar.sizeToFit() let flexBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: target, action: selector == nil ? #selector(UIView.endEditing(_:)) : selector) keyboardToolbar.items = [flexBarButton, doneBarButton] textView.inputAccessoryView = keyboardToolbar } } // MARK: - Extensions extension Double { var isInt: Bool { return self.truncatingRemainder(dividingBy: 1) == 0 } func asString(withSeparator separator: Bool = false) -> String { if separator { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = NumberFormatter.Style.decimal if isInt { return numberFormatter.string(from: NSNumber(value: Int64(self)))! } else { return numberFormatter.string(from: NSNumber(value: self))! } } else { if isInt { return String(Int64(self)) } else { return String(self) } } } } extension UInt { func asString(withSeparator separator: Bool = false) -> String { if separator { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = NumberFormatter.Style.decimal return numberFormatter.string(from: NSNumber(value: self))! } else { return String(self) } } } extension UIColor { func getRGBA() -> (red: Int, green: Int, blue: Int, alpha: Int)? { var flRed: CGFloat = 0 var flGreen: CGFloat = 0 var flBlue: CGFloat = 0 var flAlpha: CGFloat = 0 if self.getRed(&flRed, green: &flGreen, blue: &flBlue, alpha: &flAlpha) { return (red: Int(flRed * 255), green: Int(flGreen * 255), blue: Int(flBlue * 255), alpha: Int(flAlpha * 255)) } else { return nil } } func getRGBAString() -> String { if let (red, green, blue, alpha) = self.getRGBA() { return "R:\(red),G:\(green),B:\(blue),A:\(alpha)" } return "Error" } convenience init(red: Int, green: Int, blue: Int) { let flRed = CGFloat(red) / 255 let flGreen = CGFloat(green) / 255 let flBlue = CGFloat(blue) / 255 self.init(red: flRed, green: flGreen, blue: flBlue, alpha: 1.0) } } extension UIButton { func enable() { isEnabled = true alpha = 1 } func disable() { isEnabled = false alpha = 0.3 } } extension UIBarButtonItem { func hide() { isEnabled = false tintColor = UIColor.clear } }
mit
ee8a1009616f65c3e37741e34032abbb
33.3125
158
0.586369
5.191489
false
false
false
false
Mamadoukaba/Chillapp
Chillapp/PlacesResultViewController.swift
1
7541
// // PlacesResultViewController.swift // Chillapp // // Created by Mamadou Kaba on 7/23/15. // Copyright (c) 2015 Mamadou Kaba. All rights reserved. // import UIKit import QuadratTouch import SwiftyJSON class PlacesResultViewController: UIViewController { override func viewDidLoad() { navigationController?.setNavigationBarHidden(false, animated: true) UINavigationBar.appearance().barTintColor = UIColor.whiteColor() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default } var repositories = [Repository]() var results = [String: AnyObject]() { didSet { json = JSON(results) } } var json: JSON? var selectedURL: String? var colors: [AnyObject]? override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "urlview") { let placesResultViewController = segue.destinationViewController as! WebviewViewController placesResultViewController.URLPath = selectedURL! } } } extension PlacesResultViewController: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return myJSON["venues"].count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell cell.textLabel!.text = myJSON["venues"][indexPath.row]["name"].string cell.textLabel!.font = UIFont.boldSystemFontOfSize(20.0) cell.textLabel!.textColor = UIColor.whiteColor() if indexPath.row == 0 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 1 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 2 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 3 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 4 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 5 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 6 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 7 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 8 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 9 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 10 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 11 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 12 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 13 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 14 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 15 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 16 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 17 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 18 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 19 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 20 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 21 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 22 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 23 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 24 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 25 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 26 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 27 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 28 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 29 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 30 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 31 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 32 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 33 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 34 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } if indexPath.row == 35 { cell.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } if indexPath.row == 36 { cell.backgroundColor = UIColor(red: 0.204, green: 0.596, blue: 0.859, alpha: 1) } return cell } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { tableView.backgroundColor = UIColor(red: 0.204, green: 0.286, blue: 0.369, alpha: 1) } } extension PlacesResultViewController: UITableViewDelegate { func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { selectedURL = "http://foursquare.com/v/" + myJSON["venues"][indexPath.row]["id"].string! selectedVenue = myJSON["venues"][indexPath.row]["location"]["formattedAddress"][0].string! performSegueWithIdentifier("urlview", sender: self) } }
mit
6aea896624c83597d1cb3f94b9feb48e
38.694737
123
0.58361
3.899173
false
false
false
false
txaidw/TWControls
TWSpriteKitUtils/TWControls/TWControl.swift
1
34277
// // TWButton.swift // // The MIT License (MIT) // // Created by Txai Wieser on 25/02/15. // Copyright (c) 2015 Txai Wieser. // // //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 SpriteKit open class TWControl: SKNode { // MARK: Initializers required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** * Initializes a general TWControl of type .Texture with a single highlighted texture possibility */ public init(normalTexture: SKTexture, selectedTexture: SKTexture?, singleHighlightedTexture: SKTexture?, disabledTexture: SKTexture?) { type = .texture super.init() self.generalSprite = TWSpriteNode(texture: normalTexture, size: normalTexture.size()) (self.generalSprite as! TWSpriteNode).control = self self.addChild(self.generalSprite) self.isUserInteractionEnabled = false self.generalSprite.isUserInteractionEnabled = true self.disabledStateTexture = disabledTexture self.highlightedStateSingleTexture = singleHighlightedTexture self.normalStateTexture = normalTexture self.selectedStateTexture = selectedTexture updateVisualInterface() } /** * Initializes a general TWControl of type .Texture with multiple highlighted textures possibility */ public init(normalTexture: SKTexture, selectedTexture: SKTexture?, multiHighlightedTexture: (fromNormal: SKTexture?, fromSelected: SKTexture?), disabledTexture: SKTexture?) { type = .texture super.init() self.generalSprite = TWSpriteNode(texture: normalTexture, size: normalTexture.size()) (self.generalSprite as! TWSpriteNode).control = self self.addChild(self.generalSprite) self.isUserInteractionEnabled = false self.generalSprite.isUserInteractionEnabled = true self.disabledStateTexture = disabledTexture self.highlightedStateMultiTextureFromNormal = multiHighlightedTexture.fromNormal self.highlightedStateMultiTextureFromSelected = multiHighlightedTexture.fromSelected self.normalStateTexture = normalTexture self.selectedStateTexture = selectedTexture updateVisualInterface() } /** * Initializes a general TWControl of type .Shape with a single highlighted texture possibility */ public init(normalShape: SKShapeNode.Definition, selectedShape: SKShapeNode.Definition?, singleHighlightedShape: SKShapeNode.Definition?, disabledShape: SKShapeNode.Definition?) { type = .shape super.init() self.generalShape = TWShapeNode(definition: normalShape) (self.generalShape as! TWShapeNode).control = self self.addChild(self.generalShape) self.isUserInteractionEnabled = false self.generalShape.isUserInteractionEnabled = true self.disabledStateShapeDef = disabledShape self.highlightedStateSingleShapeDef = singleHighlightedShape self.normalStateShapeDef = normalShape self.selectedStateShapeDef = selectedShape updateVisualInterface() } /** * Initializes a general TWControl of type .Shape with multiple highlighted textures possibility */ public init(normalShape: SKShapeNode.Definition, selectedShape: SKShapeNode.Definition?, multiHighlightedShape: (fromNormal: SKShapeNode.Definition?, fromSelected: SKShapeNode.Definition?), disabledShape: SKShapeNode.Definition?) { type = .shape super.init() self.generalShape = TWShapeNode(definition: normalShape) (self.generalShape as! TWShapeNode).control = self self.addChild(self.generalShape) self.isUserInteractionEnabled = false self.generalShape.isUserInteractionEnabled = true self.disabledStateShapeDef = disabledShape self.highlightedStateMultiShapeFromNormalDef = multiHighlightedShape.fromNormal self.highlightedStateMultiShapeFromSelectedDef = multiHighlightedShape.fromSelected self.normalStateShapeDef = normalShape self.selectedStateShapeDef = selectedShape updateVisualInterface() } /** * Initializes a general TWControl of type .Color with a single highlighted color possibility */ public init(size: CGSize, normalColor: SKColor, selectedColor: SKColor?, singleHighlightedColor: SKColor?, disabledColor: SKColor?) { type = .color super.init() self.generalSprite = TWSpriteNode(texture: nil, color: normalColor, size: size) (self.generalSprite as! TWSpriteNode).control = self self.addChild(self.generalSprite) self.isUserInteractionEnabled = false self.generalSprite.isUserInteractionEnabled = true self.disabledStateColor = disabledColor self.highlightedStateSingleColor = singleHighlightedColor self.normalStateColor = normalColor self.selectedStateColor = selectedColor updateVisualInterface() } /** * Initializes a general TWControl of type .Color with with multiple highlighted color possibility */ public init(size: CGSize, normalColor: SKColor, selectedColor: SKColor?, multiHighlightedColor: (fromNormal: SKColor?, fromSelected: SKColor?), disabledColor: SKColor?) { type = .color super.init() self.generalSprite = TWSpriteNode(texture: nil, color: normalColor, size: size) (self.generalSprite as! TWSpriteNode).control = self self.addChild(self.generalSprite) self.isUserInteractionEnabled = false self.generalSprite.isUserInteractionEnabled = true self.disabledStateColor = disabledColor self.highlightedStateMultiColorFromNormal = multiHighlightedColor.fromNormal self.highlightedStateMultiColorFromSelected = multiHighlightedColor.fromSelected self.normalStateColor = normalColor self.selectedStateColor = selectedColor updateVisualInterface() } /** * Initializes a general TWControl of type .Text with multiple highlighted color possibility */ public init(normalText: String, selectedText: String?, singleHighlightedText: String?, disabledText: String?) { type = .label super.init() self.isUserInteractionEnabled = true setNormalStateLabelText(normalText) setSelectedStateLabelText(selectedText) setDisabledStateLabelText(disabledText) setHighlightedStateSingleLabelText(singleHighlightedText) updateVisualInterface() } /** * Initializes a general TWControl of type .Text with multiple highlighted color possibility */ public init(normalText: String, selectedText: String?, multiHighlightedText: (fromNormal: String?, fromSelected: String?), disabledText: String?) { type = .label super.init() self.isUserInteractionEnabled = true setNormalStateLabelText(normalText) setSelectedStateLabelText(selectedText) setDisabledStateLabelText(disabledText) setHighlightedStateMultiLabelTextFromNormal(multiHighlightedText.fromNormal) setHighlightedStateMultiLabelTextFromSelected(multiHighlightedText.fromSelected) updateVisualInterface() } // MARK: Control Actions /** * Add a closure to a event action. You should use in your closure only the objects that are on the capture list of the closure (target)! Using objects capture automatically by the closure can cause cycle-reference, and your objects will never be deallocate. You have to be CAREFUL with this! Just pass your object to the function and use inside the closure. */ open func addClosure<T: AnyObject>(_ event: ControlEvent, target: T, closure: @escaping (_ target: T, _ sender: TWControl) -> ()) { self.eventClosures.append((event:event , closure: { [weak target] (ctrl: TWControl) -> () in if let obj = target { closure(obj, ctrl) } return })) } /** * Removes all closure from a specific event. */ open func removeClosures(for event: ControlEvent) { assertionFailure("TODO: Implement Remove Target") } fileprivate func executeClosures(of event: ControlEvent) { for eventClosure in eventClosures { if eventClosure.event == event { eventClosure.closure(self) } } } // MARK: Public Properties open var size: CGSize { get { return self.calculateAccumulatedFrame().size } } open var tag: Int? open var enabled: Bool { get { return self.state != .disabled } set { if newValue { self.state = .normal } else { self.state = .disabled } updateVisualInterface() } } open var selected: Bool { get { return self.state == .selected } set { if newValue { self.state = .selected } else { self.state = .normal } updateVisualInterface() } } open var highlighted: Bool { get { return self.state == .highlighted } set { if newValue { self.state = .highlighted } else { self.state = .normal } updateVisualInterface() } } open func setGeneralTouchProperties(_ changes: (_ node: SKNode)->()) { if generalSprite != nil { changes(generalSprite) } else if generalShape != nil { changes(generalShape) } } // MARK: General Nodes fileprivate var generalSprite: SKSpriteNode! fileprivate var generalShape: SKShapeNode! override open var isUserInteractionEnabled: Bool { didSet { self.generalSprite?.isUserInteractionEnabled = isUserInteractionEnabled self.generalShape?.isUserInteractionEnabled = isUserInteractionEnabled } } open var genericNode: SKNode { get { if let gen = generalSprite { return gen } else if let gen = generalShape { return gen } else { return self } } } // MARK: Sound Properties public static var defaultSoundEffectsEnabled: Bool? = nil open var soundEffectsEnabled: Bool = true public static var defaultTouchDownSoundFileName: String? { didSet { soundPreLoad(defaultTouchDownSoundFileName) } } public static var defaultTouchUpSoundFileName: String? { didSet { soundPreLoad(defaultTouchUpSoundFileName) } } public static var defaultDisabledTouchDownFileName: String? { didSet { soundPreLoad(defaultDisabledTouchDownFileName) } } open var touchDownSoundFileName: String? { didSet { TWControl.soundPreLoad(touchDownSoundFileName) } } open var touchUpSoundFileName: String? { didSet { TWControl.soundPreLoad(touchUpSoundFileName) } } open var disabledTouchDownFileName: String? { didSet { TWControl.soundPreLoad(disabledTouchDownFileName) } } fileprivate static func soundPreLoad(_ named: String?) { // Preloads the sound if let named = named { if #available(iOS 9.0, *) { _ = SKAction.playSoundFileNamed(named, waitForCompletion: true) } } } // MARK: COLOR Type Customizations open var normalStateColor: SKColor! { didSet { updateVisualInterface() } } open var selectedStateColor: SKColor? { didSet { updateVisualInterface() } } open var disabledStateColor: SKColor? { didSet { updateVisualInterface() } } open var highlightedStateSingleColor: SKColor? { didSet { updateVisualInterface() } } open var highlightedStateMultiColorFromNormal: SKColor? { didSet { updateVisualInterface() } } open var highlightedStateMultiColorFromSelected: SKColor? { didSet { updateVisualInterface() } } // MARK: TEXTURE Type Customizations open var normalStateTexture: SKTexture! { didSet { updateVisualInterface() } } open var selectedStateTexture: SKTexture? { didSet { updateVisualInterface() } } open var disabledStateTexture: SKTexture? { didSet { updateVisualInterface() } } open var highlightedStateSingleTexture: SKTexture? { didSet { updateVisualInterface() } } open var highlightedStateMultiTextureFromNormal: SKTexture? { didSet { updateVisualInterface() } } open var highlightedStateMultiTextureFromSelected: SKTexture? { didSet { updateVisualInterface() } } // MARK: SHAPE Type Customizations open var normalStateShapeDef: SKShapeNode.Definition! { didSet { updateVisualInterface() } } open var selectedStateShapeDef: SKShapeNode.Definition? { didSet { updateVisualInterface() } } open var disabledStateShapeDef: SKShapeNode.Definition? { didSet { updateVisualInterface() } } open var highlightedStateSingleShapeDef: SKShapeNode.Definition? { didSet { updateVisualInterface() } } open var highlightedStateMultiShapeFromNormalDef: SKShapeNode.Definition? { didSet { updateVisualInterface() } } open var highlightedStateMultiShapeFromSelectedDef: SKShapeNode.Definition? { didSet { updateVisualInterface() } } // MARK: TEXT Type Customizations open var normalStateLabel: SKLabelNode? { didSet { updateVisualInterface() } } open var selectedStateLabel: SKLabelNode? { didSet { updateVisualInterface() } } open var disabledStateLabel: SKLabelNode? { didSet { updateVisualInterface() } } open var highlightedStateSingleLabel: SKLabelNode? { didSet { updateVisualInterface() } } open var highlightedStateMultiLabelFromNormal: SKLabelNode? { didSet { updateVisualInterface() } } open var highlightedStateMultiLabelFromSelected: SKLabelNode? { didSet { updateVisualInterface() } } // Labels Text Setters public static var defaultLabelFont = "Helvetica-Neue" open func setNormalStateLabelText(_ text: String?) { self.setLabelText(&normalStateLabel, text: text, pos: normalStateLabelPosition) } open func setSelectedStateLabelText(_ text: String?) { self.setLabelText(&selectedStateLabel, text: text, pos: selectedStateLabelPosition) } open func setDisabledStateLabelText(_ text: String?) { self.setLabelText(&disabledStateLabel, text: text, pos: disabledStateLabelPosition) } open func setHighlightedStateSingleLabelText(_ text: String?) { self.setLabelText(&highlightedStateSingleLabel, text: text, pos: highlightedStateSingleLabelPosition) } open func setHighlightedStateMultiLabelTextFromNormal(_ text: String?) { self.setLabelText(&highlightedStateMultiLabelFromNormal, text: text, pos: highlightedStateMultiLabelPositionFromNormal) } open func setHighlightedStateMultiLabelTextFromSelected(_ text: String?) { self.setLabelText(&highlightedStateMultiLabelFromSelected, text: text, pos: highlightedStateMultiLabelPositionFromSelected) } fileprivate func setLabelText(_ label: inout SKLabelNode?, text: String?, pos: CGPoint) { if let newText = text { if label == nil { label = generalLabel() label!.position = pos self.genericNode.addChild(label!) } label!.text = newText } else { label?.removeFromParent() label = nil } } fileprivate func generalLabel() -> SKLabelNode { let l = SKLabelNode() l.fontName = TWControl.defaultLabelFont l.verticalAlignmentMode = SKLabelVerticalAlignmentMode.center l.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center return l } // Labels Font Size Setter open func setAllStatesLabelFontSize(_ size: CGFloat) { normalStateLabel?.fontSize = size selectedStateLabel?.fontSize = size disabledStateLabel?.fontSize = size highlightedStateSingleLabel?.fontSize = size highlightedStateMultiLabelFromNormal?.fontSize = size highlightedStateMultiLabelFromSelected?.fontSize = size } // Labels Font Name Setter open func setAllStatesLabelFontName(_ fontName: String) { normalStateLabel?.fontName = fontName selectedStateLabel?.fontName = fontName disabledStateLabel?.fontName = fontName highlightedStateSingleLabel?.fontName = fontName highlightedStateMultiLabelFromNormal?.fontName = fontName highlightedStateMultiLabelFromSelected?.fontName = fontName } // Labels Font Color Setter open func setNormalStateLabelFontColor(_ color: SKColor) { normalStateLabel?.fontColor = color } open func setSelectedStateLabelFontColor(_ color: SKColor) { selectedStateLabel?.fontColor = color } open func setDisabledStateLabelFontColor(_ color: SKColor) { disabledStateLabel?.fontColor = color } open func setHighlightedStateSingleLabelFontColor(_ color: SKColor) { highlightedStateSingleLabel?.fontColor = color } open func setHighlightedStateMultiLabelFontColorFromNormal(_ color: SKColor) { highlightedStateMultiLabelFromNormal?.fontColor = color } open func setHighlightedStateMultiLabelFontColorFromSelected(_ color: SKColor) { highlightedStateMultiLabelFromSelected?.fontColor = color } open func setAllStatesLabelFontColor(_ color: SKColor) { setNormalStateLabelFontColor(color) setSelectedStateLabelFontColor(color) setDisabledStateLabelFontColor(color) setHighlightedStateSingleLabelFontColor(color) setHighlightedStateMultiLabelFontColorFromNormal(color) setHighlightedStateMultiLabelFontColorFromSelected(color) } // Default Control Label Position public static var defaultNormalStateLabelPosition = CGPoint.zero public static var defaultSelectedStateLabelPosition = CGPoint.zero public static var defaultDisabledStateLabelPosition = CGPoint.zero public static var defaultHighlightedStateSingleLabelPosition = CGPoint.zero public static var defaultHighlightedStateMultiLabelPositionFromNormal = CGPoint.zero public static var defaultHighlightedStateMultiLabelPositionFromSelected = CGPoint.zero public static func setAllDefaultStatesLabelPosition(_ pos: CGPoint) { defaultNormalStateLabelPosition = pos defaultSelectedStateLabelPosition = pos defaultDisabledStateLabelPosition = pos defaultHighlightedStateSingleLabelPosition = pos defaultHighlightedStateMultiLabelPositionFromNormal = pos defaultHighlightedStateMultiLabelPositionFromSelected = pos } // Control Instance Label Position open var normalStateLabelPosition: CGPoint = defaultNormalStateLabelPosition { didSet { normalStateLabel?.position = normalStateLabelPosition } } open var selectedStateLabelPosition: CGPoint = defaultSelectedStateLabelPosition { didSet { selectedStateLabel?.position = selectedStateLabelPosition } } open var disabledStateLabelPosition: CGPoint = defaultDisabledStateLabelPosition { didSet { disabledStateLabel?.position = disabledStateLabelPosition } } open var highlightedStateSingleLabelPosition: CGPoint = defaultHighlightedStateSingleLabelPosition { didSet { highlightedStateSingleLabel?.position = highlightedStateSingleLabelPosition } } open var highlightedStateMultiLabelPositionFromNormal: CGPoint = defaultHighlightedStateMultiLabelPositionFromNormal { didSet { highlightedStateMultiLabelFromNormal?.position = highlightedStateMultiLabelPositionFromNormal } } open var highlightedStateMultiLabelPositionFromSelected: CGPoint = defaultHighlightedStateMultiLabelPositionFromSelected { didSet { highlightedStateMultiLabelFromSelected?.position = highlightedStateMultiLabelPositionFromSelected } } open func setAllStatesLabelPosition(_ pos: CGPoint) { normalStateLabelPosition = pos selectedStateLabelPosition = pos disabledStateLabelPosition = pos highlightedStateSingleLabelPosition = pos highlightedStateMultiLabelPositionFromNormal = pos highlightedStateMultiLabelPositionFromSelected = pos } // Control Animations public static var defaultAnimationHighlightedAction: (to: SKAction, back: SKAction)? = nil open var animationHighlightedAction: (to: SKAction, back: SKAction)? = defaultAnimationHighlightedAction // MARK: Private Properties fileprivate let type: TWControlType fileprivate var state: TWControlState = .normal { didSet { lastState = oldValue } } fileprivate var lastState: TWControlState = .normal internal var eventClosures: [(event: ControlEvent, closure: (TWControl) -> ())] = [] fileprivate var touch:UITouch? fileprivate var touchLocationLast: CGPoint? fileprivate var moved = false // MARK: Control Functionality fileprivate func updateVisualInterface() { switch type { case .color: updateColorVisualInterface() case .texture: updateTextureVisualInterface() case .shape: updateShapeVisualInterface() case .label: break //Doesnt need to do nothing } updateLabelsVisualInterface() if self.scene?.view?.window != nil { updateAnimationInterface() } } func updateAnimationInterface() { let ANIMATION_HIGHLIGHTED_ACTION = "ANIMATION_HIGHLIGHTED_ACTION" if let animation = animationHighlightedAction { genericNode.removeAction(forKey: ANIMATION_HIGHLIGHTED_ACTION) switch state { case .normal: fallthrough case .disabled: genericNode.run(animation.back, withKey: ANIMATION_HIGHLIGHTED_ACTION) case .highlighted: fallthrough case .selected: genericNode.run(animation.to, withKey: ANIMATION_HIGHLIGHTED_ACTION) } } } fileprivate func updateColorVisualInterface() { switch state { case .normal: self.generalSprite.color = self.normalStateColor case .selected: if let selColor = self.selectedStateColor { self.generalSprite.color = selColor } else { self.generalSprite.color = normalStateColor } case .disabled: if let disColor = self.disabledStateColor { self.generalSprite.color = disColor } else { self.generalSprite.color = normalStateColor } case .highlighted: if let single = highlightedStateSingleColor { self.generalSprite.color = single } else { if lastState == .normal { if let fromNormal = self.highlightedStateMultiColorFromNormal { self.generalSprite.color = fromNormal } else if let sel = self.selectedStateColor { self.generalSprite.color = sel } else { self.generalSprite.color = self.normalStateColor } } else if lastState == .selected { if let fromSelected = self.highlightedStateMultiColorFromSelected { self.generalSprite.color = fromSelected } else { self.generalSprite.color = self.normalStateColor } } } } } fileprivate func updateTextureVisualInterface() { switch state { case .normal: self.generalSprite.texture = self.normalStateTexture case .selected: if let selTex = self.selectedStateTexture { self.generalSprite.texture = selTex } else { self.generalSprite.texture = normalStateTexture } case .disabled: if let disTex = self.disabledStateTexture { self.generalSprite.texture = disTex } else { self.generalSprite.texture = normalStateTexture } case .highlighted: if let single = highlightedStateSingleTexture { self.generalSprite.texture = single } else { if lastState == .normal { if let fromNormal = self.highlightedStateMultiTextureFromNormal { self.generalSprite.texture = fromNormal } else if let sel = self.selectedStateTexture { self.generalSprite.texture = sel } else { self.generalSprite.texture = self.normalStateTexture } } else if lastState == .selected { if let fromSelected = self.highlightedStateMultiTextureFromSelected { self.generalSprite.texture = fromSelected } else { self.generalSprite.texture = self.normalStateTexture } } } } // This line was removed to fix the animation bug where the size of the button would change after animate. It appears nothings break by the remove so far // self.generalSprite.size = self.generalSprite.texture!.size() } fileprivate func updateShapeVisualInterface() { switch state { case .normal: self.generalShape.redefine(normalStateShapeDef) case .selected: if let selSha = self.selectedStateShapeDef { self.generalShape.redefine(selSha) } else { self.generalShape.redefine(normalStateShapeDef) } case .disabled: if let disSha = self.disabledStateShapeDef { self.generalShape.redefine(disSha) } else { self.generalShape.redefine(normalStateShapeDef) } case .highlighted: if let single = highlightedStateSingleShapeDef { self.generalShape.redefine(single) } else { if lastState == .normal { if let fromNormal = self.highlightedStateMultiShapeFromNormalDef { self.generalShape.redefine(fromNormal) } else if let sel = self.selectedStateShapeDef { self.generalShape.redefine(sel) } else { self.generalShape.redefine(self.normalStateShapeDef) } } else if lastState == .selected { if let fromSelected = self.highlightedStateMultiShapeFromSelectedDef { self.generalShape.redefine(fromSelected) } else { self.generalShape.redefine(self.normalStateShapeDef) } } } } } fileprivate func updateLabelsVisualInterface() { // Labels normalStateLabel?.alpha = 0 selectedStateLabel?.alpha = 0 disabledStateLabel?.alpha = 0 highlightedStateSingleLabel?.alpha = 0 highlightedStateMultiLabelFromNormal?.alpha = 0 highlightedStateMultiLabelFromSelected?.alpha = 0 switch state { case .normal: normalStateLabel?.alpha = 1 case .selected: if let selLabel = self.selectedStateLabel { selLabel.alpha = 1 } else { normalStateLabel?.alpha = 1 } case .disabled: if let disLabel = self.disabledStateLabel { disLabel.alpha = 1 } else { normalStateLabel?.alpha = 1 } case .highlighted: if let single = highlightedStateSingleLabel { single.alpha = 1 } else { if lastState == .normal { if let fromNormal = self.highlightedStateMultiLabelFromNormal { fromNormal.alpha = 1 } else if let selectedLabel = self.selectedStateLabel { selectedLabel.alpha = 1 } else { self.normalStateLabel?.alpha = 1 } } else if lastState == .selected { if let fromSelected = self.highlightedStateMultiLabelFromSelected { fromSelected.alpha = 1 } else { self.normalStateLabel?.alpha = 1 } } } } } // MARK: Control Events internal func touchDown() { playSound(instanceSoundFileName: touchDownSoundFileName, defaultSoundFileName: TWControl.defaultTouchDownSoundFileName) executeClosures(of: .touchDown) } internal func disabledTouchDown() { playSound(instanceSoundFileName: disabledTouchDownFileName, defaultSoundFileName: TWControl.defaultDisabledTouchDownFileName) executeClosures(of: .disabledTouchDown) } internal func drag() {} internal func dragExit() { executeClosures(of: .touchDragExit) } internal func dragOutside() { executeClosures(of: .touchDragOutside) } internal func dragEnter() { executeClosures(of: .touchDragEnter) } internal func dragInside() { executeClosures(of: .touchDragInside) } open func touchUpInside() { executeClosures(of: .touchUpInside) playSound(instanceSoundFileName: touchUpSoundFileName, defaultSoundFileName: TWControl.defaultTouchUpSoundFileName) } internal func touchUpOutside() { executeClosures(of: .touchUpOutside) playSound(instanceSoundFileName: touchUpSoundFileName, defaultSoundFileName: TWControl.defaultTouchUpSoundFileName) } // MARK: UIResponder Methods override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch = touches.first! let touchPoint = touch.location(in: self.genericNode.parent!) if self.genericNode.contains(touchPoint) { self.touch = touch self.touchLocationLast = touchPoint if self.state == .disabled { disabledTouchDown() } else { touchDown() } } } override open func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { if self.state == .disabled { return } let touch = touches.first! let touchPoint = touch.location(in: self.genericNode.parent!) drag() self.moved = true if self.genericNode.contains(touchPoint) { // Inside if let lastPoint = self.touchLocationLast , self.genericNode.contains(lastPoint) { // All along dragInside() } else { self.dragEnter() } } else { // Outside if let lastPoint = self.touchLocationLast , self.genericNode.contains(lastPoint) { // Since now dragExit() } else { // All along dragOutside() } } self.touchLocationLast = touchPoint } override open func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { endedTouch() } override open func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { endedTouch() } fileprivate func endedTouch() { if self.state == .disabled { return } if self.moved { if let lastPoint = self.touchLocationLast , self.genericNode.contains(lastPoint) { // Ended inside touchUpInside() } else { // Ended outside touchUpOutside() } } else { // Needed?? touchUpInside() } self.moved = false } }
mit
8da679a86785da21d158142e562e343f
36.875138
235
0.636258
5.403058
false
false
false
false
steven851007/ShoppingCart
ShoppingCart/ShoppingCartTests/ShoppingCartTests.swift
1
2489
// // ShoppingCartTests.swift // ShoppingCartTests // // Created by Istvan Balogh on 2017. 08. 10.. // Copyright © 2017. Balogh István. All rights reserved. // import XCTest @testable import ShoppingCart class ShoppingCartTests: XCTestCase { var shoppingCart: ShoppingCart! override func setUp() { super.setUp() self.shoppingCart = ShoppingCart() } override func tearDown() { self.shoppingCart = nil super.tearDown() } func testIsEmpty() { XCTAssertTrue(self.shoppingCart.isEmpty) let good = Good(name: "Test", price: NSDecimalNumber(value: 1), unit: .bag) self.shoppingCart.add(good: good) XCTAssertFalse(self.shoppingCart.isEmpty) } func testCount() { XCTAssertEqual(self.shoppingCart.count, 0) let good = Good(name: "Test", price: NSDecimalNumber(value: 1), unit: .bag) self.shoppingCart.add(good: good) XCTAssertEqual(self.shoppingCart.count, 1) self.shoppingCart.add(good: good) XCTAssertEqual(self.shoppingCart.count, 1) XCTAssertEqual(self.shoppingCart[0].count, 2) } func testAdd() { let good = Good(name: "Test", price: NSDecimalNumber(value: 1), unit: .bag) self.shoppingCart.add(good: good) XCTAssertEqual(self.shoppingCart.count, 1) XCTAssertEqual(self.shoppingCart[0].good, good) } func testRemove() { let good = Good(name: "Test", price: NSDecimalNumber(value: 1), unit: .bag) self.shoppingCart.add(good: good) self.shoppingCart.remove(good: good) XCTAssertEqual(self.shoppingCart.count, 0) self.shoppingCart.add(good: good) self.shoppingCart.remove(at: 0) XCTAssertEqual(self.shoppingCart.count, 0) } func testTotalPrice() { XCTAssertEqual(self.shoppingCart.totalPrice, NSDecimalNumber(value: 0)) let good = Good(name: "Test", price: NSDecimalNumber(value: 1), unit: .bag) self.shoppingCart.add(good: good) XCTAssertEqual(self.shoppingCart.totalPrice, NSDecimalNumber(value: 1)) self.shoppingCart.add(good: good) XCTAssertEqual(self.shoppingCart.totalPrice, NSDecimalNumber(value: 2)) let good1 = Good(name: "Test1", price: NSDecimalNumber(value: 11), unit: .bag) self.shoppingCart.add(good: good1) XCTAssertEqual(self.shoppingCart.totalPrice, NSDecimalNumber(value: 13)) } }
mit
07d907c07204aeceddd9b7fad9ec98ba
33.068493
86
0.647768
4.01129
false
true
false
false
MooseMagnet/DeliciousPubSub
DeliciousPubSubTests/SubscriptionsCanBeCancelledInsideOfSubscriptionCallbacks.swift
1
1408
// // SubscriptionsCanBeCancelledInsideOfSubscriptionCallbacks.swift // DeliciousPubSub // import XCTest @testable import DeliciousPubSub // There was a bug. // During the message dispatch, subscription callbacks could be invoked after they // were prematurely unregistered inside of the body of another handler invoked previously // in the same message dispatch call. // That is to say, Handler 1 was unable to prevent the later Handler 2 from running // by calling a function to deregister it. // There's probably use case for this, so here is a test to prove it now works. class SubscriptionsCanBeCancelledInsideOfSubscriptionCallbacks : XCTestCase { func testTheCallbackWillNotBeInvokedAfterAPreviousHandlerHasCancelledIt() { let pubSub = PubSub() var invokedPrecedingHandler = false var invokedCancelledHandler = false var unsub: (() -> Void)! let _ = pubSub.sub { (_: Int) in invokedPrecedingHandler = true unsub() } unsub = pubSub.sub { (_: Int) in invokedCancelledHandler = true XCTFail() } pubSub.pub(1) XCTAssert(!invokedCancelledHandler) XCTAssert(invokedPrecedingHandler) // Ideally we'd be able to call this again without an explosion... unsub() } }
mit
3eb7b3618603402069697a118fa0e90e
27.734694
89
0.649148
4.855172
false
true
false
false
DoubleSha/BitcoinSwift
BitcoinSwift/Models/FilteredBlock.swift
1
2009
// // FilteredBlock.swift // BitcoinSwift // // Created by Kevin Greene on 10/26/14. // Copyright (c) 2014 DoubleSha. All rights reserved. // import Foundation public func ==(left: FilteredBlock, right: FilteredBlock) -> Bool { return left.header == right.header && left.partialMerkleTree == right.partialMerkleTree } /// Blocks served from a peer with a bloom filter loaded. Only includes merkle branches for /// transactions that are relevant to the current bloom filter. /// https://en.bitcoin.it/wiki/Protocol_specification#filterload.2C_filteradd.2C_filterclear.2C_merkleblock public struct FilteredBlock: Equatable { public let header: BlockHeader public let partialMerkleTree: PartialMerkleTree public init(header: BlockHeader, partialMerkleTree: PartialMerkleTree) { self.header = header self.partialMerkleTree = partialMerkleTree } public var merkleProofIsValid: Bool { return header.merkleRoot == partialMerkleTree.rootHash } } extension FilteredBlock: MessagePayload { public var command: Message.Command { return Message.Command.FilteredBlock } public var bitcoinData: NSData { let data = NSMutableData() data.appendData(header.bitcoinData) data.appendData(partialMerkleTree.bitcoinData) return data } public static func fromBitcoinStream(stream: NSInputStream) -> FilteredBlock? { let header = BlockHeader.fromBitcoinStream(stream) if header == nil { Logger.warn("Failed to parse header from FilteredBlock") return nil } let partialMerkleTree = PartialMerkleTree.fromBitcoinStream(stream) if partialMerkleTree == nil { Logger.warn("Failed to parse partialMerkleTree from FilteredBlock") return nil } let filteredBlock = FilteredBlock(header: header!, partialMerkleTree: partialMerkleTree!) if !filteredBlock.merkleProofIsValid { Logger.warn("Failed to parse FilteredBlock, invalid merkle proof") return nil } return filteredBlock } }
apache-2.0
968df138b467bd614de962b6b2c060a6
29.907692
107
0.736187
4.142268
false
false
false
false
suzuki-0000/SKPhotoBrowser
SKPhotoBrowserExample/SKPhotoBrowserExample/FromCameraRollViewController.swift
1
6728
// // CameraRollCollectionViewController.swift // SKPhotoBrowserExample // // Created by K Rummler on 11/03/16. // Copyright © 2016 suzuki_keishi. All rights reserved. // import UIKit import Photos import SKPhotoBrowser class FromCameraRollViewController: UIViewController, SKPhotoBrowserDelegate, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var collectionView: UICollectionView! fileprivate let imageManager = PHCachingImageManager.default() fileprivate var assets: [PHAsset] = [] fileprivate lazy var requestOptions: PHImageRequestOptions = { let options = PHImageRequestOptions() options.deliveryMode = .opportunistic options.resizeMode = .fast return options }() fileprivate lazy var bigRequestOptions: PHImageRequestOptions = { let options = PHImageRequestOptions() options.deliveryMode = .highQualityFormat options.resizeMode = .fast return options }() override func viewDidLoad() { super.viewDidLoad() fetchAssets() collectionView?.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDataSource func numberOfSections(in collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return assets.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "exampleCollectionViewCell", for: indexPath) let asset = assets[(indexPath as NSIndexPath).row] if let cell = cell as? AssetExampleCollectionViewCell { if let id = cell.requestId { imageManager.cancelImageRequest(id) cell.requestId = nil } cell.requestId = requestImageForAsset(asset, options: requestOptions) { image, requestId in if requestId == cell.requestId || cell.requestId == nil { cell.exampleImageView.image = image } } } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath) as? ExampleCollectionViewCell else { return } guard let originImage = cell.exampleImageView.image else { return } func open(_ images: [UIImage]) { let photoImages: [SKPhotoProtocol] = images.map({ return SKPhoto.photoWithImage($0) }) let browser = SKPhotoBrowser(originImage: cell.exampleImageView.image!, photos: photoImages, animatedFromView: cell) browser.initializePageIndex(indexPath.row) browser.delegate = self // browser.displayDeleteButton = true // browser.displayAction = false self.present(browser, animated: true, completion: {}) } var fetchedImages: [UIImage] = [UIImage](repeating: UIImage(), count: assets.count) var fetched = 0 assets.forEach { (asset) -> Void in _ = requestImageForAsset(asset, options: bigRequestOptions, completion: { [weak self] (image, _) -> Void in if let image = image, let index = self?.assets.firstIndex(of: asset) { fetchedImages[index] = image } fetched += 1 if self?.assets.count == fetched { open(fetchedImages) } }) } } fileprivate func fetchAssets() { let options = PHFetchOptions() let limit = 8 options.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] options.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) options.fetchLimit = limit let result = PHAsset.fetchAssets(with: options) let amount = min(result.count, limit) self.assets = result.objects(at: IndexSet(integersIn: Range(NSRange(location: 0, length: amount)) ?? 0..<0)) } fileprivate func requestImageForAsset(_ asset: PHAsset, options: PHImageRequestOptions, completion: @escaping (_ image: UIImage?, _ requestId: PHImageRequestID?) -> Void) -> PHImageRequestID { let scale = UIScreen.main.scale let targetSize: CGSize if options.deliveryMode == .highQualityFormat { targetSize = CGSize(width: 600 * scale, height: 600 * scale) } else { targetSize = CGSize(width: 182 * scale, height: 182 * scale) } requestOptions.isSynchronous = false // Workaround because PHImageManager.requestImageForAsset doesn't work for burst images if asset.representsBurst { return imageManager.requestImageData(for: asset, options: options) { data, _, _, dict in let image = data.flatMap { UIImage(data: $0) } let requestId = dict?[PHImageResultRequestIDKey] as? NSNumber completion(image, requestId?.int32Value) } } else { return imageManager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFill, options: options) { image, dict in let requestId = dict?[PHImageResultRequestIDKey] as? NSNumber completion(image, requestId?.int32Value) } } } override var prefersStatusBarHidden: Bool { return false } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } class AssetExampleCollectionViewCell: ExampleCollectionViewCell { var requestId: PHImageRequestID? }
mit
4f37a0c8f2724ef4d255183b9d60c690
36.581006
196
0.626133
5.619883
false
false
false
false
kickstarter/ios-oss
Library/ViewModels/HTML Parser/TextViewElementCellViewModel.swift
1
5015
import KsApi import Prelude import ReactiveSwift import UIKit public protocol TextViewElementCellViewModelInputs { /// Call to configure with a TextElement representing raw HTML func configureWith(textElement: TextViewElement) } public protocol TextViewElementCellViewModelOutputs { /// Emits attributed text containing content of HTML after styling has been applied. var attributedText: Signal<NSAttributedString, Never> { get } } public protocol TextViewElementCellViewModelType { var inputs: TextViewElementCellViewModelInputs { get } var outputs: TextViewElementCellViewModelOutputs { get } } public final class TextViewElementCellViewModel: TextViewElementCellViewModelType, TextViewElementCellViewModelInputs, TextViewElementCellViewModelOutputs { // MARK: Helpers public init() { let attributedText = self.textElement.signal .skipNil() .switchMap(attributedText(textElement:)) self.attributedText = attributedText } fileprivate let textElement = MutableProperty<TextViewElement?>(nil) public func configureWith(textElement: TextViewElement) { self.textElement.value = textElement } public let attributedText: Signal<NSAttributedString, Never> public var inputs: TextViewElementCellViewModelInputs { self } public var outputs: TextViewElementCellViewModelOutputs { self } } private func attributedText(textElement: TextViewElement) -> SignalProducer<NSAttributedString, Never> { let completedAttributedText = NSMutableAttributedString() for textItemIndex in 0..<textElement.components.count { let textItem = textElement.components[textItemIndex] let componentText = textItem.text let paragraphStyle = NSMutableParagraphStyle() let currentAttributedText = NSMutableAttributedString(string: componentText) let fullRange = (componentText as NSString).localizedStandardRange(of: textItem.text) let baseFontSize: CGFloat = 16.0 let baseFont = UIFont.ksr_body(size: baseFontSize) let headerFontSize: CGFloat = 20.0 let headerFont = UIFont.ksr_body(size: headerFontSize).bolded paragraphStyle.minimumLineHeight = 22 let baseFontAttributes = [ NSAttributedString.Key.font: baseFont, NSAttributedString.Key.foregroundColor: UIColor.ksr_support_700, NSAttributedString.Key.paragraphStyle: paragraphStyle ] guard textItem.styles.count > 0 else { currentAttributedText.addAttributes(baseFontAttributes, range: fullRange) completedAttributedText.append(currentAttributedText) continue } var combinedAttributes: [NSAttributedString.Key: Any] = baseFontAttributes textItem.styles.forEach { textStyleType in switch textStyleType { case .bold: if let existingFont = combinedAttributes[NSAttributedString.Key.font] as? UIFont, existingFont == baseFont.italicized { combinedAttributes[NSAttributedString.Key.font] = baseFont.boldItalic } else { combinedAttributes[NSAttributedString.Key.font] = baseFont.bolded } case .emphasis: if let existingFont = combinedAttributes[NSAttributedString.Key.font] as? UIFont, existingFont == baseFont.bolded { combinedAttributes[NSAttributedString.Key.font] = baseFont.boldItalic } else { combinedAttributes[NSAttributedString.Key.font] = baseFont.italicized } case .link: combinedAttributes[NSAttributedString.Key.foregroundColor] = UIColor.ksr_create_700 combinedAttributes[NSAttributedString.Key.underlineStyle] = NSUnderlineStyle.single.rawValue if let validURLString = textItem.link, let validURL = URL(string: validURLString) { combinedAttributes[NSAttributedString.Key.link] = validURL } case .bulletStart: paragraphStyle.headIndent = (textItem.text as NSString).size(withAttributes: baseFontAttributes).width combinedAttributes[NSAttributedString.Key.paragraphStyle] = paragraphStyle case .bulletEnd: let moreBulletPointsExist = !textElement.components[textItemIndex..<textElement.components.count] .compactMap { component -> TextComponent? in if !component.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return component } return nil } .isEmpty if moreBulletPointsExist { completedAttributedText.append(NSAttributedString(string: "\n")) } case .header: combinedAttributes[NSAttributedString.Key.font] = headerFont combinedAttributes[NSAttributedString.Key.foregroundColor] = UIColor.ksr_support_700 paragraphStyle.minimumLineHeight = 25 combinedAttributes[NSAttributedString.Key.paragraphStyle] = paragraphStyle } } currentAttributedText.addAttributes(combinedAttributes, range: fullRange) completedAttributedText.append(currentAttributedText) } return SignalProducer(value: completedAttributedText) }
apache-2.0
1d518024d80e3d5e7a1973f828f686b4
38.488189
110
0.743769
5.278947
false
false
false
false
dvor/Antidote
Antidote/TextViewController.swift
1
2716
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit import SnapKit private struct Constants { static let Offset = 10.0 static let TitleColorKey = "TITLE_COLOR" static let TextColorKey = "TEXT_COLOR" } class TextViewController: UIViewController { fileprivate let resourceName: String fileprivate let backgroundColor: UIColor fileprivate let titleColor: UIColor fileprivate let textColor: UIColor fileprivate var textView: UITextView! init(resourceName: String, backgroundColor: UIColor, titleColor: UIColor, textColor: UIColor) { self.resourceName = resourceName self.backgroundColor = backgroundColor self.titleColor = titleColor self.textColor = textColor super.init(nibName: nil, bundle: nil) } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { loadViewWithBackgroundColor(backgroundColor) createTextView() installConstraints() loadHtml() } } private extension TextViewController { func createTextView() { textView = UITextView() textView.isEditable = false textView.backgroundColor = .clear view.addSubview(textView) } func installConstraints() { textView.snp.makeConstraints { $0.leading.top.equalTo(view).offset(Constants.Offset) $0.trailing.bottom.equalTo(view).offset(-Constants.Offset) } } func loadHtml() { do { struct FakeError: Error {} guard let htmlFilePath = Bundle.main.path(forResource: resourceName, ofType: "html") else { throw FakeError() } var htmlString = try NSString(contentsOfFile: htmlFilePath, encoding: String.Encoding.utf8.rawValue) htmlString = htmlString.replacingOccurrences(of: Constants.TitleColorKey, with: titleColor.hexString()) as NSString htmlString = htmlString.replacingOccurrences(of: Constants.TextColorKey, with: textColor.hexString()) as NSString guard let data = htmlString.data(using: String.Encoding.unicode.rawValue) else { throw FakeError() } let options = [ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType ] try textView.attributedText = NSAttributedString(data: data, options: options, documentAttributes: nil) } catch { handleErrorWithType(.cannotLoadHTML) } } }
mit
b71a7c97e357c3eb60b7a702be283d1a
32.121951
127
0.666421
5.095685
false
false
false
false
LKY769215561/KYHandMade
KYHandMade/KYHandMade/Class/Home(首页)/Controller/KYSlideLessonController.swift
1
976
// // KYSlideLessonController.swift // KYHandMade // // Created by Kerain on 2017/6/14. // Copyright © 2017年 广州市九章信息科技有限公司. All rights reserved. // import UIKit private let GPSubCell = "subCell"; private let GPConCell = "contentCell"; private let GPUseCell = "userCell"; private let GPOtherClassCell = "otherClassCell"; private let GPAppraiseCell = "AppraiseCell"; class KYSlideLessonController: UITableViewController { public var slide:KYSlideModel? override func viewDidLoad() { super.viewDidLoad() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) KYProgressHUD.dismiss() } func loadData() { } func congigNav() { } func addFooterView() { } func regisCell() { } }
apache-2.0
797975ef7872a915eb52bb1887a223ad
15.327586
57
0.565998
4.466981
false
false
false
false
czechboy0/swift-package-crawler
Sources/AnalyzerLib/SwiftVersions.swift
1
1249
// // SwiftVersions.swift // swift-package-crawler // // Created by Honza Dvorsky on 8/25/16. // // import Redbird import Utils struct SwiftVersions: Analysis { let db: Redbird func analyze(packageIterator: PackageIterator) throws { print("Starting SwiftVersions analyzer...") var versions: [String: Int] = [:] var it = packageIterator.makeNew() while let package = try it.next() { let version = package.swiftVersion ?? "unknown" versions[version] = (versions[version] ?? 0) + 1 } //sort keys by swift versions chronologically let sortedVersions = versions .keys.sorted(isOrderedBefore: { (a, b) -> Bool in a.lowercased() < b.lowercased() }) .map { return ($0, versions[$0]!) } //render as markdown let table = makeMarkdownTable(title: "Swift versions", headers: ["Version", "# Packages"], rowCount: sortedVersions.count) { (i) -> [String] in let info = sortedVersions[i] return [info.0, String(info.1)] } try saveStat(db: db, name: "swift_versions_stat", value: table) print("Finished SwiftVersions analyzer...") } }
mit
173d67c5fa11fb3bebcf1f1856cb32ff
30.225
151
0.581265
4.248299
false
false
false
false
dparnell/swift-parser-generator
Sources/Parser.swift
1
13201
import Foundation public typealias ParserFunction = (_ parser: Parser, _ reader: Reader) throws -> Bool public typealias ParserAction = (_ parser: Parser) throws -> () public typealias ParserActionWithoutParameter = () throws -> () /** Definition of a grammar for the parser. Can be reused between multiple parsings. */ public class Grammar { /** This rule determines what is seen as 'whitespace' by the '~~' operator, which allows whitespace between two following items.*/ public var whitespace: ParserRule = (" " | "\t" | "\r\n" | "\r" | "\n")* public var nestingDepthLimit: Int? = nil /** The start rule for this grammar. */ public var startRule: ParserRule! = nil internal var namedRules: [String: ParserRule] = [:] public init() { } public init(_ creator: (Grammar) -> (ParserRule)) { self.startRule = creator(self) } public subscript(name: String) -> ParserRule { get { return self.namedRules[name]! } set(newValue) { self.namedRules[name] = newValue } } } open class Parser { public struct ParserCapture : CustomStringConvertible { public var start: Int public var end: Int public var action: ParserAction let reader: Reader var text: String { return reader.substring(start, ending_at:end) } public var description: String { return "[\(start),\(end):\(text)]" } } public var debugRules = false public var captures: [ParserCapture] = [] public var currentCapture: ParserCapture? public var lastCapture: ParserCapture? public var currentReader: Reader? public var grammar: Grammar internal var matches: [ParserRule: [Int: Bool]] = [:] internal var nestingDepth = 0 public var text: String { get { if let capture = currentCapture { return capture.text } return "" } } public init() { self.grammar = Grammar() } public init(grammar: Grammar) { self.grammar = grammar } public func parse(_ string: String) throws -> Bool { matches.removeAll(keepingCapacity: false) captures.removeAll(keepingCapacity: false) currentCapture = nil lastCapture = nil defer { currentReader = nil currentCapture = nil lastCapture = nil matches.removeAll(keepingCapacity: false) captures.removeAll(keepingCapacity:false) } let reader = StringReader(string: string) if try grammar.startRule!.matches(self, reader) { currentReader = reader for capture in captures { lastCapture = currentCapture currentCapture = capture try capture.action(self) } return true } return false } var depth = 0 func leave(_ name: String) { if(debugRules) { self.out("-- \(name)") } depth -= 1 } func leave(_ name: String, _ res: Bool) { if(debugRules) { self.out("-- \(name):\t\(res)") } depth -= 1 } func enter(_ name: String) { depth += 1 if(debugRules) { self.out("++ \(name)") } } func out(_ name: String) { var spaces = "" for _ in 0..<depth-1 { spaces += " " } print("\(spaces)\(name)") } } public class ParserRule: Hashable { internal var function: ParserFunction public init(_ function: @escaping ParserFunction) { self.function = function } public func matches(_ parser: Parser, _ reader: Reader) throws -> Bool { return try self.function(parser, reader) } public var hashValue: Int { return ObjectIdentifier(self).hashValue } public static func ==(lhs: ParserRule, rhs: ParserRule) -> Bool { return ObjectIdentifier(lhs) == ObjectIdentifier(rhs) } } public final class ParserMemoizingRule: ParserRule { public override func matches(_ parser: Parser, _ reader: Reader) throws -> Bool { let position = reader.position if let m = parser.matches[self]?[position] { return m } let r = try self.function(parser, reader) if parser.matches[self] == nil { parser.matches[self] = [position: r] } else { parser.matches[self]![position] = r } return r } } // EOF operator postfix operator *!* public postfix func *!* (rule: ParserRule) -> ParserRule { return ParserRule { (parser: Parser, reader: Reader) -> Bool in return try rule.matches(parser, reader) && reader.eof() } } // call a named rule - this allows for cycles, so be careful! prefix operator ^ public prefix func ^(name:String) -> ParserRule { return ParserMemoizingRule { (parser: Parser, reader: Reader) -> Bool in // TODO: check stack to see if this named rule is already on there to prevent loops parser.enter("named rule: \(name)") let result = try parser.grammar[name].function(parser, reader) parser.leave("named rule: \(name)",result) return result } } // match a regex #if !os(Linux) prefix operator %! public prefix func %!(pattern:String) -> ParserRule { return ParserRule { (parser: Parser, reader: Reader) -> Bool in parser.enter("regex '\(pattern)'") let pos = reader.position var found = true let remainder = reader.remainder() do { let re = try NSRegularExpression(pattern: pattern, options: []) let target = remainder as NSString let match = re.firstMatch(in: remainder, options: [], range: NSMakeRange(0, target.length)) if let m = match { let res = target.substring(with: m.range) // reset to end of match reader.seek(pos + res.characters.count) parser.leave("regex", true) return true } } catch { found = false } if(!found) { reader.seek(pos) parser.leave("regex", false) } return false } } #endif public enum ParserError: LocalizedError { case nestingDepthLimitExceeded public var errorDescription: String? { switch self { case .nestingDepthLimitExceeded: return "nesting depth limit exceeded" } } } /** Wrap the rule with a nesting depth check. All rules wrapped with this check also increase the current nesting depth. */ public func nest(_ rule: ParserRule) -> ParserRule { return ParserRule { (parser: Parser, reader: Reader) throws -> Bool in parser.nestingDepth += 1 defer { parser.nestingDepth -= 1 } if let nd = parser.grammar.nestingDepthLimit, parser.nestingDepth > nd { throw ParserError.nestingDepthLimitExceeded } return try rule.matches(parser, reader) } } // match a literal string prefix operator % public prefix func %(lit:String) -> ParserRule { return literal(lit) } public func literal(_ string:String) -> ParserRule { return ParserRule { (parser: Parser, reader: Reader) -> Bool in parser.enter("literal '\(string)'") let pos = reader.position for ch in string.characters { let flag = ch == reader.read() if !flag { reader.seek(pos) parser.leave("literal", false) return false } } parser.leave("literal", true) return true } } // match a range of characters eg: "0"-"9" public func - (left: Character, right: Character) -> ParserRule { return ParserRule { (parser: Parser, reader: Reader) -> Bool in parser.enter("range [\(left)-\(right)]") let pos = reader.position let lower = String(left) let upper = String(right) let ch = String(reader.read()) let found = (lower <= ch) && (ch <= upper) parser.leave("range \t\t\(ch)", found) if(!found) { reader.seek(pos) } return found } } // invert match public prefix func !(rule: ParserRule) -> ParserRule { return ParserRule { (parser: Parser, reader: Reader) -> Bool in return try !rule.matches(parser, reader) } } public prefix func !(lit: String) -> ParserRule { return !literal(lit) } // match one or more postfix operator + public postfix func + (rule: ParserRule) -> ParserRule { return ParserRule { (parser: Parser, reader: Reader) -> Bool in let pos = reader.position var found = false var flag: Bool parser.enter("one or more") repeat { flag = try rule.matches(parser, reader) found = found || flag } while(flag) if(!found) { reader.seek(pos) } parser.leave("one or more", found) return found } } public postfix func + (lit: String) -> ParserRule { return literal(lit)+ } // match zero or more postfix operator * public postfix func * (rule: ParserRule) -> ParserRule { return ParserRule { (parser: Parser, reader: Reader) -> Bool in var flag: Bool var matched = false parser.enter("zero or more") repeat { let pos = reader.position flag = try rule.matches(parser, reader) if(!flag) { reader.seek(pos) } else { matched = true } } while(flag) parser.leave("zero or more", matched) return true } } public postfix func * (lit: String) -> ParserRule { return literal(lit)* } // optional postfix operator /~ public postfix func /~ (rule: ParserRule) -> ParserRule { return ParserRule { (parser: Parser, reader: Reader) -> Bool in parser.enter("optionally") let pos = reader.position if(try !rule.matches(parser, reader)) { reader.seek(pos) } parser.leave("optionally", true) return true } } public postfix func /~ (lit: String) -> ParserRule { return literal(lit)/~ } // match either public func | (left: String, right: String) -> ParserRule { return literal(left) | literal(right) } public func | (left: String, right: ParserRule) -> ParserRule { return literal(left) | right } public func | (left: ParserRule, right: String) -> ParserRule { return left | literal(right) } public func | (left: ParserRule, right: ParserRule) -> ParserRule { return ParserMemoizingRule { (parser: Parser, reader: Reader) -> Bool in parser.enter("|") let pos = reader.position var result = try left.matches(parser, reader) if(!result) { reader.seek(pos) result = try right.matches(parser, reader) } if(!result) { reader.seek(pos) } parser.leave("|", result) return result } } precedencegroup MinPrecedence { associativity: left higherThan: AssignmentPrecedence } precedencegroup MaxPrecedence { associativity: left higherThan: MinPrecedence } // match all infix operator ~ : MinPrecedence public func ~ (left: String, right: String) -> ParserRule { return literal(left) ~ literal(right) } public func ~ (left: String, right: ParserRule) -> ParserRule { return literal(left) ~ right } public func ~ (left: ParserRule, right: String) -> ParserRule { return left ~ literal(right) } public func ~ (left : ParserRule, right: ParserRule) -> ParserRule { return ParserRule { (parser: Parser, reader: Reader) -> Bool in parser.enter("~") let res = try left.matches(parser, reader) && right.matches(parser, reader) parser.leave("~", res) return res } } // on match infix operator => : MaxPrecedence public func => (rule : ParserRule, action: @escaping ParserAction) -> ParserRule { return ParserRule { (parser: Parser, reader: Reader) -> Bool in let start = reader.position let capture_count = parser.captures.count parser.enter("=>") if(try rule.matches(parser, reader)) { let capture = Parser.ParserCapture(start: start, end: reader.position, action: action, reader: reader) parser.captures.append(capture) parser.leave("=>", true) return true } while(parser.captures.count > capture_count) { parser.captures.removeLast() } parser.leave("=>", false) return false } } public func => (rule : ParserRule, action: @escaping ParserActionWithoutParameter) -> ParserRule { return rule => { _ in try action() } } /** The ~~ operator matches two following elements, optionally with whitespace (Parser.whitespace) in between. */ infix operator ~~ : MinPrecedence public func ~~ (left: String, right: String) -> ParserRule { return literal(left) ~~ literal(right) } public func ~~ (left: String, right: ParserRule) -> ParserRule { return literal(left) ~~ right } public func ~~ (left: ParserRule, right: String) -> ParserRule { return left ~~ literal(right) } public func ~~ (left : ParserRule, right: ParserRule) -> ParserRule { return ParserRule { (parser: Parser, reader: Reader) -> Bool in return try left.matches(parser, reader) && parser.grammar.whitespace.matches(parser, reader) && right.matches(parser, reader) } } /** Parser rule that matches the given parser rule at least once, but possibly more */ public postfix func ++ (left: ParserRule) -> ParserRule { return left ~~ left* }
unlicense
d2e4d7b17df774bc601d13ad6af1c830
24.386538
114
0.620105
3.86107
false
false
false
false
eBardX/XestiMonitors
Examples/XestiMonitorsDemo-iOS/XestiMonitorsDemo/CoreLocationViewController.swift
1
20015
// // CoreLocationViewController.swift // XestiMonitorsDemo-iOS // // Created by J. G. Pusey on 2018-03-24. // // © 2018 J. G. Pusey (see LICENSE.md) // import CoreLocation import UIKit import XestiMonitors // swiftlint:disable type_body_length public class CoreLocationViewController: UITableViewController { // MARK: Private Instance Properties @IBOutlet private weak var beaconRangingAccuracyLabel: UILabel! @IBOutlet private weak var beaconRangingMajorMinorLabel: UILabel! @IBOutlet private weak var beaconRangingProximityLabel: UILabel! @IBOutlet private weak var beaconRangingProximityUUIDLabel: UILabel! @IBOutlet private weak var beaconRangingRSSILabel: UILabel! @IBOutlet private weak var headingAccuracyLabel: UILabel! @IBOutlet private weak var headingGeomagnetismLabel: UILabel! @IBOutlet private weak var headingMagneticHeadingLabel: UILabel! @IBOutlet private weak var headingTimestampLabel: UILabel! @IBOutlet private weak var headingTrueHeadingLabel: UILabel! @IBOutlet private weak var locationAuthorizationStatusLabel: UILabel! @IBOutlet private weak var regionIdentifierLabel: UILabel! @IBOutlet private weak var regionStateLabel: UILabel! @IBOutlet private weak var significantLocationAltitudeLabel: UILabel! @IBOutlet private weak var significantLocationCoordinateLabel: UILabel! @IBOutlet private weak var significantLocationCourseLabel: UILabel! @IBOutlet private weak var significantLocationFloorLabel: UILabel! @IBOutlet private weak var significantLocationHorizontalAccuracyLabel: UILabel! @IBOutlet private weak var significantLocationSpeedLabel: UILabel! @IBOutlet private weak var significantLocationTimestampLabel: UILabel! @IBOutlet private weak var significantLocationVerticalAccuracyLabel: UILabel! @IBOutlet private weak var standardLocationAltitudeLabel: UILabel! @IBOutlet private weak var standardLocationCoordinateLabel: UILabel! @IBOutlet private weak var standardLocationCourseLabel: UILabel! @IBOutlet private weak var standardLocationFloorLabel: UILabel! @IBOutlet private weak var standardLocationHorizontalAccuracyLabel: UILabel! @IBOutlet private weak var standardLocationSpeedLabel: UILabel! @IBOutlet private weak var standardLocationTimestampLabel: UILabel! @IBOutlet private weak var standardLocationVerticalAccuracyLabel: UILabel! @IBOutlet private weak var visitArrivalDateLabel: UILabel! @IBOutlet private weak var visitCoordinateLabel: UILabel! @IBOutlet private weak var visitDepartureDateLabel: UILabel! @IBOutlet private weak var visitHorizontalAccuracyLabel: UILabel! private lazy var beaconRangingMonitor = BeaconRangingMonitor(region: beaconRegion, queue: .main) { [unowned self] in self.displayBeaconRanging($0) } private lazy var beaconRegion = CLBeaconRegion(proximityUUID: UUID(), identifier: "Test Region") private lazy var headingMonitor = HeadingMonitor(queue: .main) { [unowned self] in self.displayHeading($0) } private lazy var locationAuthorizationMonitor = LocationAuthorizationMonitor(queue: .main) { [unowned self] in self.displayLocationAuthorization($0) } private lazy var regionMonitor = RegionMonitor(region: beaconRegion, queue: .main) { [unowned self] in self.displayRegion($0) } private lazy var significantLocationMonitor = SignificantLocationMonitor(queue: .main) { [unowned self] in self.displaySignificantLocation($0) } private lazy var standardLocationMonitor = StandardLocationMonitor(queue: .main) { [unowned self] in self.displayStandardLocation($0) } private lazy var visitMonitor = VisitMonitor(queue: .main) { [unowned self] in self.displayVisit($0) } private lazy var monitors: [Monitor] = [beaconRangingMonitor, headingMonitor, locationAuthorizationMonitor, regionMonitor, significantLocationMonitor, standardLocationMonitor, visitMonitor] // MARK: Private Instance Methods private func displayBeaconRanging(_ event: BeaconRangingMonitor.Event?) { if !beaconRangingMonitor.isAvailable { displayBeaconRanging(nil, altText: "Not available", altColor: .red) } else if let event = event, case let .didUpdate(info) = event { switch info { case let .beacons(beacons, region): displayBeaconRanging(beacons.first, altText: region.proximityUUID.uuidString, altColor: .gray) case let .error(error, region): displayBeaconRanging(nil, altText: region.proximityUUID.uuidString, altColor: .gray, altText2: error.localizedDescription, altColor2: .red) } } else { displayBeaconRanging(nil, altText: "Unknown", altColor: .gray) } } private func displayBeaconRanging(_ beacon: CLBeacon?, altText: String, altColor: UIColor, altText2: String = " ", altColor2: UIColor = .black) { if let beacon = beacon { beaconRangingAccuracyLabel.text = formatLocationAccuracy(beacon.accuracy) beaconRangingMajorMinorLabel.text = formatBeaconValues(beacon.major, beacon.minor) beaconRangingMajorMinorLabel.textColor = .black beaconRangingProximityLabel.text = formatProximity(beacon.proximity) beaconRangingProximityUUIDLabel.text = beacon.proximityUUID.uuidString beaconRangingProximityUUIDLabel.textColor = .black beaconRangingRSSILabel.text = formatRSSI(beacon.rssi) } else { beaconRangingAccuracyLabel.text = " " beaconRangingMajorMinorLabel.text = altText2 beaconRangingMajorMinorLabel.textColor = altColor2 beaconRangingProximityLabel.text = " " beaconRangingProximityUUIDLabel.text = altText beaconRangingProximityUUIDLabel.textColor = altColor beaconRangingRSSILabel.text = " " } } private func displayHeading(_ event: HeadingMonitor.Event?) { if !headingMonitor.isAvailable { displayHeading(nil, altText: "Not available", altColor: .red) } else if let event = event, case let .didUpdate(info) = event { switch info { case let .error(error): displayHeading(nil, altText: error.localizedDescription, altColor: .red) case let .heading(heading): displayHeading(heading, altText: "Unknown", altColor: .gray) } } else { displayHeading(nil, altText: "Unknown", altColor: .gray) } } private func displayHeading(_ heading: CLHeading?, altText: String, altColor: UIColor) { if let heading = heading { headingAccuracyLabel.text = formatLocationDirection(heading.headingAccuracy) headingGeomagnetismLabel.text = formatHeadingComponentValues(heading.x, heading.y, heading.z) headingMagneticHeadingLabel.text = formatLocationDirection(heading.magneticHeading) headingTimestampLabel.text = formatDate(heading.timestamp) headingTimestampLabel.textColor = .black headingTrueHeadingLabel.text = formatLocationDirection(heading.trueHeading) } else { headingAccuracyLabel.text = " " headingGeomagnetismLabel.text = " " headingMagneticHeadingLabel.text = " " headingTimestampLabel.text = altText headingTimestampLabel.textColor = altColor headingTrueHeadingLabel.text = " " } } private func displayLocationAuthorization(_ event: LocationAuthorizationMonitor.Event?) { if !locationAuthorizationMonitor.isEnabled { displayLocationAuthorization(nil, altText: "Not enabled", altColor: .red) } else if let event = event, case let .didUpdate(info) = event { switch info { case let .error(error): displayLocationAuthorization(nil, altText: error.localizedDescription, altColor: .red) case let .status(status): displayLocationAuthorization(status, altText: "Unknown", altColor: .gray) } } else { displayLocationAuthorization(nil, altText: "Unknown", altColor: .gray) } } private func displayLocationAuthorization(_ status: CLAuthorizationStatus?, altText: String, altColor: UIColor) { if let status = status { locationAuthorizationStatusLabel.text = formatAuthorizationStatus(status) locationAuthorizationStatusLabel.textColor = .black } else { locationAuthorizationStatusLabel.text = altText locationAuthorizationStatusLabel.textColor = altColor } } private func displayRegion(_ event: RegionMonitor.Event?) { if !regionMonitor.isAvailable { displayRegion(nil, altText: "Not available", altColor: .red) } else if let event = event, case let .didUpdate(info) = event { switch info { case let .error(error, region): displayRegion(nil, altText: region.identifier, altColor: .gray, altText2: error.localizedDescription, altColor2: .red) case let .regionState(state, region): displayRegion(region, state: state, altText: "Unknown", altColor: .gray) } } else { displayRegion(nil, altText: "Unknown", altColor: .gray) } } private func displayRegion(_ region: CLRegion?, state: CLRegionState = .unknown, altText: String, altColor: UIColor, altText2: String = " ", altColor2: UIColor = .black) { if let region = region { regionIdentifierLabel.text = region.identifier regionIdentifierLabel.textColor = .black regionStateLabel.text = formatRegionState(state) regionStateLabel.textColor = .black } else { regionIdentifierLabel.text = altText regionIdentifierLabel.textColor = altColor regionStateLabel.text = altText2 regionStateLabel.textColor = altColor2 } } private func displaySignificantLocation(_ event: SignificantLocationMonitor.Event?) { if !significantLocationMonitor.isAvailable { displaySignificantLocation(nil, altText: "Not available", altColor: .red) } else if let event = event, case let .didUpdate(info) = event { switch info { case let .error(error): displaySignificantLocation(nil, altText: error.localizedDescription, altColor: .red) case let .location(location): displaySignificantLocation(location, altText: "Unknown", altColor: .gray) } } else { displaySignificantLocation(nil, altText: "Unknown", altColor: .gray) } } private func displaySignificantLocation(_ location: CLLocation?, altText: String, altColor: UIColor) { if let location = location { significantLocationAltitudeLabel.text = formatLocationDistance(location.altitude) significantLocationCoordinateLabel.text = formatLocationCoordinate2D(location.coordinate) significantLocationCourseLabel.text = formatLocationDirection(location.course) significantLocationFloorLabel.text = formatFloor(location.floor) significantLocationHorizontalAccuracyLabel.text = formatLocationAccuracy(location.horizontalAccuracy) significantLocationSpeedLabel.text = formatLocationSpeed(location.speed) significantLocationTimestampLabel.text = formatDate(location.timestamp) significantLocationTimestampLabel.textColor = .black significantLocationVerticalAccuracyLabel.text = formatLocationAccuracy(location.verticalAccuracy) } else { significantLocationAltitudeLabel.text = " " significantLocationCoordinateLabel.text = " " significantLocationCourseLabel.text = " " significantLocationFloorLabel.text = " " significantLocationHorizontalAccuracyLabel.text = " " significantLocationSpeedLabel.text = " " significantLocationTimestampLabel.text = altText significantLocationTimestampLabel.textColor = altColor significantLocationVerticalAccuracyLabel.text = " " } } private func displayStandardLocation(_ event: StandardLocationMonitor.Event?) { if let event = event, case let .didUpdate(info) = event { switch info { case let .error(error): displayStandardLocation(nil, altText: error.localizedDescription, altColor: .red) case let .location(location): displayStandardLocation(location, altText: "Unknown", altColor: .gray) } } else { displayStandardLocation(nil, altText: "Unknown", altColor: .gray) } } private func displayStandardLocation(_ location: CLLocation?, altText: String, altColor: UIColor) { if let location = location { standardLocationAltitudeLabel.text = formatLocationDistance(location.altitude) standardLocationCoordinateLabel.text = "\(formatLocationCoordinate2D(location.coordinate))" standardLocationCourseLabel.text = formatLocationDirection(location.course) standardLocationFloorLabel.text = formatFloor(location.floor) standardLocationHorizontalAccuracyLabel.text = formatLocationAccuracy(location.horizontalAccuracy) standardLocationSpeedLabel.text = formatLocationSpeed(location.speed) standardLocationTimestampLabel.text = formatDate(location.timestamp) standardLocationTimestampLabel.textColor = .black standardLocationVerticalAccuracyLabel.text = formatLocationAccuracy(location.verticalAccuracy) } else { standardLocationAltitudeLabel.text = " " standardLocationCoordinateLabel.text = " " standardLocationCourseLabel.text = " " standardLocationFloorLabel.text = " " standardLocationHorizontalAccuracyLabel.text = " " standardLocationSpeedLabel.text = " " standardLocationTimestampLabel.text = altText standardLocationTimestampLabel.textColor = altColor standardLocationVerticalAccuracyLabel.text = " " } } private func displayVisit(_ event: VisitMonitor.Event?) { if let event = event, case let .didUpdate(info) = event { switch info { case let .error(error): displayVisit(nil, altText: error.localizedDescription, altColor: .red) case let .visit(visit): displayVisit(visit, altText: "Unknown", altColor: .gray) } } else { displayVisit(nil, altText: "Unknown", altColor: .gray) } } private func displayVisit(_ visit: CLVisit?, altText: String, altColor: UIColor) { if let visit = visit { visitArrivalDateLabel.text = formatDate(visit.arrivalDate) visitCoordinateLabel.text = "\(formatLocationCoordinate2D(visit.coordinate))" visitCoordinateLabel.textColor = .black visitDepartureDateLabel.text = formatDate(visit.departureDate) visitHorizontalAccuracyLabel.text = formatLocationAccuracy(visit.horizontalAccuracy) } else { visitArrivalDateLabel.text = " " visitCoordinateLabel.text = altText visitCoordinateLabel.textColor = altColor visitDepartureDateLabel.text = " " visitHorizontalAccuracyLabel.text = " " } } // MARK: Overridden UIViewController Methods override public func viewDidLoad() { super.viewDidLoad() displayBeaconRanging(nil) displayHeading(nil) displayLocationAuthorization(nil) displayRegion(nil) displaySignificantLocation(nil) displayStandardLocation(nil) displayVisit(nil) } override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) monitors.forEach { $0.startMonitoring() } locationAuthorizationMonitor.requestAlways() } override public func viewWillDisappear(_ animated: Bool) { monitors.forEach { $0.stopMonitoring() } super.viewWillDisappear(animated) } }
mit
d2cb762efa720cdca1f2c8daf9bba3ee
39.350806
114
0.565604
5.928318
false
false
false
false
Urinx/SublimeCode
Sublime/Pods/Swifter/Sources/String+SHA1.swift
3
5035
// // String+SHA1.swift // Swifter // // Copyright 2014-2016 Damian Kołakowski. All rights reserved. // #if os(Linux) import Glibc #else import Foundation #endif extension String { public func SHA1() -> String { return SHA1().reduce("") { $0 + String(format: "%02x", $1) } } public func SHA1() -> [UInt8] { // Alghorithm from: https://en.wikipedia.org/wiki/SHA-1 var message = [UInt8](self.utf8) var h0 = UInt32(littleEndian: 0x67452301) var h1 = UInt32(littleEndian: 0xEFCDAB89) var h2 = UInt32(littleEndian: 0x98BADCFE) var h3 = UInt32(littleEndian: 0x10325476) var h4 = UInt32(littleEndian: 0xC3D2E1F0) // ml = message length in bits (always a multiple of the number of bits in a character). let ml = UInt64(message.count * 8) // append the bit '1' to the message e.g. by adding 0x80 if message length is a multiple of 8 bits. message.append(0x80) // append 0 ≤ k < 512 bits '0', such that the resulting message length in bits is congruent to −64 ≡ 448 (mod 512) let padBytesCount = ( message.count + 8 ) % 64 message.appendContentsOf([UInt8](count: 64 - padBytesCount, repeatedValue: 0)) // append ml, in a 64-bit big-endian integer. Thus, the total length is a multiple of 512 bits. var mlBigEndian = ml.bigEndian let bytePtr = withUnsafePointer(&mlBigEndian) { UnsafeBufferPointer<UInt8>(start: UnsafePointer($0), count: sizeofValue(mlBigEndian)) } message.appendContentsOf(Array(bytePtr)) // Process the message in successive 512-bit chunks ( 64 bytes chunks ): for chunkStart in 0..<message.count/64 { var words = [UInt32]() let chunk = message[chunkStart*64..<chunkStart*64+64] // break chunk into sixteen 32-bit big-endian words w[i], 0 ≤ i ≤ 15 for i in 0...15 { let value = chunk.withUnsafeBufferPointer({ UnsafePointer<UInt32>($0.baseAddress + (i*4)).memory }) words.append(value.bigEndian) } // Extend the sixteen 32-bit words into eighty 32-bit words: for i in 16...79 { let value = words[i-3] ^ words[i-8] ^ words[i-14] ^ words[i-16] words.append(rotateLeft(value, 1)) } // Initialize hash value for this chunk: var a = h0 var b = h1 var c = h2 var d = h3 var e = h4 for i in 0..<80 { var f = UInt32(0) var k = UInt32(0) switch i { case 0...19: f = (b & c) | ((~b) & d) k = 0x5A827999 case 20...39: f = b ^ c ^ d k = 0x6ED9EBA1 case 40...59: f = (b & c) | (b & d) | (c & d) k = 0x8F1BBCDC case 60...79: f = b ^ c ^ d k = 0xCA62C1D6 default: break } let temp = (rotateLeft(a, 5) &+ f &+ e &+ k &+ words[i]) & 0xFFFFFFFF e = d d = c c = rotateLeft(b, 30) b = a a = temp } // Add this chunk's hash to result so far: h0 = ( h0 &+ a ) & 0xFFFFFFFF h1 = ( h1 &+ b ) & 0xFFFFFFFF h2 = ( h2 &+ c ) & 0xFFFFFFFF h3 = ( h3 &+ d ) & 0xFFFFFFFF h4 = ( h4 &+ e ) & 0xFFFFFFFF } // Produce the final hash value (big-endian) as a 160 bit number: var result = [UInt8]() let h0Big = h0.bigEndian let h1Big = h1.bigEndian let h2Big = h2.bigEndian let h3Big = h3.bigEndian let h4Big = h4.bigEndian result += ([UInt8(h0Big & 0xFF), UInt8((h0Big >> 8) & 0xFF), UInt8((h0Big >> 16) & 0xFF), UInt8((h0Big >> 24) & 0xFF)]); result += ([UInt8(h1Big & 0xFF), UInt8((h1Big >> 8) & 0xFF), UInt8((h1Big >> 16) & 0xFF), UInt8((h1Big >> 24) & 0xFF)]); result += ([UInt8(h2Big & 0xFF), UInt8((h2Big >> 8) & 0xFF), UInt8((h2Big >> 16) & 0xFF), UInt8((h2Big >> 24) & 0xFF)]); result += ([UInt8(h3Big & 0xFF), UInt8((h3Big >> 8) & 0xFF), UInt8((h3Big >> 16) & 0xFF), UInt8((h3Big >> 24) & 0xFF)]); result += ([UInt8(h4Big & 0xff), UInt8((h4Big >> 8) & 0xFF), UInt8((h4Big >> 16) & 0xFF), UInt8((h4Big >> 24) & 0xFF)]); return result; } func rotateLeft(v: UInt32, _ n: UInt32) -> UInt32 { return ((v << n) & 0xFFFFFFFF) | (v >> (32 - n)) } }
gpl-3.0
54f97830a7e1552e34f6453defb7cffb
35.143885
143
0.471736
3.752054
false
false
false
false
JovannyEspinal/Movies
Movies/Movies/ViewController.swift
1
4317
// // ViewController.swift // Movies // // Created by Jovanny Espinal on 5/27/16. // Copyright © 2016 Jovanny Espinal. All rights reserved. // import UIKit import ReactiveCocoa class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var textField: UITextField! @IBOutlet weak var tableView: UITableView! lazy var movieResult = [[String: AnyObject]]() override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self textField.rac_textSignal() .filter( { (input) -> Bool in let text = input as! String return text.characters.count >= 2 }) .throttle(0.5) .flattenMap({ (input) -> RACStream! in let text = input as! String return self.signalForQuery(text) }) .deliverOn(RACScheduler.mainThreadScheduler()) .subscribeNext({ (input) -> Void in let result = input as! [String:AnyObject] self.movieResult = result["results"] as! [[String:AnyObject]] self.tableView.reloadData() }, error: { (error) -> Void in let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .Alert) let alertAction = UIAlertAction(title: "Dismiss", style: .Cancel, handler: nil) alertController.addAction(alertAction) self.presentViewController(alertController, animated: true, completion: nil) }) self.rac_signalForSelector(#selector(UITableViewDelegate.tableView(_:didSelectRowAtIndexPath:)), fromProtocol: UITableViewDelegate.self) .subscribeNext { (input) -> Void in let arguments = input as! RACTuple let indexPath = arguments.second as! NSIndexPath let title = self.movieResult[indexPath.row]["original_title"] as! String print("You have chosen the move: \(title)") } tableView.delegate = self } func signalForQuery(query: String) -> RACSignal { let apiKey = "0759d9c7260fd564aeaa4194783cad28" let encodedQuery = query.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())! let url = NSURL(string: "https://api.themoviedb.org/3/search/movie?api_key=\(apiKey)&query=\(encodedQuery)")! return RACSignal.createSignal({ (subscriber) -> RACDisposable! in let session = NSURLSession.sharedSession() let task = session.dataTaskWithURL(url, completionHandler: { (data, urlResponse, error) -> Void in if let error = error { subscriber.sendError(error) } else { do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) subscriber.sendNext(json) } catch let raisedError as NSError { subscriber.sendError(raisedError) } } subscriber.sendCompleted() }) task.resume() return RACDisposable(block: { task.cancel() }) }) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return movieResult.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("cell") if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: "cell") } cell?.textLabel?.text = movieResult[indexPath.row]["original_title"] as? String return cell! } }
mit
fae94741a94fef80c5bcefca67e62cce
35.888889
144
0.543327
5.832432
false
false
false
false
superman-coder/pakr
pakr/pakr/UserInterface/PostParking/VerifyScreen/VerifyController.swift
1
3522
// // Created by Huynh Quang Thao on 4/11/16. // Copyright (c) 2016 Pakr. All rights reserved. // import Foundation import UIKit import MBProgressHUD class VerifyController: BaseViewController { @IBOutlet weak var uploadStatusTextView: UILabel! @IBOutlet weak var progressStatusTextView: UILabel! @IBOutlet weak var controlButton: UIButton! @IBOutlet weak var progressBar: UIProgressView! @IBOutlet weak var imageStatusView: UIImageView! var postParkingController : PostParkingController! override func viewDidLoad() { super.viewDidLoad() controlButton.layer.cornerRadius = 5 controlButton.layer.borderColor = UIColor.UIColorFromRGB(Constants.Color.PrimaryColor).CGColor controlButton.layer.borderWidth=2.0; controlButton.setTitleColor(UIColor.UIColorFromRGB(Constants.Color.PrimaryColor), forState: UIControlState.Normal) imageStatusView.layer.borderWidth = 3 imageStatusView.layer.borderColor = (UIColor(patternImage: UIImage(named: "dot")!)).CGColor progressStatusTextView.text = "0%" progressStatusTextView.hidden = true progressBar.progress = 0 uploadStatusTextView.text = "Upload your parking to the world" } @IBAction func postParkingEvent(sender: AnyObject) { //controlButton.enabled = false MBProgressHUD.showHUDAddedTo(self.view, animated: true) postParkingController.upLoadParking() } } extension VerifyController: UploadManagerDelegate { func startUpload(order: Int) { switch order { // start upload topic case -1: uploadStatusTextView.text = "Saving parking ..." break // start upload cover case 0: uploadStatusTextView.text = "Saving cover photos ..." imageStatusView.image = postParkingController.getImageByOrder(order) break // all sub images default: uploadStatusTextView.text = "Saving photos ...." imageStatusView.image = postParkingController.getImageByOrder(order) break } } func uploadProgress(order: Int, progress: Int, progressAll: Int) { if imageStatusView.image != nil { imageStatusView.alpha = CGFloat(progress / 100) print("debug: \(CGFloat(progress / 100))") } progressBar.progress = Float( progressAll / 100) progressStatusTextView.text = "\(progressAll) %" } func doneUploadTopic(topic: Topic) { MBProgressHUD.hideHUDForView(self.view, animated: true) uploadStatusTextView.text = "Finish :D :D :D" let alert = UIAlertController(title: "Upload Finish", message: "Your parking lot is ready", preferredStyle: .Alert) let okAction = UIAlertAction(title:"OK", style: .Default) { (action: UIAlertAction) in // move to detail screen let detailViewController = DetailParkingController(nibName: "DetailParkingController", bundle: nil) detailViewController.topic = topic var controllers = self.navigationController?.viewControllers controllers?.removeLast() controllers?.append(detailViewController) self.navigationController?.setViewControllers(controllers!, animated: true) } alert.addAction(okAction) presentViewController(alert, animated: true, completion: nil) } }
apache-2.0
bcc18a8b5b74749ca6267d0bc6db0ff6
35.697917
123
0.658433
5.202363
false
false
false
false
RoRoche/iOSSwiftStarter
iOSSwiftStarter/Pods/CoreStore/CoreStore/Internal/Functions.swift
2
2251
// // Functions.swift // CoreStore // // Copyright © 2014 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 Foundation internal func autoreleasepool<T>(@noescape closure: () -> T) -> T { var closureValue: T! ObjectiveC.autoreleasepool { closureValue = closure() } return closureValue } internal func autoreleasepool<T>(@noescape closure: () throws -> T) throws -> T { var closureValue: T! var closureError: ErrorType? ObjectiveC.autoreleasepool { do { closureValue = try closure() } catch { closureError = error } } if let closureError = closureError { throw closureError } return closureValue } internal func autoreleasepool(@noescape closure: () throws -> Void) throws { var closureError: ErrorType? ObjectiveC.autoreleasepool { do { try closure() } catch { closureError = error } } if let closureError = closureError { throw closureError } }
apache-2.0
f89d166ac99e867516e082e655923f24
26.777778
82
0.639111
4.817987
false
false
false
false
ZachOrr/TBAKit
Tests/TBATeamTests.swift
1
14422
import Foundation import XCTest import TBAKitTesting @testable import TBAKit class TBATeamTests: XCTestCase, TBAKitMockable { var kit: TBAKit! var session: MockURLSession! override func setUp() { super.setUp() setUpTBAKitMockable() } func test_team_init() { let team = TBATeam(key: "frc7332", teamNumber: 7332, name: "Rawrbotz", rookieYear: 2012) XCTAssertEqual(team.key, "frc7332") XCTAssertEqual(team.teamNumber, 7332) XCTAssertEqual(team.name, "Rawrbotz") XCTAssertEqual(team.rookieYear, 2012) } func test_robot_init() { let robot = TBARobot(key: "frc7332_2012", name: "DorkX", teamKey: "frc7332", year: 2012) XCTAssertEqual(robot.key, "frc7332_2012") XCTAssertEqual(robot.name, "DorkX") XCTAssertEqual(robot.teamKey, "frc7332") XCTAssertEqual(robot.year, 2012) } func test_eventStatus_init() { let eventStatus = TBAEventStatus(teamKey: "frc7332", eventKey: "2018miket") XCTAssertEqual(eventStatus.teamKey, "frc7332") XCTAssertEqual(eventStatus.eventKey, "2018miket") } func test_eventStatusQual_init() { let eventStatusQual = TBAEventStatusQual() XCTAssertNotNil(eventStatusQual) } func test_eventStatusAlliance_int() { let eventStatusAlliance = TBAEventStatusAlliance(number: 7332, pick: 1) XCTAssertEqual(eventStatusAlliance.number, 7332) XCTAssertEqual(eventStatusAlliance.pick, 1) } func test_media_init() { let media = TBAMedia(type: "avatar") XCTAssertEqual(media.type, "avatar") } func testTeamsPage() { let ex = expectation(description: "teams_page") let task = kit.fetchTeams(page: 0) { (teams, error) in XCTAssertNotNil(teams) XCTAssertGreaterThan(teams!.count, 0) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamsPageEmpty() { let ex = expectation(description: "teams_page_empty") let task = kit.fetchTeams(page: 100) { (teams, error) in XCTAssertNotNil(teams) XCTAssertEqual(teams!.count, 0) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamsYearPage() { let ex = expectation(description: "teams_year_page") let task = kit.fetchTeams(page: 0, year: 2017) { (teams, error) in XCTAssertNotNil(teams) XCTAssertGreaterThan(teams!.count, 0) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamsYearPageEmpty() { let ex = expectation(description: "teams_year_page_empty") let task = kit.fetchTeams(page: 100, year: 2017) { (teams, error) in XCTAssertNotNil(teams) XCTAssertEqual(teams!.count, 0) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeam() { let ex = expectation(description: "team") let task = kit.fetchTeam(key: "frc2337") { (team, error) in XCTAssertNotNil(team) XCTAssertNotNil(team?.key) XCTAssertNotNil(team?.name) XCTAssertNotNil(team?.teamNumber) XCTAssertNotNil(team?.rookieYear) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamEmpty() { let ex = expectation(description: "team_empty") let task = kit.fetchTeam(key: "frc13") { (team, error) in XCTAssertNil(team) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamAwards() { let ex = expectation(description: "team_awards") let task = kit.fetchTeamAwards(key: "frc2337") { (awards, error) in XCTAssertNotNil(awards) XCTAssertGreaterThan(awards!.count, 0) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamAwardsYear() { let ex = expectation(description: "team_awards_year") let task = kit.fetchTeamAwards(key: "frc2337", year: 2017) { (awards, error) in XCTAssertNotNil(awards) XCTAssertGreaterThan(awards!.count, 0) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamDistricts() { let ex = expectation(description: "team_districts") let task = kit.fetchTeamDistricts(key: "frc2337") { (districts, error) in XCTAssertNotNil(districts) XCTAssertGreaterThan(districts!.count, 0) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamEventsYear() { let ex = expectation(description: "team_events_year") let task = kit.fetchTeamEvents(key: "frc2337", year: 2017) { (events, error) in XCTAssertNotNil(events) XCTAssertGreaterThan(events!.count, 0) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamEventAwards() { let ex = expectation(description: "team_event_awards") let task = kit.fetchTeamAwards(key: "frc2337", eventKey: "2017mike2") { (awards, error) in XCTAssertNotNil(awards) XCTAssertGreaterThan(awards!.count, 0) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamEventMatches() { let ex = expectation(description: "team_event_matches") let task = kit.fetchTeamMatches(key: "frc2337", eventKey: "2017mike2") { (matches, error) in XCTAssertNotNil(matches) XCTAssertGreaterThan(matches!.count, 0) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamStatues() { let ex = expectation(description: "team_event_statuses") let task = kit.fetchTeamStatuses(key: "frc2337", year: 2018) { (statuses, error) in XCTAssertNotNil(statuses) XCTAssertGreaterThan(statuses!.count, 0) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamEventStatus() { let ex = expectation(description: "team_event_status") let task = kit.fetchTeamStatus(key: "frc2337", eventKey: "2017mike2") { (status, error) in XCTAssertNotNil(status) XCTAssertEqual(status?.teamKey, "frc2337") XCTAssertEqual(status?.eventKey, "2017mike2") XCTAssertNotNil(status?.qual) XCTAssertNotNil(status?.qual?.numTeams) XCTAssertNotNil(status?.qual?.status) XCTAssertNotNil(status?.qual?.ranking) XCTAssertNotNil(status?.qual?.sortOrder) XCTAssertGreaterThan(status!.qual!.sortOrder!.count, 0) XCTAssertNotNil(status?.alliance) XCTAssertNotNil(status?.alliance?.number) XCTAssertNotNil(status?.alliance?.pick) XCTAssertNotNil(status?.playoff) XCTAssertNotNil(status?.allianceStatusString) XCTAssertNotNil(status?.playoffStatusString) XCTAssertNotNil(status?.overallStatusString) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamEventStatusNoElims() { let ex = expectation(description: "team_event_status_no_elims") let task = kit.fetchTeamStatus(key: "frc2337", eventKey: "2016micmp") { (status, error) in XCTAssertNotNil(status) XCTAssertNotNil(status?.qual) XCTAssertNil(status?.alliance) XCTAssertNil(status?.playoff) XCTAssertNotNil(status?.allianceStatusString) XCTAssertNotNil(status?.playoffStatusString) XCTAssertNotNil(status?.overallStatusString) XCTAssertNotNil(status?.lastMatchKey) XCTAssertNil(status?.nextMatchKey) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamEventStatusEmpty() { let ex = expectation(description: "team_event_status_empty") let task = kit.fetchTeamStatus(key: "frc20", eventKey: "1992cmp") { (status, error) in XCTAssertNotNil(status) XCTAssertNil(status?.qual) XCTAssertNil(status?.alliance) XCTAssertNil(status?.playoff) XCTAssertNotNil(status?.allianceStatusString) XCTAssertNotNil(status?.playoffStatusString) XCTAssertNotNil(status?.overallStatusString) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamMatchesYear() { let ex = expectation(description: "team_matches_year") let task = kit.fetchTeamMatches(key: "frc2337", year: 2017) { (matches, error) in XCTAssertNotNil(matches) XCTAssertGreaterThan(matches!.count, 0) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamMediaYear() { let ex = expectation(description: "team_media_year") let task = kit.fetchTeamMedia(key: "frc2337", year: 2017) { (media, error) in XCTAssertNotNil(media) XCTAssertGreaterThan(media!.count, 0) let m = media!.first! XCTAssertNotNil(m.type) XCTAssertNotNil(m.foreignKey) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testTeamRobots() { let ex = expectation(description: "team_robots") let task = kit.fetchTeamRobots(key: "frc2337") { (robots, error) in XCTAssertNotNil(robots) XCTAssertGreaterThan(robots!.count, 0) let robot = robots!.first! XCTAssertNotNil(robot.key) XCTAssertNotNil(robot.name) XCTAssertNotNil(robot.teamKey) XCTAssertNotNil(robot.year) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testSocialMedia() { let ex = expectation(description: "team_social_media") let task = kit.fetchTeamSocialMedia(key: "frc2337") { (socialMedia, error) in XCTAssertNotNil(socialMedia) XCTAssertGreaterThan(socialMedia!.count, 0) let media = socialMedia!.first! XCTAssertNotNil(media.type) XCTAssertNotNil(media.foreignKey) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } func testYearsParticipated() { let ex = expectation(description: "team_years_participated") let task = kit.fetchTeamYearsParticipated(key: "frc2337") { (years, error) in XCTAssertNotNil(years) XCTAssertGreaterThan(years!.count, 0) XCTAssertNil(error) ex.fulfill() } sendSuccessStub(for: task) waitForExpectations(timeout: 2) { (error) in XCTAssertNil(error) } } }
mit
649edfed1b29bcaf4382705bd6589652
28.797521
100
0.546179
4.867364
false
true
false
false
sessionm/ios-smp-example
Auth/UserInfoViewController.swift
1
1815
// // UserInfoViewController.swift // SMPExample // // Copyright © 2018 SessionM. All rights reserved. // import SessionMIdentityKit import UIKit class UserInfoViewController: UIViewController { @IBOutlet var userInfo: UITextView! private let authProvider = SessionM.authenticationProvider() as? SessionMOAuthProvider private let userManager = SMUserManager.instance() override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let user = userManager.currentUser { let info = NSMutableAttributedString(string: "") let sortedUser = user.asDictionary().sorted(by: { ( kv1: (key: String, value: Any), kv2: (key: String, value: Any) ) -> Bool in return kv1.key < (kv2.key) }) for (key, value) in sortedUser { let keyValue = NSMutableAttributedString(string: "\(key): \(value)\n") keyValue.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.blue, range: NSMakeRange(0, key.count)) info.append(keyValue) } userInfo.attributedText = info } } @IBAction private func logout(_ sender: AnyObject) { let alert = UIAlertController(title: "Logging out...", message: nil, preferredStyle: .alert) present(alert, animated: true) { self.authProvider?.logOutUser { (state: SMAuthState, error: SMError?) in alert.dismiss(animated: true) { if let error = error { Util.failed(self, message: error.message) } else if state == .loggedOut { self.navigationController?.popViewController(animated: true) } } } } } }
mit
66e41e369db06f1726e0dd46b90caef1
36.791667
139
0.597574
4.902703
false
false
false
false
ashfurrow/eidolon
KioskTests/App/SwiftExtensionsTests.swift
2
3718
import Quick import Nimble import RxSwift import RxOptional @testable import Kiosk let Empty = "empty" let NonEmpty = "nonEmpty" // Workaround due to limitations in the compiler. See: https://twitter.com/jckarter/status/636969467713458176 class AnyOccupiable: NSObject, Occupiable { let value: Occupiable init(value: Occupiable) { self.value = value super.init() } var isEmpty: Bool { return value.isEmpty } var isNotEmpty: Bool { return value.isNotEmpty } } class SwiftExtensionsConfiguration: QuickConfiguration { override class func configure(_ configuration: Configuration) { sharedExamples("an Occupiable") { (sharedExampleContext: @escaping SharedExampleContext) in var empty: AnyOccupiable? var nonEmpty: AnyOccupiable? beforeEach { let context = sharedExampleContext() empty = context[Empty] as? AnyOccupiable nonEmpty = context[NonEmpty] as? AnyOccupiable } it("returns isNilOrEmpty as true when nil") { let subject: AnyOccupiable? = nil expect(subject.isNilOrEmpty).to( beTrue() ) } it("returns isNilOrEmpty as true when empty") { let subject = empty expect(subject.isNilOrEmpty).to( beTrue() ) } it("returns isNilOrEmpty as false when not empty") { let subject = nonEmpty expect(subject.isNilOrEmpty).to( beFalse() ) } it("returns isNotNilNotEmpty as false when nil") { let subject: AnyOccupiable? = nil expect(subject.isNotNilNotEmpty).to( beFalse() ) } it("returns isNotNilNotEmpty as false when empty") { let subject = empty expect(subject.isNotNilNotEmpty).to( beFalse() ) } it("returns isNotNilNotEmpty as true when not empty") { let subject = nonEmpty expect(subject.isNotNilNotEmpty).to( beTrue() ) } describe("unwrapped") { it("returns isNotEmpty as true when not not empty") { let subject = nonEmpty! expect(subject.isNotEmpty).to( beTrue() ) } it("returns isNotEmpty as false when empty") { let subject = empty! expect(subject.isNotEmpty).to( beFalse() ) } } } } } class SwiftExtensionsTests: QuickSpec { override func spec() { describe("String") { it("converts to UInt") { let input = "4" expect(input.toUInt()) == 4 } it("returns nil if no conversion is available") { let input = "not a number" expect(input.toUInt()).to( beNil() ) } it("uses a default if no conversion is available") { let input = "not a number" expect(input.toUInt(withDefault: 4)) == 4 } } describe("String") { itBehavesLike("an Occupiable") { [ Empty: AnyOccupiable(value: ""), NonEmpty: AnyOccupiable(value: "hi") ] } } describe("Array") { itBehavesLike("an Occupiable") { [ Empty: AnyOccupiable(value: Array<String>()), NonEmpty: AnyOccupiable(value: ["hi"]) ] } } describe("Dictionary") { itBehavesLike("an Occupiable") { [ Empty: AnyOccupiable(value: Dictionary<String, String>()), NonEmpty: AnyOccupiable(value: ["hi": "yo"]) ] } } } }
mit
48aae4fdbdc801cba231f13421f2937d
30.243697
154
0.544648
4.950732
false
false
false
false
huonw/swift
test/IRGen/class_resilience.swift
1
27248
// RUN: %empty-directory(%t) // RUN: %{python} %utils/chex.py < %s > %t/class_resilience.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift // RUN: %target-swift-frontend -emit-module -enable-resilience -enable-class-resilience -emit-module-path=%t/resilient_class.swiftmodule -module-name=resilient_class -I %t %S/../Inputs/resilient_class.swift // RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -enable-class-resilience %t/class_resilience.swift | %FileCheck %t/class_resilience.swift --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize -DINT=i%target-ptrsize // RUN: %target-swift-frontend -I %t -emit-ir -enable-resilience -enable-class-resilience -O %t/class_resilience.swift // CHECK: @"$S16class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvpWvd" = hidden global [[INT]] 0 // CHECK: @"$S16class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd" = hidden global [[INT]] 0 // CHECK: @"$S16class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvpWvd" = hidden global [[INT]] 0 // CHECK: @"$S16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd" = hidden global [[INT]] 0 // CHECK: @"$S16class_resilience14ResilientChildC5fields5Int32VvpWvd" = hidden global [[INT]] {{8|16}} // CHECK: @"$S16class_resilience21ResilientGenericChildCMo" = {{(protected )?}}{{(dllexport )?}}global [[BOUNDS:{ (i32|i64), i32, i32 }]] zeroinitializer // CHECK: @"$S16class_resilience26ClassWithResilientPropertyCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]] // CHECK-SAME-32: { [[INT]] 52, i32 2, i32 13 } // CHECK-SAME-64: { [[INT]] 80, i32 2, i32 10 } // CHECK: @"$S16class_resilience28ClassWithMyResilientPropertyC1rAA0eF6StructVvpWvd" = hidden constant [[INT]] {{8|16}} // CHECK: @"$S16class_resilience28ClassWithMyResilientPropertyC5colors5Int32VvpWvd" = hidden constant [[INT]] {{12|20}} // CHECK: @"$S16class_resilience30ClassWithIndirectResilientEnumC1s14resilient_enum10FunnyShapeOvpWvd" = hidden constant [[INT]] {{8|16}} // CHECK: @"$S16class_resilience30ClassWithIndirectResilientEnumC5colors5Int32VvpWvd" = hidden constant [[INT]] {{12|24}} // CHECK: [[RESILIENTCHILD_NAME:@.*]] = private constant [15 x i8] c"ResilientChild\00" // CHECK: @"$S16class_resilience14ResilientChildCMo" = {{(protected )?}}{{(dllexport )?}}global [[BOUNDS]] zeroinitializer // CHECK: @"$S16class_resilience14ResilientChildCMn" = {{(protected )?}}{{(dllexport )?}}constant <{{.*}}> <{ // -- flags: class, unique, reflectable, has vtable, has resilient superclass // CHECK-SAME: <i32 0xD004_0050> // -- name: // CHECK-SAME: [15 x i8]* [[RESILIENTCHILD_NAME]] // -- num fields // CHECK-SAME: i32 1, // -- field offset vector offset // CHECK-SAME: i32 3, // CHECK-SAME: }> // CHECK: @"$S16class_resilience16FixedLayoutChildCMo" = {{(protected )?}}{{(dllexport )?}}global [[BOUNDS]] zeroinitializer // CHECK: @"$S16class_resilience17MyResilientParentCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]] // CHECK-SAME-32: { [[INT]] 52, i32 2, i32 13 } // CHECK-SAME-64: { [[INT]] 80, i32 2, i32 10 } // CHECK: @"$S16class_resilience16MyResilientChildCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]] // CHECK-SAME-32: { [[INT]] 60, i32 2, i32 15 } // CHECK-SAME-64: { [[INT]] 96, i32 2, i32 12 } // CHECK: @"$S16class_resilience24MyResilientGenericParentCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]] // CHECK-SAME-32: { [[INT]] 52, i32 2, i32 13 } // CHECK-SAME-64: { [[INT]] 80, i32 2, i32 10 } // CHECK: @"$S16class_resilience24MyResilientConcreteChildCMo" = {{(protected )?}}{{(dllexport )?}}constant [[BOUNDS]] // CHECK-SAME-32: { [[INT]] 64, i32 2, i32 16 } // CHECK-SAME-64: { [[INT]] 104, i32 2, i32 13 } import resilient_class import resilient_struct import resilient_enum // Concrete class with resilient stored property public class ClassWithResilientProperty { public let p: Point public let s: Size public let color: Int32 public init(p: Point, s: Size, color: Int32) { self.p = p self.s = s self.color = color } } // Concrete class with non-fixed size stored property public class ClassWithResilientlySizedProperty { public let r: Rectangle public let color: Int32 public init(r: Rectangle, color: Int32) { self.r = r self.color = color } } // Concrete class with resilient stored property that // is fixed-layout inside this resilience domain public struct MyResilientStruct { public let x: Int32 } public class ClassWithMyResilientProperty { public let r: MyResilientStruct public let color: Int32 public init(r: MyResilientStruct, color: Int32) { self.r = r self.color = color } } // Enums with indirect payloads are fixed-size public class ClassWithIndirectResilientEnum { public let s: FunnyShape public let color: Int32 public init(s: FunnyShape, color: Int32) { self.s = s self.color = color } } // Superclass is resilient, so the number of fields and their // offsets is not known at compile time public class ResilientChild : ResilientOutsideParent { public var field: Int32 = 0 public override func getValue() -> Int { return 1 } } // Superclass is resilient, but the class is fixed-layout. // This simulates a user app subclassing a class in a resilient // framework. In this case, we still want to emit a base offset // global. @_fixed_layout public class FixedLayoutChild : ResilientOutsideParent { public var field: Int32 = 0 } // Superclass is resilient, so the number of fields and their // offsets is not known at compile time public class ResilientGenericChild<T> : ResilientGenericOutsideParent<T> { public var field: Int32 = 0 } // Superclass is resilient and has a resilient value type payload, // but everything is in one module public class MyResilientParent { public let s: MyResilientStruct = MyResilientStruct(x: 0) } public class MyResilientChild : MyResilientParent { public let field: Int32 = 0 } public class MyResilientGenericParent<T> { public let t: T public init(t: T) { self.t = t } } public class MyResilientConcreteChild : MyResilientGenericParent<Int> { public let x: Int public init(x: Int) { self.x = x super.init(t: x) } } extension ResilientGenericOutsideParent { public func genericExtensionMethod() -> A.Type { return A.self } } // ClassWithResilientProperty.color getter // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$S16class_resilience26ClassWithResilientPropertyC5colors5Int32Vvg"(%T16class_resilience26ClassWithResilientPropertyC* swiftself) // CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$S16class_resilience26ClassWithResilientPropertyC5colors5Int32VvpWvd" // CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience26ClassWithResilientPropertyC* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V* // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]] // CHECK: ret i32 [[FIELD_VALUE]] // ClassWithResilientProperty metadata accessor // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$S16class_resilience26ClassWithResilientPropertyCMa"( // CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** @"$S16class_resilience26ClassWithResilientPropertyCML" // CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null // CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: call void @swift_once([[INT]]* @"$S16class_resilience26ClassWithResilientPropertyCMa.once_token", i8* bitcast (void (i8*)* @initialize_metadata_ClassWithResilientProperty to i8*), i8* undef) // CHECK-NEXT: [[METADATA:%.*]] = load %swift.type*, %swift.type** @"$S16class_resilience26ClassWithResilientPropertyCML" // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ] // CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[RESULT]], 0 // CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] 0, 1 // CHECK-NEXT: ret %swift.metadata_response [[T1]] // ClassWithResilientlySizedProperty.color getter // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$S16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32Vvg"(%T16class_resilience33ClassWithResilientlySizedPropertyC* swiftself) // CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$S16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvpWvd" // CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience33ClassWithResilientlySizedPropertyC* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V* // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]] // CHECK: ret i32 [[FIELD_VALUE]] // ClassWithResilientlySizedProperty metadata accessor // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$S16class_resilience33ClassWithResilientlySizedPropertyCMa"( // CHECK: [[CACHE:%.*]] = load %swift.type*, %swift.type** @"$S16class_resilience33ClassWithResilientlySizedPropertyCML" // CHECK-NEXT: [[COND:%.*]] = icmp eq %swift.type* [[CACHE]], null // CHECK-NEXT: br i1 [[COND]], label %cacheIsNull, label %cont // CHECK: cacheIsNull: // CHECK-NEXT: call void @swift_once([[INT]]* @"$S16class_resilience33ClassWithResilientlySizedPropertyCMa.once_token", i8* bitcast (void (i8*)* @initialize_metadata_ClassWithResilientlySizedProperty to i8*), i8* undef) // CHECK-NEXT: [[METADATA:%.*]] = load %swift.type*, %swift.type** @"$S16class_resilience33ClassWithResilientlySizedPropertyCML" // CHECK-NEXT: br label %cont // CHECK: cont: // CHECK-NEXT: [[RESULT:%.*]] = phi %swift.type* [ [[CACHE]], %entry ], [ [[METADATA]], %cacheIsNull ] // CHECK-NEXT: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[RESULT]], 0 // CHECK-NEXT: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] 0, 1 // CHECK-NEXT: ret %swift.metadata_response [[T1]] // ClassWithIndirectResilientEnum.color getter // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$S16class_resilience30ClassWithIndirectResilientEnumC5colors5Int32Vvg"(%T16class_resilience30ClassWithIndirectResilientEnumC* swiftself) // CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T16class_resilience30ClassWithIndirectResilientEnumC, %T16class_resilience30ClassWithIndirectResilientEnumC* %0, i32 0, i32 2 // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]] // CHECK: ret i32 [[FIELD_VALUE]] // ResilientChild.field getter // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$S16class_resilience14ResilientChildC5fields5Int32Vvg"(%T16class_resilience14ResilientChildC* swiftself) // CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$S16class_resilience14ResilientChildC5fields5Int32VvpWvd" // CHECK-NEXT: [[PTR:%.*]] = bitcast %T16class_resilience14ResilientChildC* %0 to i8* // CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[PTR]], [[INT]] [[OFFSET]] // CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %Ts5Int32V* // CHECK: call void @swift_beginAccess // CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_PTR]], i32 0, i32 0 // CHECK-NEXT: [[FIELD_VALUE:%.*]] = load i32, i32* [[FIELD_PAYLOAD]] // CHECK-NEXT: call void @swift_endAccess // CHECK: ret i32 [[FIELD_VALUE]] // ResilientGenericChild.field getter // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$S16class_resilience21ResilientGenericChildC5fields5Int32Vvg"(%T16class_resilience21ResilientGenericChildC* swiftself) // FIXME: we could eliminate the unnecessary isa load by lazily emitting // metadata sources in EmitPolymorphicParameters // CHECK: load %swift.type* // CHECK: [[ADDR:%.*]] = getelementptr inbounds %T16class_resilience21ResilientGenericChildC, %T16class_resilience21ResilientGenericChildC* %0, i32 0, i32 0, i32 0 // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ADDR]] // CHECK-NEXT: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S16class_resilience21ResilientGenericChildCMo", i32 0, i32 0) // CHECK-NEXT: [[METADATA_OFFSET:%.*]] = add [[INT]] [[BASE]], {{16|32}} // CHECK-NEXT: [[ISA_ADDR:%.*]] = bitcast %swift.type* [[ISA]] to i8* // CHECK-NEXT: [[FIELD_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_ADDR]], [[INT]] [[METADATA_OFFSET]] // CHECK-NEXT: [[FIELD_OFFSET_ADDR:%.*]] = bitcast i8* [[FIELD_OFFSET_TMP]] to [[INT]]* // CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_ADDR:%.*]] // CHECK-NEXT: [[OBJECT:%.*]] = bitcast %T16class_resilience21ResilientGenericChildC* %0 to i8* // CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[FIELD_OFFSET]] // CHECK-NEXT: [[FIELD_ADDR:%.*]] = bitcast i8* [[ADDR]] to %Ts5Int32V* // CHECK: call void @swift_beginAccess // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0 // CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]] // CHECK-NEXT: call void @swift_endAccess // CHECK: ret i32 [[RESULT]] // MyResilientChild.field getter // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$S16class_resilience16MyResilientChildC5fields5Int32Vvg"(%T16class_resilience16MyResilientChildC* swiftself) // CHECK: [[FIELD_ADDR:%.*]] = getelementptr inbounds %T16class_resilience16MyResilientChildC, %T16class_resilience16MyResilientChildC* %0, i32 0, i32 2 // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0 // CHECK-NEXT: [[RESULT:%.*]] = load i32, i32* [[PAYLOAD_ADDR]] // CHECK: ret i32 [[RESULT]] // ResilientGenericOutsideParent.genericExtensionMethod() // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.type* @"$S15resilient_class29ResilientGenericOutsideParentC0B11_resilienceE22genericExtensionMethodxmyF"(%T15resilient_class29ResilientGenericOutsideParentC* swiftself) #0 { // CHECK: [[ISA_ADDR:%.*]] = bitcast %T15resilient_class29ResilientGenericOutsideParentC* %0 to %swift.type** // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]] // CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S15resilient_class29ResilientGenericOutsideParentCMo", i32 0, i32 0) // CHECK-NEXT: [[GENERIC_PARAM_OFFSET:%.*]] = add [[INT]] [[BASE]], 0 // CHECK-NEXT: [[ISA_TMP:%.*]] = bitcast %swift.type* [[ISA]] to i8* // CHECK-NEXT: [[GENERIC_PARAM_TMP:%.*]] = getelementptr inbounds i8, i8* [[ISA_TMP]], [[INT]] [[GENERIC_PARAM_OFFSET]] // CHECK-NEXT: [[GENERIC_PARAM_ADDR:%.*]] = bitcast i8* [[GENERIC_PARAM_TMP]] to %swift.type** // CHECK-NEXT: [[GENERIC_PARAM:%.*]] = load %swift.type*, %swift.type** [[GENERIC_PARAM_ADDR]] // CHECK: ret %swift.type* [[GENERIC_PARAM]] // ClassWithResilientProperty metadata initialization function // CHECK-LABEL: define private void @initialize_metadata_ClassWithResilientProperty // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata({{.*}}, [[INT]] {{60|96}}, [[INT]] 4) // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S16resilient_struct4SizeVMa"([[INT]] 63) // CHECK-NEXT: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: call void @swift_initClassMetadata(%swift.type* [[METADATA]], [[INT]] 0, [[INT]] 3, {{.*}}) // CHECK-native: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]* // CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{12|15}} // CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]] // CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$S16class_resilience26ClassWithResilientPropertyC1s16resilient_struct4SizeVvWvd" // CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{13|16}} // CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]] // CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$S16class_resilience26ClassWithResilientPropertyC5colors5Int32VvWvd" // CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @"$S16class_resilience26ClassWithResilientPropertyCML" release, // CHECK: ret void // ClassWithResilientlySizedProperty metadata initialization function // CHECK-LABEL: define private void @initialize_metadata_ClassWithResilientlySizedProperty // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata({{.*}}, [[INT]] {{60|96}}, [[INT]] 3) // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S16resilient_struct9RectangleVMa"([[INT]] 63) // CHECK-NEXT: [[RECTANGLE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: call void @swift_initClassMetadata(%swift.type* [[METADATA]], [[INT]] 0, [[INT]] 2, {{.*}}) // CHECK-native: [[METADATA_PTR:%.*]] = bitcast %swift.type* [[METADATA]] to [[INT]]* // CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{11|14}} // CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]] // CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$S16class_resilience33ClassWithResilientlySizedPropertyC1r16resilient_struct9RectangleVvWvd" // CHECK-native-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[METADATA_PTR]], [[INT]] {{12|15}} // CHECK-native-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_PTR]] // CHECK-native-NEXT: store [[INT]] [[FIELD_OFFSET]], [[INT]]* @"$S16class_resilience33ClassWithResilientlySizedPropertyC5colors5Int32VvWvd" // CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @"$S16class_resilience33ClassWithResilientlySizedPropertyCML" release, // CHECK: ret void // ResilientChild metadata initialization function // CHECK-LABEL: define private void @initialize_metadata_ResilientChild(i8*) // Initialize the superclass field... // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S15resilient_class22ResilientOutsideParentCMa"([[INT]] 1) // CHECK: [[SUPER:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: store %swift.type* [[SUPER]], %swift.type** getelementptr inbounds ({{.*}}) // Relocate metadata if necessary... // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_relocateClassMetadata(%swift.type* {{.*}}, [[INT]] {{60|96}}, [[INT]] 4) // Initialize field offset vector... // CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S16class_resilience14ResilientChildCMo", i32 0, i32 0) // CHECK: [[OFFSET:%.*]] = add [[INT]] [[BASE]], {{12|24}} // CHECK: call void @swift_initClassMetadata(%swift.type* [[METADATA]], [[INT]] 0, [[INT]] 1, i8*** {{.*}}, [[INT]]* {{.*}}) // Initialize constructor vtable override... // CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S15resilient_class22ResilientOutsideParentCMo", i32 0, i32 0) // CHECK: [[OFFSET:%.*]] = add [[INT]] [[BASE]], {{16|32}} // CHECK: [[METADATA_BYTES:%.*]] = bitcast %swift.type* [[METADATA]] to i8* // CHECK: [[VTABLE_ENTRY_ADDR:%.*]] = getelementptr inbounds i8, i8* [[METADATA_BYTES]], [[INT]] [[OFFSET]] // CHECK: [[VTABLE_ENTRY_TMP:%.*]] = bitcast i8* [[VTABLE_ENTRY_ADDR]] to i8** // CHECK: store i8* bitcast (%T16class_resilience14ResilientChildC* (%T16class_resilience14ResilientChildC*)* @"$S16class_resilience14ResilientChildCACycfc" to i8*), i8** [[VTABLE_ENTRY_TMP]] // Initialize getValue() vtable override... // CHECK: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S15resilient_class22ResilientOutsideParentCMo", i32 0, i32 0) // CHECK: [[OFFSET:%.*]] = add [[INT]] [[BASE]], {{28|56}} // CHECK: [[METADATA_BYTES:%.*]] = bitcast %swift.type* [[METADATA]] to i8* // CHECK: [[VTABLE_ENTRY_ADDR:%.*]] = getelementptr inbounds i8, i8* [[METADATA_BYTES]], [[INT]] [[OFFSET]] // CHECK: [[VTABLE_ENTRY_TMP:%.*]] = bitcast i8* [[VTABLE_ENTRY_ADDR]] to i8** // CHECK: store i8* bitcast ([[INT]] (%T16class_resilience14ResilientChildC*)* @"$S16class_resilience14ResilientChildC8getValueSiyF" to i8*), i8** [[VTABLE_ENTRY_TMP]] // Store the completed metadata in the cache variable... // CHECK: store atomic %swift.type* [[METADATA]], %swift.type** @"$S16class_resilience14ResilientChildCML" release // CHECK: ret void // ResilientChild.field getter dispatch thunk // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc i32 @"$S16class_resilience14ResilientChildC5fields5Int32VvgTj"(%T16class_resilience14ResilientChildC* swiftself) // CHECK: [[ISA_ADDR:%.*]] = getelementptr inbounds %T16class_resilience14ResilientChildC, %T16class_resilience14ResilientChildC* %0, i32 0, i32 0, i32 0 // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]] // CHECK-NEXT: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S16class_resilience14ResilientChildCMo", i32 0, i32 0) // CHECK-NEXT: [[METADATA_BYTES:%.*]] = bitcast %swift.type* [[ISA]] to i8* // CHECK-NEXT: [[VTABLE_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[METADATA_BYTES]], [[INT]] [[BASE]] // CHECK-NEXT: [[VTABLE_OFFSET_ADDR:%.*]] = bitcast i8* [[VTABLE_OFFSET_TMP]] to i32 (%T16class_resilience14ResilientChildC*)** // CHECK-NEXT: [[METHOD:%.*]] = load i32 (%T16class_resilience14ResilientChildC*)*, i32 (%T16class_resilience14ResilientChildC*)** [[VTABLE_OFFSET_ADDR]] // CHECK-NEXT: [[RESULT:%.*]] = call swiftcc i32 [[METHOD]](%T16class_resilience14ResilientChildC* swiftself %0) // CHECK-NEXT: ret i32 [[RESULT]] // ResilientChild.field setter dispatch thunk // CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$S16class_resilience14ResilientChildC5fields5Int32VvsTj"(i32, %T16class_resilience14ResilientChildC* swiftself) // CHECK: [[ISA_ADDR:%.*]] = getelementptr inbounds %T16class_resilience14ResilientChildC, %T16class_resilience14ResilientChildC* %1, i32 0, i32 0, i32 0 // CHECK-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ISA_ADDR]] // CHECK-NEXT: [[BASE:%.*]] = load [[INT]], [[INT]]* getelementptr inbounds ([[BOUNDS]], [[BOUNDS]]* @"$S16class_resilience14ResilientChildCMo", i32 0, i32 0) // CHECK-NEXT: [[METADATA_OFFSET:%.*]] = add [[INT]] [[BASE]], {{4|8}} // CHECK-NEXT: [[METADATA_BYTES:%.*]] = bitcast %swift.type* [[ISA]] to i8* // CHECK-NEXT: [[VTABLE_OFFSET_TMP:%.*]] = getelementptr inbounds i8, i8* [[METADATA_BYTES]], [[INT]] [[METADATA_OFFSET]] // CHECK-NEXT: [[VTABLE_OFFSET_ADDR:%.*]] = bitcast i8* [[VTABLE_OFFSET_TMP]] to void (i32, %T16class_resilience14ResilientChildC*)** // CHECK-NEXT: [[METHOD:%.*]] = load void (i32, %T16class_resilience14ResilientChildC*)*, void (i32, %T16class_resilience14ResilientChildC*)** [[VTABLE_OFFSET_ADDR]] // CHECK-NEXT: call swiftcc void [[METHOD]](i32 %0, %T16class_resilience14ResilientChildC* swiftself %1) // CHECK-NEXT: ret void // FixedLayoutChild metadata initialization function // CHECK-LABEL: define private void @initialize_metadata_FixedLayoutChild(i8*) // Initialize the superclass field... // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S15resilient_class22ResilientOutsideParentCMa"([[INT]] 1) // CHECK: [[SUPER:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: store %swift.type* [[SUPER]], %swift.type** getelementptr inbounds ({{.*}}) // Relocate metadata if necessary... // CHECK: call %swift.type* @swift_relocateClassMetadata(%swift.type* {{.*}}, [[INT]] {{60|96}}, [[INT]] 4) // CHECK: ret void // ResilientGenericChild metadata initialization function // CHECK-LABEL: define internal %swift.type* @"$S16class_resilience21ResilientGenericChildCMi"(%swift.type_descriptor*, i8**, i8**) // CHECK: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_descriptor* %0, i8** %1, i8** %2) // CHECK: ret %swift.type* [[METADATA]] // CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$S16class_resilience21ResilientGenericChildCMr" // CHECK-SAME: (%swift.type* [[METADATA:%.*]], i8*, i8**) // Initialize the superclass pointer... // CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$S15resilient_class29ResilientGenericOutsideParentCMa"([[INT]] 257, %swift.type* %T) // CHECK: [[SUPER:%.*]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: [[SUPER_STATUS:%.*]] = extractvalue %swift.metadata_response [[T0]], 1 // CHECK: [[SUPER_OK:%.*]] = icmp ule [[INT]] [[SUPER_STATUS]], 1 // CHECK: br i1 [[SUPER_OK]], // CHECK: [[T0:%.*]] = bitcast %swift.type* [[METADATA]] to %swift.type** // CHECK: [[SUPER_ADDR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[T0]], i32 1 // CHECK: store %swift.type* [[SUPER]], %swift.type** [[SUPER_ADDR]], // CHECK: call void @swift_initClassMetadata(%swift.type* [[METADATA]], [[INT]] 0, // CHECK: [[DEP:%.*]] = phi %swift.type* [ [[SUPER]], {{.*}} ], [ null, {{.*}} ] // CHECK: [[DEP_REQ:%.*]] = phi [[INT]] [ 1, {{.*}} ], [ 0, {{.*}} ] // CHECK: [[T0:%.*]] = insertvalue %swift.metadata_response undef, %swift.type* [[DEP]], 0 // CHECK: [[T1:%.*]] = insertvalue %swift.metadata_response [[T0]], [[INT]] [[DEP_REQ]], 1 // CHECK: ret %swift.metadata_response [[T1]]
apache-2.0
c21b6beed92647e1364558c94d307bc2
57.850972
245
0.666838
3.731069
false
false
false
false
vector-im/riot-ios
Riot/Managers/Widgets/WidgetManagerConfig.swift
2
3583
/* Copyright 2019 New Vector Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation /// Configuration for an integration manager. /// By default, it uses URLs defined in the app settings but they can be overidden. @objcMembers class WidgetManagerConfig: NSObject, NSCoding { /// The URL for the REST api let apiUrl: NSString? /// The URL of the integration manager interface let uiUrl: NSString? /// The token if the user has been authenticated var scalarToken: NSString? var hasUrls: Bool { if apiUrl != nil && uiUrl != nil { return true } else { return false } } var baseUrl: NSString? { // Same comment as https://github.com/matrix-org/matrix-react-sdk/blob/1b0d8510a2ee93beddcd34c2d5770aa9fc76b1d9/src/ScalarAuthClient.js#L108 // The terms endpoints are new and so live on standard _matrix prefixes, // but IM rest urls are currently configured with paths, so remove the // path from the base URL before passing it to the js-sdk // We continue to use the full URL for the calls done by // Riot-iOS, but the standard terms API called // by the matrix-ios-sdk lives on the standard _matrix path. This means we // don't support running IMs on a non-root path, but it's the only // realistic way of transitioning to _matrix paths since configs in // the wild contain bits of the API path. // Once we've fully transitioned to _matrix URLs, we can give people // a grace period to update their configs, then use the rest url as // a regular base url. guard let apiUrl = self.apiUrl as String?, let imApiUrl = URL(string: apiUrl) else { return nil } guard var baseUrl = URL(string: "/", relativeTo: imApiUrl)?.absoluteString else { return nil } if baseUrl.hasSuffix("/") { // SDK doest not like trailing / baseUrl = String(baseUrl.dropLast()) } return baseUrl as NSString } init(apiUrl: NSString?, uiUrl: NSString?) { self.apiUrl = apiUrl self.uiUrl = uiUrl super.init() } /// MARK: - NSCoding enum CodingKeys: String { case apiUrl = "apiUrl" case uiUrl = "uiUrl" case scalarToken = "scalarToken" } func encode(with aCoder: NSCoder) { aCoder.encode(self.apiUrl, forKey: CodingKeys.apiUrl.rawValue) aCoder.encode(self.uiUrl, forKey: CodingKeys.uiUrl.rawValue) aCoder.encode(self.scalarToken, forKey: CodingKeys.scalarToken.rawValue) } convenience required init?(coder aDecoder: NSCoder) { let apiUrl = aDecoder.decodeObject(forKey: CodingKeys.apiUrl.rawValue) as? NSString let uiUrl = aDecoder.decodeObject(forKey: CodingKeys.uiUrl.rawValue) as? NSString let scalarToken = aDecoder.decodeObject(forKey: CodingKeys.scalarToken.rawValue) as? NSString self.init(apiUrl: apiUrl, uiUrl: uiUrl) self.scalarToken = scalarToken } }
apache-2.0
34c5ddd2856b823f9ccc5002cc9e46fb
34.83
148
0.665085
4.34303
false
false
false
false
julongdragon/myweb
Sources/App/Models/Human.swift
1
1139
import Fluent import PostgreSQLProvider import FluentProvider final class Human : Model { var storage = Storage() var item : String var price : String init(item:String,price:String){ self.item = item self.price = price } init(row: Row) throws { self.item = try row.get("item") self.price = try row.get("price") } } extension Human : Preparation { static func prepare(_ database: Database) throws { try database.create(self, closure: { (product) in product.id() product.string("item") product.string("price") }) } static func revert(_ database: Database) throws { try database.delete(self) } } /* extension Human : JSONRepresentable { func makeJSON() throws -> JSON { var json = JSON() try json.set("id", id?.string) try json.set("item", item) try json.set("price",price) return json } } */ extension Human : RowRepresentable { func makeRow() throws -> Row { var row = Row() try row.set("item", item) try row.set("price", price) return row } }
mit
2866d8819be0830c44d4b23bbd9af9a6
21.333333
57
0.589113
3.982517
false
false
false
false
norio-nomura/RxSwift
RxSwift/AnonymousObservable.swift
1
704
// // AnonymousObservable.swift // RxSwift // // Created by 野村 憲男 on 4/1/15. // Copyright (c) 2015 Norio Nomura. All rights reserved. // import Foundation // MARK: internal public final class AnonymousObservable<T>: ObservableBase<T> { public init<TObserver: IObserver where TObserver.Input == Output>(_ subscribe: TObserver -> IDisposable?) { _subscribe = subscribe as! AnyObject -> IDisposable? super.init() } override func subscribeCore<TObserver: IObserver where TObserver.Input == Output>(observer: TObserver) -> IDisposable? { return _subscribe(observer) } // MARK: private private let _subscribe: AnyObject -> IDisposable? }
mit
b1c58b569af6bc5e03be05535942cd72
28
124
0.676724
4.023121
false
false
false
false
xiaoyouPrince/WeiBo
WeiBo/WeiBo/Classes/Tools/HttpTool/NetworkTools.swift
1
4709
// // NetworkTools.swift // WeiBo // // Created by 渠晓友 on 2017/5/24. // Copyright © 2017年 xiaoyouPrince. All rights reserved. // // 封装一个网络请求工具(基于alamofire) import UIKit import Alamofire enum RequestMethod { case GET case POST } // 封装一个网络请求工具,这里不继承NSObject了,更加简洁一些 class NetworkTools { // 自定义一个类方法 class func requestData(type:RequestMethod , URLString : String , parameters : [String : Any]? = nil , finishCallBack:@escaping (_ response : AnyObject) -> ()){ // 获取类型 let method = type == .GET ? HTTPMethod.get : HTTPMethod.post Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in // 1.校验返回值 guard let result = response.result.value else{ print(response.error!) return } // 2.回调正确的返回 finishCallBack(result as AnyObject) } } // get请求 class func getData(URLString : String , finishCallBack:@escaping (_ response : AnyObject) -> ()) { // 调用类方法 requestData(type: .GET, URLString: URLString) { (response) in finishCallBack(response) } } /// post请求 // MARK: - post请求 class func postData(URLString : String , parameters : [String : NSString]? = nil, finishCallBack:@escaping (_ response : AnyObject) -> ()) { requestData(type:.POST, URLString: URLString, parameters: parameters) { (response) in finishCallBack(response) } } } // MARK: - 获取AccessToken专用 extension NetworkTools{ class func loadAccessToken(code : String , finishCallBack: @escaping (_ result : [String : Any]? ) -> ()){ let params = ["client_id" : app_key , "client_secret" : app_secret , "grant_type" : "authorization_code", "code" : code ,"redirect_uri" : redirect_uri] requestData(type: .POST, URLString: "https://api.weibo.com/oauth2/access_token", parameters: params) { (result) in finishCallBack(result as? [String : Any]) } } } // MARK: - 请求用户数据 extension NetworkTools{ class func loadUserInfo(accessToken : String ,uid : String , finishCallBack :@escaping (_ result : Any) -> ()) { requestData(type: .GET, URLString: "https://api.weibo.com/2/users/show.json", parameters: ["access_token" : accessToken , "uid" : uid]) { (result) in finishCallBack(result) } } } extension NetworkTools{ class func loadHomeData(_ since_id : Int , max_id : Int , finishCallBack:@escaping (_ result : [[String : AnyObject]]? ) -> ()){ // 请求接口 print(homgDataUrl + "?access_token" + UserAccountViewModel.shareInstance.account!.access_token!) let accessToken = UserAccountViewModel.shareInstance.account!.access_token! requestData(type: .GET, URLString: homgDataUrl, parameters: ["access_token" : accessToken , "since_id" : "\(since_id)" , "max_id" : "\(max_id)"]) { (result) in // 简单处理,之返回微博数据 guard result is [String : AnyObject] else{ return } // 判断请求是否出错 // if (result["error_code"]) != nil{ // // finishCallBack(result as? [[String : AnyObject]]) // // }else{ // 为出错 guard let statusesArray = result["statuses"] as? [[String : AnyObject]] else { return } finishCallBack(statusesArray) // } } } /// 发送文字微博 /// /// - Parameters: /// - statusText: 微博内容 /// - finishCallBack: 回调 class func postStatus( statusText : String , finishCallBack : @escaping (_ isSuccess : Bool) -> ()) { let accessToken = UserAccountViewModel.shareInstance.account?.access_token let params = ["access_token" : accessToken , "status" : statusText] requestData(type: .POST, URLString: "https://api.weibo.com/2/statuses/update.json", parameters: params as Any as? [String : Any]) { (result) in Dlog(result) finishCallBack(true) } } }
mit
bbcb892d2df18fb49a2522b1dc4be9cb
27.935065
167
0.537926
4.570256
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/PullToRefresher/PullToRefresh/DefaultRefreshView.swift
4
1197
// // DefaultRefreshView.swift // PullToRefreshDemo // // Created by Serhii Butenko on 26/7/16. // Copyright © 2016 Yalantis. All rights reserved. // import UIKit class DefaultRefreshView: UIView { fileprivate(set) lazy var activityIndicator: UIActivityIndicatorView! = { let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) self.addSubview(activityIndicator) return activityIndicator }() override func layoutSubviews() { centerActivityIndicator() setupFrame(in: superview) super.layoutSubviews() } override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) centerActivityIndicator() setupFrame(in: superview) } } private extension DefaultRefreshView { func setupFrame(in newSuperview: UIView?) { guard let superview = newSuperview else { return } frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: superview.frame.width, height: frame.height) } func centerActivityIndicator() { activityIndicator.center = convert(center, from: superview) } }
mit
e6384d2e353bd3549ef45e9d49eed172
26.181818
112
0.677258
4.942149
false
false
false
false
SheffieldKevin/SwiftGraphics
Playgrounds/ConvexHull.playground/contents.swift
1
1017
// Playground - noun: a place where people can play // Order of imports is very important import CoreGraphics import SwiftUtilities import SwiftRandom import SwiftGraphics import SwiftGraphicsPlayground let context = CGContextRef.bitmapContext(CGSize(w: 480, h: 320), origin: CGPoint(x: 0.0, y: 0.0)) context.style let bad_points = [ CGPoint(x: 101.15234375, y: 243.140625), CGPoint(x: 101.15234375, y: 241.05859375), CGPoint(x: 101.15234375, y: 237.93359375), CGPoint(x: 101.15234375, y: 235.8515625), ] let bad_hull = monotoneChain(bad_points) let rng = SwiftRandom.random var points = random.arrayOfRandomPoints(50, range: CGRect(w: 480, h: 320)) points.count //let hull = grahamScan(points) for (index, point) in points.enumerate() { context.strokeCross(CGRect(center: point, radius: 5)) context.drawLabel("\(index)", point: point + CGPoint(x: 2, y: 0), size: 10) } let hull = monotoneChain(points, sorted: false) hull.count context.strokeLine(hull, closed: true) context.nsimage
bsd-2-clause
82a41519e2da056c3663d93542f7614d
26.486486
97
0.725664
3.259615
false
false
false
false
esttorhe/RxSwift
RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchCell.swift
1
1834
// // WikipediaSearchCell.swift // Example // // Created by Krunoslav Zaher on 3/28/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import UIKit import RxSwift import RxCocoa public class WikipediaSearchCell: UITableViewCell { @IBOutlet var titleOutlet: UILabel! @IBOutlet var URLOutlet: UILabel! @IBOutlet var imagesOutlet: UICollectionView! var disposeBag: DisposeBag! let imageService = DefaultImageService.sharedImageService public override func awakeFromNib() { super.awakeFromNib() self.imagesOutlet.registerNib(UINib(nibName: "WikipediaImageCell", bundle: nil), forCellWithReuseIdentifier: "ImageCell") } var viewModel: SearchResultViewModel! { didSet { let $ = viewModel.$ let disposeBag = DisposeBag() self.titleOutlet.rx_subscribeTextTo(viewModel?.title ?? just("")) >- disposeBag.addDisposable self.URLOutlet.text = viewModel.searchResult.URL.absoluteString ?? "" viewModel.imageURLs >- self.imagesOutlet.rx_subscribeItemsToWithCellIdentifier("ImageCell") { [unowned self] (_, URL, cell: CollectionViewImageCell) in let loadingPlaceholder: UIImage? = nil cell.image = self.imageService.imageFromURL(URL) >- map { $0 as UIImage? } >- onError(nil) >- startWith(loadingPlaceholder) } >- disposeBag.addDisposable self.disposeBag = disposeBag } } public override func prepareForReuse() { super.prepareForReuse() self.disposeBag = nil } deinit { } }
mit
c75d25b10a975256024f215d87e430d0
28.596774
147
0.594329
5.442136
false
false
false
false
alonecuzzo/ystrdy
ystrdy/Network/WeatherUndergroundRouter.swift
1
1747
// // WeatherUndergroundRouter.swift // ystrdy // // Created by Jabari Bell on 2/6/17. // Copyright © 2017 theowl. All rights reserved. // import Foundation import Alamofire enum WeatherUndergroundRouter: URLRequestConvertible { //MARK: Case case getCurrentWeatherForLocation(LocationCoordinate), getYesterdaysWeatherForLocation(LocationCoordinate), getLocationDataForLocation(LocationCoordinate) //MARK: Property private static let baseURLString = "http://api.wunderground.com/api/9caa09c5d1399971/" var method: HTTPMethod { return .get } var path: String { switch self { case .getCurrentWeatherForLocation(_): return "conditions" case .getYesterdaysWeatherForLocation(_): return "yesterday" case .getLocationDataForLocation(_): return "geolookup" } } //MARK: Method func asURLRequest() throws -> URLRequest { let url = try WeatherUndergroundRouter.baseURLString.asURL() let urlWithPath = url.appendingPathComponent(path) let urlWithQ = urlWithPath.appendingPathComponent("q") var finalURL: URL? = nil switch self { case let .getYesterdaysWeatherForLocation(location), let .getCurrentWeatherForLocation(location), let .getLocationDataForLocation(location): finalURL = urlWithQ.appendingPathComponent("\(location.latitude),\(location.longitude).json") } var urlRequest = URLRequest(url: finalURL!) urlRequest.httpMethod = method.rawValue // urlRequest = try URLEncoding.default.encode(urlRequest, with: params) return urlRequest } }
apache-2.0
eb193b06b590829ce60b4defb1ad93b4
29.631579
158
0.658076
4.988571
false
false
false
false
aishpant/Calculator
Calculator/CalculatorButton.swift
1
772
// // CalculatorButton.swift // Calculator // // Created by aishwarya pant on 29/07/17. // Copyright © 2017 aishwarya. All rights reserved. // import UIKit class CalculatorButton: UIButton { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ var borderColor: CGColor = UIColor.lightText.cgColor var borderWidth: CGFloat = 1 var cornerRadius: CGFloat = 1 override func awakeFromNib() { super.awakeFromNib() self.layer.borderColor = borderColor self.layer.borderWidth = borderWidth // self.layer.cornerRadius = cornerRadius } }
mit
badcb634f59d5ed415a2db19d3db001b
23.09375
78
0.656291
4.482558
false
false
false
false
MaartenBrijker/project
project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Parameter Ramp Time.xcplaygroundpage/Contents.swift
2
869
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Parameter Ramp Time //: ### Ramping to values at different rates import XCPlayground import AudioKit var noise = AKWhiteNoise(amplitude: 1) var filter = AKMoogLadder(noise) filter.resonance = 0.94 AudioKit.output = filter AudioKit.start() noise.start() var counter = 0 AKPlaygroundLoop(frequency: 2.66) { let frequencyToggle = counter % 2 let rampTimeToggle = counter % 16 if frequencyToggle > 0 { filter.cutoffFrequency = 111 } else { filter.cutoffFrequency = 666 } if rampTimeToggle > 8 { filter.rampTime = 0.2 } else { filter.rampTime = 0.0002 } counter += 1 } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
apache-2.0
b643622e7d89fb2d3dc3f8f9b7b78559
21.282051
72
0.654776
3.79476
false
false
false
false
naohta/Spring
Spring/Spring.swift
1
23201
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([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 @objc public protocol Springable { var autostart: Bool { get set } var autohide: Bool { get set } var animation: String { get set } var force: CGFloat { get set } var delay: CGFloat { get set } var duration: CGFloat { get set } var damping: CGFloat { get set } var velocity: CGFloat { get set } var repeatCount: Float { get set } var x: CGFloat { get set } var y: CGFloat { get set } var scaleX: CGFloat { get set } var scaleY: CGFloat { get set } var rotate: CGFloat { get set } var opacity: CGFloat { get set } var animateFrom: Bool { get set } var curve: String { get set } // UIView var layer : CALayer { get } var transform : CGAffineTransform { get set } var alpha : CGFloat { get set } func animate() func animateNext(completion: () -> ()) func animateTo() func animateToNext(completion: () -> ()) } public class Spring : NSObject { private unowned var view : Springable private var shouldAnimateAfterActive = false init(_ view: Springable) { self.view = view super.init() commonInit() } func commonInit() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActiveNotification:", name: UIApplicationDidBecomeActiveNotification, object: nil) } func didBecomeActiveNotification(notification: NSNotification) { if shouldAnimateAfterActive { alpha = 0 animate() shouldAnimateAfterActive = false } } deinit { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil) } private var autostart: Bool { set { self.view.autostart = newValue } get { return self.view.autostart }} private var autohide: Bool { set { self.view.autohide = newValue } get { return self.view.autohide }} private var animation: String { set { self.view.animation = newValue } get { return self.view.animation }} private var force: CGFloat { set { self.view.force = newValue } get { return self.view.force }} private var delay: CGFloat { set { self.view.delay = newValue } get { return self.view.delay }} private var duration: CGFloat { set { self.view.duration = newValue } get { return self.view.duration }} private var damping: CGFloat { set { self.view.damping = newValue } get { return self.view.damping }} private var velocity: CGFloat { set { self.view.velocity = newValue } get { return self.view.velocity }} private var repeatCount: Float { set { self.view.repeatCount = newValue } get { return self.view.repeatCount }} private var x: CGFloat { set { self.view.x = newValue } get { return self.view.x }} private var y: CGFloat { set { self.view.y = newValue } get { return self.view.y }} private var scaleX: CGFloat { set { self.view.scaleX = newValue } get { return self.view.scaleX }} private var scaleY: CGFloat { set { self.view.scaleY = newValue } get { return self.view.scaleY }} private var rotate: CGFloat { set { self.view.rotate = newValue } get { return self.view.rotate }} private var opacity: CGFloat { set { self.view.opacity = newValue } get { return self.view.opacity }} private var animateFrom: Bool { set { self.view.animateFrom = newValue } get { return self.view.animateFrom }} private var curve: String { set { self.view.curve = newValue } get { return self.view.curve }} // UIView private var layer : CALayer { return view.layer } private var transform : CGAffineTransform { get { return view.transform } set { view.transform = newValue }} private var alpha: CGFloat { get { return view.alpha } set { view.alpha = newValue } } public enum AnimationPreset: String { case SlideLeft = "slideLeft" case SlideRight = "slideRight" case SlideDown = "slideDown" case SlideUp = "slideUp" case SqueezeLeft = "squeezeLeft" case SqueezeRight = "squeezeRight" case SqueezeDown = "squeezeDown" case SqueezeUp = "squeezeUp" case FadeIn = "fadeIn" case FadeOut = "fadeOut" case FadeOutIn = "fadeOutIn" case FadeInLeft = "fadeInLeft" case FadeInRight = "fadeInRight" case FadeInDown = "fadeInDown" case FadeInUp = "fadeInUp" case ZoomIn = "zoomIn" case ZoomOut = "zoomOut" case Fall = "fall" case Shake = "shake" case Pop = "pop" case FlipX = "flipX" case FlipY = "flipY" case Morph = "morph" case Squeeze = "squeeze" case Flash = "flash" case Wobble = "wobble" case Swing = "swing" } public enum AnimationCurve: String { case EaseIn = "easeIn" case EaseOut = "easeOut" case EaseInOut = "easeInOut" case Linear = "linear" case Spring = "spring" case EaseInSine = "easeInSine" case EaseOutSine = "easeOutSine" case EaseInOutSine = "easeInOutSine" case EaseInQuad = "easeInQuad" case EaseOutQuad = "easeOutQuad" case EaseInOutQuad = "easeInOutQuad" case EaseInCubic = "easeInCubic" case EaseOutCubic = "easeOutCubic" case EaseInOutCubic = "easeInOutCubic" case EaseInQuart = "easeInQuart" case EaseOutQuart = "easeOutQuart" case EaseInOutQuart = "easeInOutQuart" case EaseInQuint = "easeInQuint" case EaseOutQuint = "easeOutQuint" case EaseInOutQuint = "easeInOutQuint" case EaseInExpo = "easeInExpo" case EaseOutExpo = "easeOutExpo" case EaseInOutExpo = "easeInOutExpo" case EaseInCirc = "easeInCirc" case EaseOutCirc = "easeOutCirc" case EaseInOutCirc = "easeInOutCirc" case EaseInBack = "easeInBack" case EaseOutBack = "easeOutBack" case EaseInOutBack = "easeInOutBack" } func animatePreset() { alpha = 0.99 if let animation = AnimationPreset(rawValue: animation) { switch animation { case .SlideLeft: x = 300*force case .SlideRight: x = -300*force case .SlideDown: y = -300*force case .SlideUp: y = 300*force case .SqueezeLeft: x = 300 scaleX = 3*force case .SqueezeRight: x = -300 scaleX = 3*force case .SqueezeDown: y = -300 scaleY = 3*force case .SqueezeUp: y = 300 scaleY = 3*force case .FadeIn: opacity = 0 case .FadeOut: animateFrom = false opacity = 0 case .FadeOutIn: let animation = CABasicAnimation() animation.keyPath = "opacity" animation.fromValue = 1 animation.toValue = 0 animation.timingFunction = getTimingFunction(curve) animation.duration = CFTimeInterval(duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) animation.autoreverses = true layer.addAnimation(animation, forKey: "fade") case .FadeInLeft: opacity = 0 x = 300*force case .FadeInRight: x = -300*force opacity = 0 case .FadeInDown: y = -300*force opacity = 0 case .FadeInUp: y = 300*force opacity = 0 case .ZoomIn: opacity = 0 scaleX = 2*force scaleY = 2*force case .ZoomOut: animateFrom = false opacity = 0 scaleX = 2*force scaleY = 2*force case .Fall: animateFrom = false rotate = 15 * CGFloat(M_PI/180) y = 600*force case .Shake: let animation = CAKeyframeAnimation() animation.keyPath = "position.x" animation.values = [0, 30*force, -30*force, 30*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.timingFunction = getTimingFunction(curve) animation.duration = CFTimeInterval(duration) animation.additive = true animation.repeatCount = repeatCount animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(animation, forKey: "shake") case .Pop: let animation = CAKeyframeAnimation() animation.keyPath = "transform.scale" animation.values = [0, 0.2*force, -0.2*force, 0.2*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.timingFunction = getTimingFunction(curve) animation.duration = CFTimeInterval(duration) animation.additive = true animation.repeatCount = repeatCount animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(animation, forKey: "pop") case .FlipX: rotate = 0 scaleX = 1 scaleY = 1 var perspective = CATransform3DIdentity perspective.m34 = -1.0 / layer.frame.size.width/2 let animation = CABasicAnimation() animation.keyPath = "transform" animation.fromValue = NSValue(CATransform3D: CATransform3DMakeRotation(0, 0, 0, 0)) animation.toValue = NSValue(CATransform3D: CATransform3DConcat(perspective, CATransform3DMakeRotation(CGFloat(M_PI), 0, 1, 0))) animation.duration = CFTimeInterval(duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) animation.timingFunction = getTimingFunction(curve) layer.addAnimation(animation, forKey: "3d") case .FlipY: var perspective = CATransform3DIdentity perspective.m34 = -1.0 / layer.frame.size.width/2 let animation = CABasicAnimation() animation.keyPath = "transform" animation.fromValue = NSValue(CATransform3D: CATransform3DMakeRotation(0, 0, 0, 0)) animation.toValue = NSValue(CATransform3D: CATransform3DConcat(perspective,CATransform3DMakeRotation(CGFloat(M_PI), 1, 0, 0))) animation.duration = CFTimeInterval(duration) animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) animation.timingFunction = getTimingFunction(curve) layer.addAnimation(animation, forKey: "3d") case .Morph: let morphX = CAKeyframeAnimation() morphX.keyPath = "transform.scale.x" morphX.values = [1, 1.3*force, 0.7, 1.3*force, 1] morphX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphX.timingFunction = getTimingFunction(curve) morphX.duration = CFTimeInterval(duration) morphX.repeatCount = repeatCount morphX.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(morphX, forKey: "morphX") let morphY = CAKeyframeAnimation() morphY.keyPath = "transform.scale.y" morphY.values = [1, 0.7, 1.3*force, 0.7, 1] morphY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphY.timingFunction = getTimingFunction(curve) morphY.duration = CFTimeInterval(duration) morphY.repeatCount = repeatCount morphY.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(morphY, forKey: "morphY") case .Squeeze: let morphX = CAKeyframeAnimation() morphX.keyPath = "transform.scale.x" morphX.values = [1, 1.5*force, 0.5, 1.5*force, 1] morphX.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphX.timingFunction = getTimingFunction(curve) morphX.duration = CFTimeInterval(duration) morphX.repeatCount = repeatCount morphX.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(morphX, forKey: "morphX") let morphY = CAKeyframeAnimation() morphY.keyPath = "transform.scale.y" morphY.values = [1, 0.5, 1, 0.5, 1] morphY.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] morphY.timingFunction = getTimingFunction(curve) morphY.duration = CFTimeInterval(duration) morphY.repeatCount = repeatCount morphY.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(morphY, forKey: "morphY") case .Flash: let animation = CABasicAnimation() animation.keyPath = "opacity" animation.fromValue = 1 animation.toValue = 0 animation.duration = CFTimeInterval(duration) animation.repeatCount = repeatCount * 2.0 animation.autoreverses = true animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(animation, forKey: "flash") case .Wobble: let animation = CAKeyframeAnimation() animation.keyPath = "transform.rotation" animation.values = [0, 0.3*force, -0.3*force, 0.3*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.duration = CFTimeInterval(duration) animation.additive = true animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(animation, forKey: "wobble") let x = CAKeyframeAnimation() x.keyPath = "position.x" x.values = [0, 30*force, -30*force, 30*force, 0] x.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] x.timingFunction = getTimingFunction(curve) x.duration = CFTimeInterval(duration) x.additive = true x.repeatCount = repeatCount x.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(x, forKey: "x") case .Swing: let animation = CAKeyframeAnimation() animation.keyPath = "transform.rotation" animation.values = [0, 0.3*force, -0.3*force, 0.3*force, 0] animation.keyTimes = [0, 0.2, 0.4, 0.6, 0.8, 1] animation.duration = CFTimeInterval(duration) animation.additive = true animation.beginTime = CACurrentMediaTime() + CFTimeInterval(delay) layer.addAnimation(animation, forKey: "swing") } } } func getTimingFunction(curve: String) -> CAMediaTimingFunction { if let curve = AnimationCurve(rawValue: curve) { switch curve { case .EaseIn: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn) case .EaseOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut) case .EaseInOut: return CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) case .Linear: return CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) case .Spring: return CAMediaTimingFunction(controlPoints: 0.5, 1.1+Float(force/3), 1, 1) case .EaseInSine: return CAMediaTimingFunction(controlPoints: 0.47, 0, 0.745, 0.715) case .EaseOutSine: return CAMediaTimingFunction(controlPoints: 0.39, 0.575, 0.565, 1) case .EaseInOutSine: return CAMediaTimingFunction(controlPoints: 0.445, 0.05, 0.55, 0.95) case .EaseInQuad: return CAMediaTimingFunction(controlPoints: 0.55, 0.085, 0.68, 0.53) case .EaseOutQuad: return CAMediaTimingFunction(controlPoints: 0.25, 0.46, 0.45, 0.94) case .EaseInOutQuad: return CAMediaTimingFunction(controlPoints: 0.455, 0.03, 0.515, 0.955) case .EaseInCubic: return CAMediaTimingFunction(controlPoints: 0.55, 0.055, 0.675, 0.19) case .EaseOutCubic: return CAMediaTimingFunction(controlPoints: 0.215, 0.61, 0.355, 1) case .EaseInOutCubic: return CAMediaTimingFunction(controlPoints: 0.645, 0.045, 0.355, 1) case .EaseInQuart: return CAMediaTimingFunction(controlPoints: 0.895, 0.03, 0.685, 0.22) case .EaseOutQuart: return CAMediaTimingFunction(controlPoints: 0.165, 0.84, 0.44, 1) case .EaseInOutQuart: return CAMediaTimingFunction(controlPoints: 0.77, 0, 0.175, 1) case .EaseInQuint: return CAMediaTimingFunction(controlPoints: 0.755, 0.05, 0.855, 0.06) case .EaseOutQuint: return CAMediaTimingFunction(controlPoints: 0.23, 1, 0.32, 1) case .EaseInOutQuint: return CAMediaTimingFunction(controlPoints: 0.86, 0, 0.07, 1) case .EaseInExpo: return CAMediaTimingFunction(controlPoints: 0.95, 0.05, 0.795, 0.035) case .EaseOutExpo: return CAMediaTimingFunction(controlPoints: 0.19, 1, 0.22, 1) case .EaseInOutExpo: return CAMediaTimingFunction(controlPoints: 1, 0, 0, 1) case .EaseInCirc: return CAMediaTimingFunction(controlPoints: 0.6, 0.04, 0.98, 0.335) case .EaseOutCirc: return CAMediaTimingFunction(controlPoints: 0.075, 0.82, 0.165, 1) case .EaseInOutCirc: return CAMediaTimingFunction(controlPoints: 0.785, 0.135, 0.15, 0.86) case .EaseInBack: return CAMediaTimingFunction(controlPoints: 0.6, -0.28, 0.735, 0.045) case .EaseOutBack: return CAMediaTimingFunction(controlPoints: 0.175, 0.885, 0.32, 1.275) case .EaseInOutBack: return CAMediaTimingFunction(controlPoints: 0.68, -0.55, 0.265, 1.55) } } return CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) } func getAnimationOptions(curve: String) -> UIViewAnimationOptions { if let curve = AnimationCurve(rawValue: curve) { switch curve { case .EaseIn: return UIViewAnimationOptions.CurveEaseIn case .EaseOut: return UIViewAnimationOptions.CurveEaseOut case .EaseInOut: return UIViewAnimationOptions.CurveEaseInOut default: break } } return UIViewAnimationOptions.CurveLinear } public func animate() { animateFrom = true animatePreset() setView {} } public func animateNext(completion: () -> ()) { animateFrom = true animatePreset() setView { completion() } } public func animateTo() { animateFrom = false animatePreset() setView {} } public func animateToNext(completion: () -> ()) { animateFrom = false animatePreset() setView { completion() } } public func customAwakeFromNib() { if autohide { alpha = 0 } } public func customDidMoveToWindow() { if autostart { if UIApplication.sharedApplication().applicationState != .Active { shouldAnimateAfterActive = true return } alpha = 0 animate() } } func setView(completion: () -> ()) { if animateFrom { let translate = CGAffineTransformMakeTranslation(self.x, self.y) let scale = CGAffineTransformMakeScale(self.scaleX, self.scaleY) let rotate = CGAffineTransformMakeRotation(self.rotate) let translateAndScale = CGAffineTransformConcat(translate, scale) self.transform = CGAffineTransformConcat(rotate, translateAndScale) self.alpha = self.opacity } UIView.animateWithDuration( NSTimeInterval(duration), delay: NSTimeInterval(delay), usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: getAnimationOptions(curve), animations: { [weak self] in if let _self = self { if _self.animateFrom { _self.transform = CGAffineTransformIdentity _self.alpha = 1 } else { let translate = CGAffineTransformMakeTranslation(_self.x, _self.y) let scale = CGAffineTransformMakeScale(_self.scaleX, _self.scaleY) let rotate = CGAffineTransformMakeRotation(_self.rotate) let translateAndScale = CGAffineTransformConcat(translate, scale) _self.transform = CGAffineTransformConcat(rotate, translateAndScale) _self.alpha = _self.opacity } } }, completion: { [weak self] finished in completion() self?.resetAll() }) } func reset() { x = 0 y = 0 opacity = 1 } func resetAll() { x = 0 y = 0 animation = "" opacity = 1 scaleX = 1 scaleY = 1 rotate = 0 damping = 0.7 velocity = 0.7 repeatCount = 1 delay = 0 duration = 0.7 } }
mit
d1d0df8c78ce7c00ae1d4912f86bde5a
42.860113
165
0.587087
4.854781
false
false
false
false
paulofaria/SwiftHTTPServer
JSON/JSON.swift
3
10800
// JSON.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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. public enum JSON { case NullValue case BooleanValue(Bool) case NumberValue(Double) case StringValue(String) case ArrayValue([JSON]) case ObjectValue([String: JSON]) static func from(value: Bool) -> JSON { return .BooleanValue(value) } static func from(value: Double) -> JSON { return .NumberValue(value) } static func from(value: String) -> JSON { return .StringValue(value) } static func from(value: [JSON]) -> JSON { return .ArrayValue(value) } static func from(value: [String: JSON]) -> JSON { return .ObjectValue(value) } // TODO: decide what to do if Any is not a JSON value static func from(values: [Any]) -> JSON { var jsonArray: [JSON] = [] for value in values { if let value = value as? Bool { jsonArray.append(JSON.from(value)) } if let value = value as? Double { jsonArray.append(JSON.from(value)) } if let value = value as? String { jsonArray.append(JSON.from(value)) } if let value = value as? [Any] { jsonArray.append(JSON.from(value)) } if let value = value as? [String: Any] { jsonArray.append(JSON.from(value)) } } return JSON.from(jsonArray) } // TODO: decide what to do if Any is not a JSON value static func from(value: [String: Any]) -> JSON { var jsonDictionary: [String: JSON] = [:] for (key, value) in value { if let value = value as? Bool { jsonDictionary[key] = JSON.from(value) } if let value = value as? Double { jsonDictionary[key] = JSON.from(value) } if let value = value as? String { jsonDictionary[key] = JSON.from(value) } if let value = value as? [Any] { jsonDictionary[key] = JSON.from(value) } if let value = value as? [String: Any] { jsonDictionary[key] = JSON.from(value) } } return JSON.from(jsonDictionary) } public var isBoolean: Bool { switch self { case .BooleanValue: return true default: return false } } public var isNumber: Bool { switch self { case .NumberValue: return true default: return false } } public var isString: Bool { switch self { case .StringValue: return true default: return false } } public var isArray: Bool { switch self { case .ArrayValue: return true default: return false } } public var isObject: Bool { switch self { case .ObjectValue: return true default: return false } } public var boolValue: Bool { switch self { case .NullValue: return false case .BooleanValue(let b): return b default: return true } } public var doubleValue: Double { switch self { case .NumberValue(let n): return n case .StringValue(let s): return atof(s) case .BooleanValue(let b): return b ? 1.0 : 0.0 default: return 0.0 } } public var intValue: Int { return Int(doubleValue) } public var uintValue: UInt { return UInt(doubleValue) } public var stringValue: String { switch self { case .NullValue: return "" case .StringValue(let s): return s default: return description } } public var arrayValue: [JSON] { switch self { case .NullValue: return [] case .ArrayValue(let array): return array default: return [] } } public var dictionaryValue: [String: JSON] { switch self { case .NullValue: return [:] case .ObjectValue(let dictionary): return dictionary default: return [:] } } public var anyValue: Any { switch self { case NullValue: let array: [Any] = [] return array case BooleanValue(let bool): return bool case NumberValue(let double): return double case StringValue(let string): return string case ArrayValue(let array): return array.map { $0.anyValue } case ObjectValue(let object): var dictionaryOfAny: [String: Any] = [:] for (key, json) in object { dictionaryOfAny[key] = json.anyValue } return dictionaryOfAny } } public var dictionaryOfAnyValue: [String: Any] { if let dictionaryOfAny = anyValue as? [String: Any] { return dictionaryOfAny } return [:] } public subscript(index: UInt) -> JSON { set { switch self { case .ArrayValue(var a): if Int(index) < a.count { a[Int(index)] = newValue self = .ArrayValue(a) } default: break } } get { switch self { case .ArrayValue(let a): return Int(index) < a.count ? a[Int(index)] : .NullValue default: return .NullValue } } } public subscript(key: String) -> JSON { set { switch self { case .ObjectValue(var o): o[key] = newValue self = .ObjectValue(o) default: break } } get { switch self { case .ObjectValue(let o): return o[key] ?? .NullValue default: return .NullValue } } } public func serialize(serializer: JSONSerializer) -> String { return serializer.serialize(self) } } extension JSON: CustomStringConvertible { public var description: String { return serialize(DefaultJSONSerializer()) } } extension JSON: CustomDebugStringConvertible { public var debugDescription: String { return serialize(PrettyJSONSerializer()) } } extension JSON: Equatable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch lhs { case .NullValue: switch rhs { case .NullValue: return true default: return false } case .BooleanValue(let lhsValue): switch rhs { case .BooleanValue(let rhsValue): return lhsValue == rhsValue default: return false } case .StringValue(let lhsValue): switch rhs { case .StringValue(let rhsValue): return lhsValue == rhsValue default: return false } case .NumberValue(let lhsValue): switch rhs { case .NumberValue(let rhsValue): return lhsValue == rhsValue default: return false } case .ArrayValue(let lhsValue): switch rhs { case .ArrayValue(let rhsValue): return lhsValue == rhsValue default: return false } case .ObjectValue(let lhsValue): switch rhs { case .ObjectValue(let rhsValue): return lhsValue == rhsValue default: return false } } } extension JSON: NilLiteralConvertible { public init(nilLiteral value: Void) { self = .NullValue } } extension JSON: BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self = .BooleanValue(value) } } extension JSON: IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self = .NumberValue(Double(value)) } } extension JSON: FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self = .NumberValue(Double(value)) } } extension JSON: StringLiteralConvertible { public typealias UnicodeScalarLiteralType = String public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { self = .StringValue(value) } public typealias ExtendedGraphemeClusterLiteralType = String public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterType) { self = .StringValue(value) } public init(stringLiteral value: StringLiteralType) { self = .StringValue(value) } } extension JSON: ArrayLiteralConvertible { public init(arrayLiteral elements: JSON...) { self = .ArrayValue(elements) } } extension JSON: DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, JSON)...) { var dictionary = [String: JSON](minimumCapacity: elements.count) for pair in elements { dictionary[pair.0] = pair.1 } self = .ObjectValue(dictionary) } }
mit
1f03b98803d81a06401bca6590d3cc84
17.337861
84
0.541019
5.046729
false
false
false
false
Esri/arcgis-runtime-samples-ios
arcgis-ios-sdk-samples/Layers/List KML contents/ListKMLContentsSceneViewController.swift
1
8898
// Copyright 2018 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import ArcGIS class ListKMLContentsSceneViewController: UIViewController { @IBOutlet weak var sceneView: AGSSceneView? { didSet { sceneView?.scene = scene } } private let scene: AGSScene = { // initialize scene with labeled imagery let scene = AGSScene(basemapStyle: .arcGISImagery) // create an elevation source and add it to the scene's surface let elevationSourceURL = URL(string: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer")! let elevationSource = AGSArcGISTiledElevationSource(url: elevationSourceURL) scene.baseSurface?.elevationSources.append(elevationSource) return scene }() var kmlDataset: AGSKMLDataset? { didSet { guard kmlDataset != oldValue, let kmlDataset = kmlDataset else { return } // clear any existing layers scene.operationalLayers.removeAllObjects() // create a layer to display the dataset let kmlLayer = AGSKMLLayer(kmlDataset: kmlDataset) // add the kml layer to the scene scene.operationalLayers.add(kmlLayer) } } var node: AGSKMLNode? { didSet { guard kmlDataset != oldValue, let node = node else { return } // set the title so the name will appear in the navigation bar title = node.name // set the viewpoint based on the new node setSceneViewpoint(for: node) } } /// A queue for calculating the node viewpoint in the background. private let dispatchQueue = DispatchQueue(label: "node viewpoint getter", qos: .userInitiated, attributes: .concurrent, autoreleaseFrequency: .workItem, target: nil) // MARK: - Viewpoint /// Sets the viewpoint of the scene based on the node, or hides the node /// if a viewpoint cannot be determined. private func setSceneViewpoint(for node: AGSKMLNode) { dispatchQueue.async { // get the viewpoint asynchronously so not to block the main thread let nodeViewpoint = self.viewpoint(for: node) // run UI updates on the main thread DispatchQueue.main.async { // load the view before setting a viewpoint self.loadViewIfNeeded() guard let sceneView = self.sceneView else { return } if let nodeViewpoint = nodeViewpoint, !nodeViewpoint.targetGeometry.isEmpty { // reveal the view in case it was previously hidden sceneView.isHidden = false // set the viewpoint for the node sceneView.setViewpoint(nodeViewpoint) } else { // this node has no viewpoint so hide the scene view, showing the info text sceneView.isHidden = true } } } } /// Returns the elevation of the scene's surface corresponding to the point's x/y. private func sceneSurfaceElevation(for point: AGSPoint) -> Double? { guard let surface = scene.baseSurface else { return nil } var surfaceElevation: Double? let group = DispatchGroup() group.enter() // we want to return the elevation synchronously, so run the task in the background and wait surface.elevation(for: point) { (elevation, error) in if error == nil { surfaceElevation = elevation } group.leave() } // wait, but not longer than three seconds _ = group.wait(timeout: .now() + 3) return surfaceElevation } /// Returns the viewpoint showing the node, converting it from the node's AGSKMLViewPoint if possible. private func viewpoint(for node: AGSKMLNode) -> AGSViewpoint? { if let kmlViewpoint = node.viewpoint { return viewpointFromKMLViewpoint(kmlViewpoint) } else if let extent = node.extent { // the node does not have a predefined viewpoint, so create a viewpoint based on its extent return viewpointFromKMLNodeExtent(extent) } // the node doesn't have a predefined viewpoint or geometry return nil } // Converts the KML viewpoint to a viewpoint for the scene. // The KML viewpoint may not correspond to the node's geometry. private func viewpointFromKMLViewpoint(_ kmlViewpoint: AGSKMLViewpoint) -> AGSViewpoint? { switch kmlViewpoint.type { case .lookAt: var lookAtPoint = kmlViewpoint.location if kmlViewpoint.altitudeMode != .absolute { // if the elevation is relative, account for the surface's elevation let elevation = sceneSurfaceElevation(for: lookAtPoint) ?? 0 lookAtPoint = AGSPoint(x: lookAtPoint.x, y: lookAtPoint.y, z: lookAtPoint.z + elevation, spatialReference: lookAtPoint.spatialReference) } let camera = AGSCamera(lookAt: lookAtPoint, distance: kmlViewpoint.range, heading: kmlViewpoint.heading, pitch: kmlViewpoint.pitch, roll: kmlViewpoint.roll) // only the camera parameter is used by the scene return AGSViewpoint(center: kmlViewpoint.location, scale: 1, camera: camera) case .camera: // convert the KML viewpoint to a camera let camera = AGSCamera(location: kmlViewpoint.location, heading: kmlViewpoint.heading, pitch: kmlViewpoint.pitch, roll: kmlViewpoint.roll) // only the camera parameter is used by the scene return AGSViewpoint(center: kmlViewpoint.location, scale: 1, camera: camera) case .unknown: fallthrough @unknown default: print("Unexpected AGSKMLViewpointType \(kmlViewpoint.type)") return nil } } /// Creates a default viewpoint framing the node based on its extent. private func viewpointFromKMLNodeExtent(_ extent: AGSEnvelope) -> AGSViewpoint? { // some nodes do not include a geometry, so check that the extent isn't empty guard !extent.isEmpty else { return nil } let extentCenter = extent.center // take the scene's elevation into account let elevation = sceneSurfaceElevation(for: extentCenter) ?? 0 // It's possible for `isEmpty` to be false but for width/height to still be zero. if extent.width == 0, extent.height == 0 { let lookAtPoint = AGSPoint( x: extentCenter.x, y: extentCenter.y, z: extentCenter.z + elevation, spatialReference: extent.spatialReference ) // Defaults based on Google Earth. let camera = AGSCamera(lookAt: lookAtPoint, distance: 1000, heading: 0, pitch: 45, roll: 0) // only the camera parameter is used by the scene return AGSViewpoint(targetExtent: extent, camera: camera) } else { // expand the extent to give some margins when framing the node let bufferRadius = max(extent.width, extent.height) / 20 let bufferedExtent = AGSEnvelope( xMin: extent.xMin - bufferRadius, yMin: extent.yMin - bufferRadius, zMin: extent.zMin - bufferRadius + elevation, xMax: extent.xMax + bufferRadius, yMax: extent.yMax + bufferRadius, zMax: extent.zMax + bufferRadius + elevation, spatialReference: .wgs84() ) return AGSViewpoint(targetExtent: bufferedExtent) } } }
apache-2.0
869b84560ccba2604d73de92c18e7e74
41.574163
169
0.587885
5.027119
false
false
false
false
manfengjun/FJAddressPicker
FJAddressPicker/FJSQLiteUtils.swift
1
7159
// // SQLiteManager.swift // FJAddressPickerDemo // // Created by jun on 2017/6/22. // Copyright © 2017年 JUN. All rights reserved. // import UIKit import FMDB /// 屏幕宽度 let SCREEN_WIDTH = UIScreen.main.bounds.width /// 屏幕高度 let SCREEN_HEIGHT = UIScreen.main.bounds.height class FJSQLiteUtils: NSObject { /// 单例 static let instance = FJSQLiteUtils() /// 选中的 var itemArray:[FJAddressModel] = [] /// 配置信息 var arribute = AddressAttribute() /// 数据库 var db:FMDatabase! /// sql文件名称 var sqlName = "tp_region" /// 数据库名称 var databaseName = "location.db" /// 表名 var tableName = "tp_region" override init() { super.init() } // MARK: ------ 查询操作 /// 查询全部省份 /// /// - Returns: return value description func queryAllProvince() -> [FJAddressModel] { if db.open() { let sql = "SELECT * FROM \(tableName) WHERE `level` = 1" let rs = try? db.executeQuery(sql, values: nil) var dataArray:[FJAddressModel] = [] if let result = rs { while result.next() { let model = FJAddressModel() model.id = Int(result.int(forColumn: "id")) model.parent_id = Int(result.int(forColumn: "parent_id")) model.name = result.string(forColumn: "name") model.level = Int(result.int(forColumn: "level")) dataArray.append(model) } return dataArray } db.close() } return [] } /// 查询下一级数据 /// /// - Parameters: /// - level: level description /// - parent_id: parent_id description /// - Returns: return value description func queryData(level:Int,parent_id:Int) -> [FJAddressModel] { if db.open() { let sql = "SELECT * FROM \(tableName) WHERE `level` = \(level) and `parent_id` = \(parent_id)" let rs = try? db.executeQuery(sql, values: nil) var dataArray:[FJAddressModel] = [] if let result = rs { while result.next() { let model = FJAddressModel() model.id = Int(result.int(forColumn: "id")) model.parent_id = Int(result.int(forColumn: "parent_id")) model.name = result.string(forColumn: "name") model.level = Int(result.int(forColumn: "level")) dataArray.append(model) } return dataArray } db.close() } return [] } func queryData(id:Int) -> [FJAddressModel] { if db.open() { let sql = "SELECT name FROM %@ WHERE `id` = \(id)" let rs = try? db.executeQuery(sql, values: nil) var dataArray:[FJAddressModel] = [] if let result = rs { while result.next() { let model = FJAddressModel() model.id = Int(result.int(forColumn: "id")) model.parent_id = Int(result.int(forColumn: "parent_id")) model.name = result.string(forColumn: "name") model.level = Int(result.int(forColumn: "level")) dataArray.append(model) } return dataArray } db.close() } return [] } } extension FJSQLiteUtils{ // MARK: ------ 数据库管理 // 初始化数据 func setupData() { if isTableOK() { return } if createTable() { insertRecords() } } /// 数据库初始化 func dbInit() { let dbPath = self.pathForName(name: databaseName) print(dbPath) db = FMDatabase(path: dbPath) setupData() } /// 删除数据库 func dbDelete() { let dbPath = pathForName(name: databaseName) try? FileManager.default.removeItem(atPath: dbPath) } /// 本地路径 /// /// - Parameter name: name description /// - Returns: return value description func pathForName(name:String) -> String { let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) let documentDirectory = paths.last let dbPath = "\(documentDirectory!)/\(name)" return dbPath } /// 表是否存在 /// /// - Returns: return value description func isTableOK() -> Bool { let openSuccess = db.open() if openSuccess { let rs = try? db.executeQuery("SELECT count(*) as 'count' FROM sqlite_master WHERE type ='table' and name = ?", values: [tableName]) while (rs?.next())! { let count = rs?.int(forColumn: "count") if count == 0 { db.close() return false } else { db.close() return true } } } else { } db.close() return false } /// 插入数据 func insertRecords() { if db.open() && db.beginTransaction() { do { let filePath = Bundle.main.path(forResource: sqlName, ofType: "sql") let sql = try String(contentsOfFile: filePath!, encoding: String.Encoding.utf8) let isSuccess = db.executeUpdate(sql, withArgumentsIn: []) if isSuccess { db.commit() print("插入信息成功") } else{ print("插入信息失败") } } catch{ print("插入信息失败") } } db.close() } /// 创建表 /// /// - Returns: return value description func createTable() -> Bool{ var rs = false let openSuccess = db.open() if openSuccess { let sql = "create table if not exists \(tableName) (id int primary key,name text,level int,parent_id int);" rs = db.executeUpdate(sql, withArgumentsIn: []) if rs { print("创建地址表成功") } else{ print("创建地址表失败") } } db.close() return rs } /// 删除表 /// /// - Returns: return value description func delTable() -> Bool { var rs = false let openSuccess = db.open() if openSuccess { let sql = "DROP TABLE \(tableName)" rs = db.executeStatements(sql) if rs { print("删除地址表成功") } else{ print("删除地址表失败") } } db.close() return rs } }
mit
7f5b995f33d2ba1ae3a5f9da3eb6219a
27.345679
144
0.472706
4.555556
false
false
false
false
vuvankhac/KVRefreshable
KVRefreshable/Classes/UIScrollView+KVPullToRefresh.swift
1
4294
/** Copyright (c) 2017 Vu Van Khac <[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 extension UIScrollView { private struct KVPullToRefreshObject { static var pullToRefreshView = "PullToRefreshView" } public private(set) var pullToRefreshView: KVPullToRefreshView { get { if let pullToRefreshView = objc_getAssociatedObject(self, &KVPullToRefreshObject.pullToRefreshView) as? KVPullToRefreshView { return pullToRefreshView } else { let pullToRefreshView = KVPullToRefreshView(frame: CGRect(x: 0, y: -60, width: bounds.size.width, height: 60)) objc_setAssociatedObject(self, &KVPullToRefreshObject.pullToRefreshView, pullToRefreshView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return pullToRefreshView } } set { willChangeValue(forKey: KVPullToRefreshObject.pullToRefreshView) objc_setAssociatedObject(self, &KVPullToRefreshObject.pullToRefreshView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) didChangeValue(forKey: KVPullToRefreshObject.pullToRefreshView) } } public var showsPullToRefresh: Bool { get { return pullToRefreshView.isHidden } set { pullToRefreshView.isHidden = !newValue if newValue { if !pullToRefreshView.observing { addObserver(pullToRefreshView, forKeyPath: "contentOffset", options: .new, context: nil) addObserver(pullToRefreshView, forKeyPath: "contentSize", options: .new, context: nil) addObserver(pullToRefreshView, forKeyPath: "frame", options: .new, context: nil) pullToRefreshView.frame = CGRect(x: 0, y: -60, width: bounds.size.width, height: 60) pullToRefreshView.observing = true } } else { if pullToRefreshView.observing { removeObserver(pullToRefreshView, forKeyPath: "contentOffset") removeObserver(pullToRefreshView, forKeyPath: "contentSize") removeObserver(pullToRefreshView, forKeyPath: "frame") pullToRefreshView.resetScrollViewContentInset() pullToRefreshView.observing = false } } } } public func addPullToRefreshWithActionHandler(_ actionHandler: @escaping () -> Void, withConfig config: () -> Void) { pullToRefreshView.pullToRefreshHandler = actionHandler pullToRefreshView.scrollView = self pullToRefreshView.originalTopInset = contentInset.top addSubview(pullToRefreshView) showsPullToRefresh = true config() } public func triggerPullToRefresh() { pullToRefreshView.alpha = 0 DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in guard let weakSelf = self else { return } weakSelf.pullToRefreshView.alpha = 1.0 } pullToRefreshView.isFirstTrigger = true pullToRefreshView.state = .triggered pullToRefreshView.startAnimating() } }
mit
3f2ee300c19d6647ac729a584d0b0cee
41.94
143
0.660456
5.657444
false
false
false
false
kingcos/Swift-3-Design-Patterns
01-Simple_Factory_Pattern.playground/Contents.swift
1
1653
//: Playground - noun: a place where people can play // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Design-Patterns import UIKit // 协议 protocol Operator { var nums: (Double, Double) { get set } func getResult() -> Double? } // 遵守协议 struct Addition: Operator { var nums = (0.0, 0.0) func getResult() -> Double? { return nums.0 + nums.1 } } struct Subtraction: Operator { var nums = (0.0, 0.0) func getResult() -> Double? { return nums.0 - nums.1 } } struct Multiplication: Operator { var nums = (0.0, 0.0) func getResult() -> Double? { return nums.0 * nums.1 } } struct Division: Operator { var nums = (0.0, 0.0) func getResult() -> Double? { guard nums.1 != 0 else { return nil } return nums.0 / nums.1 } } // 操作符枚举 enum Operators { case addition, subtraction, multiplication, division } // 工厂 struct OperatorFactory { static func calculateForOperator(_ opt: Operators) -> Operator { switch opt { case .addition: return Addition() case .subtraction: return Subtraction() case .multiplication: return Multiplication() case .division: return Division() } } } var testDivision = OperatorFactory.calculateForOperator(.division) testDivision.nums = (1, 0) print(testDivision.getResult() ?? "Error") var testAddition = OperatorFactory.calculateForOperator(.addition) testAddition.nums = (1, 1) print(testAddition.getResult() ?? "Error")
apache-2.0
cbdcae3104e278ac3e6a87ac735a00ac
20.12987
90
0.596804
3.846336
false
true
false
false
bsorrentino/slidesOnTV
slides/slides/URL+Extensions.swift
1
1394
// // URL+Extensions.swift // slides // // Created by Bartolomeo Sorrentino on 21/12/21. // Copyright © 2021 bsorrentino. All rights reserved. // import Foundation import UIKit extension URL { static func fromXCAsset(name: String) -> URL? { let fileManager = FileManager.default guard let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first else {return nil} let url = cacheDirectory.appendingPathComponent("\(name).png") let path = url.path if !fileManager.fileExists(atPath: path) { guard let image = UIImage(named: name), let data = image.pngData() else {return nil} fileManager.createFile(atPath: path, contents: data, attributes: nil) } return url } static func fromXCAsset(systemName: String) -> URL? { let fileManager = FileManager.default guard let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask).first else {return nil} let url = cacheDirectory.appendingPathComponent("\(systemName).png") let path = url.path if !fileManager.fileExists(atPath: path) { guard let image = UIImage(systemName: systemName), let data = image.pngData() else {return nil} fileManager.createFile(atPath: path, contents: data, attributes: nil) } return url } }
mit
671feb366eb04adba30faca36c6d661e
37.694444
119
0.659009
4.422222
false
false
false
false
kouky/PrimaryFlightDisplay
Sources/TapeCellModel.swift
1
2221
// // TapeCellModel.swift // PrimaryFlightDisplay // // Created by Michael Koukoullis on 3/02/2016. // Copyright © 2016 Michael Koukoullis. All rights reserved. // public protocol TapeCellModelType { var lowerValue: Int { get } var upperValue: Int { get } var magnitude: UInt { get } var midValue: Double { get } func containsValue(value: Double) -> Bool func next() -> TapeCellModelType func previous() -> TapeCellModelType init(lowerValue: Int, upperValue: Int) } extension TapeCellModelType { var magnitude: UInt { return UInt(abs(upperValue - lowerValue)) } var midValue: Double { let halfRange = (Double(upperValue) - Double(lowerValue)) / 2 return Double(lowerValue) + halfRange } func containsValue(value: Double) -> Bool { return Double(lowerValue) <= value && value <= Double(upperValue) } func next() -> TapeCellModelType { return Self(lowerValue: upperValue, upperValue: upperValue + Int(magnitude)) } func previous() -> TapeCellModelType { return Self(lowerValue: lowerValue - Int(magnitude), upperValue: lowerValue) } } struct ContinuousTapeCellModel: TapeCellModelType { let lowerValue: Int let upperValue: Int init(lowerValue: Int, upperValue: Int) { guard upperValue > lowerValue else { fatalError("Tape cell model upper value must be smaller than lower value") } self.lowerValue = lowerValue self.upperValue = upperValue } } struct CompassTapeCellModel: TapeCellModelType { let lowerValue: Int let upperValue: Int init(lowerValue: Int, upperValue: Int) { guard upperValue > lowerValue else { fatalError("Tape cell model upper value must be smaller than lower value") } self.lowerValue = lowerValue self.upperValue = upperValue } } extension CompassTapeCellModel { func containsValue(value: Double) -> Bool { let leftValue = lowerValue.compassValue let rightValue = upperValue.compassValue == 0 ? 360 : upperValue.compassValue return leftValue <= value && value <= rightValue } }
mit
7fe07596a0a278a1c754d29212a71f69
27.101266
86
0.652252
4.530612
false
false
false
false
mrdepth/EVEUniverse
Legacy/Neocom/Neocom/NCIncursionTableViewCell.swift
2
2829
// // NCIncursionTableViewCell.swift // Neocom // // Created by Artem Shimanski on 22.06.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit import EVEAPI class NCIncursionTableViewCell: NCTableViewCell { @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var bossImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var stateLabel: UILabel! @IBOutlet weak var progressLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! override func awakeFromNib() { super.awakeFromNib() let layer = self.progressView.superview?.layer; layer?.borderColor = UIColor(number: 0x3d5866ff).cgColor layer?.borderWidth = 1.0 / UIScreen.main.scale } } extension Prototype { enum NCIncursionTableViewCell { static let `default` = Prototype(nib: nil, reuseIdentifier: "NCIncursionTableViewCell") } } class NCIncursionRow: TreeRow { let incursion: ESI.Incursions.Incursion let contact: NCContact? init(incursion: ESI.Incursions.Incursion, contact: NCContact?) { self.incursion = incursion self.contact = contact super.init(prototype: Prototype.NCIncursionTableViewCell.default) } lazy var title: String = { if let constellation = NCDatabase.sharedDatabase?.mapConstellations[self.incursion.constellationID] { return "\(constellation.constellationName ?? "") / \(constellation.region?.regionName ?? "")" } else { return NSLocalizedString("Unknown", comment: "") } }() lazy var solaySystem: NCLocation? = { guard let solarSystem = NCDatabase.sharedDatabase?.mapSolarSystems[self.incursion.stagingSolarSystemID] else {return nil} return NCLocation(solarSystem) }() private var image: UIImage? override func configure(cell: UITableViewCell) { guard let cell = cell as? NCIncursionTableViewCell else {return} cell.object = incursion cell.titleLabel.text = title cell.bossImageView.alpha = incursion.hasBoss ? 1.0 : 0.4 cell.progressView.progress = incursion.influence cell.progressLabel.text = NSLocalizedString("Warzone Control: ", comment: "") + "\(Int((incursion.influence * 100).rounded(.down)))%" cell.locationLabel.attributedText = solaySystem?.displayName cell.stateLabel.text = incursion.state.title cell.iconView.image = image if image == nil { NCDataManager().image(allianceID: Int64(incursion.factionID), dimension: Int(cell.iconView.bounds.size.width)).then(on: .main) { result in self.image = result.value ?? UIImage() if (cell.object as? ESI.Incursions.Incursion) == self.incursion { cell.iconView.image = self.image } } } } override var hash: Int { return incursion.hashValue } override func isEqual(_ object: Any?) -> Bool { return (object as? NCIncursionRow)?.hashValue == hashValue } }
lgpl-2.1
da4134c59e5e0bf4c469fa23cbe749c8
30.076923
141
0.73727
3.530587
false
false
false
false
GrandCentralBoard/GrandCentralBoard
GrandCentralBoard/Widgets/GitHub/View/EllipseView.swift
2
851
// // EllipseView.swift // GrandCentralBoard // // Created by mlaskowski on 21/05/16. // Copyright © 2016 Oktawian Chojnacki. All rights reserved. // import UIKit @IBDesignable final class EllipseView: UIView { @IBInspectable var color: UIColor = .blackColor() { didSet { setNeedsDisplay() } } @IBInspectable var strokeWidth: CGFloat = 1 { didSet { setNeedsDisplay() } } override func drawRect(rect: CGRect) { let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextSetLineWidth(context, strokeWidth) let margin = strokeWidth / 2 let strokedRect = CGRect(x: margin, y: margin, width: rect.width - margin * 2, height: rect.height - margin * 2) CGContextStrokeEllipseInRect(context, strokedRect) } }
gpl-3.0
022b2302696131dca55bc6c4564cde2f
26.419355
120
0.675294
4.497354
false
false
false
false
LKY769215561/KYPageView
KYPageView/KYPageView/Classes/KYPageStyle.swift
2
1419
// // HYPageStyle.swift // KYPageView // // Created by Kerain on 2017/3/14. // Copyright © 2017年 Kerain. All rights reserved. // import UIKit struct KYPageStyle { // MARK:文字底部滚动条 // 选项卡条背景色 var titleViewBG : UIColor = UIColor.white // 选项卡条高度 var tabHeight:CGFloat = 40 // 选项卡标题间距 let titleMargin:CGFloat = 10 // 选项卡字体普通颜色 var normalColor : UIColor = UIColor.lightGray // 选项卡字体选中颜色 var selectColor : UIColor = UIColor.red // 选项卡字体 var titleFont : UIFont = UIFont.boldSystemFont(ofSize: 15) // 选项卡是否可以滚动 var isScrollEnable : Bool = false // 颜色渐变 var titleColorChange : Bool = true // 是否显示文字底部滑动 var isShowBottomLine : Bool = true // MARK:文字底部滚动条 // 默认等于文字宽度 否则会平分屏幕宽度 var isEqueToTitleLength : Bool = true // 背景色 var bottomLineBackGroundColor : UIColor = UIColor.red // 高度 var bottomLineHeight : CGFloat = 1 // MARK:选项卡内容区 // 背景色 var contentViewBG : UIColor = UIColor.lightGray var bottomLineY : CGFloat = 0 init() { bottomLineY = tabHeight - bottomLineHeight } }
apache-2.0
b56a8d4fc4906cea16a59fb3e8f12171
18.258065
62
0.596315
3.754717
false
false
false
false
chatspry/rubygens
Pods/Nimble/Nimble/Adapters/AssertionRecorder.swift
46
3643
import Foundation /// A data structure that stores information about an assertion when /// AssertionRecorder is set as the Nimble assertion handler. /// /// @see AssertionRecorder /// @see AssertionHandler public struct AssertionRecord: CustomStringConvertible { /// Whether the assertion succeeded or failed public let success: Bool /// The failure message the assertion would display on failure. public let message: FailureMessage /// The source location the expectation occurred on. public let location: SourceLocation public var description: String { return "AssertionRecord { success=\(success), message='\(message.stringValue)', location=\(location) }" } } /// An AssertionHandler that silently records assertions that Nimble makes. /// This is useful for testing failure messages for matchers. /// /// @see AssertionHandler public class AssertionRecorder : AssertionHandler { /// All the assertions that were captured by this recorder public var assertions = [AssertionRecord]() public init() {} public func assert(assertion: Bool, message: FailureMessage, location: SourceLocation) { assertions.append( AssertionRecord( success: assertion, message: message, location: location)) } } /// Allows you to temporarily replace the current Nimble assertion handler with /// the one provided for the scope of the closure. /// /// Once the closure finishes, then the original Nimble assertion handler is restored. /// /// @see AssertionHandler public func withAssertionHandler(tempAssertionHandler: AssertionHandler, closure: () -> Void) { let oldRecorder = NimbleAssertionHandler let capturer = NMBExceptionCapture(handler: nil, finally: ({ NimbleAssertionHandler = oldRecorder })) NimbleAssertionHandler = tempAssertionHandler capturer.tryBlock { closure() } } /// Captures expectations that occur in the given closure. Note that all /// expectations will still go through to the default Nimble handler. /// /// This can be useful if you want to gather information about expectations /// that occur within a closure. /// /// @param silently expectations are no longer send to the default Nimble /// assertion handler when this is true. Defaults to false. /// /// @see gatherFailingExpectations public func gatherExpectations(silently: Bool = false, closure: () -> Void) -> [AssertionRecord] { let previousRecorder = NimbleAssertionHandler let recorder = AssertionRecorder() let handlers: [AssertionHandler] if silently { handlers = [recorder] } else { handlers = [recorder, previousRecorder] } let dispatcher = AssertionDispatcher(handlers: handlers) withAssertionHandler(dispatcher, closure: closure) return recorder.assertions } /// Captures failed expectations that occur in the given closure. Note that all /// expectations will still go through to the default Nimble handler. /// /// This can be useful if you want to gather information about failed /// expectations that occur within a closure. /// /// @param silently expectations are no longer send to the default Nimble /// assertion handler when this is true. Defaults to false. /// /// @see gatherExpectations /// @see raiseException source for an example use case. public func gatherFailingExpectations(silently: Bool = false, closure: () -> Void) -> [AssertionRecord] { let assertions = gatherExpectations(silently, closure: closure) return assertions.filter { assertion in !assertion.success } }
mit
71ad79d42d4516e7fe706a40606d4824
35.808081
111
0.714521
5.031768
false
false
false
false
dreamsxin/swift
validation-test/compiler_crashers_fixed/01028-swift-camel-case-getfirstword.swift
11
1078
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse print("") import Founda (h() as p).dynamicType.g() func j<f: l: e -> e = { { l) { m } } protocol k { } class e: k{ class func j class A : NSManagedObject { func b<T: A>() -> [T] { } } extension NSSet { init <A: A f<T>() -> T -> T { } } protocol P { } struct d<f : e, g: e where g.h == f.h> {{ } struct B<T : A> { } protocol C { ty } } func b<d-> d { class d:b class b protocol A { } func f() { } func ^(d: e, Bool) -> Bool {g !(d) } protocol d { f k } } protocol n { } class o: n{ cla) u p).v.c() k e.w == l> { ) -> (i o " class m: f { j h) { } func j() { } func j<d { enum j { } } struct j<d : Sequencpe> { } func f<d>() -> [j<d>] { let d: Int = { convenience init(array: Atati
apache-2.0
826f961e0c83c6ab40a98c42daf62ef0
15.584615
78
0.592764
2.554502
false
false
false
false
thelowlypeon/bikeshare-kit
BikeshareKit/BikeshareKit/Persistence/BSPersistentServices.swift
1
1739
// // BSPersistentServices.swift // BikeshareKit // // Created by Peter Compernolle on 12/22/15. // Copyright © 2015 Out of Something, LLC. All rights reserved. // import Foundation private var kBSManagerServices = "bikeshare_kit__services" private var kBSManagerFavoriteServiceID = "bikeshare_kit__favorite_service_id" extension BSManager { public func persistServices() { let data = NSKeyedArchiver.archivedData(withRootObject: services) UserDefaults.standard.set(data, forKey: kBSManagerServices) } public func persistFavoriteService() { if let service = favoriteService { UserDefaults.standard.set(service.id, forKey: kBSManagerFavoriteServiceID) } else { //cannot remove integer for some reason, so set it to invalid ID UserDefaults.standard.set(-1, forKey: kBSManagerFavoriteServiceID) } } public func restoreServices() { if let unarchivedServicesData = UserDefaults.standard.object(forKey: kBSManagerServices) as? Data { if let unarchivedServices = NSKeyedUnarchiver.unarchiveObject(with: unarchivedServicesData) as? Set<BSService> { self.services = unarchivedServices } } } //caution! do this only after services are restored or otherwise populated // calling this with no services in self.services will remove favorite public func restoreFavoriteService() { let favoriteServiceID = UserDefaults.standard.integer(forKey: kBSManagerFavoriteServiceID) // do not call refreshFavoriteService because that will yield a different service instance self.favoriteService = self.services.filter{$0.id == favoriteServiceID}.first } }
mit
b0856ed2ccd97a2190b8985563755c2e
37.622222
124
0.709436
4.549738
false
false
false
false
andrebocchini/SwiftChatty
SwiftChatty/Requests/Client Data/SetCategoryFiltersRequest.swift
1
997
// // SetCategoryFiltersRequest.swift // SwiftChatty // // Created by Andre Bocchini on 1/27/16. // Copyright © 2016 Andre Bocchini. All rights reserved. import Alamofire /// -SeeAlso: http://winchatty.com/v2/readme#_Toc421451698 public struct SetCategoryFiltersRequest: Request { public let endpoint: ApiEndpoint = .SetCategoryFilters public let httpMethod: HTTPMethod = .post public var customParameters: [String : Any] = [:] public init(withUsername username: String, nws: Bool, stupid: Bool, political: Bool, tangent: Bool, informative: Bool) { self.customParameters["username"] = username self.customParameters["nws"] = nws ? "true" : "false" self.customParameters["stupid"] = stupid ? "true" : "false" self.customParameters["political"] = political ? "true" : "false" self.customParameters["tangent"] = tangent ? "true" : "false" self.customParameters["informative"] = informative ? "true" : "false" } }
mit
d3bfe404ec5a59b582c1652e0070814b
34.571429
88
0.675703
3.92126
false
false
false
false
harlanhaskins/swift
test/Driver/PrivateDependencies/fail-simple-fine.swift
1
1827
/// bad ==> main | bad --> other // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/fail-simple-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./main.swift ./bad.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // CHECK-FIRST-NOT: warning // CHECK-FIRST: Handled main.swift // CHECK-FIRST: Handled bad.swift // CHECK-FIRST: Handled other.swift // RUN: touch -t 201401240006 %t/bad.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./bad.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s // RUN: %FileCheck -check-prefix=CHECK-RECORD %s < %t/main~buildrecord.swiftdeps // CHECK-SECOND: Handled bad.swift // CHECK-SECOND-NOT: Handled main.swift // CHECK-SECOND-NOT: Handled other.swift // CHECK-RECORD-DAG: "./bad.swift": !private [ // CHECK-RECORD-DAG: "./main.swift": !private [ // CHECK-RECORD-DAG: "./other.swift": !private [ // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./bad.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-THIRD %s // CHECK-THIRD-DAG: Handled main.swift // CHECK-THIRD-DAG: Handled bad.swift // CHECK-THIRD-DAG: Handled other.swift
apache-2.0
f5f040060b401f3872a4d1ef69207e52
59.9
352
0.718664
3.216549
false
false
false
false
sag333ar/sagarrkothari.com
nToDo/nToDo/nToDo/SidePanels/Center/ViewController/ViewController.swift
1
6240
// // ViewController.swift // nToDo // // Created by Kothari, Sagar on 8/17/17. // Copyright © 2017 Sagar R. Kothari. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var tableViewDelegate: ViewControllerTableViewDelegate! @IBOutlet weak var searchBar: UISearchBar! weak var listViewController: ListViewController! var titleButton: UIButton? var isExpanded: Bool = false { didSet { updateTitle() } } var titleForButton: String = "All Tasks" { didSet { updateTitle() } } @IBOutlet weak var layoutConstraintListBottom: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() // storeData() // let list1 = List(context: context) // list1.title = "HomeToDos" // let list2 = List(context: context) // list2.title = "Viman Nagar" // let list3 = List(context: context) // list3.title = "Movies to watch" // appDel.saveContext() addTitleView() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) collapseListView() } @objc func navigationItemTapped() { if layoutConstraintListBottom.constant < 0 { expandListView() } else { collapseListView() } } func expandListView() { isExpanded = true layoutConstraintListBottom.constant = 0 animateListView() } func collapseListView() { isExpanded = false layoutConstraintListBottom.constant = (tableView.frame.size.height + tableView.frame.origin.y ) * -1 animateListView() } func animateListView() { view.setNeedsUpdateConstraints() UIView.animate(withDuration: 0.25, animations: { self.view.layoutIfNeeded() }, completion: nil) } func addTitleView() { let rect = CGRect(x: 0, y: 0, width: 200, height: 40) titleButton = UIButton(frame: rect) titleButton?.setTitleColor(navigationController?.navigationBar.tintColor, for: .normal) titleButton?.titleLabel?.font = UIFont.boldSystemFont(ofSize: 17) titleButton?.backgroundColor = UIColor.clear titleButton?.titleLabel?.adjustsFontSizeToFitWidth = true titleButton?.titleLabel?.textAlignment = .center titleButton?.addTarget(self, action: #selector(ViewController.navigationItemTapped), for: .touchUpInside) self.navigationItem.titleView = titleButton } func updateTitle() { let arrow = isExpanded ? "↑" : "↓" titleButton?.setTitle("\(arrow) \(titleForButton)", for: .normal) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "listview", let listview = segue.destination as? ListViewController { listViewController = listview listViewController.viewController = self } } } extension ViewController { func getTomorrowDate() -> Date { let cal = NSCalendar.current let now = Date() let compSet = Set(arrayLiteral:Calendar.Component.day, Calendar.Component.month, Calendar.Component.year) var comp = cal.dateComponents(compSet as Set<Calendar.Component>, from: now) comp.timeZone = TimeZone.current comp.day = comp.day! + 1 return cal.date(from: comp)! } func storeData() { let location1 = Location(context: context) location1.title = "Brahma Suncity" let location2 = Location(context: context) location2.title = "Viman Nagar" let location3 = Location(context: context) location3.title = "Pimpri Chinchwad" let location4 = Location(context: context) location4.title = "Lunkad Gardens" let location5 = Location(context: context) location5.title = "Durshet, Maharashtra" let location6 = Location(context: context) location6.title = "Swati Greens" let location7 = Location(context: context) location7.title = "Shukan Homes" let tag1 = Tag(context: context) tag1.title = "Important" let tag2 = Tag(context: context) tag2.title = "Dreams" let tag3 = Tag(context: context) tag3.title = "Ideas" let tag4 = Tag(context: context) tag4.title = "Budget" let tag5 = Tag(context: context) tag5.title = "Expenses" let list1 = List(context: context) list1.title = "Inbox" let task1 = Task(context: context) task1.title = "Remember the milk" task1.priority = 1 task1.estimate = 1 task1.start = Date() task1.due = getTomorrowDate() task1.locations = location1 task1.list = list1 task1.tags = NSSet(arrayLiteral: tag1, tag2) task1.completed = false appDel.saveContext() } } /** let location1 = Location(context: context) location1.title = "Brahma Suncity" let location2 = Location(context: context) location2.title = "Viman Nagar" let location3 = Location(context: context) location3.title = "Pimpri Chinchwad" let location4 = Location(context: context) location4.title = "Lunkad Gardens" let location5 = Location(context: context) location5.title = "Durshet, Maharashtra" let location6 = Location(context: context) location6.title = "Swati Greens" let location7 = Location(context: context) location7.title = "Shukan Homes" let tag1 = Tag(context: context) tag1.title = "Important" let tag2 = Tag(context: context) tag2.title = "Dreams" let tag3 = Tag(context: context) tag3.title = "Ideas" let tag4 = Tag(context: context) tag4.title = "Budget" let tag5 = Tag(context: context) tag5.title = "Expenses" let list1 = List(context: context) list1.title = "Inbox" AppDel.saveContext() let task1 = Task(context: context) task1.title = "Remember the milk" task1.priority = 1 task1.estimate = 1 task1.start = Date() task1.due = getTomorrowDate() task1.locations = locations[0] task1.list = lists[0] task1.tags = NSSet(arrayLiteral: tags[0], tags[1]) */ /* do { locations = try context.fetch(Location.fetchRequest()) } catch { locations = [] } */
mit
904337971443ed4daef00a446dfc14b3
27.865741
96
0.66239
3.918919
false
false
false
false
lzpfmh/actor-platform
actor-apps/app-ios/ActorApp/Resources/AppTheme.swift
1
15037
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation var MainAppTheme = AppTheme() class AppTheme { var navigation: AppNavigationBar { get { return AppNavigationBar() } } var tab: AppTabBar { get { return AppTabBar() } } var search: AppSearchBar { get { return AppSearchBar() } } var list: AppList { get { return AppList() } } var bubbles: ChatBubbles { get { return ChatBubbles() } } var text: AppText { get { return AppText() } } var chat: AppChat { get { return AppChat() } } var common: AppCommon { get { return AppCommon() } } var placeholder: AppPlaceholder { get { return AppPlaceholder() } } func applyAppearance(application: UIApplication) { navigation.applyAppearance(application) tab.applyAppearance(application) search.applyAppearance(application) list.applyAppearance(application) } } class AppText { var textPrimary: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var bigAvatarPrimary: UIColor { get { return UIColor.whiteColor() } } var bigAvatarSecondary: UIColor { get { return UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1) } } } class AppPlaceholder { var textTitle: UIColor { get { return UIColor.RGB(0x5085CB) } } var textHint: UIColor { get { return UIColor(red: 80/255.0, green: 80/255.0, blue: 80/255.0, alpha: 1.0) } } } class AppChat { var chatField: UIColor { get { return UIColor.whiteColor() } } var attachColor: UIColor { get { return UIColor.RGB(0x5085CB) } } var sendEnabled: UIColor { get { return UIColor.RGB(0x50A1D6) } } var sendDisabled: UIColor { get { return UIColor.alphaBlack(0.56) } } var profileBgTint: UIColor { get { return UIColor.RGB(0x5085CB) } } var autocompleteHighlight: UIColor { get { return UIColor.RGB(0x5085CB) } } } class AppCommon { var isDarkKeyboard: Bool { get { return false } } var tokenFieldText: UIColor { get { return UIColor.alphaBlack(0xDE/255.0) } } var tokenFieldTextSelected: UIColor { get { return UIColor.alphaBlack(0xDE/255.0) } } var tokenFieldBg: UIColor { get { return UIColor.RGB(0x5085CB) } } var placeholders: [UIColor] { get { return [UIColor.RGB(0x59b7d3), UIColor.RGB(0x1d4e6f), UIColor.RGB(0x995794), UIColor.RGB(0xff506c), UIColor.RGB(0xf99341), UIColor.RGB(0xe4d027), UIColor.RGB(0x87c743)] } } } class ChatBubbles { // Basic colors var text : UIColor { get { return UIColor.RGB(0x141617) } } var textUnsupported : UIColor { get { return UIColor.RGB(0x50b1ae) } } var bgOut: UIColor { get { return UIColor.RGB(0xD2FEFD) } } var bgOutBorder: UIColor { get { return UIColor.RGB(0x99E4E3) } } var bgIn : UIColor { get { return UIColor.whiteColor() } } var bgInBorder:UIColor { get { return UIColor.RGB(0xCCCCCC) } } var statusActive : UIColor { get { return UIColor.RGB(0x3397f9) } } var statusPassive : UIColor { get { return UIColor.alphaBlack(0.27) } } // TODO: Fix var statusDanger : UIColor { get { return UIColor.redColor() } } var statusMediaActive : UIColor { get { return UIColor.RGB(0x1ed2f9) } } var statusMediaPassive : UIColor { get { return UIColor.whiteColor() } } // TODO: Fix var statusMediaDanger : UIColor { get { return UIColor.redColor() } } var statusDialogActive : UIColor { get { return UIColor.RGB(0x3397f9) } } var statusDialogPassive : UIColor { get { return UIColor.alphaBlack(0.27) } } // TODO: Fix var statusDialogDanger : UIColor { get { return UIColor.redColor() } } // Dialog-based colors var statusDialogSending : UIColor { get { return statusDialogPassive } } var statusDialogSent : UIColor { get { return statusDialogPassive } } var statusDialogReceived : UIColor { get { return statusDialogPassive } } var statusDialogRead : UIColor { get { return statusDialogActive } } var statusDialogError : UIColor { get { return statusDialogDanger } } // Text-based bubble colors var statusSending : UIColor { get { return statusPassive } } var statusSent : UIColor { get { return statusPassive } } var statusReceived : UIColor { get { return statusPassive } } var statusRead : UIColor { get { return statusActive } } var statusError : UIColor { get { return statusDanger } } var textBgOut: UIColor { get { return bgOut } } var textBgOutBorder : UIColor { get { return bgOutBorder } } var textBgIn : UIColor { get { return bgIn } } var textBgInBorder : UIColor { get { return bgInBorder } } var textDateOut : UIColor { get { return UIColor.alphaBlack(0.27) } } var textDateIn : UIColor { get { return UIColor.RGB(0x979797) } } var textOut : UIColor { get { return text } } var textIn : UIColor { get { return text } } var textUnsupportedOut : UIColor { get { return textUnsupported } } var textUnsupportedIn : UIColor { get { return textUnsupported } } // Media-based bubble colors var statusMediaSending : UIColor { get { return statusMediaPassive } } var statusMediaSent : UIColor { get { return statusMediaPassive } } var statusMediaReceived : UIColor { get { return statusMediaPassive } } var statusMediaRead : UIColor { get { return statusMediaActive } } var statusMediaError : UIColor { get { return statusMediaDanger } } var mediaBgOut: UIColor { get { return UIColor.whiteColor() } } var mediaBgOutBorder: UIColor { get { return UIColor.RGB(0xCCCCCC) } } var mediaBgIn: UIColor { get { return mediaBgOut } } var mediaBgInBorder: UIColor { get { return mediaBgOutBorder } } var mediaDateBg: UIColor { get { return UIColor.RGB(0x2D394A, alpha: 0.54) } } var mediaDate: UIColor { get { return UIColor.whiteColor() } } // Service-based bubble colors var serviceBg: UIColor { get { return UIColor.RGB(0x2D394A, alpha: 0.56) } } var chatBgTint: UIColor { get { return UIColor.RGB(0xe7e0c4) } } } class AppList { var actionColor : UIColor { get { return UIColor.RGB(0x5085CB) } } var bgColor: UIColor { get { return UIColor.whiteColor() } } var bgSelectedColor : UIColor { get { return UIColor.RGB(0xd9d9d9) } } var backyardColor : UIColor { get { return UIColor(red: 238/255.0, green: 238/255.0, blue: 238/255.0, alpha: 1) } } var separatorColor : UIColor { get { return UIColor.RGB(0xd4d4d4) } } var textColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var hintColor : UIColor { get { return UIColor(red: 164/255.0, green: 164/255.0, blue: 164/255.0, alpha: 1) } } var sectionColor : UIColor { get { return UIColor.RGB(0x5b5a60) } } var sectionHintColor : UIColor { get { return UIColor.RGB(0x5b5a60) } } // var arrowColor : UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var dialogTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var dialogText: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x8A/255.0) } } var dialogDate: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0x8A/255.0) } } var unreadText: UIColor { get { return UIColor.whiteColor() } } var unreadBg: UIColor { get { return UIColor.RGB(0x50A1D6) } } var contactsTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } var contactsShortTitle: UIColor { get { return UIColor(red: 0, green: 0, blue: 0, alpha: 0xDE/255.0) } } func applyAppearance(application: UIApplication) { UITableViewHeaderFooterView.appearance().tintColor = sectionColor } } class AppSearchBar { var statusBarLightContent : Bool { get { return false } } var backgroundColor : UIColor { get { return UIColor.RGB(0xf1f1f1) } } var cancelColor : UIColor { get { return UIColor.RGB(0x8E8E93) } } var fieldBackgroundColor: UIColor { get { return UIColor.whiteColor() } } var fieldTextColor: UIColor { get { return UIColor.blackColor().alpha(0.56) } } func applyAppearance(application: UIApplication) { // SearchBar Text Color let textField = UITextField.my_appearanceWhenContainedIn(UISearchBar.self) // textField.tintColor = UIColor.redColor() let font = UIFont.systemFontOfSize(14) textField.defaultTextAttributes = [NSFontAttributeName: font, NSForegroundColorAttributeName : fieldTextColor] } func applyStatusBar() { if (statusBarLightContent) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) } else { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) } } func styleSearchBar(searchBar: UISearchBar) { // SearchBar Minimal Style searchBar.searchBarStyle = UISearchBarStyle.Default // SearchBar Transculent searchBar.translucent = false // SearchBar placeholder animation fix searchBar.placeholder = ""; // SearchBar background color searchBar.barTintColor = backgroundColor.forTransparentBar() searchBar.setBackgroundImage(Imaging.imageWithColor(backgroundColor, size: CGSize(width: 1, height: 1)), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default) searchBar.backgroundColor = backgroundColor // SearchBar field color let fieldBg = Imaging.imageWithColor(fieldBackgroundColor, size: CGSize(width: 14,height: 28)) .roundCorners(14, h: 28, roundSize: 4) searchBar.setSearchFieldBackgroundImage(fieldBg.stretchableImageWithLeftCapWidth(7, topCapHeight: 0), forState: UIControlState.Normal) // SearchBar cancel color searchBar.tintColor = cancelColor // Apply keyboard color searchBar.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light } } class AppTabBar { private let mainColor = UIColor.RGB(0x5085CB) var backgroundColor : UIColor { get { return UIColor.whiteColor() } } var showText : Bool { get { return true } } var selectedIconColor: UIColor { get { return mainColor } } var selectedTextColor : UIColor { get { return mainColor } } var unselectedIconColor:UIColor { get { return UIColor.RGB(0x929292) } } var unselectedTextColor : UIColor { get { return UIColor.RGB(0x949494) } } var barShadow : String? { get { return "CardTop2" } } func createSelectedIcon(name: String) -> UIImage { return UIImage(named: name)!.tintImage(selectedIconColor) .imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) } func createUnselectedIcon(name: String) -> UIImage { return UIImage(named: name)!.tintImage(unselectedIconColor) .imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) } func applyAppearance(application: UIApplication) { let tabBar = UITabBar.appearance() // TabBar Background color tabBar.barTintColor = backgroundColor; // // TabBar Shadow // if (barShadow != nil) { // tabBar.shadowImage = UIImage(named: barShadow!); // } else { // tabBar.shadowImage = nil // } let tabBarItem = UITabBarItem.appearance() // TabBar Unselected Text tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: unselectedTextColor], forState: UIControlState.Normal) // TabBar Selected Text tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: selectedTextColor], forState: UIControlState.Selected) } } class AppNavigationBar { var statusBarLightContent : Bool { get { return true } } var barColor:UIColor { get { return /*UIColor.RGB(0x5085CB)*/ UIColor.RGB(0x3576cc) } } var barSolidColor:UIColor { get { return UIColor.RGB(0x5085CB) } } var titleColor: UIColor { get { return UIColor.whiteColor() } } var subtitleColor: UIColor { get { return UIColor.whiteColor() } } var subtitleActiveColor: UIColor { get { return UIColor.whiteColor() } } var shadowImage : String? { get { return nil } } var progressPrimary: UIColor { get { return UIColor.RGB(0x1484ee) } } var progressSecondary: UIColor { get { return UIColor.RGB(0xaccceb) } } func applyAppearance(application: UIApplication) { // StatusBar style if (statusBarLightContent) { application.statusBarStyle = UIStatusBarStyle.LightContent } else { application.statusBarStyle = UIStatusBarStyle.Default } let navAppearance = UINavigationBar.appearance(); // NavigationBar Icon navAppearance.tintColor = titleColor; // NavigationBar Text navAppearance.titleTextAttributes = [NSForegroundColorAttributeName: titleColor]; // NavigationBar Background navAppearance.barTintColor = barColor; // navAppearance.setBackgroundImage(Imaging.imageWithColor(barColor, size: CGSize(width: 1, height: 1)), forBarMetrics: UIBarMetrics.Default) // navAppearance.shadowImage = Imaging.imageWithColor(barColor, size: CGSize(width: 1, height: 2)) // Small hack for correct background color UISearchBar.appearance().backgroundColor = barColor // NavigationBar Shadow // navAppearance.shadowImage = nil // if (shadowImage == nil) { // navAppearance.shadowImage = UIImage() // navAppearance.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) // } else { // navAppearance.shadowImage = UIImage(named: shadowImage!) // } } func applyAuthStatusBar() { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) } func applyStatusBar() { if (statusBarLightContent) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) } else { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: true) } } func applyStatusBarFast() { if (statusBarLightContent) { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false) } else { UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.Default, animated: false) } } }
mit
183154e8cbc86b41a6d33e7710558d01
41.480226
181
0.657711
4.410971
false
false
false
false
skyfe79/TIL
about.iOS/about.Swift/18.ErrorHandling.playground/Contents.swift
1
4600
/*: # Error Handling */ import UIKit /*: ## Representing and Throwing Errors */ do { enum VendingMachineError: ErrorType { case InvalidSelection case InsufficientFunds(coinsNeeded: Int) case OutOfStock } //throw VendingMachineError.InsufficientFunds(coinsNeeded: 5) } /*: ## Handling Errors */ /*: ### Propagating Errors Using Throwing Functions */ do { func canThrowErrors() throws -> String { return "" } func cannotThrowErrors() -> String { return "" } } do { enum VendingMachineError: ErrorType { case InvalidSelection case InsufficientFunds(coinsNeeded: Int) case OutOfStock } struct Item { var price: Int var count: Int } class VendingMachine { var inventory = [ "Candy Bar": Item(price: 12, count: 7), "Chips": Item(price: 10, count: 4), "Pretzels": Item(price: 7, count: 11) ] var coinsDeposited = 0 func dispenseSnack(snack: String) { print("Dispensing \(snack)") } func vend(itemNamed name: String) throws { guard let item = inventory[name] else { throw VendingMachineError.InvalidSelection } guard item.count > 0 else { throw VendingMachineError.OutOfStock } guard item.price <= coinsDeposited else { throw VendingMachineError.InsufficientFunds(coinsNeeded: item.price - coinsDeposited) } coinsDeposited -= item.price var newItem = item newItem.count -= 1 inventory[name] = newItem dispenseSnack(name) } } let favoriteSnacks = [ "Alice": "Chips", "Bob": "Licorice", "Eve": "Pretzels", ] // propagation func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws { let snackName = favoriteSnacks[person] ?? "Candy Bar" try vendingMachine.vend(itemNamed: snackName) } struct PurchasedSnack { let name: String // propagation init(name: String, vendingMachine: VendingMachine) throws { try vendingMachine.vend(itemNamed: name) self.name = name } } // 예외 처리 var vendingMachine = VendingMachine() vendingMachine.coinsDeposited = 8 do { try buyFavoriteSnack("Alice", vendingMachine: vendingMachine) } catch VendingMachineError.InvalidSelection { print("Invalid Selection.") } catch VendingMachineError.OutOfStock { print("Out of Stock.") } catch VendingMachineError.InsufficientFunds(let coinsNeeded) { print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.") } // Prints "Insufficient funds. Please insert an additional 2 coins." } /*: ## Converting Errors to Optional Values * You use try? to handle an error by converting it to an optional value * If an error is thrown while evaluating the try? expression, the value of the expression is nil. */ do { func someThrowingFunction() throws -> Int { // ... return 10 } let x = try? someThrowingFunction() // 아래의 코드를 let y: Int? do { y = try someThrowingFunction() } catch { y = nil } // 아래처럼 쓸 수 있다. /* func fetchData() -> Data? { if let data = try? fetchDataFromDisk() { return data } if let data = try? fetchDataFromServer() { return data } return nil } */ } /*: ## Disabling Error Propagation * sometimes you know a throwing function or method won’t, in fact, throw an error at runtime. * On those occasions, you can write try! before the expression to disable error propagation and wrap the call in a runtime assertion that no error will be thrown. * !!! If an error actually is thrown, you’ll get a runtime error. */ do { // let photo = try! loadImage("./Resources/John Appleseed.jpg") } /*: ## Specifying Cleanup Actions */ do { func processFile(filename: String) throws { if exists(filename) { let file = open(filename) defer { close(file) } while let line = try file.readline() { // Work with the file. } // close(file) is called here, at the end of the scope. } } }
mit
8278fb4b01534c6299ef69a6611bbf12
24.909091
163
0.577412
4.701031
false
false
false
false
huangboju/Moots
UICollectionViewLayout/CollectionKit-master/Sources/Other/LayoutHelper.swift
2
3169
// // LayoutHelper.swift // CollectionKit // // Created by Luke Zhao on 2017-09-08. // Copyright © 2017 lkzhao. All rights reserved. // import UIKit public enum JustifyContent { case start, end, center, spaceBetween, spaceAround, spaceEvenly } public typealias AlignContent = JustifyContent public enum AlignItem { case start, end, center, stretch } struct LayoutHelper { static func alignItem<SizeArray: Sequence>(alignItems: AlignItem, startingPrimaryOffset: CGFloat, spacing: CGFloat, sizes: SizeArray, secondaryRange: ClosedRange<CGFloat>) -> [CGRect] where SizeArray.Iterator.Element == CGSize { var frames: [CGRect] = [] var offset = startingPrimaryOffset for cellSize in sizes { let cellFrame: CGRect switch alignItems { case .start: cellFrame = CGRect(origin: CGPoint(x: offset, y: secondaryRange.lowerBound), size: cellSize) case .end: cellFrame = CGRect(origin: CGPoint(x: offset, y: secondaryRange.upperBound - cellSize.height), size: cellSize) case .center: let secondaryOffset = secondaryRange.lowerBound + (secondaryRange.upperBound - secondaryRange.lowerBound - cellSize.height) / 2 cellFrame = CGRect(origin: CGPoint(x: offset, y: secondaryOffset), size: cellSize) case .stretch: cellFrame = CGRect(origin: CGPoint(x: offset, y: secondaryRange.lowerBound), size: CGSize(width: cellSize.width, height: secondaryRange.upperBound - secondaryRange.lowerBound)) } frames.append(cellFrame) offset += cellSize.width + spacing } return frames } static func distribute(justifyContent: JustifyContent, maxPrimary: CGFloat, totalPrimary: CGFloat, minimunSpacing: CGFloat, numberOfItems: Int) -> (offset: CGFloat, spacing: CGFloat) { var offset: CGFloat = 0 var spacing = minimunSpacing guard numberOfItems > 0 else { return (offset, spacing) } if totalPrimary + CGFloat(numberOfItems - 1) * minimunSpacing < maxPrimary { let leftOverPrimary = maxPrimary - totalPrimary switch justifyContent { case .start: break case .center: offset += (leftOverPrimary - minimunSpacing * CGFloat(numberOfItems - 1)) / 2 case .end: offset += (leftOverPrimary - minimunSpacing * CGFloat(numberOfItems - 1)) case .spaceBetween: guard numberOfItems > 1 else { break } spacing = leftOverPrimary / CGFloat(numberOfItems - 1) case .spaceAround: spacing = leftOverPrimary / CGFloat(numberOfItems) offset = spacing / 2 case .spaceEvenly: spacing = leftOverPrimary / CGFloat(numberOfItems + 1) offset = spacing } } return (offset, spacing) } }
mit
360b7cf82de9aff18be64ff66a3fd053
35.837209
103
0.590278
4.926905
false
false
false
false
huonw/swift
test/Compatibility/MixAndMatch/Inputs/witness_change_swift4.swift
20
2391
// Swift 3 sees the ObjC class NSRuncibleSpoon as the class, and uses methods // with type signatures involving NSRuncibleSpoon to conform to protocols // across the language boundary. Swift 4 sees the type as bridged to // a RuncibleSpoon value type, but still needs to be able to use conformances // declared by Swift 3. // Swift 4 import SomeObjCModule import SomeSwift3Module public func testMixAndMatch(bridged: RuncibleSpoon, unbridged: NSRuncibleSpoon) { let objcInstanceViaClass = SomeObjCClass(someSwiftInitRequirement: bridged) let objcClassAsProtocol: SomeSwift3Protocol.Type = SomeObjCClass.self let objcInstanceViaProtocol = objcClassAsProtocol.init(someSwiftInitRequirement: unbridged) var bridgedSink: RuncibleSpoon var unbridgedSink: NSRuncibleSpoon let swiftPropertyViaClass = objcInstanceViaClass.someSwiftPropertyRequirement bridgedSink = swiftPropertyViaClass let swiftPropertyViaProtocol = objcInstanceViaProtocol.someSwiftPropertyRequirement unbridgedSink = swiftPropertyViaProtocol objcInstanceViaClass.someSwiftMethodRequirement(bridged) objcInstanceViaProtocol.someSwiftMethodRequirement(unbridged) let swiftInstanceViaClass = SomeSwift3Class(someObjCInitRequirement: unbridged) let swiftClassAsProtocol: SomeObjCProtocol.Type = SomeSwift3Class.self let swiftInstanceViaProtocol = swiftClassAsProtocol.init(someObjCInitRequirement: bridged) let objcPropertyViaClass = swiftInstanceViaClass.someObjCPropertyRequirement unbridgedSink = objcPropertyViaClass let objcPropertyViaProtocol = swiftInstanceViaProtocol.someObjCPropertyRequirement bridgedSink = objcPropertyViaProtocol swiftInstanceViaClass.someObjCMethodRequirement(unbridged) swiftInstanceViaProtocol.someObjCMethodRequirement(bridged) _ = bridgedSink _ = unbridgedSink } public protocol SomeSwift4Protocol { init(someSwiftInitRequirement: RuncibleSpoon) func someSwiftMethodRequirement(_: RuncibleSpoon) var someSwiftPropertyRequirement: RuncibleSpoon { get } } extension SomeObjCClass: SomeSwift4Protocol {} public class SomeSwift4Class: NSObject { public required init(someObjCInitRequirement x: RuncibleSpoon) { someObjCPropertyRequirement = x } public func someObjCMethodRequirement(_: RuncibleSpoon) {} public var someObjCPropertyRequirement: RuncibleSpoon } extension SomeSwift4Class: SomeObjCProtocol {}
apache-2.0
4621c5a3248f12675fb34ad7b121fbd6
35.784615
85
0.83187
4.562977
false
false
false
false
testpress/ios-app
ios-app/UI/CourseTableViewCell.swift
1
4217
// // CourseTableViewCell.swift // ios-app // // Copyright © 2017 Testpress. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit class CourseTableViewCell: UITableViewCell { @IBOutlet weak var courseName: UILabel! @IBOutlet weak var courseViewCell: UIView! @IBOutlet weak var thumbnailImage: UIImageView! @IBOutlet weak var externalLinkLabel: UILabel! var parentViewController: UIViewController! = nil var course: Course! func initCell(_ course: Course, viewController: UIViewController) { parentViewController = viewController self.course = course courseName.text = course.title thumbnailImage.kf.setImage(with: URL(string: course.image), placeholder: Images.PlaceHolder.image) let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.onItemClick)) courseViewCell.addGestureRecognizer(tapRecognizer) externalLinkLabel.isHidden = true if !course.external_content_link.isEmpty { displayExternalLabel() } } func displayExternalLabel() { externalLinkLabel.text = course.external_link_label externalLinkLabel.sizeToFit() externalLinkLabel.frame.size.width = externalLinkLabel.intrinsicContentSize.width + 10 externalLinkLabel.frame.size.height = externalLinkLabel.intrinsicContentSize.height + 10 externalLinkLabel.textAlignment = .center externalLinkLabel.isHidden = false externalLinkLabel.layer.borderWidth = 1.0 externalLinkLabel.layer.cornerRadius = 2 externalLinkLabel.layer.borderColor = Colors.getRGB(Colors.PRIMARY).cgColor externalLinkLabel.textColor = Colors.getRGB(Colors.PRIMARY) } override func layoutSubviews() { /* In case of device rotation, external link label should be redrawn. */ super.layoutSubviews() if !course.external_content_link.isEmpty { displayExternalLabel() } } @objc func onItemClick() { let storyboard = UIStoryboard(name: Constants.CHAPTER_CONTENT_STORYBOARD, bundle: nil) let viewController: UIViewController if !course.external_content_link.isEmpty { let webViewController = WebViewController() webViewController.url = course.external_content_link webViewController.title = course.title parentViewController.present(webViewController, animated: true, completion: nil) } else { let chaptersViewController = storyboard.instantiateViewController(withIdentifier: Constants.CHAPTERS_VIEW_CONTROLLER) as! ChaptersViewController chaptersViewController.courseId = course.id chaptersViewController.coursesUrl = course.url chaptersViewController.title = course.title viewController = chaptersViewController parentViewController.present(viewController, animated: true, completion: nil) } } }
mit
e755029c5258c6b0e91944801b4c3536
41.585859
96
0.689991
5.192118
false
false
false
false
austinzheng/swift
validation-test/compiler_crashers_2_fixed/0093-sr-4471.swift
53
967
// RUN: %target-swift-frontend -primary-file %s -emit-ir protocol P: AnyObject {} protocol Foo { // The compiler crash goes away if you remove the P constraint on this associated type associatedtype ObjectType: P } protocol UpcastHelper { associatedtype Sub: Foo associatedtype Super: Foo // ObjectIdentifier(object) == ObjectIdentifier(Self.cast(object)) static func cast(_ object: Sub.ObjectType) -> Super.ObjectType } struct AnyFoo<Object: P>: Foo { typealias ObjectType = Object class Base {} final class Derived<Helper: UpcastHelper>: Base where Helper.Super == AnyFoo<Object> { init(_ foo: Helper.Sub) { self.foo = foo } let foo: Helper.Sub } init<Helper: UpcastHelper> (foo: Helper.Sub, helper: Helper.Type) where Helper.Super == AnyFoo<Object> { // This is the expression that causes the crash _ = Derived<Helper>(foo) } }
apache-2.0
27b620d4dae02956f46c63a4c5fc90d9
23.175
90
0.641158
4.150215
false
false
false
false