repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 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
itsaboutcode/WordPress-iOS
WordPress/Classes/Models/Blog+HomepageSettings.swift
1
2878
import Foundation enum HomepageType: String { case page case posts var title: String { switch self { case .page: return NSLocalizedString("Static Homepage", comment: "Name of setting configured when a site uses a static page as its homepage") case .posts: return NSLocalizedString("Classic Blog", comment: "Name of setting configured when a site uses a list of blog posts as its homepage") } } var remoteType: RemoteHomepageType { switch self { case .page: return .page case .posts: return .posts } } } extension Blog { private enum OptionsKeys { static let homepageType = "show_on_front" static let homepageID = "page_on_front" static let postsPageID = "page_for_posts" } /// The type of homepage used for the site: blog posts, or static pages /// var homepageType: HomepageType? { get { guard let options = options, !options.isEmpty, let type = getOptionString(name: OptionsKeys.homepageType) else { return nil } return HomepageType(rawValue: type) } set { if let value = newValue?.rawValue { setValue(value, forOption: OptionsKeys.homepageType) } } } /// The ID of the page to use for the site's 'posts' page, /// if `homepageType` is set to `.posts` /// var homepagePostsPageID: Int? { get { guard let options = options, !options.isEmpty, let pageID = getOptionNumeric(name: OptionsKeys.postsPageID) else { return nil } return pageID.intValue } set { let number: NSNumber? if let newValue = newValue { number = NSNumber(integerLiteral: newValue) } else { number = nil } setValue(number as Any, forOption: OptionsKeys.postsPageID) } } /// The ID of the page to use for the site's homepage, /// if `homepageType` is set to `.page` /// var homepagePageID: Int? { get { guard let options = options, !options.isEmpty, let pageID = getOptionNumeric(name: OptionsKeys.homepageID) else { return nil } return pageID.intValue } set { let number: NSNumber? if let newValue = newValue { number = NSNumber(integerLiteral: newValue) } else { number = nil } setValue(number as Any, forOption: OptionsKeys.homepageID) } } }
gpl-2.0
e8e14e6670faeec0655bc6d964af4edd
27.215686
145
0.519805
4.936535
false
false
false
false
hooman/swift
test/Generics/unify_superclass_types_3.swift
1
2099
// RUN: %target-typecheck-verify-swift -requirement-machine=on -dump-requirement-machine 2>&1 | %FileCheck %s // Note: The GSB fails this test, because it doesn't implement unification of // superclass type constructor arguments. class Generic<T, U, V> {} class Derived<TT, UU> : Generic<Int, TT, UU> {} protocol P1 { associatedtype X : Derived<A1, B1> associatedtype A1 associatedtype B1 } protocol P2 { associatedtype X : Generic<A2, String, B2> associatedtype A2 associatedtype B2 } func sameType<T>(_: T.Type, _: T.Type) {} func takesDerivedString<U>(_: Derived<String, U>.Type) {} func unifySuperclassTest<T : P1 & P2>(_: T) { sameType(T.A1.self, String.self) sameType(T.A2.self, Int.self) sameType(T.B1.self, T.B2.self) takesDerivedString(T.X.self) } // CHECK-LABEL: Requirement machine for <τ_0_0 where τ_0_0 : P1, τ_0_0 : P2> // CHECK-NEXT: Rewrite system: { // CHECK: - τ_0_0.[P1&P2:X].[superclass: Generic<τ_0_0, String, τ_0_1> with <τ_0_0.[P2:A2], τ_0_0.[P2:B2]>] => τ_0_0.[P1&P2:X] // CHECK-NEXT: - τ_0_0.[P1&P2:X].[layout: _NativeClass] => τ_0_0.[P1&P2:X] // CHECK-NEXT: - τ_0_0.[P1&P2:X].[superclass: Derived<τ_0_0, τ_0_1> with <τ_0_0.[P1:A1], τ_0_0.[P1:B1]>] => τ_0_0.[P1&P2:X] // CHECK-NEXT: - τ_0_0.[P2:A2].[concrete: Int] => τ_0_0.[P2:A2] // CHECK-NEXT: - τ_0_0.[P1:A1].[concrete: String] => τ_0_0.[P1:A1] // CHECK-NEXT: - τ_0_0.[P2:B2] => τ_0_0.[P1:B1] // CHECK-NEXT: } // CHECK-NEXT: Property map: { // CHECK-NEXT: [P1:X] => { layout: _NativeClass superclass: [superclass: Derived<τ_0_0, τ_0_1> with <[P1:A1], [P1:B1]>] } // CHECK-NEXT: [P2:X] => { layout: _NativeClass superclass: [superclass: Generic<τ_0_0, String, τ_0_1> with <[P2:A2], [P2:B2]>] } // CHECK-NEXT: τ_0_0 => { conforms_to: [P1 P2] } // CHECK-NEXT: τ_0_0.[P1&P2:X] => { layout: _NativeClass superclass: [superclass: Derived<τ_0_0, τ_0_1> with <τ_0_0.[P1:A1], τ_0_0.[P1:B1]>] } // CHECK-NEXT: τ_0_0.[P2:A2] => { concrete_type: [concrete: Int] } // CHECK-NEXT: τ_0_0.[P1:A1] => { concrete_type: [concrete: String] } // CHECK-NEXT: }
apache-2.0
26de256976c5590c4f679496e4467552
41.122449
144
0.617733
2.293333
false
false
false
false
onevcat/Rainbow
Sources/ModesExtractor.swift
1
3238
// // ModesExtractor.swift // Rainbow // // Created by Wei Wang on 15/12/23. // // Copyright (c) 2018 Wei Wang <onevcat@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Parse a console string to `Entry` class ConsoleEntryParser { let text: String var iter: String.Iterator? init(text: String) { self.text = text } // Not thread safe. func parse() -> Rainbow.Entry { func appendSegment(text: String, codes: [UInt8]) { let modes = ConsoleCodesParser().parse(modeCodes: codes) segments.append(.init(text: text, color: modes.color, backgroundColor: modes.backgroundColor, styles: modes.styles)) tempCodes = [] } iter = text.makeIterator() var segments = [Rainbow.Segment]() var tempCodes = [UInt8]() var startingNewSegment = false while let c = iter!.next() { if startingNewSegment, c == ControlCode.OPEN_BRACKET { tempCodes = parseCodes() startingNewSegment = false } else if c == ControlCode.ESC { if !tempCodes.isEmpty { appendSegment(text: "", codes: tempCodes) } startingNewSegment = true } else { let text = parseText(firstCharacter: c) appendSegment(text: text, codes: tempCodes) startingNewSegment = true } } return Rainbow.Entry(segments: segments) } func parseCodes() -> [UInt8] { var codes = [UInt8]() var current: String = "" while let c = iter!.next(), c != "m" { if c == ";", let code = UInt8(current) { codes.append(code) current = "" } else { current.append(c) } } if let code = UInt8(current) { codes.append(code) } return codes } func parseText(firstCharacter: Character) -> String { var text = String(firstCharacter) while let c = iter!.next(), c != ControlCode.ESC { text.append(c) } return text } }
mit
f20bb6aff17091dbb3547c586ac94ceb
33.084211
128
0.600679
4.399457
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Models/Common/RequestOptions.swift
1
4201
// // RequestOptions.swift // // // Created by Vladislav Fitc on 19/02/2020. // import Foundation /** Every endpoint can configure a request locally by passing additional headers, urlParameters, body, writeTimeout, readTimeout. */ public struct RequestOptions { public var headers: [HTTPHeaderKey: String] public var urlParameters: [HTTPParameterKey: String?] public var writeTimeout: TimeInterval? public var readTimeout: TimeInterval? public var body: [String: Any]? public init(headers: [HTTPHeaderKey: String] = [:], urlParameters: [HTTPParameterKey: String?] = [:], writeTimeout: TimeInterval? = nil, readTimeout: TimeInterval? = nil, body: [String: Any]? = nil) { self.headers = headers self.urlParameters = urlParameters self.writeTimeout = writeTimeout self.readTimeout = readTimeout self.body = body } /// Add a header with key and value to headers. public mutating func setHeader(_ value: String?, forKey key: HTTPHeaderKey) { headers[key] = value } /// Add a url parameter with key and value to urlParameters. public mutating func setParameter(_ value: String?, forKey key: HTTPParameterKey) { urlParameters[key] = value } /// Set timeout for a call type public mutating func setTimeout(_ timeout: TimeInterval?, for callType: CallType) { switch callType { case .read: self.readTimeout = timeout case .write: self.writeTimeout = timeout } } /// Get timeout for a call type public func timeout(for callType: CallType) -> TimeInterval? { switch callType { case .read: return readTimeout case .write: return writeTimeout } } } public struct HTTPParameterKey: RawRepresentable, Hashable { public let rawValue: String public init(rawValue: String) { self.rawValue = rawValue } } extension HTTPParameterKey: ExpressibleByStringInterpolation { public init(stringLiteral value: String) { rawValue = value } } extension HTTPParameterKey { static var attributesToRetreive: HTTPParameterKey { #function } static var forwardToReplicas: HTTPParameterKey { #function } static var clearExistingRules: HTTPParameterKey { #function } static var replaceExistingSynonyms: HTTPParameterKey { #function } static var createIfNotExists: HTTPParameterKey { #function } static var cursor: HTTPParameterKey { #function } static var indexName: HTTPParameterKey { #function } static var offset: HTTPParameterKey { #function } static var limit: HTTPParameterKey { #function } static var length: HTTPParameterKey { #function } static var type: HTTPParameterKey { #function } static var language: HTTPParameterKey { #function } static var aroundLatLng: HTTPParameterKey { #function } static var page: HTTPParameterKey { #function } static var hitsPerPage: HTTPParameterKey { #function } static var getClusters: HTTPParameterKey { #function } } extension HTTPHeaderKey { static let contentType: HTTPHeaderKey = "Content-Type" static let algoliaUserID: HTTPHeaderKey = "X-Algolia-User-ID" static let forwardedFor: HTTPHeaderKey = "X-Forwarded-For" static let applicationID: HTTPHeaderKey = "X-Algolia-Application-Id" static let apiKey: HTTPHeaderKey = "X-Algolia-API-Key" static let userAgent: HTTPHeaderKey = "User-Agent" } extension HTTPHeaderKey: ExpressibleByStringInterpolation { public init(stringLiteral value: String) { rawValue = value } } public struct HTTPHeaderKey: RawRepresentable, Hashable { public let rawValue: String public init(rawValue: String) { self.rawValue = rawValue } } extension Optional where Wrapped == RequestOptions { func unwrapOrCreate() -> RequestOptions { return self ?? RequestOptions() } func updateOrCreate(_ parameters: @autoclosure () -> [HTTPParameterKey: String?]) -> RequestOptions? { let parameters = parameters() guard !parameters.isEmpty else { return self } var mutableRequestOptions = unwrapOrCreate() for (key, value) in parameters { mutableRequestOptions.setParameter(value, forKey: key) } return mutableRequestOptions } }
mit
1f1302c5ecd1669afe953534fad6183c
26.457516
104
0.713878
4.512352
false
false
false
false
kenwilcox/SlotMachine
SlotMachine/SlotBrain.swift
1
2025
// // SlotBrain.swift // SlotMachine // // Created by Kenneth Wilcox on 1/1/15. // Copyright (c) 2015 Kenneth Wilcox. All rights reserved. // import Foundation class SlotBrain { class func computeWinnings (slots: [[Slot]]) -> Int { var winnings = 0 var flushWinCount = 0 var threeOfAKindWinCount = 0 var straightWinCount = 0 for slotRow in slots { if checkFlush(slotRow) == true { println("flush") winnings += 1 flushWinCount += 1 } if checkInARow(slotRow) == true { println("\(slotRow.count) in a row") winnings += 1 straightWinCount += 1 } if ofAKind(slotRow) == true { println("\(slotRow.count) of a kind") winnings += 3 threeOfAKindWinCount += 1 } } if flushWinCount == slots.count { println("Royal Flush") winnings += 15 } if straightWinCount == slots.count { println("Epic straight") winnings += 1000 } if threeOfAKindWinCount == slots.count { println("Threes all around") winnings += 50 } return winnings } class func checkFlush(slotRow: [Slot]) -> Bool { var redColorCount = 0 var blackColorCount = 0 for slot in slotRow { if slot.isRed { redColorCount++ } else { blackColorCount++ } } if redColorCount == slotRow.count || blackColorCount == slotRow.count { return true } else { return false } } class func checkInARow(slotRow: [Slot]) -> Bool { var values = slotRow.map({$0.value}) values.sort({$0 < $1}) for (i, value) in enumerate(values) { if i > 0 && value != values[i - 1] + 1 { return false } } return true } class func ofAKind(slotRow: [Slot]) -> Bool { let firstValue = slotRow[0].value for slot in slotRow { if firstValue != slot.value { return false } } return true } }
mit
ec6e3b9912b7b7331aa3d59e43fcda83
19.673469
75
0.548642
3.894231
false
false
false
false
crazypoo/PTools
Pods/CollectionViewPagingLayout/Lib/SwiftUI/PagingCollectionViewCell.swift
1
6234
import SwiftUI import UIKit class PagingCollectionViewCell<ValueType: Identifiable, Content: View>: UICollectionViewCell { typealias Parent = PagingCollectionViewController<ValueType, Content> // MARK: Properties private weak var hostingController: UIHostingController<Content>? private var viewBuilder: ((ValueType, CGFloat) -> Content)? private var value: ValueType! private var index: IndexPath! private weak var parent: Parent? private var parentBoundsObserver: NSKeyValueObservation? private var parentSize: CGSize? // MARK: Public functions func update(value: ValueType, index: IndexPath, parent: Parent) { self.parent = parent viewBuilder = parent.pageViewBuilder self.value = value self.index = index if hostingController != nil { updateView() } else { let viewController = UIHostingController(rootView: updateView()!) hostingController = viewController viewController.view.backgroundColor = .clear parent.addChild(viewController) contentView.addSubview(viewController.view) viewController.view.translatesAutoresizingMaskIntoConstraints = false parentBoundsObserver = parent.view .observe(\.bounds, options: [.initial, .new, .old, .prior]) { [weak self] _, _ in self?.updatePagePaddings() } viewController.didMove(toParent: parent) viewController.view.layoutIfNeeded() } } // MARK: Private functions @discardableResult private func updateView(progress: CGFloat? = nil) -> Content? { guard let viewBuilder = viewBuilder else { return nil } let view = viewBuilder(value, progress ?? 0) hostingController?.rootView = view hostingController?.view.layoutIfNeeded() return view } private func updatePagePaddings() { guard let parent = parent, let viewController = hostingController, parent.view.bounds.size != parentSize else { return } parentSize = parent.view.bounds.size func constraint<T>(_ first: NSLayoutAnchor<T>, _ second: NSLayoutAnchor<T>, _ paddingKeyPath: KeyPath<PagePadding, PagePadding.Padding?>, _ inside: Bool) { let padding = parent.modifierData?.pagePadding?[keyPath: paddingKeyPath] ?? .absolute(0) let constant: CGFloat switch padding { case .fractionalWidth(let fraction): constant = parent.view.bounds.size.width * fraction case .fractionalHeight(let fraction): constant = parent.view.bounds.size.height * fraction case .absolute(let absolute): constant = absolute } let identifier = "pagePaddingConstraint_\(inside)_\(T.self)" if let constraint = contentView.constraints.first(where: { $0.identifier == identifier }) ?? viewController.view.constraints.first(where: { $0.identifier == identifier }) { constraint.constant = constant * (inside ? 1 : -1) } else { let constraint = first.constraint(equalTo: second, constant: constant * (inside ? 1 : -1)) constraint.identifier = identifier constraint.isActive = true } } constraint(contentView.leadingAnchor, viewController.view.leadingAnchor, \.left, false) constraint(contentView.trailingAnchor, viewController.view.trailingAnchor, \.right, true) constraint(contentView.topAnchor, viewController.view.topAnchor, \.top, false) constraint(contentView.bottomAnchor, viewController.view.bottomAnchor, \.bottom, true) } } extension PagingCollectionViewCell: TransformableView, ScaleTransformView, StackTransformView, SnapshotTransformView { var scalableView: UIView { hostingController?.view ?? contentView } var cardView: UIView { hostingController?.view ?? contentView } var targetView: UIView { hostingController?.view ?? contentView } var selectableView: UIView? { scalableView } var scaleOptions: ScaleTransformViewOptions { parent?.modifierData?.scaleOptions ?? .init() } var stackOptions: StackTransformViewOptions { parent?.modifierData?.stackOptions ?? .init() } var snapshotOptions: SnapshotTransformViewOptions { parent?.modifierData?.snapshotOptions ?? .init() } func transform(progress: CGFloat) { if parent?.modifierData?.scaleOptions != nil { applyScaleTransform(progress: progress) } if parent?.modifierData?.stackOptions != nil { applyStackTransform(progress: progress) } if parent?.modifierData?.snapshotOptions != nil { if let snapshot = getSnapshot() { applySnapshotTransform(snapshot: snapshot, progress: progress) } } updateView(progress: progress) } func zPosition(progress: CGFloat) -> Int { parent?.modifierData?.zPositionProvider?(progress) ?? Int(-abs(round(progress))) } var snapshotIdentifier: String { if let snapshotIdentifier = parent?.modifierData?.snapshotIdentifier { return snapshotIdentifier(index.item, hostingController?.view) } var identifier = String(describing: value.id) if let scrollView = targetView as? UIScrollView { identifier.append("\(scrollView.contentOffset)") } if let scrollView = targetView.subviews.first(where: { $0 is UIScrollView }) as? UIScrollView { identifier.append("\(scrollView.contentOffset)") } return identifier } func canReuse(snapshot: SnapshotContainerView) -> Bool { if let canReuse = parent?.modifierData?.canReuseSnapshot { return canReuse(snapshot, hostingController?.view) } return snapshot.snapshotSize == targetView.bounds.size } }
mit
15e5bffc67314d2fe1482adce6c127b0
34.622857
106
0.629612
5.332763
false
false
false
false
xgdgsc/AlecrimCoreData
Source/AlecrimCoreData/Core/Extensions/NSManagedObjectContextExtensions.swift
1
5264
// // NSManagedObjectContextExtensions.swift // AlecrimCoreData // // Created by Vanderlei Martinelli on 2015-07-27. // Copyright (c) 2015 Alecrim. All rights reserved. // import Foundation import CoreData extension NSManagedObjectContext { /// Asynchronously performs a given closure on the receiver’s queue. /// /// - parameter closure: The closure to perform. /// /// - note: Calling this method is the same as calling `performBlock:` method. /// /// - seealso: `performBlock:` public func perform(closure: () -> Void) { self.performBlock(closure) } /// Synchronously performs a given closure on the receiver’s queue. /// /// - parameter closure: The closure to perform /// /// - note: Calling this method is the same as calling `performBlockAndWait:` method. /// /// - seealso: `performBlockAndWait:` public func performAndWait(closure: () -> Void) { self.performBlockAndWait(closure) } } extension NSManagedObjectContext { @available(OSX 10.10, iOS 8.0, *) internal func executeAsynchronousFetchRequestWithFetchRequest(fetchRequest: NSFetchRequest, completion completionHandler: ([AnyObject]?, NSError?) -> Void) throws { let asynchronousFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { asynchronousFetchResult in completionHandler(asynchronousFetchResult.finalResult, asynchronousFetchResult.operationError) } let persistentStoreResult = try self.executeRequest(asynchronousFetchRequest) if let _ = persistentStoreResult as? NSAsynchronousFetchResult { } else { throw AlecrimCoreDataError.UnexpectedValue(value: persistentStoreResult) } } } extension NSManagedObjectContext { @available(OSX 10.10, iOS 8.0, *) internal func executeBatchUpdateRequestWithEntityDescription(entityDescription: NSEntityDescription, propertiesToUpdate: [NSObject : AnyObject], predicate: NSPredicate, completion completionHandler: (Int, ErrorType?) -> Void) { let batchUpdateRequest = NSBatchUpdateRequest(entity: entityDescription) batchUpdateRequest.propertiesToUpdate = propertiesToUpdate batchUpdateRequest.predicate = predicate batchUpdateRequest.resultType = .UpdatedObjectsCountResultType // // HAX: // The `executeRequest:` method for a batch update only works in the root saving context. // If called in a context that has a parent context, both the `batchUpdateResult` and the `error` will be quietly set to `nil` by Core Data. // var moc: NSManagedObjectContext = self while moc.parentContext != nil { moc = moc.parentContext! } moc.performBlock { do { let persistentStoreResult = try moc.executeRequest(batchUpdateRequest) if let batchUpdateResult = persistentStoreResult as? NSBatchUpdateResult { if let count = batchUpdateResult.result as? Int { completionHandler(count, nil) } else { throw AlecrimCoreDataError.UnexpectedValue(value: batchUpdateResult.result) } } else { throw AlecrimCoreDataError.UnexpectedValue(value: persistentStoreResult) } } catch let error { completionHandler(0, error) } } } @available(OSX 10.11, iOS 9.0, *) internal func executeBatchDeleteRequestWithEntityDescription(entityDescription: NSEntityDescription, objectIDs: [NSManagedObjectID], completion completionHandler: (Int, ErrorType?) -> Void) { let batchDeleteRequest = NSBatchDeleteRequest(objectIDs: objectIDs) batchDeleteRequest.resultType = .ResultTypeCount // // HAX: // The `executeRequest:` method for a batch delete may only works in the root saving context. // If called in a context that has a parent context, both the `batchDeleteResult` and the `error` will be quietly set to `nil` by Core Data. // var moc: NSManagedObjectContext = self while moc.parentContext != nil { moc = moc.parentContext! } moc.performBlock { do { let persistentStoreResult = try moc.executeRequest(batchDeleteRequest) if let batchDeleteResult = persistentStoreResult as? NSBatchDeleteResult { if let count = batchDeleteResult.result as? Int { completionHandler(count, nil) } else { throw AlecrimCoreDataError.UnexpectedValue(value: batchDeleteResult.result) } } else { throw AlecrimCoreDataError.UnexpectedValue(value: persistentStoreResult) } } catch let error { completionHandler(0, error) } } } }
mit
cb9e020e1fae3645cfdd3c387284b2dc
37.394161
231
0.615209
5.711183
false
false
false
false
IngmarStein/swift
test/SILGen/specialize_attr.swift
1
4449
// RUN: %target-swift-frontend -emit-silgen -emit-verbose-sil %s | %FileCheck %s // CHECK-LABEL: @_specialize(Int, Float) // CHECK-NEXT: func specializeThis<T, U>(_ t: T, u: U) @_specialize(Int, Float) func specializeThis<T, U>(_ t: T, u: U) {} public protocol PP { associatedtype PElt } public protocol QQ { associatedtype QElt } public struct RR : PP { public typealias PElt = Float } public struct SS : QQ { public typealias QElt = Int } public struct GG<T : PP> {} // CHECK-LABEL: public class CC<T : PP> { // CHECK-NEXT: @_specialize(RR, SS) // CHECK-NEXT: @inline(never) public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) public class CC<T : PP> { @inline(never) @_specialize(RR, SS) public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) { return (u, g) } } // CHECK-LABEL: sil hidden [_specialize <Int, Float>] @_TF15specialize_attr14specializeThisu0_rFTx1uq__T_ : $@convention(thin) <T, U> (@in T, @in U) -> () { // CHECK-LABEL: sil [noinline] [_specialize <RR, SS, Float, Int>] @_TFC15specialize_attr2CC3foouRd__S_2QQrfTqd__1gGVS_2GGx__Tqd__GS2_x__ : $@convention(method) <T where T : PP><U where U : QQ> (@in U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) { // ----------------------------------------------------------------------------- // Test user-specialized subscript accessors. public protocol TestSubscriptable { associatedtype Element subscript(i: Int) -> Element { get set } } public class ASubscriptable<Element> : TestSubscriptable { var storage: UnsafeMutablePointer<Element> init(capacity: Int) { storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity) } public subscript(i: Int) -> Element { @_specialize(Int) get { return storage[i] } @_specialize(Int) set(rhs) { storage[i] = rhs } } } // ASubscriptable.subscript.getter with _specialize // CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr14ASubscriptableg9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed ASubscriptable<Element>) -> @out Element { // ASubscriptable.subscript.setter with _specialize // CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr14ASubscriptables9subscriptFSix : $@convention(method) <Element> (@in Element, Int, @guaranteed ASubscriptable<Element>) -> () { // ASubscriptable.subscript.materializeForSet with no attribute // CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr14ASubscriptablem9subscriptFSix : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed ASubscriptable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { public class Addressable<Element> : TestSubscriptable { var storage: UnsafeMutablePointer<Element> init(capacity: Int) { storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity) } public subscript(i: Int) -> Element { @_specialize(Int) unsafeAddress { return UnsafePointer<Element>(storage + i) } @_specialize(Int) unsafeMutableAddress { return UnsafeMutablePointer<Element>(storage + i) } } } // Addressable.subscript.unsafeAddressor with _specialize // CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr11Addressablelu9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafePointer<Element> { // Addressable.subscript.unsafeMutableAddressor with _specialize // CHECK-LABEL: sil [_specialize <Int>] @_TFC15specialize_attr11Addressableau9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafeMutablePointer<Element> { // Addressable.subscript.getter with no attribute // CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr11Addressableg9subscriptFSix : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> @out Element { // Addressable.subscript.setter with no attribute // CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr11Addressables9subscriptFSix : $@convention(method) <Element> (@in Element, Int, @guaranteed Addressable<Element>) -> () { // Addressable.subscript.materializeForSet with no attribute // CHECK-LABEL: sil [transparent] [fragile] @_TFC15specialize_attr11Addressablem9subscriptFSix : $@convention(method) <Element> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, Int, @guaranteed Addressable<Element>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
apache-2.0
0d46df8dfc5e81222d8603f2e8cd917a
40.194444
283
0.70263
3.726131
false
false
false
false
MetalPetal/MetalPetal
MetalPetalExamples/Shared/MetalKitView.swift
1
1732
// // MetalKitView.swift // MetalPetalDemo // // Created by YuAo on 2021/4/3. // import Foundation import SwiftUI import MetalKit import MetalPetal #if os(iOS) fileprivate typealias ViewRepresentable = UIViewRepresentable #elseif os(macOS) fileprivate typealias ViewRepresentable = NSViewRepresentable #endif struct MetalKitView: ViewRepresentable { typealias ViewUpdater = (MTKView) -> Void private let viewUpdater: ViewUpdater private let device: MTLDevice init(device: MTLDevice, viewUpdater: @escaping ViewUpdater) { self.viewUpdater = viewUpdater self.device = device } func makeUIView(context: Context) -> MTKView { let mtkView = MTKView(frame: .zero, device: device) mtkView.delegate = context.coordinator mtkView.autoResizeDrawable = true mtkView.colorPixelFormat = .bgra8Unorm return mtkView } func updateUIView(_ uiView: MTKView, context: Context) { } func makeNSView(context: Context) -> MTKView { makeUIView(context: context) } func updateNSView(_ nsView: MTKView, context: Context) { updateUIView(nsView, context: context) } func makeCoordinator() -> Coordinator { Coordinator(viewUpdater: self.viewUpdater) } class Coordinator: NSObject, MTKViewDelegate { private let viewUpdater: ViewUpdater init(viewUpdater: @escaping ViewUpdater) { self.viewUpdater = viewUpdater } func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) { } func draw(in view: MTKView) { viewUpdater(view) } } }
mit
867cc889051bc6f9deb22c23067dd240
23.742857
76
0.639723
4.545932
false
false
false
false
castillejoale/Bluefruit_LE_Connect_v2_Minimized_UART
bluefruitconnect/Platform/OSX/Controllers/PinIOViewController.swift
1
11236
// // PinIOViewController.swift // Bluefruit Connect // // Created by Antonio García on 16/02/16. // Copyright © 2016 Adafruit. All rights reserved. // import Cocoa class PinIOViewController: NSViewController { // UI @IBOutlet weak var baseTableView: NSTableView! @IBOutlet weak var statusLabel: NSTextField! private var queryCapabilitiesAlert: NSAlert? // Data private let pinIO = PinIOModuleManager() private var tableRowOpen: Int? private var isQueryingFinished = false private var isTabVisible = false private var waitingDiscoveryAlert: NSAlert? var infoFinishedScanning = false { didSet { if infoFinishedScanning != oldValue { DLog("pinio infoFinishedScanning: \(infoFinishedScanning)") if infoFinishedScanning && waitingDiscoveryAlert != nil { view.window?.endSheet(waitingDiscoveryAlert!.window) waitingDiscoveryAlert = nil startPinIo() } } } } override func viewDidLoad() { super.viewDidLoad() // Init pinIO.delegate = self baseTableView.rowHeight = 52 } func uartIsReady(notification: NSNotification) { DLog("Uart is ready") let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.removeObserver(self, name: UartManager.UartNotifications.DidBecomeReady.rawValue, object: nil) dispatch_async(dispatch_get_main_queue(),{ [unowned self] in self.setupFirmata() }) } private func setupFirmata() { // Reset Firmata and query capabilities pinIO.reset() tableRowOpen = nil baseTableView.reloadData() startQueryCapabilitiesProcess() } private func startQueryCapabilitiesProcess() { guard isTabVisible else { return } guard !pinIO.isQueryingCapabilities() else { DLog("error: queryCapabilities called while querying capabilities") return } if queryCapabilitiesAlert != nil { DLog("Warning: Trying to create a new queryCapabilitiesAlert while the current one is not nil") } isQueryingFinished = false statusLabel.stringValue = "Querying capabilities..." // Show dialog if let window = self.view.window { let localizationManager = LocalizationManager.sharedInstance let alert = NSAlert() alert.messageText = localizationManager.localizedString("pinio_capabilityquery_querying_title") alert.addButtonWithTitle(localizationManager.localizedString("dialog_cancel")) alert.alertStyle = .WarningAlertStyle alert.beginSheetModalForWindow(window) { [unowned self] (returnCode) -> Void in if returnCode == NSAlertFirstButtonReturn { self.pinIO.endPinQuery(true) } } queryCapabilitiesAlert = alert } self.pinIO.queryCapabilities() } func defaultCapabilitiesAssumedDialog() { guard isTabVisible else { return } DLog("QueryCapabilities not found") if let window = self.view.window { let localizationManager = LocalizationManager.sharedInstance let alert = NSAlert() alert.messageText = localizationManager.localizedString("pinio_capabilityquery_expired_title") alert.informativeText = localizationManager.localizedString("pinio_capabilityquery_expired_message") alert.addButtonWithTitle(localizationManager.localizedString("dialog_ok")) alert.alertStyle = .WarningAlertStyle alert.beginSheetModalForWindow(window) { (returnCode) -> Void in if returnCode == NSAlertFirstButtonReturn { } } } } @IBAction func onClickQuery(sender: AnyObject) { setupFirmata() } } // MARK: - DetailTab extension PinIOViewController : DetailTab { func tabWillAppear() { pinIO.start() // Hack: wait a moment because a disconnect could call tabWillAppear just before disconnecting let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.2 * Double(NSEC_PER_SEC))) dispatch_after(dispatchTime, dispatch_get_main_queue(), { [weak self] in self?.startPinIo() }) } func tabWillDissapear() { isTabVisible = false pinIO.stop() } func tabReset() { } private func startPinIo() { guard BleManager.sharedInstance.blePeripheralConnected != nil else { DLog("trying to make pionio tab visible while disconnecting") isTabVisible = false return } isTabVisible = true if !isQueryingFinished { // Start Uart Manager UartManager.sharedInstance.blePeripheral = BleManager.sharedInstance.blePeripheralConnected // Note: this will start the service discovery if !infoFinishedScanning { DLog("pinio: waiting for info scanning...") if let window = view.window { let localizationManager = LocalizationManager.sharedInstance waitingDiscoveryAlert = NSAlert() waitingDiscoveryAlert!.messageText = "Waiting for discovery to finish..." waitingDiscoveryAlert!.addButtonWithTitle(localizationManager.localizedString("dialog_cancel")) waitingDiscoveryAlert!.alertStyle = .WarningAlertStyle waitingDiscoveryAlert!.beginSheetModalForWindow(window) { [unowned self] (returnCode) -> Void in if returnCode == NSAlertFirstButtonReturn { self.waitingDiscoveryAlert = nil self.pinIO.endPinQuery(true) } } } } else if (UartManager.sharedInstance.isReady()) { setupFirmata() } else { DLog("Wait for uart to be ready to start PinIO setup") let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: #selector(PinIOViewController.uartIsReady(_:)), name: UartManager.UartNotifications.DidBecomeReady.rawValue, object: nil) } } } } // MARK: - NSOutlineViewDataSource extension PinIOViewController : NSTableViewDataSource { func numberOfRowsInTableView(tableView: NSTableView) -> Int { return pinIO.pins.count } } // MARK: NSOutlineViewDelegate extension PinIOViewController: NSTableViewDelegate { func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { let pin = pinIO.pins[row] let cell = tableView.makeViewWithIdentifier("PinCell", owner: self) as! PinTableCellView cell.setPin(pin, pinIndex:row) cell.delegate = self return cell; } func tableView(tableView: NSTableView, heightOfRow row: Int) -> CGFloat { if let tableRowOpen = tableRowOpen where row == tableRowOpen { let pinOpen = pinIO.pins[tableRowOpen] return pinOpen.mode == .Input || pinOpen.mode == .Analog ? 106 : 130 } else { return 52 } } /* func tableViewSelectionDidChange(notification: NSNotification) { onPinToggleCell(baseTableView.selectedRow) }*/ } // MARK: PinTableCellViewDelegate extension PinIOViewController : PinTableCellViewDelegate { func onPinToggleCell(pinIndex: Int) { // Change open row let previousTableRowOpen = tableRowOpen tableRowOpen = pinIndex == tableRowOpen ? nil: pinIndex // Animate changes NSAnimationContext.beginGrouping() NSAnimationContext.currentContext().duration = 0.25 baseTableView.noteHeightOfRowsWithIndexesChanged(NSIndexSet(index: pinIndex)) if let previousTableRowOpen = previousTableRowOpen where previousTableRowOpen >= 0 { baseTableView.noteHeightOfRowsWithIndexesChanged(NSIndexSet(index: previousTableRowOpen)) } let rowRect = baseTableView.rectOfRow(pinIndex) baseTableView.scrollRectToVisible(rowRect) NSAnimationContext.endGrouping() } func onPinModeChanged(mode: PinIOModuleManager.PinData.Mode, pinIndex: Int) { let pin = pinIO.pins[pinIndex] pinIO.setControlMode(pin, mode: mode) //DLog("pin \(pin.digitalPinId): mode: \(pin.mode.rawValue)") // Animate changes NSAnimationContext.beginGrouping() NSAnimationContext.currentContext().duration = 0.25 baseTableView.reloadDataForRowIndexes(NSIndexSet(index: pinIndex), columnIndexes: NSIndexSet(index: 0)) baseTableView.noteHeightOfRowsWithIndexesChanged(NSIndexSet(index: pinIndex)) let rowRect = baseTableView.rectOfRow(pinIndex) baseTableView.scrollRectToVisible(rowRect) NSAnimationContext.endGrouping() } func onPinDigitalValueChanged(value: PinIOModuleManager.PinData.DigitalValue, pinIndex: Int) { let pin = pinIO.pins[pinIndex] pinIO.setDigitalValue(pin, value: value) baseTableView.reloadDataForRowIndexes(NSIndexSet(index: pinIndex), columnIndexes: NSIndexSet(index: 0)) } func onPinAnalogValueChanged(value: Double, pinIndex: Int) { let pin = pinIO.pins[pinIndex] if pinIO.setPMWValue(pin, value: Int(value)) { baseTableView.reloadDataForRowIndexes(NSIndexSet(index: pinIndex), columnIndexes: NSIndexSet(index: 0)) } } } // MARK: - PinIOModuleManagerDelegate extension PinIOViewController: PinIOModuleManagerDelegate { func onPinIODidEndPinQuery(isDefaultConfigurationAssumed: Bool) { dispatch_async(dispatch_get_main_queue(),{ [unowned self] in self.isQueryingFinished = true self.baseTableView.reloadData() // Dismiss current alert if let window = self.view.window, queryCapabilitiesAlert = self.queryCapabilitiesAlert { window.endSheet(queryCapabilitiesAlert.window) self.queryCapabilitiesAlert = nil } if isDefaultConfigurationAssumed { self.statusLabel.stringValue = "Default Arduino capabilities" self.defaultCapabilitiesAssumedDialog() } else { self.statusLabel.stringValue = "\(self.pinIO.digitalPinCount) digital pins. \(self.pinIO.analogPinCount) analog pins" } }) } func onPinIODidReceivePinState() { dispatch_async(dispatch_get_main_queue(),{ [unowned self] in self.baseTableView.reloadData() }) } }
mit
376af37ee7983e6344b93d3ee409f3d5
35.592834
184
0.627648
5.167433
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Binary Search/704_Binary Search.swift
1
1460
// 704. Binary Search // https://leetcode.com/problems/binary-search/ // // Created by Honghao Zhang on 9/15/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Given a sorted (in ascending order) integer array nums of n elements and a target value, write a function to search target in nums. If target exists, then return its index, otherwise return -1. // // //Example 1: // //Input: nums = [-1,0,3,5,9,12], target = 9 //Output: 4 //Explanation: 9 exists in nums and its index is 4 // //Example 2: // //Input: nums = [-1,0,3,5,9,12], target = 2 //Output: -1 //Explanation: 2 does not exist in nums so return -1 // // //Note: // //You may assume that all elements in nums are unique. //n will be in the range [1, 10000]. //The value of each element in nums will be in the range [-9999, 9999]. // // 标准的二分法查找 import Foundation class Num704 { // standard binary search func search(_ nums: [Int], _ target: Int) -> Int { guard nums.count > 0 else { return -1 } var start = 0 var end = nums.count - 1 while start + 1 < end { let mid = start + (end - start) / 2 if nums[mid] < target { start = mid } else if nums[mid] > target { end = mid } else { return mid } } if nums[start] == target { return start } else if nums[end] == target { return end } else { return -1 } } }
mit
42a03722ded4f7e59a74166ba0410cfc
19.913043
196
0.589051
3.355814
false
false
false
false
bdsimmons/ios-exercises
SwiftExercises.playground/section-1.swift
1
3366
import UIKit /* Strings */ func favoriteCheeseStringWithCheese(cheese: String) -> String { // WORK HERE return "My favorite cheese is \(cheese)." } let fullSentence = favoriteCheeseStringWithCheese("cheddar") // Make fullSentence say "My favorite cheese is cheddar." /* Arrays & Dictionaries */ var numberArray = [1, 2, 3, 4] // Add 5 to this array // WORK HERE numberArray.append(5) var numberDictionary = [1 : "one", 2 : "two", 3 : "three", 4 : "four"] // Add 5 : "five" to this dictionary // WORK HERE numberDictionary[5] = "five" /* Loops */ // Use a closed range loop to print 1 - 10, inclusively // WORK HERE for i in 1...10 { print(i) } // Use a half-closed range loop to print 1 - 10, inclusively // WORK HERE for i in 1..<10 { print(i) } let worf = [ "name": "Worf", "rank": "lieutenant", "information": "son of Mogh, slayer of Gowron", "favorite drink": "prune juice", "quote" : "Today is a good day to die."] let picard = [ "name": "Jean-Luc Picard", "rank": "captain", "information": "Captain of the USS Enterprise", "favorite drink": "tea, Earl Grey, hot"] let characters = [worf, picard] func favoriteDrinksArrayForCharacters(characters:[[String : String]]) -> [String] { // return an array of favorite drinks, like ["prune juice", "tea, Earl Grey, hot"] // WORK HERE var favoriteDrinks = [String](); for character in characters { if let favoriteDrink = character["favorite drink"] { favoriteDrinks.append(favoriteDrink) } } return favoriteDrinks } let favoriteDrinks = favoriteDrinksArrayForCharacters(characters) favoriteDrinks /* Optionals */ func emailFromUserDict(userDict : [String : String]) -> String { // Return the user's email address from userDict, or return "" if they don't have one // WORK HERE if let email = userDict["email"] { return email } else { return "" } } let mostafaElSayedUser = ["name" : "Mostafa A. El-Sayed", "occupation" : "Chemical Physicist", "email" : "mael-sayed@gatech.edu", "awards" : "Langmuir Award in Chemical Physics, Arabian Nobel Prize, Ahmed Zewail prize, The Class of 1943 Distinguished Professor, 2007 US National Medal of Science", "birthday" : "8 May 1933"] let marjorieBrowneUser = ["name" : "Marjorie Lee Browne", "occupation" : "Mathematician", "birthday" : "September 9, 1914"] // If your emailFromUserDict function is implemented correctly, both of these should output "true": emailFromUserDict(mostafaElSayedUser) == "mael-sayed@gatech.edu" emailFromUserDict(marjorieBrowneUser) == "" /* Functions */ // Make a function that inputs an array of strings and outputs the strings separated by a semicolon let strings = ["milk", "eggs", "bread", "challah"] // WORK HERE - make your function and pass `strings` in func addInSemiColons(strings : [String]) -> String { var returnString = "" for word in strings { returnString += "\(word);" } return returnString.substringToIndex(returnString.endIndex.predecessor()) } addInSemiColons(strings) let expectedOutput = "milk;eggs;bread;challah" /* Closures */ let cerealArray = ["Golden Grahams", "Cheerios", "Trix", "Cap'n Crunch OOPS! All Berries", "Cookie Crisp"] // Use a closure to sort this array alphabetically // WORK HERE cerealArray.sort()
mit
d77a979df7a3c482d6fbaa3f4c13ae65
22.87234
324
0.671717
3.441718
false
false
false
false
pkadams67/PKA-Project---Advent-16
Controllers/CalendarLogic.swift
1
4247
// // CalendarLogic.swift // Advent '16 // // Created by Paul Kirk Adams on 11/15/16. // Copyright © 2016 Paul Kirk Adams. All rights reserved. // import Foundation class CalendarLogic: Hashable { var hashValue: Int { return baseDate.hashValue } var baseDate: NSDate { didSet { calculateVisibleDays() } } private lazy var dateFormatter = NSDateFormatter() var currentMonthAndYear: NSString { dateFormatter.dateFormat = "LLLL yyyy" return dateFormatter.stringFromDate(baseDate) } var currentMonthDays: [Date]? var previousMonthVisibleDays: [Date]? var nextMonthVisibleDays: [Date]? init(date: NSDate) { baseDate = date.firstDayOfTheMonth calculateVisibleDays() } func retreatToPreviousMonth() { baseDate = baseDate.firstDayOfPreviousMonth } func advanceToNextMonth() { baseDate = baseDate.firstDayOfFollowingMonth } func moveToMonth(date: NSDate) { baseDate = date } func isVisible(date: NSDate) -> Bool { let internalDate = Date(date: date) if (currentMonthDays!).contains(internalDate) { return true } else if (previousMonthVisibleDays!).contains(internalDate) { return true } else if (nextMonthVisibleDays!).contains(internalDate) { return true } return false } func containsDate(date: NSDate) -> Bool { let date = Date(date: date) let logicBaseDate = Date(date: baseDate) if (date.month == logicBaseDate.month) && (date.year == logicBaseDate.year) { return true } return false } private var numberOfDaysInPreviousPartialWeek: Int { return baseDate.weekDay - 1 } private var numberOfVisibleDaysforFollowingMonth: Int { // Traverse to last day of month let parts = baseDate.monthDayAndYearComponents parts.day = baseDate.numberOfDaysInMonth // 7 * 6 = 42 :- 7 columns (7 days in a week) and 6 rows (max 6 weeks in a month) return 42 - (numberOfDaysInPreviousPartialWeek + baseDate.numberOfDaysInMonth) } private var calculateCurrentMonthVisibleDays: [Date] { var dates = [Date]() let numberOfDaysInMonth = baseDate.numberOfDaysInMonth let component = baseDate.monthDayAndYearComponents for var i = 1; i <= numberOfDaysInMonth; i += 1 { dates.append(Date(day: i, month: component.month, year: component.year)) } return dates } private var calculatePreviousMonthVisibleDays: [Date] { var dates = [Date]() let date = baseDate.firstDayOfPreviousMonth let numberOfDaysInMonth = date.numberOfDaysInMonth let numberOfVisibleDays = numberOfDaysInPreviousPartialWeek let parts = date.monthDayAndYearComponents for var i = numberOfDaysInMonth - (numberOfVisibleDays - 1); i <= numberOfDaysInMonth; i += 1 { dates.append(Date(day: i, month: parts.month, year: parts.year)) } return dates } private var calculateFollowingMonthVisibleDays: [Date] { var dates = [Date]() let date = baseDate.firstDayOfFollowingMonth let numberOfDays = numberOfVisibleDaysforFollowingMonth let parts = date.monthDayAndYearComponents for var i = 1; i <= numberOfDays; i += 1 { dates.append(Date(day: i, month: parts.month, year: parts.year)) } return dates } private func calculateVisibleDays() { currentMonthDays = calculateCurrentMonthVisibleDays previousMonthVisibleDays = calculatePreviousMonthVisibleDays nextMonthVisibleDays = calculateFollowingMonthVisibleDays } } func ==(lhs: CalendarLogic, rhs: CalendarLogic) -> Bool { return lhs.hashValue == rhs.hashValue } func <(lhs: CalendarLogic, rhs: CalendarLogic) -> Bool { return (lhs.baseDate.compare(rhs.baseDate) == .OrderedAscending) } func >(lhs: CalendarLogic, rhs: CalendarLogic) -> Bool { return (lhs.baseDate.compare(rhs.baseDate) == .OrderedDescending) }
mit
fe642a5f28a9168e5bd2525f8f0e0180
30.451852
103
0.638954
4.620239
false
false
false
false
airspeedswift/swift
test/IRGen/prespecialized-metadata/struct-inmodule-1argument-5conformance-1distinct_use.swift
3
16221
// RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK: @"$sytN" = external{{( dllimport)?}} global %swift.full_type // CHECK: @"$s4main5ValueVySiGMf" = linkonce_odr hidden constant <{ // CHECK-SAME: i8**, // CHECK-SAME: [[INT]], // CHECK-SAME: %swift.type_descriptor*, // CHECK-SAME: %swift.type*, // CHECK-SAME: i8**, // CHECK-SAME: i8**, // CHECK-SAME: i8**, // CHECK-SAME: i8**, // CHECK-SAME: i8**, // CHECK-SAME: i32{{(, \[4 x i8\])?}}, // CHECk-SAME: i64 // CHECK-SAME: }> <{ // i8** @"$sB[[INT]]_WV", // i8** getelementptr inbounds (%swift.vwtable, %swift.vwtable* @"$s4main5ValueVySiGWV", i32 0, i32 0) // CHECK-SAME: [[INT]] 512, // CHECK-SAME: %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*), // CHECK-SAME: %swift.type* @"$sSiN", // CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1PAAWP", i32 0, i32 0), // CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1QAAWP", i32 0, i32 0), // CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1RAAWP", i32 0, i32 0), // CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1SAAWP", i32 0, i32 0), // CHECK-SAME: i8** getelementptr inbounds ([1 x i8*], [1 x i8*]* @"$sSi4main1TAAWP", i32 0, i32 0), // CHECK-SAME: i32 0{{(, \[4 x i8\] zeroinitializer)?}}, // CHECK-SAME: i64 3 // CHECK-SAME: }>, align [[ALIGNMENT]] protocol P {} protocol Q {} protocol R {} protocol S {} protocol T {} extension Int : P {} extension Int : Q {} extension Int : R {} extension Int : S {} extension Int : T {} struct Value<First : P & Q & R & S & T> { let first: First } @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture %{{[0-9]+}}, %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i8**, i8**, i8**, i8**, i8**, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1)) // CHECK: } func doit() { consume( Value(first: 13) ) } doit() // CHECK: ; Function Attrs: noinline nounwind // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, i8** %1) #{{[0-9]+}} { // CHECK: entry: // CHECK: [[ERASED_ARGUMENT_BUFFER:%[0-9]+]] = bitcast i8** %1 to i8* // CHECK: br label %[[TYPE_COMPARISON_1:[0-9]+]] // CHECK: [[TYPE_COMPARISON_1]]: // CHECK: [[ERASED_TYPE_ADDRESS:%[0-9]+]] = getelementptr i8*, i8** %1, i64 0 // CHECK: %"load argument at index 0 from buffer" = load i8*, i8** [[ERASED_TYPE_ADDRESS]] // CHECK: [[EQUAL_TYPE:%[0-9]+]] = icmp eq i8* bitcast (%swift.type* @"$sSiN" to i8*), %"load argument at index 0 from buffer" // CHECK: [[EQUAL_TYPES:%[0-9]+]] = and i1 true, [[EQUAL_TYPE]] // CHECK: [[POINTER_TO_ERASED_TABLE_1:%[0-9]+]] = getelementptr i8*, i8** %1, i64 1 // CHECK: [[ERASED_TABLE_1:%"load argument at index 1 from buffer"]] = load i8*, i8** [[POINTER_TO_ERASED_TABLE_1]], align 1 // CHECK: [[UNERASED_TABLE_1:%[0-9]+]] = bitcast i8* [[ERASED_TABLE_1]] to i8** // CHECK: [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_1:%[0-9]+]] = load i8*, i8** [[UNERASED_TABLE_1]], align 1 // CHECK: [[PROVIDED_PROTOCOL_DESCRIPTOR_1:%[0-9]+]] = bitcast i8* [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_1]] to %swift.protocol_conformance_descriptor* // CHECK-arm64e: [[ERASED_TABLE_INT_1:%[0-9]+]] = ptrtoint i8* [[ERASED_TABLE_1]] to i64 // CHECK-arm64e: [[TABLE_SIGNATURE_1:%[0-9]+]] = call i64 @llvm.ptrauth.blend.i64(i64 [[ERASED_TABLE_INT_1]], i64 50923) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_1:%[0-9]+]] = call i64 @llvm.ptrauth.auth.i64(i64 %13, i32 2, i64 [[TABLE_SIGNATURE_1]]) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_1:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_1]] to %swift.protocol_conformance_descriptor* // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_1:%[0-9]+]] = ptrtoint %swift.protocol_conformance_descriptor* [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_1]] to i64 // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_1:%[0-9]+]] = call i64 @llvm.ptrauth.sign.i64(i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_1]], i32 2, i64 50923) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_1:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_1]] to %swift.protocol_conformance_descriptor* // CHECK: [[EQUAL_DESCRIPTORS_1:%[0-9]+]] = call swiftcc i1 @swift_compareProtocolConformanceDescriptors( // CHECK-SAME: %swift.protocol_conformance_descriptor* // CHECK-arm64e-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_1]], // CHECK-i386-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-x86_64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7s-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7k-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-arm64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-SAME: %swift.protocol_conformance_descriptor* // CHECK-SAME: $sSi4main1PAAMc // CHECK-SAME: ) // CHECK: [[EQUAL_ARGUMENTS_1:%[0-9]+]] = and i1 [[EQUAL_TYPES]], [[EQUAL_DESCRIPTORS_1]] // CHECK: [[POINTER_TO_ERASED_TABLE_2:%[0-9]+]] = getelementptr i8*, i8** %1, i64 2 // CHECK: [[ERASED_TABLE_2:%"load argument at index 2 from buffer"]] = load i8*, i8** [[POINTER_TO_ERASED_TABLE_2]], align 1 // CHECK: [[UNERASED_TABLE_2:%[0-9]+]] = bitcast i8* [[ERASED_TABLE_2]] to i8** // CHECK: [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_2:%[0-9]+]] = load i8*, i8** [[UNERASED_TABLE_2]], align 1 // CHECK: [[PROVIDED_PROTOCOL_DESCRIPTOR_2:%[0-9]+]] = bitcast i8* [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_2]] to %swift.protocol_conformance_descriptor* // CHECK-arm64e: [[ERASED_TABLE_INT_2:%[0-9]+]] = ptrtoint i8* [[ERASED_TABLE_2]] to i64 // CHECK-arm64e: [[TABLE_SIGNATURE_2:%[0-9]+]] = call i64 @llvm.ptrauth.blend.i64(i64 [[ERASED_TABLE_INT_2]], i64 50923) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_2:%[0-9]+]] = call i64 @llvm.ptrauth.auth.i64(i64 %13, i32 2, i64 [[TABLE_SIGNATURE_2]]) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_2:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_2]] to %swift.protocol_conformance_descriptor* // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_2:%[0-9]+]] = ptrtoint %swift.protocol_conformance_descriptor* [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_2]] to i64 // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_2:%[0-9]+]] = call i64 @llvm.ptrauth.sign.i64(i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_2]], i32 2, i64 50923) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_2:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_2]] to %swift.protocol_conformance_descriptor* // CHECK: [[EQUAL_DESCRIPTORS_2:%[0-9]+]] = call swiftcc i1 @swift_compareProtocolConformanceDescriptors( // CHECK-SAME: %swift.protocol_conformance_descriptor* // CHECK-arm64e-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_2]], // CHECK-i386-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-x86_64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7s-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7k-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-arm64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-SAME: %swift.protocol_conformance_descriptor* // CHECK-SAME: $sSi4main1QAAMc // CHECK-SAME: ) // CHECK: [[EQUAL_ARGUMENTS_2:%[0-9]+]] = and i1 [[EQUAL_ARGUMENTS_1]], [[EQUAL_DESCRIPTORS_2]] // CHECK: [[POINTER_TO_ERASED_TABLE_3:%[0-9]+]] = getelementptr i8*, i8** %1, i64 3 // CHECK: [[ERASED_TABLE_3:%"load argument at index 3 from buffer"]] = load i8*, i8** [[POINTER_TO_ERASED_TABLE_3]], align 1 // CHECK: [[UNERASED_TABLE_3:%[0-9]+]] = bitcast i8* [[ERASED_TABLE_3]] to i8** // CHECK: [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_3:%[0-9]+]] = load i8*, i8** [[UNERASED_TABLE_3]], align 1 // CHECK: [[PROVIDED_PROTOCOL_DESCRIPTOR_3:%[0-9]+]] = bitcast i8* [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_3]] to %swift.protocol_conformance_descriptor* // CHECK-arm64e: [[ERASED_TABLE_INT_3:%[0-9]+]] = ptrtoint i8* [[ERASED_TABLE_3]] to i64 // CHECK-arm64e: [[TABLE_SIGNATURE_3:%[0-9]+]] = call i64 @llvm.ptrauth.blend.i64(i64 [[ERASED_TABLE_INT_3]], i64 50923) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_3:%[0-9]+]] = call i64 @llvm.ptrauth.auth.i64(i64 %13, i32 2, i64 [[TABLE_SIGNATURE_3]]) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_3:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_3]] to %swift.protocol_conformance_descriptor* // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_3:%[0-9]+]] = ptrtoint %swift.protocol_conformance_descriptor* [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_3]] to i64 // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_3:%[0-9]+]] = call i64 @llvm.ptrauth.sign.i64(i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_3]], i32 2, i64 50923) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_3:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_3]] to %swift.protocol_conformance_descriptor* // CHECK: [[EQUAL_DESCRIPTORS_3:%[0-9]+]] = call swiftcc i1 @swift_compareProtocolConformanceDescriptors( // CHECK-SAME: %swift.protocol_conformance_descriptor* // CHECK-arm64e-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_3]], // CHECK-i386-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-x86_64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7s-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7k-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-arm64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-SAME: %swift.protocol_conformance_descriptor* // CHECK-SAME: $sSi4main1RAAMc // CHECK-SAME: ) // CHECK: [[EQUAL_ARGUMENTS_3:%[0-9]+]] = and i1 [[EQUAL_ARGUMENTS_2]], [[EQUAL_DESCRIPTORS_3]] // CHECK: [[POINTER_TO_ERASED_TABLE_4:%[0-9]+]] = getelementptr i8*, i8** %1, i64 4 // CHECK: [[ERASED_TABLE_4:%"load argument at index 4 from buffer"]] = load i8*, i8** [[POINTER_TO_ERASED_TABLE_4]], align 1 // CHECK: [[UNERASED_TABLE_4:%[0-9]+]] = bitcast i8* [[ERASED_TABLE_4]] to i8** // CHECK: [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_4:%[0-9]+]] = load i8*, i8** [[UNERASED_TABLE_4]], align 1 // CHECK: [[PROVIDED_PROTOCOL_DESCRIPTOR_4:%[0-9]+]] = bitcast i8* [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_4]] to %swift.protocol_conformance_descriptor* // CHECK-arm64e: [[ERASED_TABLE_INT_4:%[0-9]+]] = ptrtoint i8* [[ERASED_TABLE_4]] to i64 // CHECK-arm64e: [[TABLE_SIGNATURE_4:%[0-9]+]] = call i64 @llvm.ptrauth.blend.i64(i64 [[ERASED_TABLE_INT_4]], i64 50923) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_4:%[0-9]+]] = call i64 @llvm.ptrauth.auth.i64(i64 %13, i32 2, i64 [[TABLE_SIGNATURE_4]]) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_4:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_4]] to %swift.protocol_conformance_descriptor* // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_4:%[0-9]+]] = ptrtoint %swift.protocol_conformance_descriptor* [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_4]] to i64 // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_4:%[0-9]+]] = call i64 @llvm.ptrauth.sign.i64(i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_4]], i32 2, i64 50923) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_4:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_4]] to %swift.protocol_conformance_descriptor* // CHECK: [[EQUAL_DESCRIPTORS_4:%[0-9]+]] = call swiftcc i1 @swift_compareProtocolConformanceDescriptors( // CHECK-SAME: %swift.protocol_conformance_descriptor* // CHECK-arm64e-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_4]], // CHECK-i386-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-x86_64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7s-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7k-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-arm64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-SAME: %swift.protocol_conformance_descriptor* // CHECK-SAME: $sSi4main1SAAMc // CHECK-SAME: ) // CHECK: [[EQUAL_ARGUMENTS_4:%[0-9]+]] = and i1 [[EQUAL_ARGUMENTS_3]], [[EQUAL_DESCRIPTORS_4]] // CHECK: [[POINTER_TO_ERASED_TABLE_5:%[0-9]+]] = getelementptr i8*, i8** %1, i64 5 // CHECK: [[ERASED_TABLE_5:%"load argument at index 5 from buffer"]] = load i8*, i8** [[POINTER_TO_ERASED_TABLE_5]], align 1 // CHECK: [[UNERASED_TABLE_5:%[0-9]+]] = bitcast i8* [[ERASED_TABLE_5]] to i8** // CHECK: [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_5:%[0-9]+]] = load i8*, i8** [[UNERASED_TABLE_5]], align 1 // CHECK: [[PROVIDED_PROTOCOL_DESCRIPTOR_5:%[0-9]+]] = bitcast i8* [[UNCAST_PROVIDED_PROTOCOL_DESCRIPTOR_5]] to %swift.protocol_conformance_descriptor* // CHECK-arm64e: [[ERASED_TABLE_INT_5:%[0-9]+]] = ptrtoint i8* [[ERASED_TABLE_5]] to i64 // CHECK-arm64e: [[TABLE_SIGNATURE_5:%[0-9]+]] = call i64 @llvm.ptrauth.blend.i64(i64 [[ERASED_TABLE_INT_5]], i64 50923) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_5:%[0-9]+]] = call i64 @llvm.ptrauth.auth.i64(i64 %13, i32 2, i64 [[TABLE_SIGNATURE_5]]) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_5:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_5]] to %swift.protocol_conformance_descriptor* // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_5:%[0-9]+]] = ptrtoint %swift.protocol_conformance_descriptor* [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_5]] to i64 // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_5:%[0-9]+]] = call i64 @llvm.ptrauth.sign.i64(i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_AUTHED_PTR_INT_5]], i32 2, i64 50923) // CHECK-arm64e: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_5:%[0-9]+]] = inttoptr i64 [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_INT_5]] to %swift.protocol_conformance_descriptor* // CHECK: [[EQUAL_DESCRIPTORS_5:%[0-9]+]] = call swiftcc i1 @swift_compareProtocolConformanceDescriptors( // CHECK-SAME: %swift.protocol_conformance_descriptor* // CHECK-arm64e-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR_SIGNED_5]], // CHECK-i386-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-x86_64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7s-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-armv7k-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-arm64-SAME: [[PROVIDED_PROTOCOL_DESCRIPTOR]], // CHECK-SAME: %swift.protocol_conformance_descriptor* // CHECK-SAME: $sSi4main1TAAMc // CHECK-SAME: ) // CHECK: [[EQUAL_ARGUMENTS_5:%[0-9]+]] = and i1 [[EQUAL_ARGUMENTS_4]], [[EQUAL_DESCRIPTORS_5]] // CHECK: br i1 [[EQUAL_ARGUMENTS_5]], label %[[EXIT_PRESPECIALIZED:[0-9]+]], label %[[EXIT_NORMAL:[0-9]+]] // CHECK: [[EXIT_PRESPECIALIZED]]: // CHECK: ret %swift.metadata_response { %swift.type* getelementptr inbounds (%swift.full_type, %swift.full_type* bitcast (<{ i8**, [[INT]], %swift.type_descriptor*, %swift.type*, i8**, i8**, i8**, i8**, i8**, i32{{(, \[4 x i8\])?}}, i64 }>* @"$s4main5ValueVySiGMf" to %swift.full_type*), i32 0, i32 1), [[INT]] 0 } // CHECK: [[EXIT_NORMAL]]: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @swift_getGenericMetadata([[INT]] %0, i8* [[ERASED_ARGUMENT_BUFFER]], %swift.type_descriptor* bitcast ({{.+}}$s4main5ValueVMn{{.+}} to %swift.type_descriptor*)) #{{[0-9]+}} // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: }
apache-2.0
4244124521ac18b7ab306e2f33ecafae
77.742718
362
0.661427
2.842797
false
false
false
false
RabbitMC/ElectronFrontPerfectBackX
Backend/Sources/main.swift
1
1226
import PerfectLib import PerfectHTTP import PerfectHTTPServer import PerfectLogger // -------- LogFile.location = "./customLogFile.log" let eventid = LogFile.info("Server Setup message") let server = HTTPServer() // -------- // ROUTES var routes = Routes(baseUri:"/api/v1") func JSONMessage(message: String, response: HTTPResponse) { do { try response.setBody(json: ["message" : message]) .setHeader(.contentType, value: "application/json") .completed() } catch { response.setBody(string: "Error in handling request: \(error)") .completed(status: .internalServerError) } } routes.add(method: .get, uri: "/hello", handler: { request, response in JSONMessage(message: "Hello, JSON!", response: response) }) // -------- // SERVER server.addRoutes(routes) server.serverPort = 8181 server.documentRoot = "webroot" LogFile.info("Server port is: \(server.serverPort)", eventid: eventid) LogFile.debug("Demonstrating a logging event without the linked event id") do { LogFile.info("Starting server", eventid: eventid) try server.start() } catch PerfectError.networkError(let err, let msg) { print("Network error thrown: \(err) \(msg)") }
mit
8b569eb5ab2faad30e5dc00045a245de
23.52
74
0.671289
3.855346
false
false
false
false
dduan/swift
test/SILGen/dynamic.swift
1
22997
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-silgen | FileCheck %s // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-sil -verify // REQUIRES: objc_interop import Foundation import gizmo class Foo: Proto { // Not objc or dynamic, so only a vtable entry init(native: Int) {} func nativeMethod() {} var nativeProp: Int = 0 subscript(native native: Int) -> Int { get { return native } set {} } // @objc, so it has an ObjC entry point but can also be dispatched // by vtable @objc init(objc: Int) {} @objc func objcMethod() {} @objc var objcProp: Int = 0 @objc subscript(objc objc: AnyObject) -> Int { get { return 0 } set {} } // dynamic, so it has only an ObjC entry point dynamic init(dynamic: Int) {} dynamic func dynamicMethod() {} dynamic var dynamicProp: Int = 0 dynamic subscript(dynamic dynamic: Int) -> Int { get { return dynamic } set {} } func overriddenByDynamic() {} @NSManaged var managedProp: Int } protocol Proto { func nativeMethod() var nativeProp: Int { get set } subscript(native native: Int) -> Int { get set } func objcMethod() var objcProp: Int { get set } subscript(objc objc: AnyObject) -> Int { get set } func dynamicMethod() var dynamicProp: Int { get set } subscript(dynamic dynamic: Int) -> Int { get set } } // ObjC entry points for @objc and dynamic entry points // normal and @objc initializing ctors can be statically dispatched // CHECK-LABEL: sil hidden @_TFC7dynamic3FooC // CHECK: function_ref @_TFC7dynamic3Fooc // CHECK-LABEL: sil hidden @_TFC7dynamic3FooC // CHECK: function_ref @_TFC7dynamic3Fooc // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Fooc // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foo10objcMethod // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foog8objcPropSi // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foos8objcPropSi // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si // TODO: dynamic initializing ctor must be objc dispatched // CHECK-LABEL: sil hidden @_TFC7dynamic3FooC // CHECK: function_ref @_TTDFC7dynamic3Fooc // CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Fooc // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.init!initializer.1.foreign : // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Fooc // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foo13dynamicMethod // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foog11dynamicPropSi // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foos11dynamicPropSi // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foog9subscriptFT7dynamicSi_Si // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foos9subscriptFT7dynamicSi_Si // Protocol witnesses use best appropriate dispatch // Native witnesses use vtable dispatch: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_12nativeMethod // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g10nativePropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s10nativePropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT6nativeSi_Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT6nativeSi_Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : // @objc witnesses use vtable dispatch: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_10objcMethod // CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g8objcPropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s8objcPropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT4objcPs9AnyObject__Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT4objcPs9AnyObject__Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : // Dynamic witnesses use objc dispatch: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_13dynamicMethod // CHECK: function_ref @_TTDFC7dynamic3Foo13dynamicMethod // CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foo13dynamicMethod // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g11dynamicPropSi // CHECK: function_ref @_TTDFC7dynamic3Foog11dynamicPropSi // CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foog11dynamicPropSi // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s11dynamicPropSi // CHECK: function_ref @_TTDFC7dynamic3Foos11dynamicPropSi // CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foos11dynamicPropSi // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT7dynamicSi_Si // CHECK: function_ref @_TTDFC7dynamic3Foog9subscriptFT7dynamicSi_Si // CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foog9subscriptFT7dynamicSi_Si // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT7dynamicSi_Si // CHECK: function_ref @_TTDFC7dynamic3Foos9subscriptFT7dynamicSi_Si // CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foos9subscriptFT7dynamicSi_Si // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign : // Superclass dispatch class Subclass: Foo { // Native and objc methods can directly reference super members override init(native: Int) { super.init(native: native) } // CHECK-LABEL: sil hidden @_TFC7dynamic8SubclassC // CHECK: function_ref @_TFC7dynamic8Subclassc override func nativeMethod() { super.nativeMethod() } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass12nativeMethod // CHECK: function_ref @_TFC7dynamic3Foo12nativeMethodfT_T_ : $@convention(method) (@guaranteed Foo) -> () override var nativeProp: Int { get { return super.nativeProp } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg10nativePropSi // CHECK: function_ref @_TFC7dynamic3Foog10nativePropSi : $@convention(method) (@guaranteed Foo) -> Int set { super.nativeProp = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss10nativePropSi // CHECK: function_ref @_TFC7dynamic3Foos10nativePropSi : $@convention(method) (Int, @guaranteed Foo) -> () } override subscript(native native: Int) -> Int { get { return super[native: native] } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT6nativeSi_Si // CHECK: function_ref @_TFC7dynamic3Foog9subscriptFT6nativeSi_Si : $@convention(method) (Int, @guaranteed Foo) -> Int set { super[native: native] = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT6nativeSi_Si // CHECK: function_ref @_TFC7dynamic3Foos9subscriptFT6nativeSi_Si : $@convention(method) (Int, Int, @guaranteed Foo) -> () } override init(objc: Int) { super.init(objc: objc) } // CHECK-LABEL: sil hidden @_TFC7dynamic8SubclasscfT4objcSi_S0_ // CHECK: function_ref @_TFC7dynamic3FoocfT4objcSi_S0_ : $@convention(method) (Int, @owned Foo) -> @owned Foo override func objcMethod() { super.objcMethod() } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass10objcMethod // CHECK: function_ref @_TFC7dynamic3Foo10objcMethodfT_T_ : $@convention(method) (@guaranteed Foo) -> () override var objcProp: Int { get { return super.objcProp } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg8objcPropSi // CHECK: function_ref @_TFC7dynamic3Foog8objcPropSi : $@convention(method) (@guaranteed Foo) -> Int set { super.objcProp = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss8objcPropSi // CHECK: function_ref @_TFC7dynamic3Foos8objcPropSi : $@convention(method) (Int, @guaranteed Foo) -> () } override subscript(objc objc: AnyObject) -> Int { get { return super[objc: objc] } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT4objcPs9AnyObject__Si // CHECK: function_ref @_TFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si : $@convention(method) (@owned AnyObject, @guaranteed Foo) -> Int set { super[objc: objc] = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT4objcPs9AnyObject__Si // CHECK: function_ref @_TFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si : $@convention(method) (Int, @owned AnyObject, @guaranteed Foo) -> () } // Dynamic methods are super-dispatched by objc_msgSend override init(dynamic: Int) { super.init(dynamic: dynamic) } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassc // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.init!initializer.1.foreign : override func dynamicMethod() { super.dynamicMethod() } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass13dynamicMethod // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicMethod!1.foreign : override var dynamicProp: Int { get { return super.dynamicProp } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg11dynamicPropSi // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!getter.1.foreign : set { super.dynamicProp = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss11dynamicPropSi // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!setter.1.foreign : } override subscript(dynamic dynamic: Int) -> Int { get { return super[dynamic: dynamic] } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT7dynamicSi_Si // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!getter.1.foreign : set { super[dynamic: dynamic] = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT7dynamicSi_Si // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!setter.1.foreign : } dynamic override func overriddenByDynamic() {} } // CHECK-LABEL: sil hidden @_TF7dynamic20nativeMethodDispatchFT_T_ : $@convention(thin) () -> () func nativeMethodDispatch() { // CHECK: function_ref @_TFC7dynamic3FooC let c = Foo(native: 0) // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 : c.nativeMethod() // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 : let x = c.nativeProp // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 : c.nativeProp = x // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : let y = c[native: 0] // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : c[native: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic18objcMethodDispatchFT_T_ : $@convention(thin) () -> () func objcMethodDispatch() { // CHECK: function_ref @_TFC7dynamic3FooC let c = Foo(objc: 0) // CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 : c.objcMethod() // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 : let x = c.objcProp // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 : c.objcProp = x // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : let y = c[objc: 0 as NSNumber] // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : c[objc: 0 as NSNumber] = y } // CHECK-LABEL: sil hidden @_TF7dynamic21dynamicMethodDispatchFT_T_ : $@convention(thin) () -> () func dynamicMethodDispatch() { // CHECK: function_ref @_TFC7dynamic3FooC let c = Foo(dynamic: 0) // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign c.dynamicMethod() // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign let x = c.dynamicProp // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign c.dynamicProp = x // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign let y = c[dynamic: 0] // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign c[dynamic: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic15managedDispatchFCS_3FooT_ func managedDispatch(c: Foo) { // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!getter.1.foreign let x = c.managedProp // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!setter.1.foreign c.managedProp = x } // CHECK-LABEL: sil hidden @_TF7dynamic21foreignMethodDispatchFT_T_ func foreignMethodDispatch() { // CHECK: function_ref @_TFCSo9GuisemeauC let g = Guisemeau() // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.frob!1.foreign g.frob() // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!getter.1.foreign let x = g.count // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!setter.1.foreign g.count = x // CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!getter.1.foreign let y: AnyObject! = g[0] // CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!setter.1.foreign g[0] = y // CHECK: class_method [volatile] {{%.*}} : $NSObject, #NSObject.description!getter.1.foreign _ = g.description } extension Gizmo { // CHECK-LABEL: sil hidden @_TFE7dynamicCSo5Gizmoc // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.init!initializer.1.foreign convenience init(convenienceInExtension: Int) { self.init(bellsOn: convenienceInExtension) } // CHECK-LABEL: sil hidden @_TFE7dynamicCSo5GizmoC // CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign convenience init(foreignClassFactory x: Int) { self.init(stuff: x) } // CHECK-LABEL: sil hidden @_TFE7dynamicCSo5GizmoC // CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign convenience init(foreignClassExactFactory x: Int) { self.init(exactlyStuff: x) } @objc func foreignObjCExtension() { } dynamic func foreignDynamicExtension() { } } // CHECK-LABEL: sil hidden @_TF7dynamic24foreignExtensionDispatchFCSo5GizmoT_ func foreignExtensionDispatch(g: Gizmo) { // CHECK: class_method [volatile] %0 : $Gizmo, #Gizmo.foreignObjCExtension!1.foreign : (Gizmo) g.foreignObjCExtension() // CHECK: class_method [volatile] %0 : $Gizmo, #Gizmo.foreignDynamicExtension!1.foreign g.foreignDynamicExtension() } // CHECK-LABEL: sil hidden @_TF7dynamic33nativeMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> () func nativeMethodDispatchFromOtherFile() { // CHECK: function_ref @_TFC7dynamic13FromOtherFileC let c = FromOtherFile(native: 0) // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeMethod!1 : c.nativeMethod() // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!getter.1 : let x = c.nativeProp // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!setter.1 : c.nativeProp = x // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 : let y = c[native: 0] // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 : c[native: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic31objcMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> () func objcMethodDispatchFromOtherFile() { // CHECK: function_ref @_TFC7dynamic13FromOtherFileC let c = FromOtherFile(objc: 0) // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcMethod!1 : c.objcMethod() // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!getter.1 : let x = c.objcProp // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!setter.1 : c.objcProp = x // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 : let y = c[objc: 0] // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 : c[objc: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic34dynamicMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> () func dynamicMethodDispatchFromOtherFile() { // CHECK: function_ref @_TFC7dynamic13FromOtherFileC let c = FromOtherFile(dynamic: 0) // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicMethod!1.foreign c.dynamicMethod() // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!getter.1.foreign let x = c.dynamicProp // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!setter.1.foreign c.dynamicProp = x // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1.foreign let y = c[dynamic: 0] // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1.foreign c[dynamic: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic28managedDispatchFromOtherFileFCS_13FromOtherFileT_ func managedDispatchFromOtherFile(c: FromOtherFile) { // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!getter.1.foreign let x = c.managedProp // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!setter.1.foreign c.managedProp = x } // CHECK-LABEL: sil hidden @_TF7dynamic23dynamicExtensionMethodsFCS_13ObjCOtherFileT_ func dynamicExtensionMethods(obj: ObjCOtherFile) { // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionMethod!1.foreign obj.extensionMethod() // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionProp!getter.1.foreign _ = obj.extensionProp // CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.extensionClassProp!getter.1.foreign // CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type _ = obj.dynamicType.extensionClassProp // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionMethod!1.foreign obj.dynExtensionMethod() // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionProp!getter.1.foreign _ = obj.dynExtensionProp // CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.dynExtensionClassProp!getter.1.foreign // CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type _ = obj.dynamicType.dynExtensionClassProp } public class Base { dynamic var x: Bool { return false } } public class Sub : Base { // CHECK-LABEL: sil hidden @_TFC7dynamic3Subg1xSb : $@convention(method) (@guaranteed Sub) -> Bool { // CHECK: [[AUTOCLOSURE:%.*]] = function_ref @_TFFC7dynamic3Subg1xSbu_KzT_Sb : $@convention(thin) (@owned Sub) -> (Bool, @error ErrorProtocol) // CHECK: = partial_apply [[AUTOCLOSURE]](%0) // CHECK: return {{%.*}} : $Bool // CHECK: } // CHECK-LABEL: sil shared [transparent] @_TFFC7dynamic3Subg1xSbu_KzT_Sb : $@convention(thin) (@owned Sub) -> (Bool, @error ErrorProtocol) { // CHECK: [[SUPER:%.*]] = super_method [volatile] %0 : $Sub, #Base.x!getter.1.foreign : (Base) -> () -> Bool , $@convention(objc_method) (Base) -> ObjCBool // CHECK: = apply [[SUPER]]({{%.*}}) // CHECK: return {{%.*}} : $Bool // CHECK: } override var x: Bool { return false || super.x } } // Vtable contains entries for native and @objc methods, but not dynamic ones // CHECK-LABEL: sil_vtable Foo { // CHECK-LABEL: #Foo.init!initializer.1: _TFC7dynamic3Fooc // CHECK-LABEL: #Foo.nativeMethod!1: _TFC7dynamic3Foo12nativeMethod // CHECK-LABEL: #Foo.subscript!getter.1: _TFC7dynamic3Foog9subscriptFT6nativeSi_Si // dynamic.Foo.subscript.getter : (native : Swift.Int) -> Swift.Int // CHECK-LABEL: #Foo.subscript!setter.1: _TFC7dynamic3Foos9subscriptFT6nativeSi_Si // dynamic.Foo.subscript.setter : (native : Swift.Int) -> Swift.Int // CHECK-LABEL: #Foo.init!initializer.1: _TFC7dynamic3Fooc // CHECK-LABEL: #Foo.objcMethod!1: _TFC7dynamic3Foo10objcMethod // CHECK-LABEL: #Foo.subscript!getter.1: _TFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si // dynamic.Foo.subscript.getter : (objc : Swift.AnyObject) -> Swift.Int // CHECK-LABEL: #Foo.subscript!setter.1: _TFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si // dynamic.Foo.subscript.setter : (objc : Swift.AnyObject) -> Swift.Int // CHECK-NOT: dynamic.Foo.init (dynamic.Foo.Type)(dynamic : Swift.Int) -> dynamic.Foo // CHECK-NOT: dynamic.Foo.dynamicMethod // CHECK-NOT: dynamic.Foo.subscript.getter (dynamic : Swift.Int) -> Swift.Int // CHECK-NOT: dynamic.Foo.subscript.setter (dynamic : Swift.Int) -> Swift.Int // CHECK-LABEL: #Foo.overriddenByDynamic!1: _TFC7dynamic3Foo19overriddenByDynamic // CHECK-LABEL: #Foo.nativeProp!getter.1: _TFC7dynamic3Foog10nativePropSi // dynamic.Foo.nativeProp.getter : Swift.Int // CHECK-LABEL: #Foo.nativeProp!setter.1: _TFC7dynamic3Foos10nativePropSi // dynamic.Foo.nativeProp.setter : Swift.Int // CHECK-LABEL: #Foo.objcProp!getter.1: _TFC7dynamic3Foog8objcPropSi // dynamic.Foo.objcProp.getter : Swift.Int // CHECK-LABEL: #Foo.objcProp!setter.1: _TFC7dynamic3Foos8objcPropSi // dynamic.Foo.objcProp.setter : Swift.Int // CHECK-NOT: dynamic.Foo.dynamicProp.getter // CHECK-NOT: dynamic.Foo.dynamicProp.setter // Vtable uses a dynamic thunk for dynamic overrides // CHECK-LABEL: sil_vtable Subclass { // CHECK-LABEL: #Foo.overriddenByDynamic!1: _TTDFC7dynamic8Subclass19overriddenByDynamic
apache-2.0
71124a8bad465211f6ddbbc814b2a25d
48.244111
165
0.693351
3.617018
false
false
false
false
Dimillian/SwiftHN
SwiftHNToday/RoundedLabel.swift
2
860
// // RoundedLabel.swift // SwiftHN // // Created by Thomas Ricouard on 31/07/14. // Copyright (c) 2014 Thomas Ricouard. All rights reserved. // import UIKit import SwiftHNShared @IBDesignable class RoundedLabel: UILabel { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } override init(frame: CGRect) { super.init(frame: frame) self.setup() } private func setup() { self.textColor = UIColor.HNColor() self.textAlignment = .Center self.text = "155" self.font = UIFont.systemFontOfSize(12.0) self.layer.borderColor = UIColor.HNColor().CGColor self.layer.borderWidth = 1.0 self.layer.cornerRadius = 12.5 } override func layoutSubviews() { super.layoutSubviews() } }
gpl-2.0
dad34162961b470cf5e42022c1aa29f6
21.631579
60
0.606977
4.056604
false
false
false
false
dklinzh/NodeExtension
NodeExtension/Classes/Node/DLSliderNode.swift
1
3202
// // DLSliderNode.swift // NodeExtension // // Created by Linzh on 8/27/17. // Copyright (c) 2017 Daniel Lin. All rights reserved. // import AsyncDisplayKit /// The Node object of slider view open class DLSliderNode: DLViewNode<DLTrackSlider> { public typealias DLSliderValueChangedBlock = (_ currentValue: Float) -> Void public var currentValue: Float { didSet { let _currentValue = currentValue self.appendViewAssociation { (view: DLTrackSlider) in view.setValue(_currentValue, animated: true) } } } public var isEnabled: Bool { get { return self.nodeView.isEnabled } set { self.appendViewAssociation { (view: DLTrackSlider) in view.isEnabled = newValue } } } public var maximumTrackTintColor: UIColor? { get { return self.nodeView.maximumTrackTintColor } set { self.appendViewAssociation { (view: DLTrackSlider) in view.maximumTrackTintColor = newValue } } } public var minimumTrackTintColor: UIColor? { get { return self.nodeView.minimumTrackTintColor } set { self.appendViewAssociation { (view: DLTrackSlider) in view.minimumTrackTintColor = newValue } } } public var thumbTintColor: UIColor? { get { return self.nodeView.thumbTintColor } set { self.appendViewAssociation { (view: DLTrackSlider) in view.thumbTintColor = newValue } } } public func setThumbImage(_ image: UIImage?, for state: UIControl.State) { self.appendViewAssociation { (view: DLTrackSlider) in view.setThumbImage(image, for: state) } } private var _step: Float private var _valueChangedBlock: DLSliderValueChangedBlock public init(trackHeight: CGFloat = 1.0, minValue: Float, maxValue: Float, step: Float, valueChanged: @escaping DLSliderValueChangedBlock) { _step = step _valueChangedBlock = valueChanged currentValue = minValue super.init() self.setViewBlock { () -> UIView in let sliderView = DLTrackSlider(trackHeight: trackHeight) sliderView.minimumValue = minValue sliderView.maximumValue = maxValue sliderView.isContinuous = true return sliderView } self.style.flexGrow = 1 self.style.minHeight = ASDimensionMake(34) } open override func didLoad() { super.didLoad() self.nodeView.addTarget(self, action: #selector(valueChanged(sender:)), for: .valueChanged) self.nodeView.addTarget(self, action: #selector(touchUpInside(sender:)), for: .touchUpInside) } @objc private func valueChanged(sender: UISlider) { currentValue = roundf(sender.value / _step) * _step } @objc private func touchUpInside(sender: UISlider) { _valueChangedBlock(currentValue) } }
mit
51713384d89a9239acdf035362c45c88
28.376147
143
0.590881
4.881098
false
false
false
false
Frostman/SalaryZen
SalaryZenKit/SalaryZenKit.swift
2
6095
// // SalaryZenKit.swift // SalaryZen // // Created by Sergey Lukjanov on 11/01/15. // Copyright (c) 2015 Sergey Lukjanov. All rights reserved. // import Foundation import Alamofire import SwiftyJSON import AlamofireSwiftyJSON public enum Bank: String { case Alfa = "Alfa" case Cbr = "CBR" public static let all = [Alfa, Cbr] public var title: String { get { return self.rawValue } } public var name: String { get { return self.rawValue.lowercaseString } } } public enum Currency: String { case USD = "USD" case EUR = "EUR" case CHF = "CHF" case GBP = "GBP" public static let all = [USD, EUR, CHF, GBP] public var title: String { get { return self.rawValue } } public var name: String { get { return self.rawValue.lowercaseString } } } public enum DataType: String { case Current = "Current" case Historic = "Hitoric" public static let all = [Current, Historic] public var title: String { get { return self.rawValue } } public var name: String { get { return self.rawValue.lowercaseString } } } public enum ExchangeType: String { case Sell = "Sell" case Buy = "Buy" case Rate = "Rate" public static let all = [Sell, Buy, Rate] public var title: String { get { return self.rawValue } } public var name: String { get { return self.rawValue.lowercaseString } } } public typealias CurrencyExchangeRate = Double public extension CurrencyExchangeRate { func format() -> String { return NSString(format: "%.2f", self) } } public class CurrencyRates { private let rates = [String: Double]() private let historic = [String: [NSDate: Double]]() public var aggregatedAtTimestamp: NSTimeInterval { get { return self.rates["aggregated_at"]! } } public init(json: JSON) { for (key: String, subJson: JSON) in json.dictionaryValue { if let rate = subJson.double { self.rates[key] = rate } else if let historic = subJson.dictionary { if key.rangeOfString("historic") == nil { // error } if self.historic[key] == nil { self.historic[key] = [NSDate: Double]() } for (date: String, rateJson: JSON) in subJson { if let rate = rateJson.double { // TBD Replace NSDate() with date parsing self.historic[key]![NSDate()] = rate } else { // error } } } else { // error! } } } public func getRate(bank: Bank, currency: Currency = Currency.USD, dataType: DataType = DataType.Current, exchangeType: ExchangeType = ExchangeType.Rate) -> CurrencyExchangeRate? { let key = "\(bank.name)_\(currency.name)_\(dataType.name)_\(exchangeType.name)" return self.rates[key] } public func getCurrentCbrUsdRate() -> CurrencyExchangeRate? { return self.getRate(Bank.Cbr, currency: Currency.USD, dataType: DataType.Current, exchangeType: ExchangeType.Rate) } public func getCurrentAlfaUsdRate(exchangeType: ExchangeType) -> CurrencyExchangeRate? { return self.getRate(Bank.Alfa, currency: Currency.USD, dataType: DataType.Current, exchangeType: exchangeType) } public func getCurrentAlfaUsdRates() -> (sell: CurrencyExchangeRate?, buy: CurrencyExchangeRate?) { return (self.getCurrentAlfaUsdRate(ExchangeType.Sell), self.getCurrentAlfaUsdRate(ExchangeType.Buy)) } } public class CurrencyRatesFetcher { private let cache = NSCache() private var cacheFor: NSTimeInterval = 10 * 60 // 10 minutes public init() { self.cache.name = "CurrencyRatesFetcherCache" } public func setConf(cacheFor: NSTimeInterval? = nil) { if let cacheFor = cacheFor { self.cacheFor = cacheFor } } public func fetch(handler: (CurrencyRates) -> Void) { let (cachedRates, outdated) = self.fetchFromCache() if let cachedRates = cachedRates { handler(cachedRates) } if outdated { fetchFromServer { (rates, error) in // if error retry? if let rates = rates { handler(rates) } } } } private func fetchFromCache() -> (rates: CurrencyRates?, outdated: Bool) { if let data = self.cache.objectForKey("data") as? CurrencyRates { let now = NSDate().timeIntervalSince1970 let outdated = now - data.aggregatedAtTimestamp > self.cacheFor return (data, outdated) } return (nil, true) } private func fetchFromServer(handler: (rates: CurrencyRates?, error: Bool) -> Void) { let url = "http://f.slukjanov.name/salaryzen/datav2.json" Alamofire.request(.GET, url).responseSwiftyJSON { (request, response, json, error) in if json != nil && error == nil { let rates = CurrencyRates(json: json) self.cache.setObject(rates, forKey: "data") handler(rates: rates, error: false) } else { handler(rates: nil, error: true) } } } } public let fetcher = CurrencyRatesFetcher() public func fetchRatesInfo(handler: (info: String) -> Void) { fetcher.fetch { rates in let cbrRate = rates.getCurrentCbrUsdRate() ?? 0.0 let (alfaSellOpt, alfaBuyOpt) = rates.getCurrentAlfaUsdRates() let alfaSell = alfaSellOpt ?? 0.0 let alfaBuy = alfaBuyOpt ?? 0.0 let coef = cbrRate / 36.93 handler(info: "$ \(alfaBuy.format()) / \(alfaSell.format()) " + "cb: \(cbrRate.format()) (\(coef.format()))") } }
apache-2.0
a09baf5c11a0b68646744032f1706818
27.485981
94
0.5726
4.238526
false
false
false
false
lhx931119/DouYuTest
DouYu/DouYu/Classes/Home/Model/CycleModel.swift
1
818
// // CycleModel.swift // DouYu // // Created by 李宏鑫 on 17/1/17. // Copyright © 2017年 hongxinli. All rights reserved. // import UIKit class CycleModel: NSObject { ///标题 var title: String = "" ///展示图片的地址 var pic_url: String = "" ///图片地址 var icon_url: String = "" ///主播信息对应的字典 var room: [String: NSObject]?{ didSet{ guard let room = room else {return} anchor = AnchorModel(dic: room) } } ///主播信息对应的模型 var anchor: AnchorModel? //自定义构造函数 init(dic: [String: NSObject]) { super.init() setValuesForKeysWithDictionary(dic) } override func setValue(value: AnyObject?, forUndefinedKey key: String) {} }
mit
4dd5c3930595426cced37184ab5774e5
18.289474
77
0.564802
3.857895
false
false
false
false
dvaughn1712/perfect-routing
PerfectLib/HTTP2.swift
2
16803
// // HTTP2.swift // PerfectLib // // Created by Kyle Jessup on 2016-02-18. // Copyright © 2016 PerfectlySoft. All rights reserved. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // // NOTE: This HTTP/2 client is competent enough to operate with Apple's push notification service, but // still lacks some functionality to make it general purpose. Consider it a work in-progress. #if os(Linux) import SwiftGlibc #endif let HTTP2_DATA = UInt8(0x0) let HTTP2_HEADERS = UInt8(0x1) let HTTP2_PRIORITY = UInt8(0x2) let HTTP2_RST_STREAM = UInt8(0x3) let HTTP2_SETTINGS = UInt8(0x4) let HTTP2_PUSH_PROMISE = UInt8(0x5) let HTTP2_PING = UInt8(0x6) let HTTP2_GOAWAY = UInt8(0x7) let HTTP2_WINDOW_UPDATE = UInt8(0x8) let HTTP2_CONTINUATION = UInt8(0x9) let HTTP2_END_STREAM = UInt8(0x1) let HTTP2_END_HEADERS = UInt8(0x4) let HTTP2_PADDED = UInt8(0x8) let HTTP2_FLAG_PRIORITY = UInt8(0x20) let HTTP2_SETTINGS_ACK = HTTP2_END_STREAM let HTTP2_PING_ACK = HTTP2_END_STREAM let SETTINGS_HEADER_TABLE_SIZE = UInt16(0x1) let SETTINGS_ENABLE_PUSH = UInt16(0x2) let SETTINGS_MAX_CONCURRENT_STREAMS = UInt16(0x3) let SETTINGS_INITIAL_WINDOW_SIZE = UInt16(0x4) let SETTINGS_MAX_FRAME_SIZE = UInt16(0x5) let SETTINGS_MAX_HEADER_LIST_SIZE = UInt16(0x6) public struct HTTP2Frame { let length: UInt32 // 24-bit let type: UInt8 let flags: UInt8 let streamId: UInt32 // 31-bit var payload: [UInt8]? var typeStr: String { switch self.type { case HTTP2_DATA: return "HTTP2_DATA" case HTTP2_HEADERS: return "HTTP2_HEADERS" case HTTP2_PRIORITY: return "HTTP2_PRIORITY" case HTTP2_RST_STREAM: return "HTTP2_RST_STREAM" case HTTP2_SETTINGS: return "HTTP2_SETTINGS" case HTTP2_PUSH_PROMISE: return "HTTP2_PUSH_PROMISE" case HTTP2_PING: return "HTTP2_PING" case HTTP2_GOAWAY: return "HTTP2_GOAWAY" case HTTP2_WINDOW_UPDATE: return "HTTP2_WINDOW_UPDATE" case HTTP2_CONTINUATION: return "HTTP2_CONTINUATION" default: return "UNKNOWN_TYPE" } } var flagsStr: String { var s = "" if flags == 0 { s.appendContentsOf("NO FLAGS") } if (flags & HTTP2_END_STREAM) != 0 { s.appendContentsOf(" +HTTP2_END_STREAM") } if (flags & HTTP2_END_HEADERS) != 0 { s.appendContentsOf(" +HTTP2_END_HEADERS") } return s } func headerBytes() -> [UInt8] { var data = [UInt8]() let l = htonl(length) >> 8 data.append(UInt8(l & 0xFF)) data.append(UInt8((l >> 8) & 0xFF)) data.append(UInt8((l >> 16) & 0xFF)) data.append(type) data.append(flags) let s = htonl(streamId) data.append(UInt8(s & 0xFF)) data.append(UInt8((s >> 8) & 0xFF)) data.append(UInt8((s >> 16) & 0xFF)) data.append(UInt8((s >> 24) & 0xFF)) return data } } class HTTP2Connection: WebConnection { weak var client: HTTP2Client? var status = (200, "OK") init(client: HTTP2Client) { self.client = client } /// The TCP based connection var connection: NetTCP { if let c = self.client { return c.net } return NetTCP() // return non-connected } /// The parameters sent by the client var requestParams = [String:String]() /// Any non mime based request body data var stdin: [UInt8]? { return nil } /// Parsed mime based body data var mimes: MimeReader? { return nil } /// Set the response status code and message. For example, 200, "OK". func setStatus(code: Int, msg: String) { self.status = (code, msg) } /// Get the response status code and message. func getStatus() -> (Int, String) { return self.status } /// Add a response header which will be sent to the client. func writeHeaderLine(h: String) {} /// Send header bytes to the client. func writeHeaderBytes(b: [UInt8]) {} /// Write body bytes ot the client. Any pending header data will be written first. func writeBodyBytes(b: [UInt8]) {} } public class HTTP2WebRequest: WebRequest { } public class HTTP2WebResponse: WebResponse, HeaderListener { public func addHeader(name: [UInt8], value: [UInt8], sensitive: Bool) { let n = UTF8Encoding.encode(name) let v = UTF8Encoding.encode(value) switch n { case ":status": self.setStatus(Int(v) ?? -1, message: "") default: headersArray.append((n, v)) } } } public class HTTP2Client { enum StreamState { case None, Idle, ReservedLocal, ReservedRemote, Open, HalfClosedRemote, HalfClosedLocal, Closed } let net = NetTCPSSL() var host = "" var timeoutSeconds = 5.0 var ssl = true var streams = [UInt32:StreamState]() var streamCounter = UInt32(1) var encoder = HPACKEncoder() let closeLock = Threading.Lock() let frameReadEvent = Threading.Event() var frameQueue = [HTTP2Frame]() var frameReadOK = false var newStreamId: UInt32 { streams[streamCounter] = .None let s = streamCounter streamCounter += 2 return s } public init() { } func dequeueFrame(timeoutSeconds: Double) -> HTTP2Frame? { var frame: HTTP2Frame? = nil self.frameReadEvent.doWithLock { if self.frameQueue.count == 0 { self.frameReadEvent.wait(Int(timeoutSeconds * 1000.0)) } if self.frameQueue.count > 0 { frame = self.frameQueue.removeFirst() } } return frame } func dequeueFrame(timeoutSeconds: Double, streamId: UInt32) -> HTTP2Frame? { var frame: HTTP2Frame? = nil self.frameReadEvent.doWithLock { if self.frameQueue.count == 0 { self.frameReadEvent.wait(Int(timeoutSeconds * 1000.0)) } if self.frameQueue.count > 0 { for i in 0..<self.frameQueue.count { let frameTest = self.frameQueue[i] if frameTest.streamId == streamId { self.frameQueue.removeAtIndex(i) frame = frameTest break } } } } return frame } func processSettingsPayload(b: Bytes) { while b.availableExportBytes >= 6 { let identifier = ntohs(b.export16Bits()) // let value = ntohl(b.export32Bits()) // print("Setting \(identifier) \(value)") switch identifier { case SETTINGS_HEADER_TABLE_SIZE: ()//self.encoder = HPACKEncoder(maxCapacity: Int(value)) case SETTINGS_ENABLE_PUSH: () case SETTINGS_MAX_CONCURRENT_STREAMS: () case SETTINGS_INITIAL_WINDOW_SIZE: () case SETTINGS_MAX_FRAME_SIZE: () case SETTINGS_MAX_HEADER_LIST_SIZE: () default: () } } } func readOneFrame() { Threading.dispatchBlock { self.readHTTP2Frame(-1) { [weak self] f in if let frame = f { // print("Read frame \(frame.typeStr) \(frame.flagsStr) \(frame.streamId)") // if frame.length > 0 { // print("Read frame payload \(frame.length) \(UTF8Encoding.encode(frame.payload!))") // } self?.frameReadEvent.doWithLock { switch frame.type { case HTTP2_SETTINGS: let endStream = (frame.flags & HTTP2_SETTINGS_ACK) != 0 if !endStream { // ACK settings receipt if let payload = frame.payload { self?.processSettingsPayload(Bytes(existingBytes: payload)) } let response = HTTP2Frame(length: 0, type: HTTP2_SETTINGS, flags: HTTP2_SETTINGS_ACK, streamId: 0, payload: nil) self?.writeHTTP2Frame(response) { b in self?.readOneFrame() } } else { // ACK of our settings frame self?.readOneFrame() } case HTTP2_PING: let endStream = (frame.flags & HTTP2_PING_ACK) != 0 if !endStream { // ACK ping receipt if let payload = frame.payload { self?.processSettingsPayload(Bytes(existingBytes: payload)) } let response = HTTP2Frame(length: frame.length, type: HTTP2_PING, flags: HTTP2_PING_ACK, streamId: 0, payload: frame.payload) self?.writeHTTP2Frame(response) { b in self?.readOneFrame() } } else { // ACK of our ping frame self?.readOneFrame() } default: self?.frameQueue.append(frame) self?.frameReadOK = true self?.frameReadEvent.broadcast() } } } else { // network error self?.frameReadEvent.doWithLock { self?.close() self?.frameReadOK = false self?.frameReadEvent.broadcast() } } } } } func startReadThread() { Threading.dispatchBlock { [weak self] in // dbg defer { print("~HTTP2Client.startReadThread") } if let net = self?.net { while net.fd.isValid { if let s = self { s.frameReadEvent.doWithLock { s.frameReadOK = false s.readOneFrame() if !s.frameReadOK && net.fd.isValid { s.frameReadEvent.wait() } } if !s.frameReadOK { s.close() break } } else { net.close() break } } } } } public func close() { self.closeLock.doWithLock { self.net.close() } } public var isConnected: Bool { return self.net.fd.isValid } public func connect(host: String, port: UInt16, ssl: Bool, timeoutSeconds: Double, callback: (Bool) -> ()) { self.host = host self.ssl = ssl self.timeoutSeconds = timeoutSeconds do { try net.connect(host, port: port, timeoutSeconds: timeoutSeconds) { n in if let net = n as? NetTCPSSL { if ssl { net.beginSSL { b in if b { self.completeConnect(callback) } else { callback(false) } } } else { self.completeConnect(callback) } } else { callback(false) } } } catch { callback(false) } } public func createRequest() -> HTTP2WebRequest { return HTTP2WebRequest(HTTP2Connection(client: self)) } func awaitResponse(streamId: UInt32, request: WebRequest, callback: (WebResponse?, String?) -> ()) { let response = HTTP2WebResponse(request.connection, request: request) var streamOpen = true while streamOpen { let f = self.dequeueFrame(self.timeoutSeconds, streamId: streamId) if let frame = f { switch frame.type { case HTTP2_GOAWAY: let bytes = Bytes(existingBytes: frame.payload!) let streamId = ntohl(bytes.export32Bits()) let errorCode = ntohl(bytes.export32Bits()) var message = "" if bytes.availableExportBytes > 0 { message = UTF8Encoding.encode(bytes.exportBytes(bytes.availableExportBytes)) } let bytes2 = Bytes(initialSize: 8) bytes2.import32Bits(htonl(streamId)) bytes2.import32Bits(0) let frame2 = HTTP2Frame(length: 8, type: HTTP2_GOAWAY, flags: 0, streamId: streamId, payload: bytes2.data) self.writeHTTP2Frame(frame2) { b in self.close() } callback(nil, "\(errorCode) \(message)") streamOpen = false case HTTP2_HEADERS: let padded = (frame.flags & HTTP2_PADDED) != 0 // let priority = (frame.flags & HTTP2_PRIORITY) != 0 // let end = (frame.flags & HTTP2_END_HEADERS) != 0 if let ba = frame.payload where ba.count > 0 { let bytes = Bytes(existingBytes: ba) var padLength = UInt8(0) // var streamDep = UInt32(0) // var weight = UInt8(0) if padded { padLength = bytes.export8Bits() } // if priority { // streamDep = bytes.export32Bits() // weight = bytes.export8Bits() // } self.decodeHeaders(bytes, endPosition: ba.count - Int(padLength), listener: response) } streamOpen = (frame.flags & HTTP2_END_STREAM) == 0 if !streamOpen { callback(response, nil) } case HTTP2_DATA: if frame.length > 0 { response.bodyData.appendContentsOf(frame.payload!) } streamOpen = (frame.flags & HTTP2_END_STREAM) == 0 if !streamOpen { callback(response, nil) } default: streamOpen = false callback(nil, "Unexpected frame type \(frame.typeStr)") } } else { self.close() streamOpen = false callback(nil, "Connection dropped") } } } public func sendRequest(request: WebRequest, callback: (WebResponse?, String?) -> ()) { let streamId = self.newStreamId self.streams[streamId] = .Idle let headerBytes = Bytes() let method = request.requestMethod() let scheme = ssl ? "https" : "http" let path = request.requestURI() do { try encoder.encodeHeader(headerBytes, name: ":method", value: method) try encoder.encodeHeader(headerBytes, name: ":scheme", value: scheme) try encoder.encodeHeader(headerBytes, name: ":path", value: path, sensitive: false, incrementalIndexing: false) try encoder.encodeHeader(headerBytes, name: "host", value: self.host) try encoder.encodeHeader(headerBytes, name: "content-length", value: "\(request.postBodyBytes.count)") for (name, value) in request.headers { let lowered = name.lowercaseString var inc = true // this is APNS specific in that Apple wants the apns-id and apns-expiration headers to be indexed on the first request but not indexed on subsequent requests // !FIX! need to enable the caller to indicate policies such as this let n = UTF8Encoding.decode(lowered) let v = UTF8Encoding.decode(value) if streamId > 1 { // at least the second request inc = !(lowered == "apns-id" || lowered == "apns-expiration") } try encoder.encodeHeader(headerBytes, name: n, value: v, sensitive: false, incrementalIndexing: inc) } } catch { callback(nil, "Header encoding exception \(error)") return } let hasData = request.postBodyBytes.count > 0 let frame = HTTP2Frame(length: UInt32(headerBytes.data.count), type: HTTP2_HEADERS, flags: HTTP2_END_HEADERS | (hasData ? 0 : HTTP2_END_STREAM), streamId: streamId, payload: headerBytes.data) self.writeHTTP2Frame(frame) { [weak self] b in guard b else { callback(nil, "Unable to write frame") return } guard let s = self else { callback(nil, nil) return } s.streams[streamId] = .Open if hasData { let frame2 = HTTP2Frame(length: UInt32(request.postBodyBytes.count), type: HTTP2_DATA, flags: HTTP2_END_STREAM, streamId: streamId, payload: request.postBodyBytes) s.writeHTTP2Frame(frame2) { [weak self] b in guard let s = self else { callback(nil, nil) return } s.awaitResponse(streamId, request: request, callback: callback) } } else { s.awaitResponse(streamId, request: request, callback: callback) } } } func completeConnect(callback: (Bool) -> ()) { net.writeString("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") { wrote in let settings = HTTP2Frame(length: 0, type: HTTP2_SETTINGS, flags: 0, streamId: 0, payload: nil) self.writeHTTP2Frame(settings) { [weak self] b in if b { self?.startReadThread() } callback(b) } } } func bytesToHeader(b: [UInt8]) -> HTTP2Frame { let payloadLength = (UInt32(b[0]) << 16) + (UInt32(b[1]) << 8) + UInt32(b[2]) let type = b[3] let flags = b[4] var sid: UInt32 = UInt32(b[5]) sid << 8 sid += UInt32(b[6]) sid << 8 sid += UInt32(b[7]) sid << 8 sid += UInt32(b[8]) sid &= ~0x80000000 return HTTP2Frame(length: payloadLength, type: type, flags: flags, streamId: sid, payload: nil) } func readHTTP2Frame(timeout: Double, callback: (HTTP2Frame?) -> ()) { let net = self.net net.readBytesFully(9, timeoutSeconds: timeout) { bytes in if let b = bytes { var header = self.bytesToHeader(b) if header.length > 0 { net.readBytesFully(Int(header.length), timeoutSeconds: timeout) { bytes in header.payload = bytes callback(header) } } else { callback(header) } } else { callback(nil) } } } func writeHTTP2Frame(frame: HTTP2Frame, callback: (Bool) -> ()) { if !net.fd.isValid { callback(false) } else if !net.writeBytesFully(frame.headerBytes()) { callback(false) } else { // print("Wrote frame \(frame.typeStr) \(frame.flagsStr) \(frame.streamId)") if let p = frame.payload { callback(net.writeBytesFully(p)) } else { callback(true) } } } func encodeHeaders(headers: [(String, String)]) -> Bytes { let b = Bytes() let encoder = HPACKEncoder(maxCapacity: 4096) for header in headers { let n = UTF8Encoding.decode(header.0) let v = UTF8Encoding.decode(header.1) do { try encoder.encodeHeader(b, name: n, value: v, sensitive: false) } catch { self.close() break } } return b } func decodeHeaders(from: Bytes, endPosition: Int, listener: HeaderListener) { let decoder = HPACKDecoder() do { try decoder.decode(from, headerListener: listener) } catch { self.close() } } }
unlicense
dda5a4db88fea5dee04a434254bada19
24.226727
193
0.638176
3.130427
false
false
false
false
ceaseless-prayer/CeaselessIOS
Ceaseless/BWWalkthroughPageViewController.swift
1
6434
/* The MIT License (MIT) Copyright (c) 2015 Yari D'areglia @bitwaker Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit public enum WalkthroughAnimationType:String{ case Linear = "Linear" case Curve = "Curve" case Zoom = "Zoom" case InOut = "InOut" init(_ name:String){ if let tempSelf = WalkthroughAnimationType(rawValue: name){ self = tempSelf }else{ self = .Linear } } } open class BWWalkthroughPageViewController: UIViewController, BWWalkthroughPage { fileprivate var animation:WalkthroughAnimationType = .Linear fileprivate var subsWeights:[CGPoint] = Array() fileprivate var notAnimatableViews:[Int] = [] // Array of views' tags that should not be animated during the scroll/transition // MARK: Inspectable Properties // Edit these values using the Attribute inspector or modify directly the "User defined runtime attributes" in IB @IBInspectable var speed:CGPoint = CGPoint(x: 0.0, y: 0.0); // Note if you set this value via Attribute inspector it can only be an Integer (change it manually via User defined runtime attribute if you need a Float) @IBInspectable var speedVariance:CGPoint = CGPoint(x: 0.0, y: 0.0) // Note if you set this value via Attribute inspector it can only be an Integer (change it manually via User defined runtime attribute if you need a Float) @IBInspectable var animationType:String { set(value){ self.animation = WalkthroughAnimationType(rawValue: value)! } get{ return self.animation.rawValue } } @IBInspectable var animateAlpha:Bool = false @IBInspectable var staticTags:String { // A comma separated list of tags that you don't want to animate during the transition/scroll set(value){ self.notAnimatableViews = value.components(separatedBy: ",").map{Int($0)!} } get{ return notAnimatableViews.map{String($0)}.joined(separator: ",") } } // MARK: BWWalkthroughPage Implementation override open func viewDidLoad() { super.viewDidLoad() self.view.layer.masksToBounds = true subsWeights = Array() for v in view.subviews{ speed.x += speedVariance.x speed.y += speedVariance.y if !notAnimatableViews.contains(v.tag) { subsWeights.append(speed) } } } open func walkthroughDidScroll(_ position: CGFloat, offset: CGFloat) { for i in (0..<subsWeights.count){ // Perform Transition/Scale/Rotate animations switch animation{ case .Linear: animationLinear(i, offset) case .Zoom: animationZoom(i, offset) case .Curve: animationCurve(i, offset) case .InOut: animationInOut(i, offset) } // Animate alpha if(animateAlpha){ animationAlpha(i, offset) } } } // MARK: Animations (WIP) private func animationAlpha(_ index:Int, _ offset:CGFloat){ var offset = offset let cView = view.subviews[index] if(offset > 1.0){ offset = 1.0 + (1.0 - offset) } cView.alpha = (offset) } fileprivate func animationCurve(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity let x:CGFloat = (1.0 - offset) * 10 transform = CATransform3DTranslate(transform, (pow(x,3) - (x * 25)) * subsWeights[index].x, (pow(x,3) - (x * 20)) * subsWeights[index].y, 0 ) applyTransform(index, transform: transform) } fileprivate func animationZoom(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity var tmpOffset = offset if(tmpOffset > 1.0){ tmpOffset = 1.0 + (1.0 - tmpOffset) } let scale:CGFloat = (1.0 - tmpOffset) transform = CATransform3DScale(transform, 1 - scale , 1 - scale, 1.0) applyTransform(index, transform: transform) } fileprivate func animationLinear(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity let mx:CGFloat = (1.0 - offset) * 100 transform = CATransform3DTranslate(transform, mx * subsWeights[index].x, mx * subsWeights[index].y, 0 ) applyTransform(index, transform: transform) } fileprivate func animationInOut(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity //var x:CGFloat = (1.0 - offset) * 20 var tmpOffset = offset if(tmpOffset > 1.0){ tmpOffset = 1.0 + (1.0 - tmpOffset) } transform = CATransform3DTranslate(transform, (1.0 - tmpOffset) * subsWeights[index].x * 100, (1.0 - tmpOffset) * subsWeights[index].y * 100, 0) applyTransform(index, transform: transform) } fileprivate func applyTransform(_ index:Int, transform:CATransform3D){ let subview = view.subviews[index] if !notAnimatableViews.contains(subview.tag){ view.subviews[index].layer.transform = transform } } }
mit
9a673553bce43acab4b57bf2df367f02
35.977011
230
0.623562
4.686089
false
false
false
false
wordpress-mobile/WordPress-Aztec-iOS
Aztec/Classes/Converters/StringAttributesToAttributes/Implementations/SubscriptStringAttributeConverter.swift
2
1683
import Foundation import UIKit /// Converts the subscript style information from string attributes and aggregates it into an /// existing array of element nodes. /// open class SubscriptStringAttributeConverter: StringAttributeConverter { private let toggler = HTMLStyleToggler(defaultElement: .sub, cssAttributeMatcher: NeverCSSAttributeMatcher()) public func convert( attributes: [NSAttributedString.Key: Any], andAggregateWith elementNodes: [ElementNode]) -> [ElementNode] { var elementNodes = elementNodes // We add the representation right away, if it exists... as it could contain attributes beyond just this // style. The enable and disable methods below can modify this as necessary. // if let representation = attributes[NSAttributedString.Key.subHtmlRepresentation] as? HTMLRepresentation, case let .element(representationElement) = representation.kind { elementNodes.append(representationElement.toElementNode()) } if shouldEnable(for: attributes) { return toggler.enable(in: elementNodes) } else { return toggler.disable(in: elementNodes) } } // MARK: - Style Detection func shouldEnable(for attributes: [NSAttributedString.Key : Any]) -> Bool { return hasTraits(for: attributes) } func hasTraits(for attributes: [NSAttributedString.Key : Any]) -> Bool { guard let baselineOffset = attributes[.baselineOffset] as? NSNumber else { return false } return baselineOffset.intValue < 0; } }
gpl-2.0
b23134fa14d5bb9fbb60e5b6c6b7b4dd
34.0625
113
0.659537
5.226708
false
false
false
false
HassanEskandari/Eureka
Source/Rows/Common/SelectorRow.swift
4
3581
// SelectorRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation open class PushSelectorCell<T: Equatable> : Cell<T>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func update() { super.update() accessoryType = .disclosureIndicator editingAccessoryType = accessoryType selectionStyle = row.isDisabled ? .none : .default } } /// Generic row type where a user must select a value among several options. open class SelectorRow<Cell: CellType>: OptionsRow<Cell>, PresenterRowType where Cell: BaseCell { public typealias PresenterRow = SelectorViewController<SelectorRow<Cell>> /// Defines how the view controller will be presented, pushed, etc. open var presentationMode: PresentationMode<PresenterRow>? /// Will be called before the presentation occurs. open var onPresentCallback: ((FormViewController, PresenterRow) -> Void)? required public init(tag: String?) { super.init(tag: tag) } /** Extends `didSelect` method */ open override func customDidSelect() { super.customDidSelect() guard let presentationMode = presentationMode, !isDisabled else { return } if let controller = presentationMode.makeController() { controller.row = self controller.title = selectorTitle ?? controller.title onPresentCallback?(cell.formViewController()!, controller) presentationMode.present(controller, row: self, presentingController: self.cell.formViewController()!) } else { presentationMode.present(nil, row: self, presentingController: self.cell.formViewController()!) } } /** Prepares the pushed row setting its title and completion callback. */ open override func prepare(for segue: UIStoryboardSegue) { super.prepare(for: segue) guard let rowVC = segue.destination as? PresenterRow else { return } rowVC.title = selectorTitle ?? rowVC.title rowVC.onDismissCallback = presentationMode?.onDismissCallback ?? rowVC.onDismissCallback onPresentCallback?(cell.formViewController()!, rowVC) rowVC.row = self } }
mit
b71a70df042b379f6ab3397945944263
39.693182
114
0.707624
5.050776
false
false
false
false
ksco/swift-algorithm-club-cn
Segment Tree/SegmentTree.playground/Contents.swift
1
5193
//: Playground - noun: a place where people can play public class SegmentTree<T> { private var value: T private var function: (T, T) -> T private var leftBound: Int private var rightBound: Int private var leftChild: SegmentTree<T>? private var rightChild: SegmentTree<T>? public init(array: [T], leftBound: Int, rightBound: Int, function: (T, T) -> T) { self.leftBound = leftBound self.rightBound = rightBound self.function = function if leftBound == rightBound { value = array[leftBound] } else { let middle = (leftBound + rightBound) / 2 leftChild = SegmentTree<T>(array: array, leftBound: leftBound, rightBound: middle, function: function) rightChild = SegmentTree<T>(array: array, leftBound: middle+1, rightBound: rightBound, function: function) value = function(leftChild!.value, rightChild!.value) } } public convenience init(array: [T], function: (T, T) -> T) { self.init(array: array, leftBound: 0, rightBound: array.count-1, function: function) } public func queryWithLeftBound(leftBound: Int, rightBound: Int) -> T { if self.leftBound == leftBound && self.rightBound == rightBound { return self.value } guard let leftChild = leftChild else { fatalError("leftChild should not be nil") } guard let rightChild = rightChild else { fatalError("rightChild should not be nil") } if leftChild.rightBound < leftBound { return rightChild.queryWithLeftBound(leftBound, rightBound: rightBound) } else if rightChild.leftBound > rightBound { return leftChild.queryWithLeftBound(leftBound, rightBound: rightBound) } else { let leftResult = leftChild.queryWithLeftBound(leftBound, rightBound: leftChild.rightBound) let rightResult = rightChild.queryWithLeftBound(rightChild.leftBound, rightBound: rightBound) return function(leftResult, rightResult) } } public func replaceItemAtIndex(index: Int, withItem item: T) { if leftBound == rightBound { value = item } else if let leftChild = leftChild, rightChild = rightChild { if leftChild.rightBound >= index { leftChild.replaceItemAtIndex(index, withItem: item) } else { rightChild.replaceItemAtIndex(index, withItem: item) } value = function(leftChild.value, rightChild.value) } } } let array = [1, 2, 3, 4] let sumSegmentTree = SegmentTree(array: array, function: +) print(sumSegmentTree.queryWithLeftBound(0, rightBound: 3)) // 1 + 2 + 3 + 4 = 10 print(sumSegmentTree.queryWithLeftBound(1, rightBound: 2)) // 2 + 3 = 5 print(sumSegmentTree.queryWithLeftBound(0, rightBound: 0)) // 1 = 1 sumSegmentTree.replaceItemAtIndex(0, withItem: 2) //our array now is [2, 2, 3, 4] print(sumSegmentTree.queryWithLeftBound(0, rightBound: 0)) // 2 = 2 print(sumSegmentTree.queryWithLeftBound(0, rightBound: 1)) // 2 + 2 = 4 //you can use any associative function (i.e (a+b)+c == a+(b+c)) as function for segment tree func gcd(m: Int, _ n: Int) -> Int { var a = 0 var b = max(m, n) var r = min(m, n) while r != 0 { a = b b = r r = a % b } return b } let gcdArray = [2, 4, 6, 3, 5] let gcdSegmentTree = SegmentTree(array: gcdArray, function: gcd) print(gcdSegmentTree.queryWithLeftBound(0, rightBound: 1)) // gcd(2, 4) = 2 print(gcdSegmentTree.queryWithLeftBound(2, rightBound: 3)) // gcd(6, 3) = 3 print(gcdSegmentTree.queryWithLeftBound(1, rightBound: 3)) // gcd(4, 6, 3) = 1 print(gcdSegmentTree.queryWithLeftBound(0, rightBound: 4)) // gcd(2, 4, 6, 3, 5) = 1 gcdSegmentTree.replaceItemAtIndex(3, withItem: 10) //gcdArray now is [2, 4, 6, 10, 5] print(gcdSegmentTree.queryWithLeftBound(3, rightBound: 4)) // gcd(10, 5) = 5 //example of segment tree which finds minimum on given range let minArray = [2, 4, 1, 5, 3] let minSegmentTree = SegmentTree(array: minArray, function: min) print(minSegmentTree.queryWithLeftBound(0, rightBound: 4)) // min(2, 4, 1, 5, 3) = 1 print(minSegmentTree.queryWithLeftBound(0, rightBound: 1)) // min(2, 4) = 2 minSegmentTree.replaceItemAtIndex(2, withItem: 10) // minArray now is [2, 4, 10, 5, 3] print(minSegmentTree.queryWithLeftBound(0, rightBound: 4)) // min(2, 4, 10, 5, 3) = 2 //type of elements in array can be any type which has some associative function let stringArray = ["a", "b", "c", "A", "B", "C"] let stringSegmentTree = SegmentTree(array: stringArray, function: +) print(stringSegmentTree.queryWithLeftBound(0, rightBound: 1)) // "a"+"b" = "ab" print(stringSegmentTree.queryWithLeftBound(2, rightBound: 3)) // "c"+"A" = "cA" print(stringSegmentTree.queryWithLeftBound(1, rightBound: 3)) // "b"+"c"+"A" = "bcA" print(stringSegmentTree.queryWithLeftBound(0, rightBound: 5)) // "a"+"b"+"c"+"A"+"B"+"C" = "abcABC" stringSegmentTree.replaceItemAtIndex(0, withItem: "I") stringSegmentTree.replaceItemAtIndex(1, withItem: " like") stringSegmentTree.replaceItemAtIndex(2, withItem: " algorithms") stringSegmentTree.replaceItemAtIndex(3, withItem: " and") stringSegmentTree.replaceItemAtIndex(4, withItem: " swift") stringSegmentTree.replaceItemAtIndex(5, withItem: "!") print(stringSegmentTree.queryWithLeftBound(0, rightBound: 5))
mit
fbaeefcc23482678aeb4facc341ee097
36.092857
112
0.694011
3.754881
false
false
false
false
KPRSN/Lr-backup
Lr backup/StatusIcon.swift
1
1627
// // StatusIcon.swift // Lr backup // // Created by Karl Persson on 2015-11-10. // Copyright © 2015 Karl Persson. All rights reserved. // // Class for handling and animating the status bar icons // import Cocoa class StatusIcon: NSObject { var button: NSButton! var animationTimer: NSTimer! let idleImage = NSImage(named: "Icon-idle") let runningImages = [NSImage(named: "Icon-running1"), NSImage(named: "Icon-running2")] let errorImage = NSImage(named: "Icon-error") init(button: NSButton) { super.init() self.button = button // Set as templates to ensure that it will work with dark theme idleImage?.template = true errorImage?.template = true for image in runningImages { image!.template = true } idle() } func idle() { animationTimer?.invalidate() button.image = NSImage(named: "Icon-idle") } func running() { animationTimer?.invalidate() button.image = NSImage(named: "Icon-running1") animationTimer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "updateRunning", userInfo: nil, repeats: true) } func error() { animationTimer?.invalidate() button.image = NSImage(named: "Icon-error") animationTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "updateError", userInfo: nil, repeats: true) } // Icon animations func updateError() { if button.image == errorImage { button.image = idleImage } else { button.image = errorImage } } func updateRunning() { if button.image == runningImages[0] { button.image = runningImages[1] } else { button.image = runningImages[0] } } }
mit
3cdcb32cc656affacc7878eb333a0bac
22.228571
133
0.691882
3.373444
false
false
false
false
Yurssoft/QuickFile
QuickFile/Additional_Classes/Extensions/YSStringExtension.swift
1
999
// // YSURLExtension.swift // QuickFile // // Created by Yurii Boiko on 8/24/17. // Copyright © 2017 Yurii Boiko. All rights reserved. // import Foundation extension String { mutating func addingPercentEncoding(_ nextPageToken: String?) { if let nextPageToken = nextPageToken { let encodedNextPageToken = CFURLCreateStringByAddingPercentEscapes( nil, nextPageToken as CFString!, nil, "!'();:@&=+$,/?%#[]" as CFString!, CFStringBuiltInEncodings.ASCII.rawValue )! self += "pageToken=\(encodedNextPageToken)&" } } } protocol OptionalString {} extension String: OptionalString {} extension Optional where Wrapped: OptionalString { func unwrapped(_ defaultValue: @autoclosure () -> String? = "") -> String { guard let unwroppedSelf = self as? String else { return defaultValue()! } return unwroppedSelf } }
mit
451ec253ad020de51ac9832038efa6a8
26.722222
79
0.596192
4.99
false
false
false
false
Yurssoft/QuickFile
QuickFile/Additional_Classes/YSAppDelegate.swift
1
11670
// // AppDelegate.swift // YSGGP // // Created by Yurii Boiko on 9/19/16. // Copyright © 2016 Yurii Boiko. All rights reserved. // import UIKit import GTMOAuth2 import Firebase import GoogleSignIn import NSLogger import UserNotifications import SafariServices import Reqres import AVFoundation protocol YSUpdatingDelegate: class { func downloadDidChange(_ download: YSDownloadProtocol, _ error: YSErrorProtocol?) func filesDidChange() } /* TODO: - search add loading indicator - show all downloads in playlist - logged as - firebase functions? - add spotlight search - add search in playlist - delete played files after 24 hours - display all files in drive and use document previewer for all files - make downloads in order - add tutorial screen - battery life - send logs - share extension - google analytics - playlist delete downloads - reverse sorting of files - rethink relogin, what to do with current data and downloads and current downloads - update to crashlitycs - fix wrong player reload after download - understand that uitabbarcontroller is already acting as coordinator, remove segways and as first step start viewmodel loading only after view did loaded - display current playing in drive VC - what happens to logs on no storage? - stop player when playing locally from cell - in search go to some foler - update downloads in this folder - go back to search - download changes are not reflected in search - why sometimes size of mp3 is not displayed? - do not save file to disk in main thread - possibility to play files from local storage with folder "local" - crash on typing ukrainian characters in search - show played sign in drive files to make a shortcut when you need to download file to see if it is played - show playlist as tree and open/close it - scroll playlist to currently playing song */ @UIApplicationMain class YSAppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var driveTopCoordinator: YSDriveTopCoordinator? var searchCoordinator: YSDriveSearchCoordinator? var playerCoordinator = YSPlayerCoordinator() var settingsCoordinator = YSSettingsCoordinator() var playlistCoordinator = YSPlaylistCoordinator() var backgroundSession: URLSession? var backgroundSessionCompletionHandler: (() -> Void)? var fileDownloader: YSDriveFileDownloader = YSDriveFileDownloader() var filesOnDisk = Set<String>() weak var downloadsDelegate: YSUpdatingDelegate? weak var playlistDelegate: YSUpdatingDelegate? weak var playerDelegate: YSUpdatingDelegate? weak var driveDelegate: YSUpdatingDelegate? override init() { super.init() UIViewController.classInit } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { startNSLogger() Reqres.logger = ReqresDefaultLogger() Reqres.register() UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor: YSConstants.kDefaultBlueColor], for: .selected) UITabBar.appearance().tintColor = YSConstants.kDefaultBlueColor FirebaseApp.configure() Database.database().isPersistenceEnabled = true GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID GIDSignIn.sharedInstance().signInSilently() logDefault(.App, .Info, "FIRApp, GIDSignIn - configured") lookUpAllFilesOnDisk() logDefault(.App, .Info, "looked Up All Files On Disk") // YSDatabaseManager.deleteDatabase { (error) in // //TODO: REMOVES DATABASE // logDefault(.App, .Error, "DATABASE DELETED") // logDefault(.App, .Error, "DATABASE DELETED") // logDefault(.App, .Error, "DATABASE DELETED") // let when = DispatchTime.now() + 3 // DispatchQueue.main.asyncAfter(deadline: when) { // self.driveDelegate?.filesDidChange() // } // } logDefault(.App, .Info, "Register for notifications") UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: { (granted, _) in guard granted else { return } UNUserNotificationCenter.current().getNotificationSettings { (settings) in guard settings.authorizationStatus == .authorized else { return } DispatchQueue.main.async { application.registerForRemoteNotifications() } } }) logDefault(.App, .Info, "Finished registering for notifications") configureAudioSession() return true } private func configureAudioSession() { let audioSession = AVAudioSession.sharedInstance() do { if #available(iOS 11.0, *) { try audioSession.setCategory(AVAudioSessionCategoryPlayback, mode: AVAudioSessionModeSpokenAudio, routeSharingPolicy: .longForm) } else { try audioSession.setCategory(AVAudioSessionCategoryPlayback) try audioSession.setMode(AVAudioSessionModeSpokenAudio) } } catch let error as NSError { logDefault(.App, .Error, "Error configuring audio session: " + error.localizedDescriptionAndUnderlyingKey) } } private func startNSLogger() { let logsDirectory = YSConstants.logsFolder do { try FileManager.default.createDirectory(atPath: logsDirectory.relativePath, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { logDefault(.App, .Error, "Error creating directory: \(error.localizedDescription)") } removeOldestLogIfNeeded() let file = "\(logsDirectory.relativePath)/NSLoggerData-" + UUID().uuidString + ".rawnsloggerdata" LoggerSetBufferFile(nil, file as CFString) LoggerSetOptions(nil, UInt32(kLoggerOption_BufferLogsUntilConnection | kLoggerOption_BrowseBonjour | kLoggerOption_BrowseOnlyLocalDomain | kLoggerOption_LogToConsole)) if let bundleName = Bundle.main.object(forInfoDictionaryKey: kCFBundleNameKey as String) as? String { LoggerSetupBonjour(nil, nil, bundleName as CFString) } LoggerStart(nil) } private func removeOldestLogIfNeeded() { DispatchQueue.global(qos: .utility).async { logDefault(.App, .Info, "removeOldestLogIfNeeded") do { let urlArray = try FileManager.default.contentsOfDirectory(at: YSConstants.logsFolder, includingPropertiesForKeys: [.contentModificationDateKey], options: .skipsHiddenFiles) if urlArray.count > YSConstants.kNumberOfLogsStored { let fileUrlsSortedByDate = urlArray.map { url in (url, (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate ?? Date.distantPast) } .sorted(by: { $0.1 > $1.1 }) // sort descending modification dates .map { $0.0 } // extract file urls if let oldestLogFileUrl = fileUrlsSortedByDate.last { try FileManager.default.removeItem(at: oldestLogFileUrl) // we delete the oldest log logDefault(.App, .Info, "Removed oldest log: " + oldestLogFileUrl.relativePath) } } } catch let error as NSError { logDefault(.App, .Error, "Error while working with logs folder contents \(error.localizedDescription)") } } } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool { return GIDSignIn.sharedInstance().handle(url as URL!, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplicationOpenURLOptionsKey.annotation]) } func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) { backgroundSessionCompletionHandler = completionHandler } func applicationDidBecomeActive(_ application: UIApplication) { logDefault(.App, .Info, "") } func applicationWillResignActive(_ application: UIApplication) { logDefault(.App, .Info, "") } func applicationWillTerminate(_ application: UIApplication) { logDefault(.App, .Info, "") } func applicationWillEnterForeground(_ application: UIApplication) { logDefault(.App, .Info, "") } class func appDelegate() -> YSAppDelegate { guard let delegate = UIApplication.shared.delegate as? YSAppDelegate else { return YSAppDelegate() } return delegate } class func topViewController() -> UIViewController? { if var topController = UIApplication.shared.keyWindow?.rootViewController { while let presentedViewController = topController.presentedViewController { topController = presentedViewController } return topController } return nil } private func lookUpAllFilesOnDisk() { filesOnDisk = YSDatabaseManager.getAllnamesOnDisk() } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let tokenParts = deviceToken.map { data -> String in return String(format: "%02.2hhx", data) } let token = tokenParts.joined() logDefault(.App, .Info, "Successfully registered for notifications. Device Token: \(token)") } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { logDefault(.App, .Info, "Failed to register: \(error)") } // { // "aps": { // "content-available": 0 // } // } //recieves remote silent notification func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { let aps = userInfo[forKey: "aps", ""] logDefault(.App, .Info, "Recieved remote silent notification: \(aps)") if aps.count > 0 { completionHandler(.newData) } else { completionHandler(.noData) } } } extension YSAppDelegate: UNUserNotificationCenterDelegate { // { // "aps": { // "alert": "New version!", // "sound": "default", // "link_url": "https://github.com/Yurssoft/QuickFile" // } // } //recieves push notification func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { logDefault(.App, .Info, "Recieved push notification: \(response.notification.request.content.userInfo)") let userInfo = response.notification.request.content.userInfo let aps = userInfo[forKey: "aps", [String: Any]()] let urlString = aps[forKey: "link_url", ""] if urlString.count > 0, let url = URL(string: urlString) { let safari = SFSafariViewController(url: url) window?.rootViewController?.present(safari, animated: true, completion: nil) } completionHandler() } }
mit
557f81e6b3b8608e9157d3fb226a6b53
40.97482
214
0.677522
5.082317
false
false
false
false
therealbnut/swift
test/Parse/invalid.swift
4
8134
// RUN: %target-typecheck-verify-swift func foo(_ a: Int) { // expected-error @+1 {{invalid character in source file}} {{8-9= }} foo(<\a\>) // expected-error {{invalid character in source file}} {{10-11= }} // expected-error @-1 {{'<' is not a prefix unary operator}} // expected-error @-2 {{'>' is not a postfix unary operator}} } // rdar://15946844 func test1(inout var x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{18-22=}} // expected-error @-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} {{12-17=}} {{26-26=inout }} func test2(inout let x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{18-22=}} // expected-error @-1 {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} {{12-17=}} {{26-26=inout }} func test3(f : (inout _ x : Int) -> Void) {} // expected-error {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} func test3() { undeclared_func( // expected-error {{use of unresolved identifier 'undeclared_func'}} } // expected-error {{expected expression in list of expressions}} func runAction() {} // expected-note {{did you mean 'runAction'?}} // rdar://16601779 func foo() { runAction(SKAction.sequence() // expected-error {{use of unresolved identifier 'SKAction'}} expected-error {{expected ',' separator}} {{32-32=,}} skview! // expected-error @-1 {{use of unresolved identifier 'skview'}} } super.init() // expected-error {{'super' cannot be used outside of class members}} switch state { // expected-error {{use of unresolved identifier 'state'}} let duration : Int = 0 // expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}} case 1: break } func testNotCoveredCase(x: Int) { switch x { let y = "foo" // expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}} switch y { case "bar": blah blah // ignored } case "baz": // expected-error {{expression pattern of type 'String' cannot match values of type 'Int'}} break case 1: break default: break } switch x { #if true // expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}} case 1: break case "foobar": // ignored break default: break #endif } } // rdar://18926814 func test4() { let abc = 123 _ = " >> \( abc } ) << " // expected-error {{expected ',' separator}} {{18-18=,}} expected-error {{expected expression in list of expressions}} expected-error {{extra tokens after interpolated string expression}} } // rdar://problem/18507467 func d(_ b: String -> <T>() -> T) {} // expected-error {{expected type for function result}} // <rdar://problem/22143680> QoI: terrible diagnostic when trying to form a generic protocol protocol Animal<Food> { // expected-error {{protocols do not allow generic parameters; use associated types instead}} func feed(_ food: Food) // expected-error {{use of undeclared type 'Food'}} } // SR-573 - Crash with invalid parameter declaration class Starfish {} struct Salmon {} func f573(s Starfish, // expected-error {{parameter requires an explicit type}} _ ss: Salmon) -> [Int] {} func g573() { f573(Starfish(), Salmon()) } func SR698(_ a: Int, b: Int) {} SR698(1, b: 2,) // expected-error {{unexpected ',' separator}} // SR-979 - Two inout crash compiler func SR979a(a : inout inout Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{17-23=}} func SR979b(inout inout b: Int) {} // expected-error {{inout' before a parameter name is not allowed, place it before the parameter type instead}} {{13-18=}} {{28-28=inout }} // expected-error@-1 {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{19-25=}} func SR979c(let a: inout Int) {} // expected-error {{'let' as a parameter attribute is not allowed}} {{13-16=}} func SR979d(let let a: Int) {} // expected-error {{'let' as a parameter attribute is not allowed}} {{13-16=}} // expected-error @-1 {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{17-21=}} func SR979e(inout x: inout String) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{13-18=}} func SR979f(var inout x : Int) { // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{17-23=}} // expected-error @-1 {{parameters may not have the 'var' specifier}} {{13-16=}}{{3-3=var x = x\n }} x += 10 } func SR979g(inout i: inout Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{13-18=}} func SR979h(let inout x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{17-23=}} // expected-error @-1 {{'let' as a parameter attribute is not allowed}} class VarTester { init(var a: Int, var b: Int) {} // expected-error {{parameters may not have the 'var' specifier}} {{8-11=}} {{33-33= var a = a }} // expected-error @-1 {{parameters may not have the 'var' specifier}} {{20-24=}} {{33-33= var b = b }} func x(var b: Int) { //expected-error {{parameters may not have the 'var' specifier}} {{12-15=}} {{9-9=var b = b\n }} b += 10 } } func repeat() {} // expected-error @-1 {{keyword 'repeat' cannot be used as an identifier here}} // expected-note @-2 {{if this name is unavoidable, use backticks to escape it}} {{6-12=`repeat`}} let for = 2 // expected-error @-1 {{keyword 'for' cannot be used as an identifier here}} // expected-note @-2 {{if this name is unavoidable, use backticks to escape it}} {{5-8=`for`}} func dog cow() {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}} // expected-note@-1 {{join the identifiers together}} {{6-13=dogcow}} // expected-note@-2 {{join the identifiers together with camel-case}} {{6-13=dogCow}} func cat Mouse() {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}} // expected-note@-1 {{join the identifiers together}} {{6-15=catMouse}} func friend ship<T>(x: T) {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}} // expected-note@-1 {{join the identifiers together}} {{6-17=friendship}} // expected-note@-2 {{join the identifiers together with camel-case}} {{6-17=friendShip}} func were wolf() {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}} // expected-note@-1 {{join the identifiers together}} {{6-5=werewolf}} // expected-note@-2 {{join the identifiers together with camel-case}} {{6-5=wereWolf}} func hammer leavings<T>(x: T) {} // expected-error {{found an unexpected second identifier in function declaration; is there an accidental break?}} // expected-note@-1 {{join the identifiers together}} {{6-9=hammerleavings}} // expected-note@-2 {{join the identifiers together with camel-case}} {{6-9=hammerLeavings}} prefix operator % prefix func %<T>(x: T) -> T { return x } // No error expected - the < is considered an identifier but is peeled off by the parser. struct Weak<T: class> { // expected-error {{'class' constraint can only appear on protocol declarations}} // expected-note@-1 {{did you mean to constrain 'T' with the 'AnyObject' protocol?}} {{16-21=AnyObject}} weak var value: T // expected-error {{'weak' may only be applied to class and class-bound protocol types}} // expected-error@-1 {{use of undeclared type 'T'}} } let x: () = () !() // expected-error {{missing argument for parameter #1 in call}} !(()) // expected-error {{cannot convert value of type '()' to expected argument type 'Bool'}} !(x) // expected-error {{cannot convert value of type '()' to expected argument type 'Bool'}} !x // expected-error {{cannot convert value of type '()' to expected argument type 'Bool'}}
apache-2.0
94fc1ff855719827810733f461686a97
51.477419
216
0.669781
3.672235
false
false
false
false
wuzzapcom/Fluffy-Book
Pods/RealmSwift/RealmSwift/List.swift
8
22645
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private /// :nodoc: /// Internal class. Do not use directly. public class ListBase: RLMListBase { // Printable requires a description property defined in Swift (and not obj-c), // and it has to be defined as override, which can't be done in a // generic class. /// Returns a human-readable description of the objects contained in the List. @objc public override var description: String { return descriptionWithMaxDepth(RLMDescriptionMaxDepth) } @objc private func descriptionWithMaxDepth(_ depth: UInt) -> String { return RLMDescriptionWithMaxDepth("List", _rlmArray, depth) } /// Returns the number of objects in this List. public var count: Int { return Int(_rlmArray.count) } } /** `List` is the container type in Realm used to define to-many relationships. Like Swift's `Array`, `List` is a generic type that is parameterized on the type of `Object` it stores. Unlike Swift's native collections, `List`s are reference types, and are only immutable if the Realm that manages them is opened as read-only. Lists can be filtered and sorted with the same predicates as `Results<T>`. Properties of `List` type defined on `Object` subclasses must be declared as `let` and cannot be `dynamic`. */ public final class List<T: Object>: ListBase { /// The type of the elements contained within the collection. public typealias Element = T // MARK: Properties /// The Realm which manages the list, or `nil` if the list is unmanaged. public var realm: Realm? { return _rlmArray.realm.map { Realm($0) } } /// Indicates if the list can no longer be accessed. public var isInvalidated: Bool { return _rlmArray.isInvalidated } // MARK: Initializers /// Creates a `List` that holds Realm model objects of type `T`. public override init() { super.init(array: RLMArray(objectClassName: (T.self as Object.Type).className())) } internal init(rlmArray: RLMArray<RLMObject>) { super.init(array: rlmArray) } // MARK: Index Retrieval /** Returns the index of an object in the list, or `nil` if the object is not present. - parameter object: An object to find. */ public func index(of object: T) -> Int? { return notFoundToNil(index: _rlmArray.index(of: object.unsafeCastToRLMObject())) } /** Returns the index of the first object in the list matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func index(matching predicate: NSPredicate) -> Int? { return notFoundToNil(index: _rlmArray.indexOfObject(with: predicate)) } /** Returns the index of the first object in the list matching the predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func index(matching predicateFormat: String, _ args: Any...) -> Int? { return index(matching: NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Object Retrieval /** Returns the object at the given index (get), or replaces the object at the given index (set). - warning: You can only set an object during a write transaction. - parameter index: The index of the object to retrieve or replace. */ public subscript(position: Int) -> T { get { throwForNegativeIndex(position) return unsafeBitCast(_rlmArray.object(at: UInt(position)), to: T.self) } set { throwForNegativeIndex(position) _rlmArray.replaceObject(at: UInt(position), with: newValue.unsafeCastToRLMObject()) } } /// Returns the first object in the list, or `nil` if the list is empty. public var first: T? { return unsafeBitCast(_rlmArray.firstObject(), to: Optional<T>.self) } /// Returns the last object in the list, or `nil` if the list is empty. public var last: T? { return unsafeBitCast(_rlmArray.lastObject(), to: Optional<T>.self) } // MARK: KVC /** Returns an `Array` containing the results of invoking `valueForKey(_:)` using `key` on each of the collection's objects. */ public override func value(forKey key: String) -> Any? { return value(forKeyPath: key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` using `keyPath` on each of the collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ public override func value(forKeyPath keyPath: String) -> Any? { return _rlmArray.value(forKeyPath: keyPath) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property whose value should be set on each object. */ public override func setValue(_ value: Any?, forKey key: String) { return _rlmArray.setValue(value, forKeyPath: key) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the list. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(_ predicateFormat: String, _ args: Any...) -> Results<T> { return Results<T>(_rlmArray.objects(with: NSPredicate(format: predicateFormat, argumentArray: args))) } /** Returns a `Results` containing all objects matching the given predicate in the list. - parameter predicate: The predicate with which to filter the objects. */ public func filter(_ predicate: NSPredicate) -> Results<T> { return Results<T>(_rlmArray.objects(with: predicate)) } // MARK: Sorting /** Returns a `Results` containing the objects in the list, but sorted. Objects are sorted based on the values of the given key path. For example, to sort a list of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byKeyPath: "age", ascending: true)`. - warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter keyPath: The key path to sort by. - parameter ascending: The direction to sort in. */ public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<T> { return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)]) } /** Returns a `Results` containing the objects in the list, but sorted. Objects are sorted based on the values of the given property. For example, to sort a list of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byProperty: "age", ascending: true)`. - warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ @available(*, deprecated, renamed: "sorted(byKeyPath:ascending:)") public func sorted(byProperty property: String, ascending: Bool = true) -> Results<T> { return sorted(byKeyPath: property, ascending: ascending) } /** Returns a `Results` containing the objects in the list, but sorted. - warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byKeyPath:ascending:)` */ public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { return Results<T>(_rlmArray.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func min<U: MinMaxType>(ofProperty property: String) -> U? { return _rlmArray.min(ofProperty: property).map(dynamicBridgeCast) } /** Returns the maximum (highest) value of the given property among all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose maximum value is desired. */ public func max<U: MinMaxType>(ofProperty property: String) -> U? { return _rlmArray.max(ofProperty: property).map(dynamicBridgeCast) } /** Returns the sum of the values of a given property over all the objects in the list. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ public func sum<U: AddableType>(ofProperty property: String) -> U { return dynamicBridgeCast(fromObjectiveC: _rlmArray.sum(ofProperty: property)) } /** Returns the average value of a given property over all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ public func average<U: AddableType>(ofProperty property: String) -> U? { return _rlmArray.average(ofProperty: property).map(dynamicBridgeCast) } // MARK: Mutation /** Appends the given object to the end of the list. If the object is managed by a different Realm than the receiver, a copy is made and added to the Realm managing the receiver. - warning: This method may only be called during a write transaction. - parameter object: An object. */ public func append(_ object: T) { _rlmArray.add(object.unsafeCastToRLMObject()) } /** Appends the objects in the given sequence to the end of the list. - warning: This method may only be called during a write transaction. */ public func append<S: Sequence>(objectsIn objects: S) where S.Iterator.Element == T { for obj in objects { _rlmArray.add(obj.unsafeCastToRLMObject()) } } /** Inserts an object at the given index. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter object: An object. - parameter index: The index at which to insert the object. */ public func insert(_ object: T, at index: Int) { throwForNegativeIndex(index) _rlmArray.insert(object.unsafeCastToRLMObject(), at: UInt(index)) } /** Removes an object at the given index. The object is not removed from the Realm that manages it. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter index: The index at which to remove the object. */ public func remove(objectAtIndex index: Int) { throwForNegativeIndex(index) _rlmArray.removeObject(at: UInt(index)) } /** Removes the last object in the list. The object is not removed from the Realm that manages it. - warning: This method may only be called during a write transaction. */ public func removeLast() { _rlmArray.removeLastObject() } /** Removes all objects from the list. The objects are not removed from the Realm that manages them. - warning: This method may only be called during a write transaction. */ public func removeAll() { _rlmArray.removeAllObjects() } /** Replaces an object at the given index with a new object. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter index: The index of the object to be replaced. - parameter object: An object. */ public func replace(index: Int, object: T) { throwForNegativeIndex(index) _rlmArray.replaceObject(at: UInt(index), with: object.unsafeCastToRLMObject()) } /** Moves the object at the given source index to the given destination index. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with invalid indices. - parameter from: The index of the object to be moved. - parameter to: index to which the object at `from` should be moved. */ public func move(from: Int, to: Int) { throwForNegativeIndex(from) throwForNegativeIndex(to) _rlmArray.moveObject(at: UInt(from), to: UInt(to)) } /** Exchanges the objects in the list at given indices. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with invalid indices. - parameter index1: The index of the object which should replace the object at index `index2`. - parameter index2: The index of the object which should replace the object at index `index1`. */ public func swap(index1: Int, _ index2: Int) { throwForNegativeIndex(index1, parameterName: "index1") throwForNegativeIndex(index2, parameterName: "index2") _rlmArray.exchangeObject(at: UInt(index1), withObjectAt: UInt(index2)) } // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let results = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.addNotificationBlock { changes in switch changes { case .initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .update: // Will not be hit in this example break case .error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `stop()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ public func addNotificationBlock(_ block: @escaping (RealmCollectionChange<List>) -> Void) -> NotificationToken { return _rlmArray.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: self, change: change, error: error)) } } } extension List: RealmCollection, RangeReplaceableCollection { // MARK: Sequence Support /// Returns a `RLMIterator` that yields successive elements in the `List`. public func makeIterator() -> RLMIterator<T> { return RLMIterator(collection: _rlmArray) } // MARK: RangeReplaceableCollection Support #if swift(>=3.1) // These should not be necessary, but Swift 3.1's compiler fails to infer the `SubSequence`, // and the standard library neglects to provide the default implementation of `subscript` /// :nodoc: public typealias SubSequence = RangeReplaceableRandomAccessSlice<List> /// :nodoc: public subscript(slice: Range<Int>) -> SubSequence { return SubSequence(base: self, bounds: slice) } #endif /** Replace the given `subRange` of elements with `newElements`. - parameter subrange: The range of elements to be replaced. - parameter newElements: The new elements to be inserted into the List. */ public func replaceSubrange<C: Collection>(_ subrange: Range<Int>, with newElements: C) where C.Iterator.Element == T { for _ in subrange.lowerBound..<subrange.upperBound { remove(objectAtIndex: subrange.lowerBound) } for x in newElements.reversed() { insert(x, at: subrange.lowerBound) } } // This should be inferred, but Xcode 8.1 is unable to /// :nodoc: public typealias Indices = DefaultRandomAccessIndices<List> /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return count } public func index(after i: Int) -> Int { return i + 1 } public func index(before i: Int) -> Int { return i - 1 } /// :nodoc: public func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<T>>) -> Void) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return _rlmArray.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error)) } } } // MARK: AssistedObjectiveCBridgeable extension List: AssistedObjectiveCBridgeable { internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> List { guard let objectiveCValue = objectiveCValue as? RLMArray<RLMObject> else { preconditionFailure() } return List(rlmArray: objectiveCValue) } internal var bridged: (objectiveCValue: Any, metadata: Any?) { return (objectiveCValue: _rlmArray, metadata: nil) } } // MARK: Unavailable extension List { @available(*, unavailable, renamed: "append(objectsIn:)") public func appendContentsOf<S: Sequence>(_ objects: S) where S.Iterator.Element == T { fatalError() } @available(*, unavailable, renamed: "remove(objectAtIndex:)") public func remove(at index: Int) { fatalError() } @available(*, unavailable, renamed: "isInvalidated") public var invalidated: Bool { fatalError() } @available(*, unavailable, renamed: "index(matching:)") public func index(of predicate: NSPredicate) -> Int? { fatalError() } @available(*, unavailable, renamed: "index(matching:_:)") public func index(of predicateFormat: String, _ args: Any...) -> Int? { fatalError() } @available(*, unavailable, renamed: "sorted(byKeyPath:ascending:)") public func sorted(_ property: String, ascending: Bool = true) -> Results<T> { fatalError() } @available(*, unavailable, renamed: "sorted(by:)") public func sorted<S: Sequence>(_ sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { fatalError() } @available(*, unavailable, renamed: "min(ofProperty:)") public func min<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "max(ofProperty:)") public func max<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "sum(ofProperty:)") public func sum<U: AddableType>(_ property: String) -> U { fatalError() } @available(*, unavailable, renamed: "average(ofProperty:)") public func average<U: AddableType>(_ property: String) -> U? { fatalError() } }
mit
72180045e37d1baad3f2e10a9d61dff9
37.842196
120
0.67335
4.678719
false
false
false
false
contentful-labs/Concorde
Code/CCBufferedImageView.swift
1
3090
// // CCBufferedImageView.swift // Concorde // // Created by Boris Bügling on 11/03/15. // Copyright (c) 2015 Contentful GmbH. All rights reserved. // import UIKit /// A subclass of UIImageView which displays a JPEG progressively while it is downloaded open class CCBufferedImageView : UIImageView, NSURLConnectionDataDelegate { fileprivate weak var connection: NSURLConnection? fileprivate let defaultContentLength = 5 * 1024 * 1024 fileprivate var data: Data? fileprivate let queue = DispatchQueue(label: "com.contentful.Concorde", attributes: []) /// Optional handler which is called after an image has been successfully downloaded open var loadedHandler: (() -> ())? deinit { connection?.cancel() } /// Initialize a new image view with the given frame public override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.gray } /// Initialize a new image view and start loading a JPEG from the given URL public init(URL: Foundation.URL) { super.init(image: nil) backgroundColor = UIColor.gray load(URL) } /// Required initializer, not implemented required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = UIColor.gray } /// Load a JPEG from the given URL open func load(_ URL: Foundation.URL) { connection?.cancel() connection = NSURLConnection(request: URLRequest(url: URL), delegate: self) } // MARK: NSURLConnectionDataDelegate /// see NSURLConnectionDataDelegate open func connection(_ connection: NSURLConnection, didFailWithError error: Error) { NSLog("Error: \(error)") } /// see NSURLConnectionDataDelegate open func connection(_ connection: NSURLConnection, didReceive data: Data) { self.data?.append(data) queue.sync { let decoder = CCBufferedImageDecoder(data: self.data! as Data) decoder?.decompress() guard let decodedImage = decoder?.toImage() else { return } UIGraphicsBeginImageContext(CGSize(width: 1,height: 1)) let context = UIGraphicsGetCurrentContext() context?.draw(decodedImage.cgImage!, in: CGRect(x: 0, y: 0, width: 1, height: 1)) UIGraphicsEndImageContext() DispatchQueue.main.async { self.image = decodedImage } } } /// see NSURLConnectionDataDelegate open func connection(_ connection: NSURLConnection, didReceive response: URLResponse) { var contentLength = Int(response.expectedContentLength) if contentLength < 0 { contentLength = defaultContentLength } data = Data(capacity: contentLength) } /// see NSURLConnectionDataDelegate open func connectionDidFinishLoading(_ connection: NSURLConnection) { data = nil if let loadedHandler = loadedHandler { loadedHandler() } } }
mit
03ebade728893531beb3e7794f9de0d8
29.584158
93
0.642603
5.131229
false
false
false
false
auermi/noted
Noted/LoginViewController.swift
1
2359
// // Login.swift // Noted // // Created by Michael Andrew Auer on 3/10/16. // Copyright © 2016 Usonia LLC. All rights reserved. // import UIKit import TwitterKit class LoginViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = true let dataInterface = DataInterface() // If a user already exists skip authentication let user = dataInterface.get("User") as! [User] if (user.count == 1) { DispatchQueue.main.async() { self.performSegue(withIdentifier: "start", sender: nil) } } else { let logInButton = TWTRLogInButton { (session, error) in if let unwrappedSession = session { // Get id and create user dataInterface.create("User", properties: [ "id": unwrappedSession.userID as NSObject, "userName": unwrappedSession.userName as NSObject ]) // Transition to notes table view screen self.performSegue(withIdentifier: "start", sender: nil) } else { NSLog("Login error: %@", error!.localizedDescription); let alert = UIAlertController(title: "Authentication Error", message: "There was an error logging into Twitter. Please try again", preferredStyle: UIAlertControllerStyle.alert) let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (UIAlertAction) -> Void in } alert.addAction(alertAction) self.present(alert, animated: true) { () -> Void in } } } logInButton.center = self.view.center self.view.addSubview(logInButton) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
dfa535e54cf0ba377d063e6c2d208551
34.19403
196
0.534775
5.723301
false
false
false
false
davidbjames/Unilib
Unilib/Sources/External/Regex/MatchResult.swift
1
2741
import class Foundation.NSTextCheckingResult /// A `MatchResult` encapsulates the result of a single match in a string, /// providing access to the matched string, as well as any capture groups within /// that string. public struct MatchResult { // MARK: Accessing match results /// The entire matched string. /// /// Example: /// /// let pattern = Regex("a*") /// /// if let match = pattern.firstMatch(in: "aaa") { /// match.matchedString // "aaa" /// } /// /// if let match = pattern.firstMatch(in: "bbb") { /// match.matchedString // "" /// } public var matchedString: String { return _result.matchedString } /// The range of the matched string. public var range: Range<String.Index> { return _result.range } /// The matching string for each capture group in the regular expression /// (if any). /// /// **Note:** Usually if the match was successful, the captures will by /// definition be non-nil. However if a given capture group is optional, the /// captured string may also be nil, depending on the particular string that /// is being matched against. /// /// Example: /// /// let regex = Regex("(a)?(b)") /// /// regex.firstMatch(in: "ab")?.captures // [Optional("a"), Optional("b")] /// regex.firstMatch(in: "b")?.captures // [nil, Optional("b")] public var captures: [String?] { return _result.captures } /// The ranges of each capture (if any). /// /// - seealso: The discussion and example for `MatchResult.captures`. public var captureRanges: [Range<String.Index>?] { return _result.captureRanges } // MARK: Internal initialisers public var matchResult: NSTextCheckingResult { return _result.result } private let _result: _MatchResult public init(_ string: String, _ result: NSTextCheckingResult) { self._result = _MatchResult(string, result) } } // Use of a private class allows for lazy vars without the need for `mutating`. private final class _MatchResult { private let string: String fileprivate let result: NSTextCheckingResult fileprivate init(_ string: String, _ result: NSTextCheckingResult) { self.string = string self.result = result } lazy var range: Range<String.Index> = { Range(self.result.range, in: string)! }() lazy var captures: [String?] = { self.captureRanges.map { range in range.map { String(self.string[$0]) } } }() lazy var captureRanges: [Range<String.Index>?] = { self.result.ranges.dropFirst().map { Range($0, in: self.string) } }() lazy var matchedString: String = { let range = Range(self.result.range, in: self.string)! return String(self.string[range]) }() }
mit
173088ae6da520d17bfed2801a8edf1f
27.257732
80
0.643561
4.054734
false
false
false
false
zhubofei/IGListKit
Examples/Examples-iOS/IGListKitExamples/ViewControllers/SupplementaryViewController.swift
4
2231
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit import UIKit final class SupplementaryViewController: UIViewController, ListAdapterDataSource { lazy var adapter: ListAdapter = { return ListAdapter(updater: ListAdapterUpdater(), viewController: self) }() let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) let feedItems = [ FeedItem(pk: 1, user: User(pk: 100, name: "Jesse", handle: "jesse_squires"), comments: ["You rock!", "Hmm you sure about that?"]), FeedItem(pk: 2, user: User(pk: 101, name: "Ryan", handle: "_ryannystrom"), comments: ["lgtm", "lol", "Let's try it!"]), FeedItem(pk: 3, user: User(pk: 102, name: "Ann", handle: "abaum"), comments: ["Good luck!"]), FeedItem(pk: 4, user: User(pk: 103, name: "Phil", handle: "phil"), comments: ["yoooooooo", "What's the eta?"]) ] override func viewDidLoad() { super.viewDidLoad() view.addSubview(collectionView) adapter.collectionView = collectionView adapter.dataSource = self } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } // MARK: ListAdapterDataSource func objects(for listAdapter: ListAdapter) -> [ListDiffable] { return feedItems } func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController { return FeedItemSectionController() } func emptyView(for listAdapter: ListAdapter) -> UIView? { return nil } }
mit
5ec1a04cee7436fe9cf6f4611ca25e7e
38.839286
138
0.701927
4.571721
false
false
false
false
mapsme/omim
iphone/Maps/UI/PlacePage/Components/PlacePageBookmarkViewController.swift
4
3098
protocol PlacePageBookmarkViewControllerDelegate: AnyObject { func bookmarkDidPressEdit() } class PlacePageBookmarkViewController: UIViewController { @IBOutlet var stackView: UIStackView! @IBOutlet var spinner: UIImageView! @IBOutlet var editButton: UIButton! @IBOutlet var topConstraint: NSLayoutConstraint! @IBOutlet var expandableLabel: ExpandableLabel! { didSet { expandableLabel.font = UIFont.regular14() expandableLabel.textColor = UIColor.blackPrimaryText() expandableLabel.numberOfLines = 5 expandableLabel.expandColor = UIColor.linkBlue() expandableLabel.expandText = L("placepage_more_button") } } var bookmarkData: PlacePageBookmarkData? { didSet { updateViews() } } weak var delegate: PlacePageBookmarkViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() updateViews() } func updateViews() { guard let bookmarkData = bookmarkData else { return } editButton.isEnabled = bookmarkData.isEditable if let description = bookmarkData.bookmarkDescription { if bookmarkData.isHtmlDescription { setHtmlDescription(description) topConstraint.constant = 16 } else { expandableLabel.text = description topConstraint.constant = description.count > 0 ? 16 : 0 } } else { topConstraint.constant = 0 } } private func setHtmlDescription(_ htmlDescription: String) { DispatchQueue.global().async { let font = UIFont.regular14() let color = UIColor.blackPrimaryText() let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 4 let attributedString: NSAttributedString if let str = NSMutableAttributedString(htmlString: htmlDescription, baseFont: font, paragraphStyle: paragraphStyle) { str.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSRange(location: 0, length: str.length)) attributedString = str; } else { attributedString = NSAttributedString(string: htmlDescription, attributes: [NSAttributedString.Key.font : font, NSAttributedString.Key.foregroundColor: color, NSAttributedString.Key.paragraphStyle: paragraphStyle]) } DispatchQueue.main.async { self.expandableLabel.attributedText = attributedString } } } private func startSpinner() { editButton.isHidden = true let postfix = UIColor.isNightMode() ? "dark" : "light" spinner.image = UIImage(named: "Spinner_" + postfix) spinner.isHidden = false spinner.startRotation() } private func stopSpinner() { editButton.isHidden = false spinner.isHidden = true spinner.stopRotation() } @IBAction func onEdit(_ sender: UIButton) { delegate?.bookmarkDidPressEdit() } override func applyTheme() { super.applyTheme() updateViews() } }
apache-2.0
7521b37784105fefef28442b706162dd
31.270833
123
0.660426
5.369151
false
false
false
false
khizkhiz/swift
stdlib/public/SDK/OpenCL/OpenCL.swift
1
943
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import OpenCL // Clang module @available(OSX, introduced=10.7) public func clSetKernelArgsListAPPLE( kernel: cl_kernel, _ uint: cl_uint, _ args: CVarArg... ) -> cl_int { // The variable arguments are num_args arguments that are the following: // cl_uint arg_indx, // size_t arg_size, // const void *arg_value, return withVaList(args) { clSetKernelArgsVaListAPPLE(kernel, uint, $0) } }
apache-2.0
6c88011875a1e3833f72c57d4224b6b8
38.291667
80
0.584305
4.266968
false
false
false
false
sgr-ksmt/FormChangeable
FormChangeable/FormChangeable.swift
1
3178
// // FormChangeable.swift // FormChangeable // // Created by Suguru Kishimoto on 2016/02/14. // // import Foundation import UIKit public protocol FormChangeable { var form: UIResponder { get } var nextForm: FormChangeable? { get set } var previousForm: FormChangeable? { get set } func setReturnKeyType(keyType: UIReturnKeyType) var returnKeyType: UIReturnKeyType { get set } } public extension FormChangeable { func changeToNextForm(){ form.resignFirstResponder() nextForm?.form.becomeFirstResponder() } func changeToPreviousForm() { form.resignFirstResponder() previousForm?.form.becomeFirstResponder() } } public func ==(lhs: FormChangeable, rhs: FormChangeable) -> Bool { return lhs.form == rhs.form } private var previousFormKey: UInt8 = 0 private var nextFormKey: UInt8 = 0 private func getStoredObject(object: AnyObject, _ key: UnsafePointer<Void>) -> FormChangeable? { return objc_getAssociatedObject(object, key) as? FormChangeable } private func setStoredObject(object: AnyObject, _ key: UnsafePointer<Void>, _ value: FormChangeable?) { objc_setAssociatedObject(object, key, value as? AnyObject, .OBJC_ASSOCIATION_ASSIGN) } public extension FormChangeable where Self: UITextField { var form: UIResponder { return self as UIResponder } var nextForm: FormChangeable? { get { return getStoredObject(self, &nextFormKey) } set { setStoredObject(self, &nextFormKey, newValue) } } var previousForm: FormChangeable? { get { return getStoredObject(self, &previousFormKey) } set { setStoredObject(self, &previousFormKey, newValue) } } func setReturnKeyType(keyType: UIReturnKeyType) { returnKeyType = keyType } } public extension FormChangeable where Self: UITextView { var form: UIResponder { return self as UIResponder } var nextForm: FormChangeable? { get { return getStoredObject(self, &nextFormKey) } set { setStoredObject(self, &nextFormKey, newValue) } } var previousForm: FormChangeable? { get { return getStoredObject(self, &previousFormKey) } set { setStoredObject(self, &previousFormKey, newValue) } } func setReturnKeyType(keyType: UIReturnKeyType) { returnKeyType = keyType } } extension UITextField: FormChangeable {} extension UITextView: FormChangeable {} public extension CollectionType where Generator.Element == FormChangeable { func registerNextForm() { var pre: FormChangeable? forEach { pre?.nextForm = $0 pre = $0 } } func registerPreviousForm() { var pre: FormChangeable? reverse().forEach { pre?.previousForm = $0 pre = $0 } } func setNextReturnKeyType(lastKeyType: UIReturnKeyType = .Done) { forEach { $0.setReturnKeyType(.Next) } reverse().first?.setReturnKeyType(lastKeyType) } }
mit
a174c750611bd196586f584eb39c759f
24.424
103
0.635935
4.371389
false
false
false
false
suragch/Chimee-iOS
Chimee/SuggestionBarTableViewCell.swift
1
1686
import UIKit class SuggestionBarTableViewCell: UITableViewCell { var mongolLabel = UIMongolSingleLineLabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() { self.mongolLabel.translatesAutoresizingMaskIntoConstraints = false self.mongolLabel.centerText = false self.mongolLabel.backgroundColor = UIColor.clear self.contentView.backgroundColor = UIColor.clear self.contentView.addSubview(mongolLabel) // Constraints let topConstraint = NSLayoutConstraint(item: mongolLabel, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.topMargin, multiplier: 1.0, constant: 0) let bottomConstraint = NSLayoutConstraint(item: mongolLabel, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.bottomMargin, multiplier: 1.0, constant: 0) let horizontalCenterConstraint = NSLayoutConstraint(item: mongolLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.contentView, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0) self.contentView.addConstraints([ topConstraint, bottomConstraint, horizontalCenterConstraint ]) } override internal class var requiresConstraintBasedLayout : Bool { return true } }
mit
d35c8f7803928b82a3e4eee791f20520
50.090909
243
0.736655
5.285266
false
false
false
false
radex/swift-compiler-crashes
crashes-fuzzing/23422-swift-constraints-constraintsystem-opengeneric.swift
11
2344
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol A : Array<T where A.c, var _=(e { } struct B<T where B : A.c, case c, struct d { struct A : T where B : A var d = B<S : Array<T where B : b { } class case c enum S<T { let i: S<T where A.c] = 0.c, protocol A { var d where H.g : T class func a{ func b: A<T : A<b struct d struct d class class a{ func a.g : T func f: b { func c, } class d<T where A<a<T var d where B : A< class var d = 0 class if true { class A : P { protocol A { struct B<S : d struct A? {{ class a: A : B) let a { typealias e =[Void{ class d class var d where g: d = "\()? protocol a { func f: A { ((v: d where H.e =(((((v: A { (e([{ case c class class protocol A { let a { struct d<T where H.c: A<T where H.dynamicType) var d where H.c] = [{ func b== A.c, var f : Int -> Void{ d class a<T where g: T where A<S : d = a return m(((" func b Void{ var d where g: Any))? enum S<T where A.g : T struct A.e =( var d where g: AnyObject.c struct B:a{deinit{ let h = [Void{ class A { class { if true { class let a { { ([Void{ d<T where g: A.c] = [Void{ i: B? { protocol e { } class class a: T where g: d = B)? println(" protocol A { { } let a { class } struct A { import Foundation class d<b> U) var d { struct A<T where I.c { struct d class a<T : d = [Void{ i: b { func a<Int>] = 0 struct d:AnyObject.d typealias e : P {deinit{ func b let a {(e == b for c, typealias e = 0 struct B { struct Q<Int func a func a<T where g: P { class protocol a = b: B<T where g: Any) struct Q<T where g: NSObject { func b== b: B, e case c let a = [Void{ { (v: A typealias b struct A.c class class a: d{ struct B<T where A? = 0 } protocol e : A { ([Void{struct Q<S : String { func a<T where g: Any)" return m(e: A let i: A : T case c, class x{{ } println()" struct d<T : b { class d struct d:AnyObject.c] = A? = 0.c, class b enum A { { class class case c ((v: d where f: Any protocol a { (\(v: A { d: A{ protocol a { i> U)"\(()" if true { } { } {var d = B<T { case c, struct B<T>: Any protocol A : B<b<I : T where A.c, var d where A.c, let i: A.d } typealias b (e let a { struct B<T let end = a<T>] = [Void{ { struct d<T where g: S let end = b if true { return m() as a: A : String { case c, return m(()" typealias e : Array
mit
e8913a7d26108adeb271c06c81727727
12.394286
87
0.610068
2.353414
false
false
false
false
naokits/my-programming-marathon
RACPlayground/RACPlayground/ViewModel.swift
1
3636
// // ViewModel.swift // RACPlayground // // Created by Naoki Tsutsui on 8/3/16. // Copyright © 2016 Naoki Tsutsui. All rights reserved. // import Foundation import RxSwift import RxCocoa import ObjectiveC enum RepeatStateType { case Off, One, All } enum ShuffleStateType { case Off, On } enum PlayStateType { case Pause case Play case TogglePlayPause case PreviousTrack case NextTrack } /*: 状態の要件 リピートボタンUI操作でのみ変更される 状態の変更は、オフ、1曲リピート、全曲リピートという順序で変更される 状態が変更されたら、ボタンのタイトルも変更する シャッフルボタンUI操作でのみ変更される 状態の変更は、オフ、オンという順序で変更される 状態が変更されたら、ボタンのタイトルも変更する */ // MARK: - States /// 管理する各種状態の定義 struct AppState { //struct AppState: StateType { // 再生状態(再生 or 一時停止) var playState: PlayStateType = .Pause // シャッフルの状態 var shuffleState = false // リピート状態(オフ、1曲リピート、全曲リピート) var repeaStatet: RepeatStateType = .Off // 再生中のビデオID var playingVideoId = "" // 選択中のプレイリスト var playlistId: Int = 0 var playerState = PlayerState() } struct PlayerState { // 再生状態(再生 or 一時停止) var playState: PlayStateType = .Pause // シャッフルの状態 var shuffleState = false // リピート状態(オフ、1曲リピート、全曲リピート) var repeaStatet: RepeatStateType = .Off } class Dog: NSObject { var event: Observable<String>? override init() { } } class Hoge { private let eventSubject = PublishSubject<String>() var event: Observable<String> { return eventSubject } func doSomething() { // 略 eventSubject.onNext("イベントが発行されました") // イベント発行 } } /* class Presenter { private let buttonHiddenSubject = BehaviorSubject(value: false) var buttonHidden: Observable<Bool> { return buttonHiddenSubject } func start() { buttonHidden.doOnNext { (<#Bool#>) in <#code#> } buttonHidden.onNext(true) // ... } func stop() { buttonHidden.onNext(false) // ... } } */ class ViewModel { // バックグラウンド再生の制御で使用 var isBackgroundPlay = false let enableShuffleButton: Observable<Bool> // let shuffleButton: Observable<Bool> var dog = Dog() init() { // // 3文字以上だったらボタンをenbaleにする // enableLoginButton = Observable.combineLatest(userName.asObservable(), password.asObservable()) { // $0.0.characters.count >= 3 && $0.1.characters.count >= 3 // } enableShuffleButton = Observable.combinela } func hoge() { let disposable = dog.event?.subscribe(onNext: { (value) in // 通常処理 print("通常処理") }, onError: { (errortype) in print(errortype) }, onCompleted: { print("終了") }, onDisposed: { print("購読解除") }) // 購読解除 disposable?.dispose() } func tappedShuffleButton() { print("たっぷ") } }
mit
b52ac4b5e1912b1423191cb08b813a2c
17.182927
106
0.583697
3.368362
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.RemainingDuration.swift
1
2073
import Foundation public extension AnyCharacteristic { static func remainingDuration( _ value: UInt32 = 0, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Remaining Duration", format: CharacteristicFormat? = .uint32, unit: CharacteristicUnit? = .seconds, maxLength: Int? = nil, maxValue: Double? = 3600, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.remainingDuration( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func remainingDuration( _ value: UInt32 = 0, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Remaining Duration", format: CharacteristicFormat? = .uint32, unit: CharacteristicUnit? = .seconds, maxLength: Int? = nil, maxValue: Double? = 3600, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<UInt32> { GenericCharacteristic<UInt32>( type: .remainingDuration, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
9ff6451bb50b15e82f502e5e81d5edba
32.983607
67
0.58273
5.426702
false
false
false
false
fuzza/functional-swift-examples
functional-swift-playground.playground/Pages/enumerations.xcplaygroundpage/Contents.swift
1
3300
//: [Previous](@previous) import Foundation enum Encoding { case ASCII case NEXTSTEP case JapaneseEUC case UTF8 } extension Encoding { var nsStringEncoding: String.Encoding { switch self { case .ASCII: return String.Encoding.ascii case .NEXTSTEP: return String.Encoding.nextstep case .JapaneseEUC: return String.Encoding.japaneseEUC case .UTF8: return String.Encoding.utf8 } } } extension Encoding { init?(enc: String.Encoding) { switch enc { case String.Encoding.ascii: self = .ASCII case String.Encoding.nextstep: self = .NEXTSTEP case String.Encoding.japaneseEUC: self = .JapaneseEUC case String.Encoding.utf8: self = .UTF8 default: return nil } } } func localizedEncodingName(_ encoding: Encoding) -> String { return .localizedName(of: encoding.nsStringEncoding) } // Associated values let cities = [ "Paris": 2241, "Madrid": 3165, "Amsterdam": 827, "Berlin": 3562 ] let capitals = [ "France": "Paris", "Spain": "Madrid", "The Netherlands": "Amsterdam", "Belgium": "Brussels" ] enum LookupError: Error { case CapitalNotFound case PopulationNotFound case MayorNotFound } enum Result <T> { case Failure(Error) case Success(T) } func populationOfCapital(_ country: String) -> Result<Int> { guard let capital = capitals[country] else { return .Failure(LookupError.CapitalNotFound) } guard let population = cities[capital] else { return .Failure(LookupError.PopulationNotFound) } return .Success(population) } switch populationOfCapital("France") { case let .Success(population): print("Population is \(population)") case let .Failure(error): print("Error is \(error)") } let mayors = [ "Paris": "Hidalgo", "Madrid": "Carmena", "Amsterdam": "van der Laan", "Berlin": "Müller" ] func mayorOfCapital1(_ country: String) -> String? { return capitals[country].flatMap { mayors[$0] } } func mayourOfCapital(_ country:String) -> Result<String> { guard let capital = capitals[country] else { return .Failure(LookupError.CapitalNotFound) } guard let mayor = mayors[capital] else { return .Failure(LookupError.MayorNotFound) } return .Success(mayor) } // Error handling func populationOfCapital1(_ country: String) throws -> Int { guard let capital = capitals[country] else { throw LookupError.CapitalNotFound } guard let population = cities[capital] else { throw LookupError.PopulationNotFound } return population } do { let population = try populationOfCapital1("France") print("Population is \(population)") } catch { print("Error is \(error)") } // Custom unwrapping with default value for Result type func ??<T>(_ result: Result<T>, _ errorHandler: @autoclosure (Error) -> T) -> T { switch result{ case let .Success(value): return value case let .Failure(error): return errorHandler(error) } } let successfullResult: Result<Int> = .Success(15) let intResult = successfullResult ?? 0 let failureResult: Result<Int> = .Failure(LookupError.CapitalNotFound) let errorResult = failureResult ?? 0 //: [Next](@next)
mit
4408c9bdcc046b4011df905d32bd6d3e
22.564286
81
0.657775
3.818287
false
false
false
false
jeromexiong/DouYuZB
DouYu/DouYu/Classes/Tools/Common.swift
1
329
// // Common.swift // DouYu // // Created by JeromeXiong on 2017/7/3. // Copyright © 2017年 JeromeXiong. All rights reserved. // import UIKit let mStatusBarH :CGFloat = 20 let mNavigationBarH :CGFloat = 44 let mTabbarH :CGFloat = 44 let mScreenW = UIScreen.main.bounds.width let mScreenH = UIScreen.main.bounds.height
mit
19a6f81214c850d72191d964a6141f32
19.375
55
0.723926
3.196078
false
false
false
false
proversity-org/edx-app-ios
Source/Swipeable Cell/SwipeableCell.swift
1
11251
// // SwipeableCell.swift // edX // // Created by Salman on 19/07/2017. // Copyright © 2017 edX. All rights reserved. // import UIKit protocol SwipeableCellDelegate: class { // The delegate for the actions to display in response to a swipe in the specified row. func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeActionButton]? } class SwipeableCell: UITableViewCell { /// The object that acts as the delegate of the `SwipeableCell`. public weak var swipeCellViewDelegate: SwipeableCellDelegate? private var animator: SwipeAnimator? private var originalCenter: CGFloat = 0 fileprivate weak var tableView: UITableView? fileprivate var actionsView: SwipeCellActionView? private var originalLayoutMargins: UIEdgeInsets = .zero fileprivate var panGestureRecognizer = UIPanGestureRecognizer() fileprivate var tapGestureRecognizer = UITapGestureRecognizer() var state = SwipeState.initial override var center: CGPoint { didSet { actionsView?.visibleWidth = abs(frame.minX) } } override var frame: CGRect { set { super.frame = state.isActive ? CGRect(origin: CGPoint(x: frame.minX, y: newValue.minY), size: newValue.size) : newValue } get { return super.frame } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) panGestureRecognizer.addAction {[weak self]_ in self?.handlePan(gesture: (self?.panGestureRecognizer)!) } tapGestureRecognizer.addAction {[weak self]_ in self?.handleTap(gesture: (self?.tapGestureRecognizer)!) } panGestureRecognizer.delegate = self tapGestureRecognizer.delegate = self configure() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } deinit { tableView?.panGestureRecognizer.removeTarget(self, action: nil) } private func configure() { clipsToBounds = false addGestureRecognizer(tapGestureRecognizer) addGestureRecognizer(panGestureRecognizer) } override func didMoveToSuperview() { super.didMoveToSuperview() var view: UIView = self while let superview = view.superview { view = superview if let tableView = view as? UITableView { self.tableView = tableView tableView.panGestureRecognizer.removeTarget(self, action: nil) tableView.panGestureRecognizer.addTarget(self, action: #selector(handleTablePan(gesture:))) return } } } private func isRTL() -> Bool { return (UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft) } private func allowedDirection(ForVelocity velocity: CGPoint) -> Bool { var swipAllowed = false if((isRTL() && velocity.x > 0) || (!isRTL() && velocity.x < 0)) { swipAllowed = true } else if ((velocity.x > 0 && state == .right) || ((velocity.x < 0 && state == .left))) { hideSwipe(animated: true) swipAllowed = false } return swipAllowed } private func handlePan(gesture: UIPanGestureRecognizer) { guard let target = gesture.view, allowedDirection(ForVelocity: gesture.velocity(in: target)) else { return } switch gesture.state { case .began: stopAnimatorIfNeeded() originalCenter = center.x if state == .initial || state == .animatingToInitial { let velocity = gesture.velocity(in: target) let orientation: SwipeActionsOrientation = velocity.x > 0 ? .left : .right showActionsView(for: orientation) state = targetState(forVelocity: velocity) } case .changed: let velocity = gesture.velocity(in: target) state = targetState(forVelocity: velocity) let targetOffset = targetCenter(active: state.isActive) let distance = targetOffset - center.x let normalizedVelocity = velocity.x * 1.0 / distance animate(toOffset: targetOffset, withInitialVelocity: normalizedVelocity) {[weak self] _ in if self?.state == .initial { self?.reset() } } default: break } } func hideSwipe(animated: Bool, completion: ((Bool) -> Void)? = nil) { state = .animatingToInitial let targetCenter = self.targetCenter(active: false) if animated { animate(toOffset: targetCenter) {[weak self] complete in self?.reset() completion?(complete) } } else { center = CGPoint(x: targetCenter, y: self.center.y) reset() } } @discardableResult private func showActionsView(for orientation: SwipeActionsOrientation) -> Bool { guard let tableView = tableView, let indexPath = tableView.indexPath(for: self), let actionButtons = swipeCellViewDelegate?.tableView(tableView, editActionsForRowAt: indexPath, for: orientation), actionButtons.count > 0 else { return false } originalLayoutMargins = super.layoutMargins // Remove highlight and deselect any selected cells let selectedIndexPaths = tableView.indexPathsForSelectedRows selectedIndexPaths?.forEach { tableView.deselectRow(at: $0, animated: false) } configureActionsView(with: actionButtons, for: orientation) return true } private func configureActionsView(with actionButtons: [SwipeActionButton], for orientation: SwipeActionsOrientation) { self.actionsView?.removeFromSuperview() self.actionsView = nil let actionsView = SwipeCellActionView(maxSize: bounds.size, orientation: orientation, actions: actionButtons) actionsView.delegate = self addSubview(actionsView) actionsView.snp.makeConstraints { make in make.height.equalTo(self) make.width.equalTo(100) make.centerY.equalTo(self) make.leading.equalTo(snp.trailing) } self.actionsView = actionsView } private func animate(duration: Double = 0.7, toOffset offset: CGFloat, withInitialVelocity velocity: CGFloat = 0, completion: ((Bool) -> Void)? = nil) { stopAnimatorIfNeeded() layoutIfNeeded() let animator: SwipeAnimator = { if velocity != 0 { return UIViewSpringAnimator(duration: duration, damping: 1.0, initialVelocity: velocity) } else { return UIViewSpringAnimator(duration: duration, damping: 1.0) } }() animator.addAnimations({[weak self] in if let owner = self { owner.center = CGPoint(x: offset, y: owner.center.y) owner.layoutIfNeeded() } }) if let completion = completion { animator.addCompletion(completion: completion) } self.animator = animator animator.startAnimation() } private func stopAnimatorIfNeeded() { if animator?.isRunning == true { animator?.stopAnimation(true) } } private func handleTap(gesture: UITapGestureRecognizer) { hideSwipe(animated: true); } @objc func handleTablePan(gesture: UIPanGestureRecognizer) { if gesture.state == .began { hideSwipe(animated: true) } } // Override so we can accept touches anywhere within the cell's minY/maxY. // This is required to detect touches on the `SwipeCellActionView` sitting alongside the // `SwipeableCell`. override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { guard let superview = superview else { return false } let point = convert(point, to: superview) for cell in tableView?.swipeCells ?? [] { if (cell.state == .left || cell.state == .right) && !cell.contains(point: point) { tableView?.hideSwipeCell() return false } } return contains(point: point) } private func contains(point: CGPoint) -> Bool { return point.y > frame.minY && point.y < frame.maxY } override var layoutMargins: UIEdgeInsets { get { return frame.origin.x != 0 ? originalLayoutMargins : super.layoutMargins } set { super.layoutMargins = newValue } } } extension SwipeableCell: SwipeActionsViewDelegate { fileprivate func targetState(forVelocity velocity: CGPoint) -> SwipeState { guard let actionsView = actionsView else { return .initial } switch actionsView.orientation { case .left: return (velocity.x < 0 && !actionsView.expanded) ? .initial : .left case .right: return (velocity.x > 0 && !actionsView.expanded) ? .initial : .right } } fileprivate func targetCenter(active: Bool) -> CGFloat { guard let actionsView = actionsView, active == true else { return bounds.midX } return bounds.midX - actionsView.preferredWidth * actionsView.orientation.scale } func reset() { state = .initial actionsView?.removeFromSuperview() actionsView = nil } override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if gestureRecognizer == tapGestureRecognizer { let cell = tableView?.swipeCells.first(where: { $0.state.isActive }) return cell == nil ? false : true } if gestureRecognizer == panGestureRecognizer, let view = gestureRecognizer.view, let gestureRecognizer = gestureRecognizer as? UIPanGestureRecognizer { let translation = gestureRecognizer.translation(in: view) return abs(translation.y) <= abs(translation.x) } return true } func swipeActionsView(_ swipeCellActionView: SwipeCellActionView, didSelect action: SwipeActionButton) { // delete action perform(action: action) } func perform(action: SwipeActionButton) { guard let tableView = tableView, let indexPath = tableView.indexPath(for: self) else { return } hideSwipe(animated: true) action.handler?(action, indexPath) } } extension UITableView { var swipeCells: [SwipeableCell] { return visibleCells.compactMap({ $0 as? SwipeableCell }) } func hideSwipeCell() { swipeCells.forEach { $0.hideSwipe(animated: true) } } }
apache-2.0
40e85c5ad65a4fd255b9cf79a44ac705
34.15625
156
0.606844
5.357143
false
false
false
false
inket/stts
stts/Services/Super/AppleStore.swift
1
4332
// // AppleStore.swift // stts // import Foundation protocol AppleStoreService { var serviceName: String { get } } // AppleStore as in a store that holds the status of each of Apple's services, and not "Apple Store" class AppleStore: Loading { let url: URL private var statuses: [String: (ServiceStatus, String)] = [:] private var loadErrorMessage: String? private var callbacks: [() -> Void] = [] private var lastUpdateTime: TimeInterval = 0 private var currentlyReloading: Bool = false init(url: String) { self.url = URL(string: url)! } func loadStatus(_ callback: @escaping () -> Void) { callbacks.append(callback) guard !currentlyReloading else { return } // Throttling to prevent multiple requests if the first one finishes too quickly guard Date.timeIntervalSinceReferenceDate - lastUpdateTime >= 3 else { return clearCallbacks() } currentlyReloading = true loadData(with: url) { data, _, error in defer { self.currentlyReloading = false self.clearCallbacks() } self.statuses = [:] guard let data = data else { return self._fail(error) } guard let jsonData = String(data: data, encoding: .utf8)?.innerJSONString.data(using: .utf8), let responseData = try? JSONDecoder().decode(AppleResponseData.self, from: jsonData) else { return self._fail("Unexpected data") } var serviceStatuses = [String: (ServiceStatus, String)]() responseData.services.forEach { if let worstEvent = $0.worstEvent { serviceStatuses[$0.serviceName] = (worstEvent.serviceStatus, worstEvent.realStatus.rawValue) } else { serviceStatuses[$0.serviceName] = (.good, "Available") } } self.statuses = serviceStatuses self.lastUpdateTime = Date.timeIntervalSinceReferenceDate } } func status(for service: AppleStoreService) -> (ServiceStatus, String) { let worstStatus: (ServiceStatus, String)? if service.serviceName == "*" { worstStatus = statuses.values.max(by: { e1, e2 in e1.0 < e2.0 }) // get the worst by service status } else { worstStatus = statuses[service.serviceName] } let status = worstStatus?.0 let message = worstStatus?.1 return (status ?? .undetermined, message ?? loadErrorMessage ?? "Unexpected error") } private func clearCallbacks() { callbacks.forEach { $0() } callbacks = [] } private func _fail(_ error: Error?) { _fail(ServiceStatusMessage.from(error)) } private func _fail(_ message: String) { loadErrorMessage = message lastUpdateTime = 0 } } struct AppleResponseData: Codable { struct Service: Codable { let serviceName: String let events: [Event] var worstEvent: Event? { return events.max { e1, e2 in e1.serviceStatus < e2.serviceStatus } } } enum EventStatus: String, Codable { case ongoing case resolved case upcoming case completed } enum EventType: String, Codable { case available = "Available" case outage = "Outage" case issue = "Issue" case performance = "Performance" case maintenance = "Maintenance" } struct Event: Codable { let statusType: EventType let eventStatus: EventStatus var realStatus: EventType { switch eventStatus { case .ongoing: return statusType case .resolved, .upcoming, .completed: return .available } } var serviceStatus: ServiceStatus { switch realStatus { case .available: return .good case .outage: return .major case .issue, .performance: return .minor case .maintenance: return .maintenance } } } let services: [Service] }
mit
6e521de2ecc2813d956c4c8cfc8908b4
27.12987
112
0.564635
4.950857
false
false
false
false
kickstarter/ios-oss
KsApi/models/lenses/ActivityLenses.swift
1
3406
import Foundation import Prelude extension Activity { public enum lens { public static let category = Lens<Activity, Activity.Category>( view: { $0.category }, set: { Activity( category: $0, comment: $1.comment, createdAt: $1.createdAt, id: $1.id, memberData: $1.memberData, project: $1.project, update: $1.update, user: $1.user ) } ) public static let comment = Lens<Activity, ActivityComment?>( view: { $0.comment }, set: { Activity( category: $1.category, comment: $0, createdAt: $1.createdAt, id: $1.id, memberData: $1.memberData, project: $1.project, update: $1.update, user: $1.user ) } ) public static let createdAt = Lens<Activity, TimeInterval>( view: { $0.createdAt }, set: { Activity( category: $1.category, comment: $1.comment, createdAt: $0, id: $1.id, memberData: $1.memberData, project: $1.project, update: $1.update, user: $1.user ) } ) public static let id = Lens<Activity, Int>( view: { $0.id }, set: { Activity( category: $1.category, comment: $1.comment, createdAt: $1.createdAt, id: $0, memberData: $1.memberData, project: $1.project, update: $1.update, user: $1.user ) } ) public static let memberData = Lens<Activity, MemberData>( view: { $0.memberData }, set: { Activity( category: $1.category, comment: $1.comment, createdAt: $1.createdAt, id: $1.id, memberData: $0, project: $1.project, update: $1.update, user: $1.user ) } ) public static let project = Lens<Activity, Project?>( view: { $0.project }, set: { Activity( category: $1.category, comment: $1.comment, createdAt: $1.createdAt, id: $1.id, memberData: $1.memberData, project: $0, update: $1.update, user: $1.user ) } ) public static let update = Lens<Activity, Update?>( view: { $0.update }, set: { Activity( category: $1.category, comment: $1.comment, createdAt: $1.createdAt, id: $1.id, memberData: $1.memberData, project: $1.project, update: $0, user: $1.user ) } ) public static let user = Lens<Activity, User?>( view: { $0.user }, set: { Activity( category: $1.category, comment: $1.comment, createdAt: $1.createdAt, id: $1.id, memberData: $1.memberData, project: $1.project, update: $1.update, user: $0 ) } ) } } extension Lens where Whole == Activity, Part == Activity.MemberData { public var amount: Lens<Activity, Int?> { return Activity.lens.memberData .. Activity.MemberData.lens.amount } public var backing: Lens<Activity, Backing?> { return Activity.lens.memberData .. Activity.MemberData.lens.backing } public var oldAmount: Lens<Activity, Int?> { return Activity.lens.memberData .. Activity.MemberData.lens.oldAmount } public var oldRewardId: Lens<Activity, Int?> { return Activity.lens.memberData .. Activity.MemberData.lens.oldRewardId } public var newAmount: Lens<Activity, Int?> { return Activity.lens.memberData .. Activity.MemberData.lens.newAmount } public var newRewardId: Lens<Activity, Int?> { return Activity.lens.memberData .. Activity.MemberData.lens.newRewardId } public var rewardId: Lens<Activity, Int?> { return Activity.lens.memberData .. Activity.MemberData.lens.rewardId } }
apache-2.0
b9b587e100804f47f3b6d005f812fb40
33.06
88
0.628009
3.457868
false
false
false
false
aryaxt/Binder
Binder/Source/TableViewDataSourceProxy.swift
1
1911
// // TableDataSourceProxy.swift // Binder // // Created by Aryan Ghassemi on 5/1/16. // Copyright © 2016 Aryan Ghassemi. All rights reserved. // import UIKit internal class TableViewDataSourceProxy: NSObject, UITableViewDataSource { private weak var dataSource: UITableViewDataSource? internal var numberOfSectionsClosure: (Void->Int)? internal var numberOfRowsClosure: (Int->Int)? internal var cellIdentifierClosure: (NSIndexPath->String)? internal var cellClosure: ((NSIndexPath, UITableViewCell)->Void)? internal var cellClassName: String? // MARK: - Initialization - override init() { super.init() } init(dataSource: UITableViewDataSource) { self.dataSource = dataSource } // MARK: - NSObject - override func respondsToSelector(aSelector: Selector) -> Bool { if let dataSource = dataSource where dataSource.respondsToSelector(aSelector) { return true } return super.respondsToSelector(aSelector) } override func forwardingTargetForSelector(aSelector: Selector) -> AnyObject? { if let dataSource = dataSource where dataSource.respondsToSelector(aSelector) { return dataSource } return super.forwardingTargetForSelector(aSelector) } // MARK: - UITableViewDataSource - func numberOfSectionsInTableView(tableView: UITableView) -> Int { return numberOfSectionsClosure?() ?? 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numberOfRowsClosure?(section) ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier = cellIdentifierClosure?(indexPath) ?? cellClassName guard let cellIdentifier = identifier else { fatalError("no cell identifier was provided") } let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) cellClosure?(indexPath, cell) return cell } }
mit
0b9c65f665c5ae45c21bb7994c34e779
27.939394
106
0.758115
4.515366
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Idiomatic/RedundantOptionalInitializationRule.swift
1
7032
import SwiftSyntax struct RedundantOptionalInitializationRule: SwiftSyntaxCorrectableRule, ConfigurationProviderRule { var configuration = SeverityConfiguration(.warning) init() {} static let description = RuleDescription( identifier: "redundant_optional_initialization", name: "Redundant Optional Initialization", description: "Initializing an optional variable with nil is redundant.", kind: .idiomatic, nonTriggeringExamples: [ Example("var myVar: Int?\n"), Example("let myVar: Int? = nil\n"), Example("var myVar: Int? = 0\n"), Example("func foo(bar: Int? = 0) { }\n"), Example("var myVar: Optional<Int>\n"), Example("let myVar: Optional<Int> = nil\n"), Example("var myVar: Optional<Int> = 0\n"), // properties with body should be ignored Example(""" var foo: Int? { if bar != nil { } return 0 } """), // properties with a closure call Example(""" var foo: Int? = { if bar != nil { } return 0 }() """), // lazy variables need to be initialized Example("lazy var test: Int? = nil"), // local variables Example(""" func funcName() { var myVar: String? } """), Example(""" func funcName() { let myVar: String? = nil } """) ], triggeringExamples: triggeringExamples, corrections: corrections ) private static let triggeringExamples: [Example] = [ Example("var myVar: Int?↓ = nil\n"), Example("var myVar: Optional<Int>↓ = nil\n"), Example("var myVar: Int?↓=nil\n"), Example("var myVar: Optional<Int>↓=nil\n)"), Example(""" var myVar: String?↓ = nil { didSet { print("didSet") } } """), Example(""" func funcName() { var myVar: String?↓ = nil } """) ] private static let corrections: [Example: Example] = [ Example("var myVar: Int?↓ = nil\n"): Example("var myVar: Int?\n"), Example("var myVar: Optional<Int>↓ = nil\n"): Example("var myVar: Optional<Int>\n"), Example("var myVar: Int?↓=nil\n"): Example("var myVar: Int?\n"), Example("var myVar: Optional<Int>↓=nil\n"): Example("var myVar: Optional<Int>\n"), Example("class C {\n#if true\nvar myVar: Int?↓ = nil\n#endif\n}"): Example("class C {\n#if true\nvar myVar: Int?\n#endif\n}"), Example(""" var myVar: Int?↓ = nil { didSet { } } """): Example(""" var myVar: Int? { didSet { } } """), Example(""" var myVar: Int?↓=nil{ didSet { } } """): Example(""" var myVar: Int?{ didSet { } } """), Example(""" func foo() { var myVar: String?↓ = nil } """): Example(""" func foo() { var myVar: String? } """) ] func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor { Visitor(viewMode: .sourceAccurate) } func makeRewriter(file: SwiftLintFile) -> ViolationsSyntaxRewriter? { Rewriter( locationConverter: file.locationConverter, disabledRegions: disabledRegions(file: file) ) } } private extension RedundantOptionalInitializationRule { final class Visitor: ViolationsSyntaxVisitor { override func visitPost(_ node: VariableDeclSyntax) { guard node.letOrVarKeyword.tokenKind == .varKeyword, !node.modifiers.containsLazy else { return } violations.append(contentsOf: node.bindings.compactMap(\.violationPosition)) } } final class Rewriter: SyntaxRewriter, ViolationsSyntaxRewriter { private(set) var correctionPositions: [AbsolutePosition] = [] private let locationConverter: SourceLocationConverter private let disabledRegions: [SourceRange] init(locationConverter: SourceLocationConverter, disabledRegions: [SourceRange]) { self.locationConverter = locationConverter self.disabledRegions = disabledRegions } override func visit(_ node: VariableDeclSyntax) -> DeclSyntax { guard node.letOrVarKeyword.tokenKind == .varKeyword, !node.modifiers.containsLazy else { return super.visit(node) } let violations = node.bindings .compactMap { binding in binding.violationPosition.map { ($0, binding) } } .filter { position, _ in !position.isContainedIn(regions: disabledRegions, locationConverter: locationConverter) } guard violations.isNotEmpty else { return super.visit(node) } correctionPositions.append(contentsOf: violations.map(\.0)) let violatingBindings = violations.map(\.1) let newBindings = PatternBindingListSyntax(node.bindings.map { binding in guard violatingBindings.contains(binding) else { return binding } let newBinding = binding.withInitializer(nil) if newBinding.accessor == nil { return newBinding.withTrailingTrivia(binding.initializer?.trailingTrivia ?? .zero) } else { return newBinding } }) return super.visit(node.withBindings(newBindings)) } } } private extension PatternBindingSyntax { var violationPosition: AbsolutePosition? { guard let initializer = initializer, let type = typeAnnotation, initializer.isInitializingToNil, type.isOptionalType else { return nil } return type.endPositionBeforeTrailingTrivia } } private extension InitializerClauseSyntax { var isInitializingToNil: Bool { value.is(NilLiteralExprSyntax.self) } } private extension TypeAnnotationSyntax { var isOptionalType: Bool { if type.is(OptionalTypeSyntax.self) { return true } if let type = type.as(SimpleTypeIdentifierSyntax.self), let genericClause = type.genericArgumentClause { return genericClause.arguments.count == 1 && type.name.text == "Optional" } return false } }
mit
86b55ed4138d6957e13f416e8aace240
31.728972
112
0.529126
5.254314
false
false
false
false
samirahmed/iosRadialMenu
RadialMenuTests/RadialMenuTests.swift
1
2983
// // RadialMenuTests.swift // RadialMenuTests // // Created by Brad Jasper on 6/5/14. // Copyright (c) 2014 Brad Jasper. All rights reserved. // import UIKit import XCTest class RadialMenuTests: XCTestCase { func testEventStateTransitions() { // Setup radial menu let radialMenu = RadialMenu(menus: [RadialSubMenu(frame: CGRectZero), RadialSubMenu(frame: CGRectZero)]) radialMenu.openDelayStep = 0.0 radialMenu.closeDelayStep = 0.0 // Setup expectations let openExpectation = self.expectationWithDescription("opens") let closeExpectation = self.expectationWithDescription("closes") // Setup event handlers for open/close radialMenu.onOpen = { XCTAssertEqual(radialMenu.state, .Opened) for subMenu in radialMenu.subMenus { XCTAssertEqual(subMenu.state, .Opened) } openExpectation.fulfill() radialMenu.close() XCTAssertEqual(radialMenu.state, .Closing) } radialMenu.onClose = { XCTAssertEqual(radialMenu.state, .Closed) for subMenu in radialMenu.subMenus { XCTAssertEqual(subMenu.state, .Closed) } closeExpectation.fulfill() } // Verify initial state XCTAssertEqual(radialMenu.subMenus.count, 4, "Unknown number of subMenus") XCTAssertEqual(radialMenu.state, .Closed) // Open & verify opening state radialMenu.openAtPosition(CGPointZero) XCTAssertEqual(radialMenu.state, .Opening) for subMenu in radialMenu.subMenus { XCTAssertEqual(subMenu.state, .Opening) } // Wait for expectations & verify final state self.waitForExpectationsWithTimeout(4, handler: { _ in XCTAssertEqual(radialMenu.state, .Closed) for subMenu in radialMenu.subMenus { XCTAssertEqual(subMenu.state, .Closed) } }) } func testStateChangeEventsFireOnce() { let radialMenu = RadialMenu(menus: [RadialSubMenu(frame: CGRectZero), RadialSubMenu(frame: CGRectZero)]) var opened = 0, closed = 0 radialMenu.onOpen = { opened += 1} radialMenu.onClose = { closed += 1} XCTAssertEqual(radialMenu.state, .Closed) radialMenu.state = .Closed XCTAssertEqual(closed, 0) XCTAssertEqual(opened, 0) radialMenu.state = .Opened XCTAssertEqual(closed, 0) XCTAssertEqual(opened, 1) radialMenu.state = .Closed XCTAssertEqual(closed, 1) XCTAssertEqual(opened, 1) // Calling the same state many times shouldn't trigger a state change radialMenu.state = .Closed radialMenu.state = .Closed radialMenu.state = .Closed XCTAssertEqual(closed, 1) XCTAssertEqual(opened, 1) } }
mit
ed9b2913e9d3804ab389dfb5ac1341c1
31.423913
112
0.610795
4.834684
false
true
false
false
rundfunk47/Juice
Juice/Classes/JSONDictionary+Encode+Transform.swift
1
5011
// // JSONDictionary+Encode+Transform.swift // Juice // // Created by Narek M on 31/08/16. // Copyright © 2016 Narek. All rights reserved. // import Foundation public extension JSONDictionary { /// Encodes a type in the dictionary, given a key. /// - Parameter key: String. /// - Parameter value: What to encode. /// - Parameter transform: The transform to apply mutating func encode<T, U: Encodable>(_ key: String, value: T, transform: (_ input: T) throws -> U?) throws { let transformedValue = try transform(value) try self.encode(key, value: transformedValue) } /// Encodes a type in the dictionary, given a key. /// - Parameter key: String. /// - Parameter value: What to encode. /// - Parameter transform: The transform to apply mutating func encode<T, U: Encodable>(_ key: String, value: T, transform: (_ input: T) throws -> Array<U>?) throws { let transformedValue = try transform(value) try self.encode(key, value: transformedValue) } /// Encodes a type in the dictionary, given a key. /// - Parameter key: String. /// - Parameter value: What to encode. /// - Parameter transform: The transform to apply mutating func encode<T, U: Encodable>(_ key: String, value: T, transform: (_ input: T) throws -> Dictionary<String, U>?) throws { let transformedValue = try transform(value) try self.encode(key, value: transformedValue) } /// Encodes a type in the dictionary, given a key. /// - Parameter key: String. /// - Parameter value: What to encode. /// - Parameter transform: The transform to apply mutating func encode<T: Encodable>(_ key: String, value: T, transform: (_ input: T) throws -> JSONDictionary) throws { let transformedValue = try transform(value) try self.encode(key, value: transformedValue) } /// Encodes a type in the dictionary, given a key. /// - Parameter key: String. /// - Parameter value: What to encode. /// - Parameter transform: The transform to apply mutating func encode<T, U: Encodable>(_ key: String, value: T, transform: (_ input: T) throws -> Array<U?>) throws { let transformedValue = try transform(value) try self.encode(key, value: transformedValue) } /// Encodes a type in the dictionary, given a key. /// - Parameter key: String. /// - Parameter value: What to encode. /// - Parameter transform: The transform to apply mutating func encode<T, U: Encodable>(_ key: String, value: T, transform: (_ input: T) throws -> Dictionary<String, U?>) throws { let transformedValue = try transform(value) try self.encode(key, value: transformedValue) } /// Encodes a type in the dictionary, given a key. /// - Parameter keyPath: Array of strings. /// - Parameter value: What to encode. /// - Parameter transform: The transform to apply mutating func encode<T, U: Encodable>(_ keyPath: [String], value: T, transform: (_ input: T) throws -> U?) throws { let transformedValue = try transform(value) try self.encode(keyPath, value: transformedValue) } /// Encodes a type in the dictionary, given a key. /// - Parameter keyPath: Array of strings. /// - Parameter value: What to encode. /// - Parameter transform: The transform to apply mutating func encode<T, U: Encodable>(_ keyPath: [String], value: T, transform: (_ input: T) throws -> Array<U>?) throws { let transformedValue = try transform(value) try self.encode(keyPath, value: transformedValue) } /// Encodes a type in the dictionary, given a key. /// - Parameter keyPath: Array of strings. /// - Parameter value: What to encode. /// - Parameter transform: The transform to apply mutating func encode<T, U: Encodable>(_ keyPath: [String], value: T, transform: (_ input: T) throws -> Dictionary<String, U>?) throws { let transformedValue = try transform(value) try self.encode(keyPath, value: transformedValue) } /// Encodes a type in the dictionary, given a key. /// - Parameter keyPath: Array of strings. /// - Parameter value: What to encode. /// - Parameter transform: The transform to apply mutating func encode<T, U: Encodable>(_ keyPath: [String], value: T, transform: (_ input: T) throws -> Array<U?>) throws { let transformedValue = try transform(value) try self.encode(keyPath, value: transformedValue) } /// Encodes a type in the dictionary, given a key. /// - Parameter keyPath: Array of strings. /// - Parameter value: What to encode. /// - Parameter transform: The transform to apply mutating func encode<T, U: Encodable>(_ keyPath: [String], value: T, transform: (_ input: T) throws -> Dictionary<String, U?>) throws { let transformedValue = try transform(value) try self.encode(keyPath, value: transformedValue) } }
mit
bf90bc0da1b5427a6002f768d455970e
44.545455
139
0.642715
4.345186
false
false
false
false
haawa799/Metal-Flaps
SimpleMetal/Nodes/Scene.swift
1
3194
// // Scene.swift // Imported Model // // Created by Andrew K. on 7/4/14. // Copyright (c) 2014 Andrew Kharchyshyn. All rights reserved. // import UIKit import Metal class Scene: Node { var avaliableUniformBuffers: DispatchSemaphore? var width: Float = 0.0 var height: Float = 0.0 let perspectiveAngleRad: Float = Matrix4.degrees(toRad: 85.0) var sceneOffsetZ: Float = 0.0 // var projectionMatrix: AnyObject init(name: String, baseEffect: BaseEffect, width: Float, height: Float) { self.width = width self.height = height sceneOffsetZ = (height * 0.5) / tanf(perspectiveAngleRad * 0.5) let ratio: Float = Float(width) / Float(height) baseEffect.projectionMatrix = Matrix4.makePerspectiveViewAngle(perspectiveAngleRad, aspectRatio: ratio, nearZ: 0.1, farZ: 10.5 * sceneOffsetZ) super.init(name: name, baseEffect: baseEffect, vertices: nil, vertexCount: 0, textureName: nil) positionZ = -1 * sceneOffsetZ } func prepareToDraw() { let numberOfUniformBuffersToUse = 3 * self.numberOfSiblings print("bufs \(numberOfUniformBuffersToUse)") avaliableUniformBuffers = DispatchSemaphore(value: numberOfUniformBuffersToUse) self.uniformBufferProvider = UniformsBufferGenerator(numberOfInflightBuffers: CInt(numberOfUniformBuffersToUse), with: baseEffect.device) } func render(commandQueue: MTLCommandQueue, metalView: MetalView, parentMVMatrix: AnyObject) { let parentModelViewMatrix: Matrix4 = parentMVMatrix as! Matrix4 let myModelViewMatrix: Matrix4 = modelMatrix() as! Matrix4 myModelViewMatrix.multiplyLeft(parentModelViewMatrix) let projectionMatrix: Matrix4 = baseEffect.projectionMatrix as! Matrix4 //We are using 3 uniform buffers, we need to wait in case CPU wants to write in first uniform buffer, while GPU is still using it (case when GPU is 2 frames ahead CPU) avaliableUniformBuffers?.wait() guard let commandBuffer = commandQueue.makeCommandBuffer(), let renderPathDescriptor = metalView.frameBuffer.renderPassDescriptor else { return } commandBuffer.addCompletedHandler { (buffer:MTLCommandBuffer!) -> Void in self.avaliableUniformBuffers?.signal() } var commandEncoder: MTLRenderCommandEncoder? for child in children { commandEncoder = renderNode(node: child, parentMatrix: myModelViewMatrix, projectionMatrix: projectionMatrix, renderPassDescriptor: renderPathDescriptor!, commandBuffer: commandBuffer, encoder: commandEncoder, uniformProvider: uniformBufferProvider) } if let drawableAnyObject = metalView.frameBuffer.currentDrawable as? MTLDrawable { commandBuffer.present(drawableAnyObject) } commandEncoder?.endEncoding() // Commit commandBuffer to his commandQueue in which he will be executed after commands before him in queue commandBuffer.commit(); } }
mit
c333607e06ed6482de3dba120ba1de3a
36.576471
261
0.674076
4.861492
false
false
false
false
OldBulls/swift-weibo
ZNWeibo/ZNWeibo/Classes/Profile/ProfileViewController.swift
1
3067
// // ProfileViewController.swift // ZNWeibo // // Created by 金宝和信 on 16/7/6. // Copyright © 2016年 zn. All rights reserved. // import UIKit class ProfileViewController: BaseViewController { override func viewDidLoad() { super.viewDidLoad() visitorView.setupVisitorViewInfo("visitordiscover_image_profile", title: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
617c0c4d5c4ad7cb4ea34d990c1a67bc
31.967033
157
0.683
5.385996
false
false
false
false
JadenGeller/Parsley
Parsley/ParsleyTests/BaseTests.swift
1
1622
// // BaseTests.swift // Parsley // // Created by Jaden Geller on 10/14/15. // Copyright © 2015 Jaden Geller. All rights reserved. // import XCTest import Parsley import Spork class BaseTests: XCTestCase { func testPure() { XCTAssertEqual("Jaden", try? pure("Jaden").parse("Hello world".characters)) } func testAny() { XCTAssertEqual("H", try? any().parse("Hello world".characters)) } func testSatisfy() { let parser = satisfy { $0 > 0 } XCTAssertEqual(1, try? parser.parse([1, 2, 3])) XCTAssertEqual(nil, try? parser.parse([0, 1, 2, 3])) } func testToken() { let parser = token(0) XCTAssertEqual(0, try? parser.parse([0])) XCTAssertEqual(nil, try? parser.parse([1])) } func testWithinInterval() { let parser = within(2...4) XCTAssertEqual(3, try? parser.parse([3])) XCTAssertEqual(nil, try? parser.parse([5])) } func testWithinSequence() { let parser = oneOf([1, 2, 3, 5, 8]) XCTAssertEqual(5, try? parser.parse([5])) XCTAssertEqual(nil, try? parser.parse([6])) } func testEnd() { do { _ = try end().parse("".characters) } catch { XCTFail() } } func testTerminating() { do { _ = try terminating(sequence(token(0), token(1))).parse(0...1) } catch { XCTFail() } do { _ = try terminating(sequence(token(0), token(1))).parse(0...2) XCTFail() } catch { } } }
mit
0f9edf7716fabe18474360a9cb7b9ffe
23.19403
83
0.520666
3.906024
false
true
false
false
Contron/Dove
Dove/Extensions/FileManagerExtensions.swift
1
1482
// // FileManagerExtensions.swift // Dove // // Created by Connor Haigh on 07/12/2018. // Copyright © 2018 Connor Haigh. All rights reserved. // import Foundation public extension FileManager { public struct Key: RawRepresentable, Equatable, Hashable { public init(rawValue: String) { self.rawValue = rawValue } public init(_ rawValue: String) { self.rawValue = rawValue } public let rawValue: String } public func extendedAttribute(for url: URL, key: FileManager.Key) -> String? { return url.withUnsafeFileSystemRepresentation({ pointer in let length = getxattr(pointer, key.rawValue, nil, 0, 0, 0) guard length != -1 else { return nil } var data = Data(count: length) let result = data.withUnsafeMutableBytes({ bytes in getxattr(pointer, key.rawValue, bytes, length, 0, 0) }) guard result != -1 else { return nil } return String(data: data, encoding: .utf8) }) } public func setExtendedAttribute(for url: URL, key: FileManager.Key, value: String) { _ = url.withUnsafeFileSystemRepresentation({ pointer in guard let data = value.data(using: .utf8) else { return } _ = data.withUnsafeBytes({ bytes in setxattr(pointer, key.rawValue, bytes, data.count, 0, 0) }) }) } public func removeExtendedAttribute(for url: URL, key: FileManager.Key) { _ = url.withUnsafeFileSystemRepresentation({ pointer in removexattr(pointer, key.rawValue, 0) }) } }
mit
c5173f68fba8e435b2bb646574cdf029
22.507937
86
0.671843
3.543062
false
false
false
false
jatoben/Redis
Redis/RedisList.swift
1
3056
/* * RedisHash.swift * Copyright (c) 2015 Ben Gollmer. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public extension Redis { public func blpop(keys: String..., timeout: Int = 0) throws -> (String, String) { return try _blockingListCommand(["BLPOP"] + keys + [String(timeout)]) } public func brpop(keys: String..., timeout: Int = 0) throws -> (String, String) { return try _blockingListCommand(["BRPOP"] + keys + [String(timeout)]) } public func brpoplpush(source: String, destination: String, timeout: Int = 0) throws -> String { return try _stringCommand("BRPOPLPUSH", source, destination, String(timeout)) } public func lindex(key: String, idx: Int) throws -> String? { return try _optionalStringCommand("LINDEX", key, String(idx)) } public func linsert(key: String, position: Position, pivot: String, value: String) throws -> Int64 { return try _intCommand("LINSERT", key, position.rawValue, pivot, value) } public func llen(key: String) throws -> Int64 { return try _intCommand("LLEN", key) } public func lpop(key: String) throws -> String? { return try _optionalStringCommand("LPOP", key) } public func lpush(key: String, values: String...) throws -> Int64 { return try _intCommand(["LPUSH", key] + values) } public func lpushx(key: String, value: String) throws -> Int64 { return try _intCommand("LPUSHX", key, value) } public func lrange(key: String, start: Int, stop: Int) throws -> [String] { return try _stringArrayCommand("LRANGE", key, String(start), String(stop)) } public func lrem(key: String, count: Int, value: String) throws -> Int64 { return try _intCommand("LREM", key, String(count), value) } public func lset(key: String, idx: Int, value: String) throws { try _stringCommand("LSET", key, String(idx), value) } public func ltrim(key: String, start: Int, stop: Int) throws { try _stringCommand("LTRIM", key, String(start), String(stop)) } public func rpop(key: String) throws -> String? { return try _optionalStringCommand("RPOP", key) } public func rpoplpush(source: String, destination: String) throws -> String? { return try _optionalStringCommand("RPOPLPUSH", source, destination) } public func rpush(key: String, values: String...) throws -> Int64 { if values.count == 0 { return 0 } return try _intCommand(["RPUSH", key] + values) } public func rpushx(key: String, value: String) throws -> Int64 { return try _intCommand("RPUSHX", key, value) } }
apache-2.0
12e4979b6b28994d252af7d0a617e037
32.955556
102
0.678992
3.65988
false
false
false
false
coderMONSTER/ioscelebrity
YStar/YStar/Scenes/Controller/WithdrawalVC.swift
1
7426
// // WithdrawalVC.swift // iOSStar // // Created by sum on 2017/4/26. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import SVProgressHUD class WithdrawalVC: BaseTableViewController,UITextFieldDelegate { // 可提现金额 @IBOutlet var withDrawMoney: UILabel! // 收款账户 @IBOutlet var account: UILabel! @IBOutlet var inputMoney: UITextField! // 0 设置了密码 1 未设置密码 var needPwd : Int = 2 override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) requestUseBalance() } // MARK: - 初始化 override func viewDidLoad() { super.viewDidLoad() inputMoney.delegate = self inputMoney.becomeFirstResponder() requestGetBankInfo() } // MARK: - 获取银行卡信息 func requestGetBankInfo(){ let model = BankCardListRequestModel() AppAPIHelper.commen().bankCardList(model: model, complete: { [weak self](result) in if let model = result as? BankListModel{ let dataModel = BankCardInfoRequestModel() dataModel.cardNo = model.cardNo AppAPIHelper.commen().bankCardInfo(model: dataModel, complete: { [weak self](result) in if let dataBank = result as? BankInfoModel{ let index1 = model.cardNo.index(model.cardNo.startIndex, offsetBy: model.cardNo.length()-3) self?.account.text = dataBank.bankName + "(" + model.cardNo.substring(from: index1) + ")" } return nil }, error:self?.errorBlockFunc()) } return nil }, error:errorBlockFunc()) } // MARK: - 获取金额,及是否设置了交易密码 func requestUseBalance() { let model = LoginModle() AppAPIHelper.commen().userinfo(model: model, complete: {[weak self] (response) -> ()? in if let objects = response as? UserBalance { self?.withDrawMoney.text = "可提现金额" + "," + "¥" + String.init(format: "%.2f", objects.balance) ShareModelHelper.instance().userinfo.balance = objects.balance self?.needPwd = objects.is_setpwd } return nil }, error: errorBlockFunc()) } // MARK: - 全部提现 @IBAction func withDrawAll(_ sender: Any) { inputMoney.text = String.init(format: "%.2f", ShareModelHelper.instance().userinfo.balance) } // MARK: - 提现 @IBAction func withDraw(_ sender: Any) { if inputMoney.text?.length() == 0 { SVProgressHUD.showErrorMessage(ErrorMessage: "请输入提现金额", ForDuration: 1.0, completion: nil) return } if inputMoney.text != ""{ if Double.init(inputMoney.text!)! > ShareModelHelper.instance().userinfo.balance{ SVProgressHUD.showErrorMessage(ErrorMessage: "最多可提现" + String.init(format: "%.2f", ShareModelHelper.instance().userinfo.balance), ForDuration: 1, completion: nil) return } if Double.init(inputMoney.text!)! <= 0{ SVProgressHUD.showErrorMessage(ErrorMessage: "提现金额大于0" , ForDuration: 1, completion: nil) return } } inputMoney.resignFirstResponder() if self.needPwd == 1 { // 未设置支付密码 let alertVC = AlertViewController() alertVC.showAlertVc(imageName: "tangkuang_kaitongzhifu", titleLabelText: "交易密码", subTitleText: "提现需要开通交易密码才能进行操作", completeButtonTitle: "开 通 支 付", action: {[weak alertVC] (completeButton) in alertVC?.dismissAlertVc() let setPayPwdVC = UIStoryboard.init(name: "Benifity", bundle: nil).instantiateViewController(withIdentifier: "SetPayPwdVC") self.navigationController?.pushViewController(setPayPwdVC, animated: true) }) } else { // 已设置支付密码 let payPwdAlertView = PayPwdAlertView(frame: self.view.bounds) payPwdAlertView.show(self.view) payPwdAlertView.completeBlock = ({[weak self](password:String) -> Void in let model = CheckPayPwdModel() model.uid = UserDefaults.standard.value(forKey: AppConst.UserDefaultKey.uid.rawValue) as! Int64 model.paypwd = password.md5() // 校验密码 AppAPIHelper.commen().CheckPayPwd(requestModel: model, complete: { (response) -> ()? in if let objects = response as? ResultModel { // 密码输入成功 if objects.result == 1 { // 发起提现 let requestModel = WithdrawalRequestModel() requestModel.price = Double.init((self?.inputMoney.text!)!)! AppAPIHelper.commen().Withdrawal(requestModel: requestModel, complete: { (responseObject) -> ()? in if let resultObj = responseObject as? ResultModel { if resultObj.result == 1 { SVProgressHUD.showSuccessMessage(SuccessMessage: "提现成功", ForDuration: 1.0, completion: { _ = self?.navigationController?.popViewController(animated: true) }) } } return nil }, error: { (error) -> ()? in self?.didRequestError(error) return nil }) } else { // 失败 SVProgressHUD.showErrorMessage(ErrorMessage: "密码输入错误", ForDuration: 2.0, completion: { payPwdAlertView.close() }) } } return nil }, error: { (error) -> ()? in self?.didRequestError(error) return nil }) }) } } // MARK: - 忘记密码 @IBAction func forgetPwdAction(_ sender: UIButton) { let resetTradePassVC = UIStoryboard.init(name: "Benifity", bundle: nil).instantiateViewController(withIdentifier: "ResetTradePassVC") self.navigationController?.pushViewController(resetTradePassVC, animated: true) } // MARK: - UITextFieldDelegate func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { let resultStr = textField.text?.replacingCharacters(in: (textField.text?.range(from: range))!, with: string) return resultStr!.isMoneyString() } }
mit
7e798f8eeef923237f6c42f67973cc18
41.511905
178
0.521423
5.116046
false
false
false
false
justindarc/firefox-ios
Client/Frontend/Browser/MailProviders.swift
14
4744
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared // mailto headers: subject, body, cc, bcc protocol MailProvider { var beginningScheme: String {get set} var supportedHeaders: [String] {get set} func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? } private func constructEmailURLString(_ beginningURLString: String, metadata: MailToMetadata, supportedHeaders: [String], bodyHName: String = "body", toHName: String = "to") -> String { var lowercasedHeaders = [String: String]() metadata.headers.forEach { (hname, hvalue) in lowercasedHeaders[hname.lowercased()] = hvalue } var toParam: String if let toHValue = lowercasedHeaders["to"] { let value = metadata.to.isEmpty ? toHValue : [metadata.to, toHValue].joined(separator: "%2C%20") lowercasedHeaders.removeValue(forKey: "to") toParam = "\(toHName)=\(value)" } else { toParam = "\(toHName)=\(metadata.to)" } var queryParams: [String] = [] lowercasedHeaders.forEach({ (hname, hvalue) in if supportedHeaders.contains(hname) { queryParams.append("\(hname)=\(hvalue)") } else if hname == "body" { queryParams.append("\(bodyHName)=\(hvalue)") } }) let stringParams = queryParams.joined(separator: "&") let finalURLString = beginningURLString + (stringParams.isEmpty ? toParam : [toParam, stringParams].joined(separator: "&")) return finalURLString } class ReaddleSparkIntegration: MailProvider { var beginningScheme = "readdle-spark://compose?" var supportedHeaders = [ "subject", "recipient", "textbody", "html", "cc", "bcc" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders, bodyHName: "textbody", toHName: "recipient").asURL } } class AirmailIntegration: MailProvider { var beginningScheme = "airmail://compose?" var supportedHeaders = [ "subject", "from", "to", "cc", "bcc", "plainBody", "htmlBody" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders, bodyHName: "htmlBody").asURL } } class MyMailIntegration: MailProvider { var beginningScheme = "mymail-mailto://?" var supportedHeaders = [ "to", "subject", "body", "cc", "bcc" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL } } class MailRuIntegration: MyMailIntegration { override init() { super.init() self.beginningScheme = "mailru-mailto://?" } } class MSOutlookIntegration: MailProvider { var beginningScheme = "ms-outlook://emails/new?" var supportedHeaders = [ "to", "cc", "bcc", "subject", "body" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL } } class YMailIntegration: MailProvider { var beginningScheme = "ymail://mail/any/compose?" var supportedHeaders = [ "to", "cc", "subject", "body" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL } } class GoogleGmailIntegration: MailProvider { var beginningScheme = "googlegmail:///co?" var supportedHeaders = [ "to", "cc", "bcc", "subject", "body" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL } } class GoogleInboxIntegration: MailProvider { var beginningScheme = "inbox-gmail://co?" var supportedHeaders = [ "to", "cc", "bcc", "subject", "body" ] func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? { return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL } }
mpl-2.0
5d95ed2de5e5a2324d2f0f5e9de76337
29.410256
184
0.645868
4.168717
false
false
false
false
arvedviehweger/swift
test/SILGen/materializeForSet.swift
1
34269
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s class Base { var stored: Int = 0 // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet4BaseC6storedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $Base): // CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.stored // CHECK: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer // CHECK: [[T2:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none // CHECK: [[T3:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T2]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T3]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet4BaseC8computedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> () { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Base, [[SELFTYPE:%.*]] : $@thick Base.Type): // CHECK: [[T0:%.*]] = load_borrow [[SELF]] // CHECK: [[T1:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T2:%.*]] = load [trivial] [[T1]] : $*Int // CHECK: [[SETTER:%.*]] = function_ref @_T017materializeForSet4BaseC8computedSifs // CHECK: apply [[SETTER]]([[T2]], [[T0]]) // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet4BaseC8computedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $Base): // CHECK: [[ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet4BaseC8computedSifg // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [trivial] [[ADDR]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[ADDR]] // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet4BaseC8computedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> () // CHECK: [[T2:%.*]] = thin_function_to_pointer [[T0]] // CHECK: [[T3:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T2]] : $Builtin.RawPointer // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[T3]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } var computed: Int { get { return 0 } set(value) {} } var storedFunction: () -> Int = { 0 } final var finalStoredFunction: () -> Int = { 0 } var computedFunction: () -> Int { get { return {0} } set {} } static var staticFunction: () -> Int { get { return {0} } set {} } } class Derived : Base {} protocol Abstractable { associatedtype Result var storedFunction: () -> Result { get set } var finalStoredFunction: () -> Result { get set } var computedFunction: () -> Result { get set } static var staticFunction: () -> Result { get set } } // Validate that we thunk materializeForSet correctly when there's // an abstraction pattern present. extension Derived : Abstractable {} // CHECK: sil private [transparent] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction6ResultQzycfmytfU_TW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Derived, @thick Derived.Type) -> () // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived, %3 : $@thick Derived.Type): // CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[VALUE:%.*]] = load [take] [[RESULT_ADDR]] : $*@callee_owned () -> @out Int // CHECK-NEXT: function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxr_SiIxd_TR : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) // CHECK-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!setter.1 : (Base) -> (@escaping () -> Int) -> () // CHECK-NEXT: apply [[FN]]([[NEWVALUE]], [[SELF]]) // CHECK-NEXT: end_borrow [[T0]] from %2 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: sil private [transparent] [thunk] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction{{[_0-9a-zA-Z]*}}fmTW // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived): // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $@callee_owned () -> Int // CHECK-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!getter.1 // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]([[SELF]]) // CHECK-NEXT: store [[RESULT]] to [init] [[TEMP]] // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[TEMP]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxd_SiIxr_TR : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int // CHECK-NEXT: [[T1:%.*]] = partial_apply [[REABSTRACTOR]]([[RESULT]]) // CHECK-NEXT: destroy_addr [[TEMP]] // CHECK-NEXT: store [[T1]] to [init] [[RESULT_ADDR]] // CHECK-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer // CHECK-NEXT: function_ref // CHECK-NEXT: [[T2:%.*]] = function_ref @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14storedFunction6ResultQzycfmytfU_TW // CHECK-NEXT: [[T3:%.*]] = thin_function_to_pointer [[T2]] // CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T3]] // CHECK-NEXT: [[T4:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: dealloc_stack [[TEMP]] // CHECK-NEXT: end_borrow [[T0]] from %2 // CHECK-NEXT: return [[T4]] // CHECK: sil private [transparent] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction6ResultQzycfmytfU_TW : // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived, %3 : $@thick Derived.Type): // CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[VALUE:%.*]] = load [take] [[RESULT_ADDR]] : $*@callee_owned () -> @out Int // CHECK-NEXT: // function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxr_SiIxd_TR : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) // CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction // CHECK-NEXT: assign [[NEWVALUE]] to [[ADDR]] // CHECK-NEXT: end_borrow [[T0]] from %2 // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: sil private [transparent] [thunk] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction{{[_0-9a-zA-Z]*}}fmTW // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived): // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[T0:%.*]] = load_borrow %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction // CHECK-NEXT: [[RESULT:%.*]] = load [copy] [[ADDR]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxd_SiIxr_TR : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int // CHECK-NEXT: [[T1:%.*]] = partial_apply [[REABSTRACTOR]]([[RESULT]]) // CHECK-NEXT: store [[T1]] to [init] [[RESULT_ADDR]] // CHECK-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer // CHECK-NEXT: function_ref // CHECK-NEXT: [[T2:%.*]] = function_ref @_T017materializeForSet7DerivedCAA12AbstractableA2aDP19finalStoredFunction6ResultQzycfmytfU_TW // CHECK-NEXT: [[T3:%.*]] = thin_function_to_pointer [[T2]] // CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T3]] // CHECK-NEXT: [[T4:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: end_borrow [[T0]] from %2 // CHECK-NEXT: return [[T4]] // CHECK-LABEL: sil private [transparent] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycfmZytfU_TW // CHECK: bb0([[ARG1:%.*]] : $Builtin.RawPointer, [[ARG2:%.*]] : $*Builtin.UnsafeValueBuffer, [[ARG3:%.*]] : $*@thick Derived.Type, [[ARG4:%.*]] : $@thick Derived.Type.Type): // CHECK-NEXT: [[SELF:%.*]] = load [trivial] [[ARG3]] : $*@thick Derived.Type // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[SELF]] : $@thick Derived.Type to $@thick Base.Type // CHECK-NEXT: [[BUFFER:%.*]] = pointer_to_address [[ARG1]] : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[VALUE:%.*]] = load [take] [[BUFFER]] : $*@callee_owned () -> @out Int // CHECK: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxr_SiIxd_TR : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK: [[SETTER_FN:%.*]] = function_ref @_T017materializeForSet4BaseC14staticFunctionSiycfsZ : $@convention(method) (@owned @callee_owned () -> Int, @thick Base.Type) -> () // CHECK-NEXT: apply [[SETTER_FN]]([[NEWVALUE]], [[BASE_SELF]]) : $@convention(method) (@owned @callee_owned () -> Int, @thick Base.Type) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-LABEL: sil private [transparent] [thunk] @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycfmZTW // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $@thick Derived.Type): // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int // CHECK-NEXT: [[SELF:%.*]] = upcast %2 : $@thick Derived.Type to $@thick Base.Type // CHECK-NEXT: [[OUT:%.*]] = alloc_stack $@callee_owned () -> Int // CHECK: [[GETTER:%.*]] = function_ref @_T017materializeForSet4BaseC14staticFunctionSiycfgZ : $@convention(method) (@thick Base.Type) -> @owned @callee_owned () -> Int // CHECK-NEXT: [[VALUE:%.*]] = apply [[GETTER]]([[SELF]]) : $@convention(method) (@thick Base.Type) -> @owned @callee_owned () -> Int // CHECK-NEXT: store [[VALUE]] to [init] [[OUT]] : $*@callee_owned () -> Int // CHECK-NEXT: [[VALUE:%.*]] = load [copy] [[OUT]] : $*@callee_owned () -> Int // CHECK: [[REABSTRACTOR:%.*]] = function_ref @_T0SiIxd_SiIxr_TR : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) // CHECK-NEXT: destroy_addr [[OUT]] : $*@callee_owned () -> Int // CHECK-NEXT: store [[NEWVALUE]] to [init] [[RESULT_ADDR]] : $*@callee_owned () -> @out Int // CHECK-NEXT: [[ADDR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T017materializeForSet7DerivedCAA12AbstractableA2aDP14staticFunction6ResultQzycfmZytfU_TW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout @thick Derived.Type, @thick Derived.Type.Type) -> () // CHECK-NEXT: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout @thick Derived.Type, @thick Derived.Type.Type) -> () to $Builtin.RawPointer // CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] : $Builtin.RawPointer // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ADDR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: dealloc_stack [[OUT]] : $*@callee_owned () -> Int // CHECK-NEXT: return [[RESULT]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) protocol ClassAbstractable : class { associatedtype Result var storedFunction: () -> Result { get set } var finalStoredFunction: () -> Result { get set } var computedFunction: () -> Result { get set } static var staticFunction: () -> Result { get set } } extension Derived : ClassAbstractable {} protocol Signatures { associatedtype Result var computedFunction: () -> Result { get set } } protocol Implementations {} extension Implementations { var computedFunction: () -> Int { get { return {0} } set {} } } class ImplementingClass : Implementations, Signatures {} struct ImplementingStruct : Implementations, Signatures { var ref: ImplementingClass? } class HasDidSet : Base { override var stored: Int { didSet {} } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet06HasDidC0C6storedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasDidSet): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet06HasDidC0C6storedSifg // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [trivial] [[T2]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T017materializeForSet06HasDidC0C6storedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> () // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } override var computed: Int { get { return 0 } set(value) {} } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet06HasDidC0C8computedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasDidSet): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet06HasDidC0C8computedSifg // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [trivial] [[T2]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T017materializeForSet06HasDidC0C8computedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> () // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } } class HasStoredDidSet { var stored: Int = 0 { didSet {} } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet012HasStoredDidC0C6storedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasStoredDidSet, @thick HasStoredDidSet.Type) -> () { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*HasStoredDidSet, [[METATYPE:%.*]] : $@thick HasStoredDidSet.Type): // CHECK: [[SELF_VALUE:%.*]] = load_borrow [[SELF]] : $*HasStoredDidSet // CHECK: [[BUFFER_ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[VALUE:%.*]] = load [trivial] [[BUFFER_ADDR]] : $*Int // CHECK: [[SETTER_FN:%.*]] = function_ref @_T017materializeForSet012HasStoredDidC0C6storedSifs : $@convention(method) (Int, @guaranteed HasStoredDidSet) -> () // CHECK: apply [[SETTER_FN]]([[VALUE]], [[SELF_VALUE]]) : $@convention(method) (Int, @guaranteed HasStoredDidSet) -> () // CHECK: return // CHECK: } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet012HasStoredDidC0C6storedSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasStoredDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasStoredDidSet): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet012HasStoredDidC0C6storedSifg // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [trivial] [[T2]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T017materializeForSet012HasStoredDidC0C6storedSifmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasStoredDidSet, @thick HasStoredDidSet.Type) -> () // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } } class HasWeak { weak var weakvar: HasWeak? } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet7HasWeakC7weakvarACSgXwfm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasWeak) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasWeak): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Optional<HasWeak> // CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $HasWeak, #HasWeak.weakvar // CHECK: [[T1:%.*]] = load_weak [[T0]] : $*@sil_weak Optional<HasWeak> // CHECK: store [[T1]] to [init] [[T2]] : $*Optional<HasWeak> // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet7HasWeakC7weakvarACSgXwfmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasWeak, @thick HasWeak.Type) -> () // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, {{.*}} : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } // rdar://22109071 // Test that we don't use materializeForSet from a protocol extension. protocol Magic {} extension Magic { var hocus: Int { get { return 0 } set {} } } struct Wizard : Magic {} func improve(_ x: inout Int) {} func improveWizard(_ wizard: inout Wizard) { improve(&wizard.hocus) } // CHECK-LABEL: sil hidden @_T017materializeForSet13improveWizardyAA0E0VzF // CHECK: [[IMPROVE:%.*]] = function_ref @_T017materializeForSet7improveySizF : // CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] %0 : $*Wizard // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Int // Call the getter and materialize the result in the temporary. // CHECK-NEXT: [[T0:%.*]] = load [trivial] [[WRITE:.*]] : $*Wizard // CHECK-NEXT: function_ref // CHECK-NEXT: [[GETTER:%.*]] = function_ref @_T017materializeForSet5MagicPAAE5hocusSifg // CHECK-NEXT: [[WTEMP:%.*]] = alloc_stack $Wizard // CHECK-NEXT: store [[T0]] to [trivial] [[WTEMP]] // CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]<Wizard>([[WTEMP]]) // CHECK-NEXT: dealloc_stack [[WTEMP]] // CHECK-NEXT: store [[T0]] to [trivial] [[TEMP]] // Call improve. // CHECK-NEXT: apply [[IMPROVE]]([[TEMP]]) // CHECK-NEXT: [[T0:%.*]] = load [trivial] [[TEMP]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T017materializeForSet5MagicPAAE5hocusSifs // CHECK-NEXT: apply [[SETTER]]<Wizard>([[T0]], [[WRITE]]) // CHECK-NEXT: end_access [[WRITE]] : $*Wizard // CHECK-NEXT: dealloc_stack [[TEMP]] protocol Totalled { var total: Int { get set } } struct Bill : Totalled { var total: Int } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet4BillV5totalSifm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Bill): // CHECK: [[T0:%.*]] = struct_element_addr [[SELF]] : $*Bill, #Bill.total // CHECK: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer // CHECK: [[T3:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none!enumelt // CHECK: [[T4:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T3]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } // CHECK-LABEL: sil private [transparent] [thunk] @_T017materializeForSet4BillVAA8TotalledA2aDP5totalSifmTW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Bill): // CHECK: [[T0:%.*]] = function_ref @_T017materializeForSet4BillV5totalSifm // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BUFFER]], [[STORAGE]], [[SELF]]) // CHECK-NEXT: [[LEFT:%.*]] = tuple_extract [[T1]] // CHECK-NEXT: [[RIGHT:%.*]] = tuple_extract [[T1]] // CHECK-NEXT: [[T1:%.*]] = tuple ([[LEFT]] : $Builtin.RawPointer, [[RIGHT]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: return [[T1]] : protocol AddressOnlySubscript { associatedtype Index subscript(i: Index) -> Index { get set } } struct Foo<T>: AddressOnlySubscript { subscript(i: T) -> T { get { return i } set { print("\(i) = \(newValue)") } } } func increment(_ x: inout Int) { x += 1 } // Generic subscripts. protocol GenericSubscriptProtocol { subscript<T>(_: T) -> T { get set } } struct GenericSubscriptWitness : GenericSubscriptProtocol { subscript<T>(_: T) -> T { get { } set { } } } // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet23GenericSubscriptWitnessV9subscriptxxclufmytfU_ : $@convention(method) <T> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericSubscriptWitness, @thick GenericSubscriptWitness.Type) -> () { // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*GenericSubscriptWitness, %3 : $@thick GenericSubscriptWitness.Type): // CHECK: [[BUFFER:%.*]] = project_value_buffer $T in %1 : $*Builtin.UnsafeValueBuffer // CHECK-NEXT: [[INDICES:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*T // CHECK: [[SETTER:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessV9subscriptxxclufs : $@convention(method) <τ_0_0> (@in τ_0_0, @in τ_0_0, @inout GenericSubscriptWitness) -> () // CHECK-NEXT: apply [[SETTER]]<T>([[INDICES]], [[BUFFER]], %2) : $@convention(method) <τ_0_0> (@in τ_0_0, @in τ_0_0, @inout GenericSubscriptWitness) -> () // CHECK-NEXT: dealloc_value_buffer $*T in %1 : $*Builtin.UnsafeValueBuffer // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-LABEL sil hidden [transparent] [thunk] @_T017materializeForSet23GenericSubscriptWitnessVAA0dE8ProtocolA2aDP9subscriptqd__qd__clufmTW : $@convention(witness_method) <τ_0_0> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in τ_0_0, @inout GenericSubscriptWitness) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*T, %3 : $*GenericSubscriptWitness): // CHECK-NEXT: [[BUFFER:%.*]] = alloc_value_buffer $T in %1 : $*Builtin.UnsafeValueBuffer // CHECK-NEXT: copy_addr %2 to [initialization] [[BUFFER]] : $*T // CHECK-NEXT: [[VALUE:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*T // CHECK-NEXT: [[SELF:%.*]] = load [trivial] %3 : $*GenericSubscriptWitness // CHECK: [[GETTER:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessV9subscriptxxclufg : $@convention(method) <τ_0_0> (@in τ_0_0, GenericSubscriptWitness) -> @out τ_0_0 // CHECK-NEXT: apply [[GETTER]]<T>([[VALUE]], %2, [[SELF]]) : $@convention(method) <τ_0_0> (@in τ_0_0, GenericSubscriptWitness) -> @out τ_0_0 // CHECK-NEXT: [[VALUE_PTR:%.*]] = address_to_pointer [[VALUE]] : $*T to $Builtin.RawPointer // CHECK: [[CALLBACK:%.*]] = function_ref @_T017materializeForSet23GenericSubscriptWitnessV9subscriptxxclufmytfU_ // CHECK-NEXT: [[CALLBACK_PTR:%.*]] = thin_function_to_pointer [[CALLBACK]] : $@convention(method) <τ_0_0> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout GenericSubscriptWitness, @thick GenericSubscriptWitness.Type) -> () to $Builtin.RawPointer // CHECK-NEXT: [[CALLBACK_OPTIONAL:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_PTR]] : $Builtin.RawPointer // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[VALUE_PTR]] : $Builtin.RawPointer, [[CALLBACK_OPTIONAL]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: return [[RESULT]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) extension GenericSubscriptProtocol { subscript<T>(t: T) -> T { get { } set { } } } struct GenericSubscriptDefaultWitness : GenericSubscriptProtocol { } // Test for materializeForSet vs static properties of structs. protocol Beverage { static var abv: Int { get set } } struct Beer : Beverage { static var abv: Int { get { return 7 } set { } } } struct Wine<Color> : Beverage { static var abv: Int { get { return 14 } set { } } } // Make sure we can perform an inout access of such a property too. func inoutAccessOfStaticProperty<T : Beverage>(_ t: T.Type) { increment(&t.abv) } // Test for materializeForSet vs overridden computed property of classes. class BaseForOverride { var valueStored: Int var valueComputed: Int { get { } set { } } init(valueStored: Int) { self.valueStored = valueStored } } class DerivedForOverride : BaseForOverride { override var valueStored: Int { get { } set { } } override var valueComputed: Int { get { } set { } } } // Test for materializeForSet vs static properties of classes. class ReferenceBeer { class var abv: Int { get { return 7 } set { } } } func inoutAccessOfClassProperty() { increment(&ReferenceBeer.abv) } // Test for materializeForSet when Self is re-abstracted. // // We have to open-code the materializeForSelf witness, and not screw up // the re-abstraction. protocol Panda { var x: (Self) -> Self { get set } } func id<T>(_ t: T) -> T { return t } extension Panda { var x: (Self) -> Self { get { return id } set { } } } struct TuxedoPanda : Panda { } // CHECK-LABEL: sil private [transparent] @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xxxcfmytfU_TW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> () // FIXME: Useless re-abstractions // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVACIxir_A2CIxyd_TR : $@convention(thin) (TuxedoPanda, @owned @callee_owned (@in TuxedoPanda) -> @out TuxedoPanda) -> TuxedoPanda // CHECK: function_ref @_T017materializeForSet5PandaPAAE1xxxcfs : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@owned @callee_owned (@in τ_0_0) -> @out τ_0_0, @inout τ_0_0) -> () // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVACIxyd_A2CIxir_TR : $@convention(thin) (@in TuxedoPanda, @owned @callee_owned (TuxedoPanda) -> TuxedoPanda) -> @out TuxedoPanda // CHECK: } // CHECK-LABEL: sil private [transparent] [thunk] @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xxxcfmTW // Call the getter: // CHECK: function_ref @_T017materializeForSet5PandaPAAE1xxxcfg : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@in_guaranteed τ_0_0) -> @owned @callee_owned (@in τ_0_0) -> @out τ_0_0 // Result of calling the getter is re-abstracted to the maximally substituted type // by SILGenFunction::emitApply(): // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVACIxir_A2CIxyd_TR : $@convention(thin) (TuxedoPanda, @owned @callee_owned (@in TuxedoPanda) -> @out TuxedoPanda) -> TuxedoPanda // ... then we re-abstract to the requirement signature: // FIXME: Peephole this away with the previous one since there's actually no // abstraction change in this case. // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVACIxyd_A2CIxir_TR : $@convention(thin) (@in TuxedoPanda, @owned @callee_owned (TuxedoPanda) -> TuxedoPanda) -> @out TuxedoPanda // The callback: // CHECK: function_ref @_T017materializeForSet11TuxedoPandaVAA0E0A2aDP1xxxcfmytfU_TW : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> () // CHECK: } // Test for materializeForSet vs lazy properties of structs. struct LazyStructProperty { lazy var cat: Int = 5 } // CHECK-LABEL: sil hidden @_T017materializeForSet31inoutAccessOfLazyStructPropertyyAA0ghI0Vz1l_tF // CHECK: function_ref @_T017materializeForSet18LazyStructPropertyV3catSifg // CHECK: function_ref @_T017materializeForSet18LazyStructPropertyV3catSifs func inoutAccessOfLazyStructProperty(l: inout LazyStructProperty) { increment(&l.cat) } // Test for materializeForSet vs lazy properties of classes. // CHECK-LABEL: sil hidden [transparent] @_T017materializeForSet17LazyClassPropertyC3catSifm class LazyClassProperty { lazy var cat: Int = 5 } // CHECK-LABEL: sil hidden @_T017materializeForSet30inoutAccessOfLazyClassPropertyyAA0ghI0Cz1l_tF // CHECK: class_method {{.*}} : $LazyClassProperty, #LazyClassProperty.cat!materializeForSet.1 func inoutAccessOfLazyClassProperty(l: inout LazyClassProperty) { increment(&l.cat) } // Test for materializeForSet vs lazy properties of final classes. final class LazyFinalClassProperty { lazy var cat: Int = 5 } // CHECK-LABEL: sil hidden @_T017materializeForSet35inoutAccessOfLazyFinalClassPropertyyAA0ghiJ0Cz1l_tF // CHECK: function_ref @_T017materializeForSet22LazyFinalClassPropertyC3catSifg // CHECK: function_ref @_T017materializeForSet22LazyFinalClassPropertyC3catSifs func inoutAccessOfLazyFinalClassProperty(l: inout LazyFinalClassProperty) { increment(&l.cat) } // Make sure the below doesn't crash SILGen struct FooClosure { var computed: (((Int) -> Int) -> Int)? { get { return stored } set {} } var stored: (((Int) -> Int) -> Int)? = nil } // CHECK-LABEL: _T017materializeForSet22testMaterializedSetteryyF func testMaterializedSetter() { // CHECK: function_ref @_T017materializeForSet10FooClosureVACycfC var f = FooClosure() // CHECK: function_ref @_T017materializeForSet10FooClosureV8computedS3iccSgfg // CHECK: function_ref @_T017materializeForSet10FooClosureV8computedS3iccSgfs f.computed = f.computed } // CHECK-LABEL: sil_vtable DerivedForOverride { // CHECK: #BaseForOverride.valueStored!getter.1: (BaseForOverride) -> () -> Int : _T017materializeForSet07DerivedB8OverrideC11valueStoredSifg // CHECK: #BaseForOverride.valueStored!setter.1: (BaseForOverride) -> (Int) -> () : _T017materializeForSet07DerivedB8OverrideC11valueStoredSifs // CHECK: #BaseForOverride.valueStored!materializeForSet.1: (BaseForOverride) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : _T017materializeForSet07DerivedB8OverrideC11valueStoredSifm // CHECK: #BaseForOverride.valueComputed!getter.1: (BaseForOverride) -> () -> Int : _T017materializeForSet07DerivedB8OverrideC13valueComputedSifg // CHECK: #BaseForOverride.valueComputed!setter.1: (BaseForOverride) -> (Int) -> () : _T017materializeForSet07DerivedB8OverrideC13valueComputedSifs // CHECK: #BaseForOverride.valueComputed!materializeForSet.1: (BaseForOverride) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : _T017materializeForSet07DerivedB8OverrideC13valueComputedSifm // CHECK: } // CHECK-LABEL: sil_witness_table hidden Bill: Totalled module materializeForSet { // CHECK: method #Totalled.total!getter.1: {{.*}} : @_T017materializeForSet4BillVAA8TotalledA2aDP5totalSifgTW // CHECK: method #Totalled.total!setter.1: {{.*}} : @_T017materializeForSet4BillVAA8TotalledA2aDP5totalSifsTW // CHECK: method #Totalled.total!materializeForSet.1: {{.*}} : @_T017materializeForSet4BillVAA8TotalledA2aDP5totalSifmTW // CHECK: }
apache-2.0
3403bd2f540bd9aad92beea484c07545
56.747049
334
0.673081
3.537603
false
false
false
false
arvedviehweger/swift
benchmark/single-source/RGBHistogram.swift
3
7252
//===--- RGBHistogram.swift -----------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Performance benchmark for creating RGB histograms // rdar://problem/18539486 // // Description: // Create a sorted sparse RGB histogram from an array of 300 RGB values. import Foundation import TestsUtils @inline(never) public func run_RGBHistogram(_ N: Int) { var histogram = [(key: rrggbb_t, value: Int)]() for _ in 1...100*N { histogram = createSortedSparseRGBHistogram(samples) if !isCorrectHistogram(histogram) { break } } CheckResults(isCorrectHistogram(histogram), "Incorrect results in histogram") } typealias rrggbb_t = UInt32 let samples: [rrggbb_t] = [ 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF, 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF, 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF, 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF, 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF, 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF, 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF, 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF, 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0xCCD45FBC, 0xA56F39E4, 0x8C08DBA7, 0xDA4413D7, 0x43926C6B, 0x592975FE, 0xC77E47ED, 0xB28F427D, 0x90D7C464, 0x805A003A, 0xAB79B390, 0x49D859B3, 0x2419213A, 0x69E8C61D, 0xC4BE948F, 0x896CC6D0, 0xE4F3DFF1, 0x466B68FA, 0xC8084E2A, 0x3FC1F2C4, 0x0E0D47F4, 0xB268BFE6, 0x9F990E6A, 0x7389F2F8, 0x0720FD81, 0x65388005, 0xD8307612, 0xEC75B9B0, 0xB0C51360, 0x29647EB4, 0x6E8B02E6, 0xEFE9F0F4, 0xFEF0EB89, 0x41BBD587, 0xCD19E510, 0x6A710BBD, 0xFF146228, 0xFB34AD0C, 0x2AEB5588, 0x71993821, 0x9FC8CA5C, 0xF99E969B, 0x8DF78241, 0x21ADFB7C, 0x4DE5E465, 0x0C171D2F, 0x2C08CECF, 0x3318440A, 0xEC8F8D1C, 0x6CAFD68E, 0xCA35F571, 0x68A37E1A, 0x3047F87F, 0x50CC39DE, 0x776CF5CB, 0x75DC4595, 0x77E32288, 0x14899C0D, 0x14835CF6, 0x0A732F76, 0xA4B05790, 0x34CBED42, 0x5A6964CE, 0xEA4CA5F7, 0x3DECB0F1, 0x5015D419, 0x84EBC299, 0xC656B381, 0xFA2840C5, 0x618D754E, 0x003B8D96, 0xCE91AA8E, 0xBD9784DB, 0x9372E919, 0xC138BEA6, 0xF0B3E3AD, 0x4E4F60BF, 0xC1598ABE, 0x930873DB, 0x0F029E3A, 0xBEFC0125, 0x10645D6D, 0x1FF93547, 0xA7069CB5, 0xCF0B7E06, 0xE33EDC17, 0x8C5E1F48, 0x2FB345E1, 0x3B0070E0, 0x0421E568, 0xB39A42A0, 0xB935DA8B, 0x281C30F0, 0xB2E48677, 0x277A9A45, 0x52AF9FC6, 0xBBDF4048, 0xC668137A, 0xF39020D1, 0x71BEE810, 0x5F2B3825, 0x25C863FB, 0x876144E8, 0x9B4108C3, 0xF735CB08, 0x8B77DEEC, 0x0185A067, 0xB964F42B, 0xA2EC236B, 0x3C08646F, 0xB514C4BE, 0x37EE9689, 0xACF97317, 0x1EA4F7C6, 0x453A6F13, 0x01C25E42, 0xA052BB3B, 0x71A699CB, 0xC728AE88, 0x128A656F, 0x78F64E55, 0x045967E0, 0xC5DC4125, 0xDA39F6FE, 0x873785B9, 0xB6BB446A, 0xF4F5093F, 0xAF05A4EC, 0xB5DB854B, 0x7ADA6A37, 0x9EA218E3, 0xCCCC9316, 0x86A133F8, 0x8AF47795, 0xCBA235D4, 0xBB9101CC, 0xBCC8C8A3, 0x02BAC911, 0x45C17A8C, 0x896C81FC, 0x4974FA22, 0xEA7CD629, 0x103ED364, 0x4C644503, 0x607F4D9F, 0x9733E55E, 0xA360439D, 0x1DB568FD, 0xB7A5C3A1, 0xBE84492D ] func isCorrectHistogram(_ histogram: [(key: rrggbb_t, value: Int)]) -> Bool { return histogram.count == 157 && histogram[0].0 == 0x00808080 && histogram[0].1 == 54 && histogram[156].0 == 0x003B8D96 && histogram[156].1 == 1 } func createSortedSparseRGBHistogram<S : Sequence>( _ samples: S ) -> [(key: rrggbb_t, value: Int)] where S.Iterator.Element == rrggbb_t { var histogram = Dictionary<rrggbb_t, Int>() for sample in samples { let i = histogram.index(forKey: sample) histogram[sample] = ((i != nil) ? histogram[i!].1 : 0) + 1 } return histogram.sorted() { if $0.1 == $1.1 { return $0.0 > $1.0 } else { return $0.1 > $1.1 } } } class Box<T : Hashable> : Hashable { var value: T init(_ v: T) { value = v } var hashValue: Int { return value.hashValue } static func ==(lhs: Box, rhs: Box) -> Bool { return lhs.value == rhs.value } } func isCorrectHistogramOfObjects(_ histogram: [(key: Box<rrggbb_t>, value: Box<Int>)]) -> Bool { return histogram.count == 157 && histogram[0].0.value == 0x00808080 && histogram[0].1.value == 54 && histogram[156].0.value == 0x003B8D96 && histogram[156].1.value == 1 } func createSortedSparseRGBHistogramOfObjects<S : Sequence>( _ samples: S ) -> [(key: Box<rrggbb_t>, value: Box<Int>)] where S.Iterator.Element == rrggbb_t { var histogram = Dictionary<Box<rrggbb_t>, Box<Int>>() for sample in samples { let boxedSample = Box(sample) let i = histogram.index(forKey: boxedSample) histogram[boxedSample] = Box(((i != nil) ? histogram[i!].1.value : 0) + 1) } return histogram.sorted() { if $0.1 == $1.1 { return $0.0.value > $1.0.value } else { return $0.1.value > $1.1.value } } } @inline(never) public func run_RGBHistogramOfObjects(_ N: Int) { var histogram = [(key: Box<rrggbb_t>, value: Box<Int>)]() for _ in 1...100*N { histogram = createSortedSparseRGBHistogramOfObjects(samples) if !isCorrectHistogramOfObjects(histogram) { break } } CheckResults(isCorrectHistogramOfObjects(histogram), "Incorrect results in histogram") }
apache-2.0
9474a31b15038f319f9d7a025781dbda
40.919075
96
0.694705
2.530356
false
false
false
false
per-dalsgaard/20-apps-in-20-weeks
App 16 - Devslopes Social/Devslopes Social/PostTableViewCell.swift
1
2629
// // PostTableViewCell.swift // Devslopes Social // // Created by Per Kristensen on 26/04/2017. // Copyright © 2017 Per Dalsgaard. All rights reserved. // import UIKit import Firebase class PostTableViewCell: UITableViewCell { @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var postImageView: UIImageView! @IBOutlet weak var captionTextView: UITextView! @IBOutlet weak var likesLabel: UILabel! @IBOutlet weak var likesButton: UIButton! var post: Post! var likesRef: FIRDatabaseReference! func configureCell(post: Post, postImage: UIImage?) { likesRef = DataSerice.ds.REF_CURRENT_USER.child("likes").child(post.postId) self.post = post captionTextView.text = post.caption likesLabel.text = "\(post.likes)" if let postImage = postImage { postImageView.image = postImage } else { let ref = FIRStorage.storage().reference(forURL: post.imageUrl) ref.data(withMaxSize: 1024 * 1024 * 2, completion: { (data, error) in if error != nil { print("Error!") } else { print("Image downloaded from Firebase storage") if let imageData = data { if let image = UIImage(data: imageData) { self.postImageView.image = image FeedViewController.imageCache.setObject(image, forKey: post.imageUrl as NSString) } } } }) } likesRef.observeSingleEvent(of: .value, with: { (snapshot) in if let _ = snapshot.value as? NSNull { self.likesButton.setImage(UIImage(named: "empty-heart")!, for: .normal) } else { self.likesButton.setImage (UIImage(named: "filled-heart")!, for: .normal) } }) } @IBAction func likeButtonPressed(sender: UIButton) { likesRef.observeSingleEvent(of: .value, with: { (snapshot) in if let _ = snapshot.value as? NSNull { self.likesButton.setImage(UIImage(named: "filled-heart"), for: .normal) self.post.adjustLikes(addLike: true) self.likesRef.setValue(true) } else { self.likesButton.setImage (UIImage(named: "empty-heart"), for: .normal) self.post.adjustLikes(addLike: false) self.likesRef.removeValue() } }) } }
mit
9845be0db45aa54c78c589bcf9fb862f
34.513514
109
0.565068
4.618629
false
false
false
false
vanjakom/photo-db
photodb view/photodb view/AppDelegate.swift
1
3408
// // AppDelegate.swift // photodb view // // Created by Vanja Komadinovic on 1/23/16. // Copyright © 2016 mungolab.com. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate /*, UISplitViewControllerDelegate */ { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. /* let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self */ 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:. } /* // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } */ }
mit
7e3a588e826984dfabf2080b098448c6
52.234375
285
0.754329
6.138739
false
false
false
false
groue/GRDB.swift
GRDB/Migration/DatabaseMigrator.swift
1
21268
#if canImport(Combine) import Combine #endif import Foundation // TODO: provide concurrent apis for migrations that run @Sendable closures. /// A `DatabaseMigrator` registers and applies database migrations. /// /// For an overview of database migrations and `DatabaseMigrator` usage, /// see <doc:Migrations>. /// /// ## Topics /// /// ### Creating a DatabaseMigrator /// /// - ``init()`` /// /// ### Registering Migrations /// /// - ``registerMigration(_:foreignKeyChecks:migrate:)`` /// - ``ForeignKeyChecks`` /// /// ### Configuring a DatabaseMigrator /// /// - ``eraseDatabaseOnSchemaChange`` /// - ``disablingDeferredForeignKeyChecks()`` /// /// ### Migrating a Database /// /// - ``asyncMigrate(_:completion:)`` /// - ``migrate(_:)`` /// - ``migrate(_:upTo:)`` /// - ``migratePublisher(_:receiveOn:)`` /// /// ### Querying Migrations /// /// - ``migrations`` /// - ``appliedIdentifiers(_:)`` /// - ``appliedMigrations(_:)`` /// - ``completedMigrations(_:)`` /// - ``hasBeenSuperseded(_:)`` /// - ``hasCompletedMigrations(_:)`` public struct DatabaseMigrator { /// Controls how a migration handle foreign keys constraints. public enum ForeignKeyChecks { /// The migration runs with disabled foreign keys. /// /// Foreign keys are checked right before changes are committed on disk, /// unless the `DatabaseMigrator` is the result of /// ``DatabaseMigrator/disablingDeferredForeignKeyChecks()``. /// /// In this case, you can perform your own deferred foreign key checks /// with ``Database/checkForeignKeys(in:)`` or /// ``Database/checkForeignKeys()``: /// /// ```swift /// migrator = migrator.disablingDeferredForeignKeyChecks() /// migrator.registerMigration("Partially checked migration") { db in /// ... /// /// // Throws an error and stops migrations if there exists a /// // foreign key violation in the 'book' table. /// try db.checkForeignKeys(in: "book") /// } /// ``` case deferred /// The migration runs with enabled foreign keys. /// /// Immediate foreign key checks are NOT compatible with migrations that /// recreate tables as described /// in <doc:Migrations#Defining-the-Database-Schema-from-a-Migration>. case immediate } /// A boolean value indicating whether the migrator recreates the whole /// database from scratch if it detects a change in the definition /// of migrations. /// /// - warning: This flag can destroy your precious users' data! /// /// When true, the database migrator wipes out the full database content, /// and runs all migrations from the start, if one of those conditions /// is met: /// /// - A migration has been removed, or renamed. /// - A schema change is detected. A schema change is any difference in /// the `sqlite_master` table, which contains the SQL used to create /// database tables, indexes, triggers, and views. /// /// This flag is useful during application development: you are still /// designing migrations, and the schema changes often. /// /// It is recommended to not ship it in the distributed application, in /// order to avoid undesired data loss. Use the `DEBUG` /// compilation condition: /// /// ```swift /// var migrator = DatabaseMigrator() /// #if DEBUG /// // Speed up development by nuking the database when migrations change /// migrator.eraseDatabaseOnSchemaChange = true /// #endif /// ``` public var eraseDatabaseOnSchemaChange = false private var defersForeignKeyChecks = true private var _migrations: [Migration] = [] /// A new migrator. public init() { } // MARK: - Disabling Foreign Key Checks /// Returns a migrator that disables foreign key checks in all newly /// registered migrations. /// /// The returned migrator is _unsafe_, because it no longer guarantees the /// integrity of the database. It is now _your_ responsibility to register /// migrations that do not break foreign key constraints. See /// ``Database/checkForeignKeys()`` and ``Database/checkForeignKeys(in:)``. /// /// Running migrations without foreign key checks can improve migration /// performance on huge databases. /// /// Example: /// /// ```swift /// var migrator = DatabaseMigrator() /// migrator.registerMigration("A") { db in /// // Runs with deferred foreign key checks /// } /// migrator.registerMigration("B", foreignKeyChecks: .immediate) { db in /// // Runs with immediate foreign key checks /// } /// /// migrator = migrator.disablingDeferredForeignKeyChecks() /// migrator.registerMigration("C") { db in /// // Runs without foreign key checks /// } /// migrator.registerMigration("D", foreignKeyChecks: .immediate) { db in /// // Runs with immediate foreign key checks /// } /// ``` /// /// - warning: Before using this unsafe method, try to register your /// migrations with the `foreignKeyChecks: .immediate` option, _if /// possible_, as in the example above. This will enhance migration /// performances, while preserving the database integrity guarantee. public func disablingDeferredForeignKeyChecks() -> DatabaseMigrator { with { $0.defersForeignKeyChecks = false } } // MARK: - Registering Migrations /// Registers a migration. /// /// The registered migration is appended to the list of migrations to run: /// it will execute after previously registered migrations, and before /// migrations that are registered later. /// /// For example: /// /// ```swift /// migrator.registerMigration("createAuthors") { db in /// try db.create(table: "author") { t in /// t.autoIncrementedPrimaryKey("id") /// t.column("creationDate", .datetime) /// t.column("name", .text).notNull() /// } /// } /// ``` /// /// Database operations are wrapped in a transaction. If they throw an /// error, the transaction is rollbacked, migrations are aborted, and the /// error is thrown by the migrating method. /// /// By default, database operations run with disabled foreign keys, and /// foreign keys are checked right before changes are committed on disk. You /// can control this behavior with the `foreignKeyChecks` argument. /// /// Database operations run in the writer dispatch queue, serialized /// with all database updates performed by the migrated `DatabaseWriter`. /// /// The `Database` argument to `migrate` is valid only during the execution /// of the closure. Do not store or return the database connection for /// later use. /// /// - parameters: /// - identifier: The migration identifier. /// - foreignKeyChecks: This parameter is ignored if the database /// ``Configuration`` has disabled foreign keys. /// /// The default `.deferred` checks have the migration run with /// disabled foreign keys, until foreign keys are checked right before /// changes are committed on disk. These deferred checks are not /// executed if the migrator is the result of /// ``disablingDeferredForeignKeyChecks()``. /// /// The `.immediate` checks have the migration run with foreign /// keys enabled. Make sure you only use `.immediate` if the migration /// does not perform schema changes described in /// <https://www.sqlite.org/lang_altertable.html#making_other_kinds_of_table_schema_changes> /// - migrate: A closure that performs database operations. /// - precondition: No migration with the same identifier as already /// been registered. public mutating func registerMigration( _ identifier: String, foreignKeyChecks: ForeignKeyChecks = .deferred, migrate: @escaping (Database) throws -> Void) { let migrationChecks: Migration.ForeignKeyChecks switch foreignKeyChecks { case .deferred: if defersForeignKeyChecks { migrationChecks = .deferred } else { migrationChecks = .disabled } case .immediate: migrationChecks = .immediate } registerMigration(Migration(identifier: identifier, foreignKeyChecks: migrationChecks, migrate: migrate)) } // MARK: - Applying Migrations /// Runs all unapplied migrations, in the same order as they /// were registered. /// /// - parameter writer: A DatabaseWriter. /// - throws: The error thrown by the first failed migration. public func migrate(_ writer: some DatabaseWriter) throws { guard let lastMigration = _migrations.last else { return } try migrate(writer, upTo: lastMigration.identifier) } /// Runs all unapplied migrations, in the same order as they /// were registered, up to the target migration identifier (included). /// /// - precondition: `targetIdentifier` is the identifier of a /// registered migration. /// /// - precondition: The database has not already been migrated beyond the /// target migration. /// /// - parameter writer: A DatabaseWriter. /// - parameter targetIdentifier: A migration identifier. /// - throws: The error thrown by the first failed migration. public func migrate(_ writer: some DatabaseWriter, upTo targetIdentifier: String) throws { try writer.barrierWriteWithoutTransaction { db in try migrate(db, upTo: targetIdentifier) } } /// Schedules unapplied migrations for execution, and returns immediately. /// /// - parameter writer: A DatabaseWriter. /// - parameter completion: A function that can access the database. Its /// argument is a `Result` that provides a connection to the migrated /// database, or the failure that prevented the migrations /// from succeeding. public func asyncMigrate( _ writer: some DatabaseWriter, completion: @escaping (Result<Database, Error>) -> Void) { writer.asyncBarrierWriteWithoutTransaction { dbResult in do { let db = try dbResult.get() if let lastMigration = self._migrations.last { try self.migrate(db, upTo: lastMigration.identifier) } completion(.success(db)) } catch { completion(.failure(error)) } } } // MARK: - Querying Migrations /// The list of registered migration identifiers, in the same order as they /// have been registered. public var migrations: [String] { _migrations.map(\.identifier) } /// Returns the identifiers of registered and applied migrations, in the /// order of registration. /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func appliedMigrations(_ db: Database) throws -> [String] { let appliedIdentifiers = try self.appliedIdentifiers(db) return _migrations.map { $0.identifier }.filter { appliedIdentifiers.contains($0) } } /// Returns the applied migration identifiers, even unregistered ones. /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func appliedIdentifiers(_ db: Database) throws -> Set<String> { do { return try String.fetchSet(db, sql: "SELECT identifier FROM grdb_migrations") } catch { // Rethrow if we can't prove grdb_migrations does not exist yet if (try? !db.tableExists("grdb_migrations")) ?? false { return [] } throw error } } /// Returns the identifiers of registered and completed migrations, in the /// order of registration. /// /// A migration is completed if and only if all previous migrations have /// been applied. /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func completedMigrations(_ db: Database) throws -> [String] { let appliedIdentifiers = try appliedMigrations(db) let knownIdentifiers = _migrations.map(\.identifier) return zip(appliedIdentifiers, knownIdentifiers) .prefix(while: { (applied: String, known: String) in applied == known }) .map { $0.0 } } /// A boolean value indicating whether all registered migrations, and only /// registered migrations, have been applied. /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func hasCompletedMigrations(_ db: Database) throws -> Bool { try completedMigrations(db).last == _migrations.last?.identifier } /// A boolean value indicating whether the database refers to /// unregistered migrations. /// /// When the result is true, the database has likely been migrated by a /// more recent migrator. /// /// - parameter db: A database connection. /// - throws: A ``DatabaseError`` whenever an SQLite error occurs. public func hasBeenSuperseded(_ db: Database) throws -> Bool { let appliedIdentifiers = try self.appliedIdentifiers(db) let knownIdentifiers = _migrations.map(\.identifier) return appliedIdentifiers.contains { !knownIdentifiers.contains($0) } } // MARK: - Non public private mutating func registerMigration(_ migration: Migration) { GRDBPrecondition( !_migrations.map({ $0.identifier }).contains(migration.identifier), "already registered migration: \(String(reflecting: migration.identifier))") _migrations.append(migration) } /// Returns unapplied migration identifier, private func unappliedMigrations(upTo targetIdentifier: String, appliedIdentifiers: [String]) -> [Migration] { var expectedMigrations: [Migration] = [] for migration in _migrations { expectedMigrations.append(migration) if migration.identifier == targetIdentifier { break } } // targetIdentifier must refer to a registered migration GRDBPrecondition( expectedMigrations.last?.identifier == targetIdentifier, "undefined migration: \(String(reflecting: targetIdentifier))") return expectedMigrations.filter { !appliedIdentifiers.contains($0.identifier) } } private func runMigrations(_ db: Database, upTo targetIdentifier: String) throws { try db.execute(sql: "CREATE TABLE IF NOT EXISTS grdb_migrations (identifier TEXT NOT NULL PRIMARY KEY)") let appliedIdentifiers = try self.appliedMigrations(db) // Subsequent migration must not be applied if let targetIndex = _migrations.firstIndex(where: { $0.identifier == targetIdentifier }), let lastAppliedIdentifier = appliedIdentifiers.last, let lastAppliedIndex = _migrations.firstIndex(where: { $0.identifier == lastAppliedIdentifier }), targetIndex < lastAppliedIndex { fatalError("database is already migrated beyond migration \(String(reflecting: targetIdentifier))") } let unappliedMigrations = self.unappliedMigrations( upTo: targetIdentifier, appliedIdentifiers: appliedIdentifiers) if unappliedMigrations.isEmpty { return } for migration in unappliedMigrations { try migration.run(db) } } private func migrate(_ db: Database, upTo targetIdentifier: String) throws { if eraseDatabaseOnSchemaChange { var needsErase = false try db.inTransaction(.deferred) { let appliedIdentifiers = try self.appliedIdentifiers(db) let knownIdentifiers = Set(_migrations.map { $0.identifier }) if !appliedIdentifiers.isSubset(of: knownIdentifiers) { // Database contains an unknown migration needsErase = true return .commit } if let lastAppliedIdentifier = _migrations .map(\.identifier) .last(where: { appliedIdentifiers.contains($0) }) { // Some migrations were already applied. // // Let's migrate a temporary database up to the same // level, and compare the database schemas. If they // differ, we'll erase the database. let tmpSchema = try { // Make sure the temporary database is configured // just as the migrated database var tmpConfig = db.configuration tmpConfig.targetQueue = nil // Avoid deadlocks tmpConfig.writeTargetQueue = nil // Avoid deadlocks tmpConfig.label = "GRDB.DatabaseMigrator.temporary" // Create the temporary database on disk, just in // case migrations would involve a lot of data. // // SQLite supports temporary on-disk databases, but // those are not guaranteed to accept the // preparation functions provided by the user. // // See https://github.com/groue/GRDB.swift/issues/931 // for an issue created by such databases. // // So let's create a "regular" temporary database: let tmpURL = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingPathComponent(ProcessInfo().globallyUniqueString) defer { try? FileManager().removeItem(at: tmpURL) } let tmpDatabase = try DatabaseQueue(path: tmpURL.path, configuration: tmpConfig) return try tmpDatabase.writeWithoutTransaction { db in try runMigrations(db, upTo: lastAppliedIdentifier) return try db.schema(.main) } }() if try db.schema(.main) != tmpSchema { needsErase = true return .commit } } return .commit } if needsErase { try db.erase() } } // Migrate to target schema try runMigrations(db, upTo: targetIdentifier) } } extension DatabaseMigrator: Refinable { } #if canImport(Combine) extension DatabaseMigrator { // MARK: - Publishing Migrations /// Returns a Publisher that asynchronously migrates a database. /// /// The database is not accessed until subscription. Value and completion /// are published on `scheduler` (the main dispatch queue by default). /// /// - parameter writer: A DatabaseWriter. /// where migrations should apply. /// - parameter scheduler: A Combine Scheduler. @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) public func migratePublisher( _ writer: some DatabaseWriter, receiveOn scheduler: some Scheduler = DispatchQueue.main) -> DatabasePublishers.Migrate { DatabasePublishers.Migrate( upstream: OnDemandFuture { promise in self.asyncMigrate(writer) { dbResult in promise(dbResult.map { _ in }) } } .receiveValues(on: scheduler) .eraseToAnyPublisher() ) } } @available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *) extension DatabasePublishers { /// A publisher that migrates a database. /// /// `Migrate` publishes exactly one element, or an error. /// /// You build such a publisher from ``DatabaseMigrator``. public struct Migrate: Publisher { public typealias Output = Void public typealias Failure = Error fileprivate let upstream: AnyPublisher<Void, Error> public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input { upstream.receive(subscriber: subscriber) } } } #endif
mit
f34e5abf6e6a99e5cfd5cca03f0d8b3f
39.204159
118
0.601232
5.126054
false
false
false
false
DungeonKeepers/DnDInventoryManager
DnDInventoryManager/DnDInventoryManager/ViewController.swift
1
1946
// // ViewController.swift // DnDInventoryManager // // Created by Mike Miksch on 4/10/17. // Copyright © 2017 Mike Miksch. All rights reserved. // import UIKit import OAuthSwift class ViewController: UIViewController { var dataSource = [Item]() override func viewDidLoad() { super.viewDidLoad() // if !Cloud kit value for user ID { // User() // } // if !Cloud kit has data for item list { JSONParser.itemsFrom(data: JSONParser.jsonData) { (success, items) in if(success) { guard let items = items else { fatalError("Items came back nil.") } for item in items { ItemList.shared.addItem(item: item) CloudKit.shared.saveItem(item: item, completion: { (success) in }) } dataSource = ItemList.shared.allItems } } } func presentActionSheet(){ let actionSheetController = UIAlertController(title: "Item Management", message: "What action would you like to perform?", preferredStyle: .actionSheet) actionSheetController.popoverPresentationController?.sourceView = self.view actionSheetController.modalPresentationStyle = .popover let addItemAction = UIAlertAction(title: "Add Item", style: .default, handler: nil) let removeItemAction = UIAlertAction(title: "Remove Item", style: .default, handler: nil) let cancelAction = UIAlertAction(title: "Cancel", style: .destructive, handler: nil) actionSheetController.addAction(addItemAction) actionSheetController.addAction(removeItemAction) actionSheetController.addAction(cancelAction) self.present(actionSheetController, animated: true, completion: nil) } }
mit
659a919f457aad43a5cf164b5b30fb5d
30.885246
160
0.597429
5.314208
false
false
false
false
coodly/ios-gambrinus
Kiosk/AppDelegate.swift
1
3295
/* * Copyright 2018 Coodly LLC * * 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 KioskUI import KioskCore import CloudKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, PersistenceConsumer, MissingDetailsConsumer { var persistence: Persistence! var missingMonitor: MissingDetailsMonitor! var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { CoreLog.enableLogs() CoreInjection.sharedInstance.inject(into: self) let presentaion = window!.rootViewController as! AppPresentationViewController Theme.apply() if let path = Bundle.main.url(forResource: "Kiosk", withExtension: "sqlite") { persistence.maybeCopyDatabase(from: path) } else { CoreLog.debug("No seed DB included") } func presentMain() { persistence.write() { context in context.resetFailedStatuses() } missingMonitor.load() let menu: MenuViewController = Storyboards.loadFromStoryboard() CoreInjection.sharedInstance.inject(into: menu) let navigation: MenuNavigationViewController = Storyboards.loadFromStoryboard() navigation.menuController = menu let posts: PostsViewController = Storyboards.loadFromStoryboard() CoreInjection.sharedInstance.inject(into: posts) navigation.present(root: posts, animated: false) presentaion.replace(with: navigation) } presentaion.afterLoad = { initialization in CoreInjection.sharedInstance.inject(into: initialization) initialization.afterLoad = presentMain if false, #available(iOS 10.0, *) { let subscription = CloudSubscription() subscription.subscribe() } } return true } func applicationDidBecomeActive(_ application: UIApplication) { application.isIdleTimerDisabled = true } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) { let cloudNotification = CKNotification(fromRemoteNotificationDictionary: userInfo)! CoreLog.debug("didReceiveRemoteNotification: \(cloudNotification)") guard application.applicationState == .active else { return } NotificationCenter.default.post(name: .postsModification, object: nil) } }
apache-2.0
176901a33c3a4bb2e1a47a2edb347e65
32.969072
145
0.64431
5.681034
false
false
false
false
Chris-Perkins/Lifting-Buddy
Lifting Buddy/ToggleablePrettyButton.swift
1
3500
// // SelectablePrettyButton.swift // Lifting Buddy // // Created by Christopher Perkins on 9/23/17. // Copyright © 2017 Christopher Perkins. All rights reserved. // import UIKit class ToggleablePrettyButton: PrettyButton { // MARK: View properties public var isToggled: Bool // Toggle text (string) private var toggleText: String? // The color when toggled private var toggleViewColor: UIColor? // The text color when toggled private var toggleTextColor: UIColor? // Sets default text private var defaultText: String? // The default color (untoggled) private var defaultViewColor: UIColor // The default text color (untoggled) private var defaultTextColor: UIColor // MARK: View inits override init(frame: CGRect) { isToggled = false defaultViewColor = .primaryBlackWhiteColor defaultTextColor = .oppositeBlackWhiteColor super.init(frame: frame) backgroundColor = defaultViewColor setTitleColor(defaultTextColor, for: .normal) addTarget(self, action: #selector(buttonPress(sender:)), for: .touchUpInside) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Encapsulated methods // The view's color when toggled public func setToggleViewColor(color: UIColor) { toggleViewColor = color if isToggled { backgroundColor = toggleViewColor } } // The text's color when toggled public func setToggleTextColor(color: UIColor) { toggleTextColor = color if isToggled { setTitleColor(toggleTextColor, for: .normal) } } // Sets the text when toggled public func setToggleText(text: String) { toggleText = text if isToggled { setTitle(text, for: .normal) } } // The view's color when not toggled public func setDefaultViewColor(color: UIColor) { defaultViewColor = color if !isToggled { backgroundColor = defaultViewColor } } // The view's color when toggled public func setDefaultTextColor(color: UIColor) { defaultTextColor = color if !isToggled { setTitleColor(defaultTextColor, for: .normal) } } // Sets the default text public func setDefaultText(text: String) { defaultText = text if !isToggled { setTitle(text, for: .normal) } } // MARK: View functions // Sets the view properties to a toggled state public func setIsToggled(toggled: Bool) { isToggled = toggled backgroundColor = toggled ? toggleViewColor : defaultViewColor setTitleColor(toggled ? toggleTextColor : defaultTextColor, for: .normal) // If we toggled to a state that has non-nil text if (!toggled && defaultText != nil) || (toggled && toggleText != nil) { setTitle(toggled ? toggleText : defaultText, for: .normal) } } // MARK: Event functions @objc public func buttonPress(sender: UIButton) { isToggled = !isToggled UIView.animate(withDuration: animationTimeInSeconds, animations: { self.setIsToggled(toggled: self.isToggled) }) } }
mit
68ec8ece60e59fe2e4697c40449b3902
26.124031
85
0.605602
5.063676
false
false
false
false
radubozga/Freedom
speech/Swift/Speech-gRPC-Streaming/Pods/DynamicButton/Sources/DynamicButtonStyles/DynamicButtonStyleCaretRight.swift
2
2076
/* * DynamicButton * * Copyright 2015-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit /// Left caret style: › struct DynamicButtonStyleCaretRight: DynamicButtonBuildableStyle { let pathVector: DynamicButtonPathVector init(center: CGPoint, size: CGFloat, offset: CGPoint, lineWidth: CGFloat) { let thirdSize = size / 3 let sixthSize = size / 6 let a = CGPoint(x: center.x + sixthSize, y: center.y) let b = CGPoint(x: center.x - sixthSize, y: center.y + thirdSize) let c = CGPoint(x: center.x - sixthSize, y: center.y - thirdSize) let offsetFromCenter = PathHelper.gravityPointOffset(fromCenter: center, a: a, b: b, c: c) let p12 = PathHelper.line(from: a, to: b, offset: offsetFromCenter) let p34 = PathHelper.line(from: a, to: c, offset: offsetFromCenter) pathVector = DynamicButtonPathVector(p1: p12, p2: p12, p3: p34, p4: p34) } /// "Caret Right" style. static var styleName: String { return "Caret Right" } }
apache-2.0
c203a1c6182ccf891c3b423341e25c3c
38.132075
94
0.727097
4.011605
false
false
false
false
nathawes/swift
test/type/types.swift
7
7530
// RUN: %target-typecheck-verify-swift var a : Int func test() { var y : a // expected-error {{cannot find type 'a' in scope}} var z : y // expected-error {{cannot find type 'y' in scope}} var w : Swift.print // expected-error {{no type named 'print' in module 'Swift'}} } var b : (Int) -> Int = { $0 } var c2 : (field : Int) // expected-error {{cannot create a single-element tuple with an element label}}{{11-19=}} var d2 : () -> Int = { 4 } var d3 : () -> Float = { 4 } var d4 : () -> Int = { d2 } // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}} {{26-26=()}} if #available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) { var e0 : [Int] e0[] // expected-error {{missing argument for parameter #1 in call}} {{6-6=<#Int#>}} } var f0 : [Float] var f1 : [(Int,Int)] var g : Swift // expected-error {{cannot find type 'Swift' in scope}} expected-note {{cannot use module 'Swift' as a type}} var h0 : Int? _ = h0 == nil // no-warning var h1 : Int?? _ = h1! == nil // no-warning var h2 : [Int?] var h3 : [Int]? var h3a : [[Int?]] var h3b : [Int?]? var h4 : ([Int])? var h5 : ([([[Int??]])?])? var h7 : (Int,Int)? var h8 : ((Int) -> Int)? var h9 : (Int?) -> Int? var h10 : Int?.Type?.Type var i = Int?(42) func testInvalidUseOfParameterAttr() { var bad_io : (Int) -> (inout Int, Int) // expected-error {{'inout' may only be used on parameters}} func bad_io2(_ a: (inout Int, Int)) {} // expected-error {{'inout' may only be used on parameters}} var bad_is : (Int) -> (__shared Int, Int) // expected-error {{'__shared' may only be used on parameters}} func bad_is2(_ a: (__shared Int, Int)) {} // expected-error {{'__shared' may only be used on parameters}} var bad_iow : (Int) -> (__owned Int, Int) // expected-error {{'__owned' may only be used on parameters}} func bad_iow2(_ a: (__owned Int, Int)) {} // expected-error {{'__owned' may only be used on parameters}} } // <rdar://problem/15588967> Array type sugar default construction syntax doesn't work func test_array_construct<T>(_: T) { _ = [T]() // 'T' is a local name _ = [Int]() // 'Int is a global name' _ = [UnsafeMutablePointer<Int>]() // UnsafeMutablePointer<Int> is a specialized name. _ = [UnsafeMutablePointer<Int?>]() // Nesting. _ = [([UnsafeMutablePointer<Int>])]() _ = [(String, Float)]() } extension Optional { init() { self = .none } } // <rdar://problem/15295763> default constructing an optional fails to typecheck func test_optional_construct<T>(_: T) { _ = T?() // Local name. _ = Int?() // Global name _ = (Int?)() // Parenthesized name. } // Test disambiguation of generic parameter lists in expression context. struct Gen<T> {} var y0 : Gen<Int?> var y1 : Gen<Int??> var y2 : Gen<[Int?]> var y3 : Gen<[Int]?> var y3a : Gen<[[Int?]]> var y3b : Gen<[Int?]?> var y4 : Gen<([Int])?> var y5 : Gen<([([[Int??]])?])?> var y7 : Gen<(Int,Int)?> var y8 : Gen<((Int) -> Int)?> var y8a : Gen<[([Int]?) -> Int]> var y9 : Gen<(Int?) -> Int?> var y10 : Gen<Int?.Type?.Type> var y11 : Gen<Gen<Int>?> var y12 : Gen<Gen<Int>?>? var y13 : Gen<Gen<Int?>?>? var y14 : Gen<Gen<Int?>>? var y15 : Gen<Gen<Gen<Int?>>?> var y16 : Gen<Gen<Gen<Int?>?>> var y17 : Gen<Gen<Gen<Int?>?>>? var z0 = Gen<Int?>() var z1 = Gen<Int??>() var z2 = Gen<[Int?]>() var z3 = Gen<[Int]?>() var z3a = Gen<[[Int?]]>() var z3b = Gen<[Int?]?>() var z4 = Gen<([Int])?>() var z5 = Gen<([([[Int??]])?])?>() var z7 = Gen<(Int,Int)?>() var z8 = Gen<((Int) -> Int)?>() var z8a = Gen<[([Int]?) -> Int]>() var z9 = Gen<(Int?) -> Int?>() var z10 = Gen<Int?.Type?.Type>() var z11 = Gen<Gen<Int>?>() var z12 = Gen<Gen<Int>?>?() var z13 = Gen<Gen<Int?>?>?() var z14 = Gen<Gen<Int?>>?() var z15 = Gen<Gen<Gen<Int?>>?>() var z16 = Gen<Gen<Gen<Int?>?>>() var z17 = Gen<Gen<Gen<Int?>?>>?() y0 = z0 y1 = z1 y2 = z2 y3 = z3 y3a = z3a y3b = z3b y4 = z4 y5 = z5 y7 = z7 y8 = z8 y8a = z8a y9 = z9 y10 = z10 y11 = z11 y12 = z12 y13 = z13 y14 = z14 y15 = z15 y16 = z16 y17 = z17 // Type repr formation. // <rdar://problem/20075582> Swift does not support short form of dictionaries with tuples (not forming TypeExpr) let tupleTypeWithNames = (age:Int, count:Int)(4, 5) let dictWithTuple = [String: (age:Int, count:Int)]() // <rdar://problem/21684837> typeexpr not being formed for postfix ! let bb2 = [Int!](repeating: nil, count: 2) // expected-warning {{using '!' is not allowed here; treating this as '?' instead}}{{15-16=?}} // <rdar://problem/21560309> inout allowed on function return type func r21560309<U>(_ body: (_: inout Int) -> inout U) {} // expected-error {{'inout' may only be used on parameters}} r21560309 { x in x } // <rdar://problem/21949448> Accepts-invalid: 'inout' shouldn't be allowed on stored properties class r21949448 { var myArray: inout [Int] = [] // expected-error {{'inout' may only be used on parameters}} } // SE-0066 - Standardize function type argument syntax to require parentheses let _ : Int -> Float // expected-error {{single argument function types require parentheses}} {{9-9=(}} {{12-12=)}} let _ : inout Int -> Float // expected-error {{'inout' may only be used on parameters}} // expected-error@-1 {{single argument function types require parentheses}} {{15-15=(}} {{18-18=)}} func testNoParenFunction(x: Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{29-29=(}} {{32-32=)}} func testNoParenFunction(x: inout Int -> Float) {} // expected-error {{single argument function types require parentheses}} {{35-35=(}} {{38-38=)}} func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{15-34=UnsafeRawPointer}} func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{15-39=UnsafeMutableRawPointer}} class C { func foo1(a : UnsafePointer<Void>) {} // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{17-36=UnsafeRawPointer}} func foo2(a : UnsafeMutablePointer<()>) {} // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{17-41=UnsafeMutableRawPointer}} func foo3() { let _ : UnsafePointer<Void> // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}{{13-32=UnsafeRawPointer}} let _ : UnsafeMutablePointer<Void> // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}{{13-39=UnsafeMutableRawPointer}} } } let _ : inout @convention(c) (Int) -> Int // expected-error {{'inout' may only be used on parameters}} func foo3(inout a: Int -> Void) {} // expected-error {{'inout' before a parameter name is not allowed, place it before the parameter type instead}} {{11-16=}} {{20-20=inout }} // expected-error @-1 {{single argument function types require parentheses}} {{20-20=(}} {{23-23=)}} func sr5505(arg: Int) -> String { return "hello" } var _: sr5505 = sr5505 // expected-error {{cannot find type 'sr5505' in scope}} typealias A = (inout Int ..., Int ... = [42, 12]) -> Void // expected-error {{'inout' must not be used on variadic parameters}} // expected-error@-1 {{only a single element can be variadic}} {{35-39=}} // expected-error@-2 {{default argument not permitted in a tuple type}} {{39-49=}}
apache-2.0
910433ec863129b0cdce3cbcbe518e4d
37.418367
175
0.618991
3.219324
false
false
false
false
FutureKit/FutureKit
FutureKit/FutureBatch.swift
1
17149
// // Future-Sequences.swift // FutureKit // // Created by Michael Gray on 4/13/15. // 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 // --------------------------------------------------------------------------------------------------- // // CONVERT an Array of Futures into a single Future // // --------------------------------------------------------------------------------------------------- public typealias FutureBatch = FutureBatchOf<Any> open class FutureBatchOf<T> { /** */ internal(set) var subFutures = [Future<T>]() fileprivate var tokens = [CancellationToken]() /** `completionsFuture` returns an array of individual Completion<T> values - returns: a `Future<[Completion<T>]>` always returns with a Success. Returns an array of the individual Future.Completion values for each subFuture. */ open internal(set) var resultsFuture : Future<[FutureResult<T>]> /** batchFuture succeeds iff all subFutures succeed. The result is an array `[T]`. it does not complete until all futures have been completed within the batch (even if some fail or are cancelled). */ open internal(set) lazy var batchFuture : Future<[T]> = FutureBatchOf.futureFromResultsFuture(self.resultsFuture) /** `future` succeeds iff all subfutures succeed. Will complete with a Fail or Cancel as soon as the first sub future is failed or cancelled. `future` may complete, while some subfutures are still running, if one completes with a Fail or Canycel. If it's important to know that all Futures have completed, you can alertnatively use `batchFuture` and `cancelRemainingFuturesOnFirstFail()` or `cancelRemainingFuturesOnFirstFailOrCancel()`. batchFuture will always wait for all subFutures to complete before finishing, but will wait for the cancellations to be processed before exiting. this wi */ open internal(set) lazy var future : Future<[T]> = self._onFirstFailOrCancel() /** takes a type-safe list of Futures. */ public init(futures f : [Future<T>]) { self.subFutures = f for s in self.subFutures { self.tokens.append(s.getCancelToken()) } self.resultsFuture = FutureBatchOf.resultsFuture(f) } /** takes a list of Futures. Each future will be converted into a Future that returns T. */ public convenience init(_ futures : [AnyFuture]) { let f : [Future<T>] = FutureBatch.convertArray(futures) self.init(futures:f) } /** will forward a cancel request to each subFuture Doesn't guarantee that a particular future gets canceled */ func cancel(_ option:CancellationOptions = []) { for t in self.tokens { t.cancel(option) } } /** will cause any other Futures to automatically be cancelled, if one of the subfutures future fails or is cancelled */ func cancelRemainingFuturesOnFirstFailOrCancel() { self.future.onComplete { (completion) -> Void in if (!completion.isSuccess) { self.cancel() } } .ignoreFailures() } /** will cause any other subfutures to automatically be cancelled, if one of the subfutures future fails. Cancellations are ignored. */ func cancelRemainingFuturesOnFirstFail() { self.future.onComplete { (completion) -> Void in if (completion.isFail) { self.cancel() } } .ignoreFailures() } /** Allows you to define a Block that will execute as soon as each Future completes. The biggest difference between using onEachComplete() or just using the `future` var, is that this block will execute as soon as each future completes. The block will be executed repeately, until all sub futures have been completed. This can also be used to compose a new Future[__Type]. All the values returned from the block will be assembled and returned in a new Future<[__Type]. If needed. - parameter executor: executor to use to run the block :block: block block to execute as soon as each Future completes. */ public final func onEachComplete<__Type>(_ executor : Executor = .primary, block:@escaping (FutureResult<T>, Future<T>, Int)-> __Type) -> Future<[__Type]> { var futures = [Future<__Type>]() for (index, future) in self.subFutures.enumerated() { let f = future.onComplete { result -> __Type in return block(result, future,index) } futures.append(f) } return FutureBatchOf<__Type>.futureFromArrayOfFutures(futures) } typealias FailOrCancelHandler = (FutureResult<T>, Future<T>, Int) -> Void fileprivate final func _onFirstFailOrCancel(_ executor : Executor = .immediate, ignoreCancel:Bool = false, block:FailOrCancelHandler? = nil) -> Future<[T]> { if let block = block { // this will complete as soon as ONE Future Fails or is Cancelled. let failOrCancelPromise = Promise<(FutureResult<T>, Future<T>, Int)>() for (index, future) in self.subFutures.enumerated() { future.onComplete { value in if (!value.isSuccess) { // fail immediately on the first subFuture failure // which ever future fails first will complete the promises // the others will be ignored if (!value.isCancelled || !ignoreCancel) { failOrCancelPromise.completeWithSuccess((value, future, index)) } } } .ignoreFailures() } // We want to 'Cancel' this future if it is successful (so we don't call the block) self.batchFuture.onSuccess (.immediate) { _ in failOrCancelPromise.completeWithCancel() }.onFail { _ in } // As soon as the first Future fails, call the block handler. failOrCancelPromise.future.onSuccess(executor) { (arg) -> Void in let (result, future, index) = arg block(result, future, index) }.ignoreFailures() } // this future will be 'almost' like batchFuture, except it fails immediately without waiting for the other futures to complete. let promise = Promise<[T]>() for future in self.subFutures { future.onComplete { value in if (!value.isSuccess) { promise.complete(value.mapAs()) } } .ignoreFailures() } self.batchFuture.onComplete (.immediate) { value in promise.complete(value) } .ignoreFailures() return promise.future } /* adds a handler that executes on the first Future that fails. :params: block a block that will execute **/ public final func onFirstFail(_ executor : Executor = .primary,block:@escaping (_ value:FutureResult<T>, _ future:Future<T>, _ index:Int)-> Void) -> Future<[T]> { return _onFirstFailOrCancel(executor, ignoreCancel:true, block: block) } /** takes an array of futures returns a new array of futures converted to the desired Type `<__Type>` `Any` is the only type that is guaranteed to always work. Useful if you have a bunch of mixed type Futures, and convert them into a list of Future types. WARNING: if `T as! __Type` isn't legal, than your code may generate an exception. works iff the following code works: let t : T let s = t as! __Type example: - parameter array: array of Futures - returns: an array of Futures converted to return type <S> */ open class func convertArray<__Type>(_ array:[Future<T>]) -> [Future<__Type>] { var futures = [Future<__Type>]() for a in array { futures.append(a.mapAs()) } return futures } /** takes an array of futures returns a new array of futures converted to the desired Type <S> 'Any' is the only type that is guaranteed to always work. Useful if you have a bunch of mixed type Futures, and convert them into a list of Future types. - parameter array: array of Futures - returns: an array of Futures converted to return type <S> */ open class func convertArray<__Type>(_ array:[AnyFuture]) -> [Future<__Type>] { return array.map { $0.mapAs() } } /** takes an array of futures of type `[Future<T>]` and returns a single future of type Future<[Completion<T>] So you can now just add a single onSuccess/onFail/onCancel handler that will be executed once all of the sub-futures in the array have completed. This future always returns .Success, with a result individual completions. This future will never complete, if one of it's sub futures doesn't complete. you have to check the result of the array individually if you care about the specific outcome of a subfuture - parameter array: an array of Futures of type `[T]`. - returns: a single future that returns an array of `Completion<T>` values. */ open class func resultsFuture(_ array : [Future<T>]) -> Future<[FutureResult<T>]> { if (array.count == 0) { return Future<[FutureResult<T>]>(success: []) } else if (array.count == 1) { let f = array.first! return f.onComplete { (c) -> [FutureResult<T>] in return [c] } } else { let promise = Promise<[FutureResult<T>]>() var total = array.count var result = [FutureResult<T>](repeating: .cancelled,count: array.count) for (index, future) in array.enumerated() { future.onComplete(.immediate) { (value) -> Void in promise.synchObject.lockAndModifyAsync(modifyBlock: { () -> Int in result[index] = value total -= 1 return total }, then: { (currentTotal) -> Void in if (currentTotal == 0) { promise.completeWithSuccess(result) } }) } .ignoreFailures() } return promise.future } } /** takes a future of type `Future<[Completion<T>]` (usually returned from `completionFutures()`) and returns a single future of type `Future<[T]>`. It checks all the completion values and will return .Fail if one of the Futures Failed. will return .Cancelled if there were no .Fail completions, but at least one subfuture was cancelled. returns .Success iff all the subfutures completed. - parameter a: completions future of type `Future<[Completion<T>]>` - returns: a single future that returns an array an array of `[T]`. */ open class func futureFromResultsFuture<T>(_ f : Future<[FutureResult<T>]>) -> Future<[T]> { return f.onSuccess { (values) -> Completion<[T]> in var results = [T]() var errors = [Error]() var cancellations = 0 for value in values { switch value { case let .success(r): results.append(r) case let .fail(error): errors.append(error) case .cancelled: cancellations += 1 } } if (errors.count > 0) { if (errors.count == 1) { return .fail(errors.first!) } else { return .fail(FutureKitError.errorForMultipleErrors("FutureBatch.futureFromCompletionsFuture", errors)) } } if (cancellations > 0) { return .cancelled } return .success(results) } } /** takes an array of futures of type `[Future<T>]` and returns a single future of type Future<[T]> So you can now just add a single onSuccess/onFail/onCancel handler that will be executed once all of the sub-futures in the array have completed. It checks all the completion values and will return .Fail if one of the Futures Failed. will return .Cancelled if there were no .Fail completions, but at least one subfuture was cancelled. returns .Success iff all the subfutures completed. this Future will not complete until ALL subfutures have finished. If you need a Future that completes as soon as single Fail or Cancel is seen, use a `FutureBatch` object and use the var `future` or the method `onFirstFail()` - parameter array: an array of Futures of type `[T]`. - returns: a single future that returns an array of `[T]`, or a .Fail or .Cancel if a single sub-future fails or is canceled. */ public final class func futureFromArrayOfFutures(_ array : [Future<T>]) -> Future<[T]> { return futureFromResultsFuture(resultsFuture(array)) } } extension Future { public func combineWith<S>(_ s:Future<S>) -> Future<(T,S)> { return FutureBatch([self,s]).future.map { $0.toTuple() } } } public func combineFutures<A, B>(_ a: Future<A>, _ b: Future<B>) -> Future<(A, B)> { return FutureBatch([a,b]).future.map { $0.toTuple() } } public func combineFutures<A, B, C>(_ a: Future<A>, _ b: Future<B>, _ c: Future<C>) -> Future<(A, B, C)> { return FutureBatch([a,b,c]).future.map { $0.toTuple() } } public func combineFutures<A, B, C, D>(_ a: Future<A>, _ b: Future<B>, _ c: Future<C>, _ d: Future<D>) -> Future<(A, B, C, D)> { return FutureBatch([a,b,c,d]).future.map { $0.toTuple() } } public func combineFutures<A, B, C, D, E>(_ a: Future<A>, _ b: Future<B>, _ c: Future<C>, _ d: Future<D>, _ e: Future<E>) -> Future<(A, B, C, D, E)> { return FutureBatch([a,b,c,d,e]).future.map { $0.toTuple() } } public func combineFutures<A, B, C, D, E, F>(_ a: Future<A>, _ b: Future<B>, _ c: Future<C>, _ d: Future<D>, _ e: Future<E>, _ f: Future<F>) -> Future<(A, B, C, D, E, F)> { return FutureBatch([a,b,c,d,e,f]).future.map { $0.toTuple() } } public func combineFutures<A, B, C, D, E, F, G>(_ a: Future<A>, _ b: Future<B>, _ c: Future<C>, _ d: Future<D>, _ e: Future<E>, _ f: Future<F>, _ g: Future<G>) -> Future<(A, B, C, D, E, F, G)> { return FutureBatch([a,b,c,d,e,f,g]).future.map { $0.toTuple() } } public func combineFutures<A, B, C, D, E, F, G, H>(_ a: Future<A>, _ b: Future<B>, _ c: Future<C>, _ d: Future<D>, _ e: Future<E>, _ f: Future<F>, _ g: Future<G>, _ h: Future<H>) -> Future<(A, B, C, D, E, F, G, H)> { return FutureBatch([a,b,c,d,e,f,g,h]).future.map { $0.toTuple() } } public func combineFutures<A, B, C, D, E, F, G, H, I>(_ a: Future<A>, _ b: Future<B>, _ c: Future<C>, _ d: Future<D>, _ e: Future<E>, _ f: Future<F>, _ g: Future<G>, _ h: Future<H>, _ i: Future<I>) -> Future<(A, B, C, D, E, F, G, H, I)> { return FutureBatch([a,b,c,d,e,f,g,h,i]).future.map { $0.toTuple() } } public func combineFutures<A, B, C, D, E, F, G, H, I, J>(_ a: Future<A>, _ b: Future<B>, _ c: Future<C>, _ d: Future<D>, _ e: Future<E>, _ f: Future<F>, _ g: Future<G>, _ h: Future<H>, _ i: Future<I>, _ j: Future<J>) -> Future<(A, B, C, D, E, F, G, H, I, J)> { return FutureBatch([a,b,c,d,e,f,g,h,i,j]).future.map { $0.toTuple() } }
mit
83029c88174b51aa424160bf8e49c4e8
41.55335
346
0.582016
4.251116
false
false
false
false
FlyKite/AwesomeAnimationsDemo
AwesomeAnimationsDemo/AwesomeAnimationsDemo/AwesomeAnimations/Waves.swift
1
3092
// // Waves.swift // AwesomeAnimationsDemo // // Created by 风筝 on 2017/7/18. // Copyright © 2017年 Doge Studio. All rights reserved. // import UIKit class Waves: BaseView { override func createAnimation() { let areaWidth: CGFloat = self.frame.width let areaHeight: CGFloat = self.frame.height let waveLengths: [CGFloat] = [areaWidth / 10 * 7, areaWidth / 10 * 9, areaWidth / 10 * 11] let waveHeights: [CGFloat] = [areaHeight / 3, areaHeight / 2, areaHeight / 3 * 2] let waveColors: [UIColor] = [UIColor.init(white: 0, alpha: 0.2), UIColor.init(white: 0, alpha: 0.3), UIColor.init(white: 0, alpha: 0.6)] let durations: [Double] = [8.0, 5.0, 3.0] self.layer.masksToBounds = true for index in 0 ..< waveLengths.count { let waveLength = waveLengths[index] let waveHeight = waveHeights[index] let waveColor = waveColors[index] let duration = durations[index] let waveLayer = self.createWaveLayer(self.bounds, waveLength: waveLength, waveHeight: waveHeight, waveColor: waveColor, animationDuration: duration) self.layer.addSublayer(waveLayer) } } func createWaveLayer(_ frame: CGRect, waveLength: CGFloat, waveHeight: CGFloat, waveColor: UIColor, animationDuration: Double) -> CAShapeLayer { let areaWidth = frame.width let areaHeight = frame.height let waveLayer = CAShapeLayer() waveLayer.frame = CGRect(x: 0, y: 0, width: areaWidth, height: areaHeight) waveLayer.fillColor = waveColor.cgColor let path1 = UIBezierPath() path1.move(to: CGPoint(x: 0, y: areaHeight / 2)) path1.addCurve(to: CGPoint(x: waveLength, y: areaHeight / 2), controlPoint1: CGPoint(x: waveLength / 2, y: areaHeight / 2 + waveHeight), controlPoint2: CGPoint(x: waveLength / 2, y: areaHeight / 2 - waveHeight)) path1.addCurve(to: CGPoint(x: waveLength * 2, y: areaHeight / 2), controlPoint1: CGPoint(x: waveLength / 2 * 3, y: areaHeight / 2 + waveHeight), controlPoint2: CGPoint(x: waveLength / 2 * 3, y: areaHeight / 2 - waveHeight)) path1.addCurve(to: CGPoint(x: waveLength * 3, y: areaHeight / 2), controlPoint1: CGPoint(x: waveLength / 2 * 5, y: areaHeight / 2 + waveHeight), controlPoint2: CGPoint(x: waveLength / 2 * 5, y: areaHeight / 2 - waveHeight)) path1.addLine(to: CGPoint(x: waveLength * 3, y: areaHeight)) path1.addLine(to: CGPoint(x: 0, y: areaHeight)) path1.close() waveLayer.path = path1.cgPath let animation = CABasicAnimation(keyPath: "bounds.origin.x") animation.fromValue = 0 animation.toValue = waveLength animation.duration = animationDuration animation.repeatCount = MAXFLOAT waveLayer.add(animation, forKey: "bounds.origin.x") return waveLayer } }
gpl-3.0
791d684765c0e79d2e1b1a0964233b56
44.367647
160
0.607131
3.910013
false
false
false
false
PJayRushton/stats
Stats/PlayerCreationViewController.swift
1
10046
// // PlayerCreationViewController.swift // Stats // // Created by Parker Rushton on 4/7/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import UIKit import AIFlatSwitch import BetterSegmentedControl import ContactsUI import Firebase import Presentr import TextFieldEffects class PlayerCreationViewController: Component, AutoStoryboardInitializable { @IBOutlet weak var topLabel: UILabel! @IBOutlet weak var nameTextField: HoshiTextField! @IBOutlet weak var jerseyNumberTextField: HoshiTextField! @IBOutlet weak var phoneTextField: HoshiTextField! @IBOutlet weak var genderSegControl: BetterSegmentedControl! @IBOutlet weak var subSwitch: AIFlatSwitch! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var saveButton: CustomButton! @IBOutlet weak var deleteButton: UIButton! @IBOutlet weak var saveAddButton: CustomButton! @IBOutlet var keyboardView: UIView! @IBOutlet weak var keyboardNextButton: UIButton! @IBOutlet weak var keyboardPreviousButton: UIButton! @IBOutlet weak var keyboardSaveButton: UIButton! @IBOutlet weak var keyboardSaveAddButton: UIButton! @IBOutlet weak var keyboardSpacerView: UIView! @IBOutlet var saveButtonsWidthConstraint: NSLayoutConstraint! var editingPlayer: Player? fileprivate var contactHelper: ContactsHelper! fileprivate lazy var newPlayerRef: DatabaseReference = { return StatsRefs.playersRef(teamId: App.core.state.teamState.currentTeam!.id).childByAutoId() }() fileprivate var saveButtons: [UIButton] { return [saveButton, saveAddButton, keyboardSaveButton, keyboardSaveAddButton] } // MARK: - ViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() contactHelper = ContactsHelper(viewController: self) contactHelper.contactSelected = contactSelected deleteButton.isHidden = true setUpSegControl() if let editingPlayer = editingPlayer { updateUI(with: editingPlayer) } nameTextField.inputAccessoryView = keyboardView jerseyNumberTextField.inputAccessoryView = keyboardView phoneTextField.inputAccessoryView = keyboardView } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if editingPlayer == nil { nameTextField.becomeFirstResponder() } } // MARK: - IBActions @IBAction func addressBookPressed(_ sender: UIButton) { contactHelper.addressButtonPressed() } @IBAction func genderChanged(_ sender: BetterSegmentedControl) { updateSaveButtons() } @IBAction func subSwitchChanged(_ sender: Any) { updateSaveButtons() } @IBAction func cancelButtonPressed(_ sender: UIButton) { dismiss(animated: true, completion: nil) } @IBAction func saveButtonPressed(_ sender: UIButton) { guard let newPlayer = constructedPlayer() else { return } savePlayer(newPlayer, add: false) } @IBAction func deleteButtonPressed(_ sender: UIButton) { showDeleteConfirmation() } @IBAction func saveAndAddButtonPressed(_ sender: UIButton) { guard let newPlayer = constructedPlayer() else { return } savePlayer(newPlayer, add: true) } @IBAction func textFieldChanged(_ sender: UITextField) { updateSaveButtons() } @IBAction func subLabelTapped(_ sender: UITapGestureRecognizer) { subSwitch.setSelected(!subSwitch.isSelected, animated: true) updateSaveButtons() } @IBAction func nextButtonPressed(_ sender: UIButton) { moveFirstResponder(next: true) } @IBAction func previousButtonPressed(_ sender: UIButton) { moveFirstResponder(next: false) } @IBAction func dismissKeyboardButtonPressed(_ sender: UIButton) { view.endEditing(false) } @IBAction func viewTapped(_ sender: UITapGestureRecognizer) { view.endEditing(false) } // MARK: - Subscriber override func update(with state: AppState) { updateSaveButtons() } } // MARK: - Fileprivate extension PlayerCreationViewController { fileprivate func updateUI(with player: Player) { topLabel.text = "Edit Player" nameTextField.text = player.name jerseyNumberTextField.text = player.jerseyNumber phoneTextField.text = player.phone try? genderSegControl.setIndex(UInt(player.gender.rawValue), animated: false) subSwitch.isSelected = player.isSubForCurrentSeason saveAddButton.isHidden = true deleteButton.isHidden = false updateSaveButtons() } fileprivate func setUpSegControl() { genderSegControl.titles = Gender.allValues.map { $0.stringValue } let font = FontType.lemonMilk.font(withSize: 13) genderSegControl.titleFont = font genderSegControl.selectedTitleFont = font genderSegControl.options = [.titleColor(.icon), .indicatorViewBackgroundColor(.secondaryAppColor), .cornerRadius(5)] } fileprivate func updateSaveButtons() { let newPlayer = constructedPlayer() var isSavable = newPlayer != nil if let editingPlayer = editingPlayer { isSavable = newPlayer != nil && !newPlayer!.isSame(as: editingPlayer) } saveButton.isEnabled = isSavable saveAddButton.isEnabled = isSavable keyboardSaveButton.isHidden = !isSavable keyboardSaveAddButton.isHidden = !isSavable || editingPlayer != nil keyboardSpacerView.isHidden = isSavable saveButtonsWidthConstraint.isActive = !keyboardSaveButton.isHidden && !keyboardSaveAddButton.isHidden } fileprivate func constructedPlayer(add: Bool = false) -> Player? { guard let team = core.state.teamState.currentTeam else { return nil } guard let name = nameTextField.text, !name.isEmpty else { return nil } let jerseyNumber = jerseyNumberTextField.text!.isEmpty ? nil : jerseyNumberTextField.text guard let gender = Gender(rawValue: Int(genderSegControl.index)) else { return nil } let id = StatsRefs.playersRef(teamId: team.id).childByAutoId().key var phone: String? if let phoneText = phoneTextField.text, !phoneText.isEmpty { guard phoneText.isValidPhoneNumber else { return nil } phone = phoneText } if var editingPlayer = editingPlayer { editingPlayer.name = name editingPlayer.jerseyNumber = jerseyNumber editingPlayer.phone = phone editingPlayer.gender = gender editingPlayer.isSubForCurrentSeason = subSwitch.isSelected return editingPlayer } else { return Player(id: id, name: name, jerseyNumber: jerseyNumber, isSub: subSwitch.isSelected, phone: phone, gender: gender, teamId: team.id) } } fileprivate func savePlayer(_ player: Player, add: Bool) { if let _ = editingPlayer { core.fire(command: UpdateObject(player)) dismiss(animated: true, completion: nil) } else { core.fire(command: CreatePlayer(player)) if add { clear() } else { dismiss(animated: true, completion: nil) } } } fileprivate func clear() { nameTextField.text = "" jerseyNumberTextField.text = "" phoneTextField.text = "" subSwitch.setSelected(false, animated: true) updateSaveButtons() nameTextField.becomeFirstResponder() } fileprivate func moveFirstResponder(next: Bool) { if (nameTextField.isFirstResponder && !next) || (phoneTextField.isFirstResponder && next) { view.endEditing(false) } else if (nameTextField.isFirstResponder && next) || (phoneTextField.isFirstResponder && !next) { jerseyNumberTextField.becomeFirstResponder() } else if jerseyNumberTextField.isFirstResponder { let nextTextField = next ? phoneTextField : nameTextField nextTextField?.becomeFirstResponder() } } fileprivate func showDeleteConfirmation() { guard let editingPlayer = editingPlayer else { return } let alert = Presentr.alertViewController(title: "Delete \(editingPlayer.name)?", body: "This cannot be undone") alert.addAction(AlertAction(title: "Cancel 😳", style: .cancel, handler: nil)) alert.addAction(AlertAction(title: "☠️", style: .destructive) { _ in self.core.fire(command: DeleteObject(editingPlayer)) self.dismiss(animated: true, completion: { self.dismiss(animated: true, completion: nil) }) }) customPresentViewController(alertPresenter, viewController: alert, animated: true, completion: nil) } } // MARK: - Contacts extension PlayerCreationViewController { func contactSelected(result: Result<(String, String)>) { switch result { case let .success(name, phone): if let nameText = nameTextField.text, nameText.isEmpty { nameTextField.text = name } phoneTextField.text = phone case let .failure(error): contactHelper.presentErrorAlert() dump(error) } } } extension PlayerCreationViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == nameTextField { jerseyNumberTextField.becomeFirstResponder() } else if textField == jerseyNumberTextField { phoneTextField.becomeFirstResponder() } else if textField == phoneTextField { view.endEditing(true) } return true } }
mit
aa7353843bc7b4d65345196e341a9af4
33.733564
149
0.656306
5.131902
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeTracking/AwesomeTracking/Classes/AwesomeTrackingV2.swift
1
7002
// // AwesomeTrackingV2.swift // AwesomeTracking // // Created by Leonardo Vinicius Kaminski Ferreira on 17/10/19. // import Foundation import AwesomeCore import AppsFlyerLib import Mixpanel import Appboy_iOS_SDK public class AwesomeTrackingV2: NSObject { private var formatter: DateFormatter = { let dateFormatter: DateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" dateFormatter.calendar = Calendar(identifier: .gregorian) return dateFormatter }() private let headers: [[String]] = [["raw", "Content-Type"]] private let requester: AwesomeCoreRequester = AwesomeCoreRequester() /// New eventstream V2 method to register the user device, call it once on `didFinishLaunch`. public func registerDevice() { let body: [String: Any] = [ "sent_at": formatter.string(from: Date()), "type": "register", "client_id": AwesomeTrackingConstants.stagingClientId, "context": [ "registered_at": formatter.string(from: Date()), "braze_device_id": String(Appboy.sharedInstance()?.getDeviceId() ?? ""), "mixpanel_id": String(Mixpanel.mainInstance().distinctId), "appsflyer_device_id": String(AppsflyerHelper.appsFlyerUID), "traits": [ "device_id": AwesomeTrackingConstants.deviceId ] ] ] _ = requester.performRequest(AwesomeTrackingConstants.registerUrl, method: .POST, bodyData: buildData(body), headerValues: headers, forceUpdate: true, shouldCache: false, timeoutAfter: 20, completion: { (data, error, _) in if let data = data { print("EVENTSTREAM V2 - register \(String(data: data, encoding: .utf8) ?? "no data")") } print("EVENTSTREAM V2 - register \(String(describing: error))") }) } /// New eventstream V2 method to identify the user, call it once after the user is logged in and you already called `AwesomeTracking.setUserProfile`. public func identify() { let body: [String: Any] = [ "sent_at": formatter.string(from: Date()), "type": "identity", "client_id": AwesomeTrackingConstants.stagingClientId, "context": [ "appsflyer_device_id": AppsflyerHelper.appsFlyerUID, "braze_id": String(Appboy.sharedInstance()?.getDeviceId() ?? ""), "mixpanel_id": Mixpanel.mainInstance().distinctId, "traits": [ "user_id": AwesomeTracking.shared.user?.uid ?? "not", "device_id": AwesomeTrackingConstants.stagingClientId ] ] ] _ = requester.performRequest(AwesomeTrackingConstants.identifyUrl, method: .POST, bodyData: buildData(body), headerValues: headers, forceUpdate: true, shouldCache: false, timeoutAfter: 20, completion: { (data, error, _) in if let data = data { print("EVENTSTREAM V2 - identify \(String(data: data, encoding: .utf8) ?? "no data")") } print("EVENTSTREAM V2 - identify \(String(describing: error))") }) } /// New eventstream V2 method to send events to MV analytics. /// - Parameter appVersion: The app version number, from the main app, library will always ask it. /// - Parameter eventName: The event name you are going to send. /// - Parameter properties: The properties for the event that you are going to send, it's represented by a dictionary of Strings. public func sendEvent(_ eventName: String, properties: [String: String]) { var properties: [String: String] = properties properties["platform"] = "iOS" properties["app_version"] = appVersion properties["email"] = AwesomeTracking.shared.user?.email ?? "not set" properties["auth0 id"] = AwesomeTracking.shared.user?.uid ?? "not set" properties["app_name"] = "Mindvalley App" let body: [String: Any] = [ "type": "event", "sent_at": formatter.string(from: Date()), "client_id": AwesomeTrackingConstants.stagingClientId, "integrations": AwesomeTracking.shared.activeEventstreamTools.map({ (tool) -> String in return tool.rawValue }), "context": [ "active": "true", "app": [ "name": "MV app iOS", "version": appVersion ], "device": [ "brand": "Apple", "model": UIDevice.current.localizedModel, "manufacturer": "Apple" ], "os": [ "name": UIDevice.current.systemName, "version": UIDevice.current.systemVersion ], "timezone": Calendar.current.timeZone.identifier, "traits": [ "device_id": AwesomeTrackingConstants.deviceId, "user_id": AwesomeTracking.shared.user?.uid ?? "not" ] ], "data": [ [ "event": eventName, "properties": properties ] ] ] _ = requester.performRequest(AwesomeTrackingConstants.eventsUrl, method: .POST, bodyData: buildData(body), headerValues: headers, forceUpdate: true, shouldCache: false, timeoutAfter: 20, completion: { (data, error, _) in if let data = data { print("EVENTSTREAM V2 - event \(String(data: data, encoding: .utf8) ?? "no data")") } print("EVENTSTREAM V2 - event \(String(describing: error))") }) } } // Data builder extension AwesomeTrackingV2 { private func buildData(_ body: [String: Any]) -> Data? { var data: Data? do { try data = JSONSerialization.data(withJSONObject: body, options: .prettyPrinted) } catch { NSLog("Error unwraping json object") } return data } } // MARK: - Helpers extension AwesomeTrackingV2 { private var appVersion: String { let dictionary = Bundle.main.infoDictionary! if let version = dictionary["CFBundleShortVersionString"] as? String, let build = dictionary["CFBundleVersion"] as? String { return "\(version) build \(build)" } return "" } }
mit
9dff53780ac9f2c663ff2a405a3e49fe
42.7625
230
0.541988
4.94841
false
false
false
false
ngthduy90/Yummy
Source/Models/BusinessFilters.swift
1
1543
// // BusinessFilters.swift // Yummy // // Created by Duy Nguyen on 6/25/17. // Copyright © 2017 Duy Nguyen. All rights reserved. // import Foundation class BusinessFilters { var term: String = "" var sortBy: YummySortMode = .bestMatched var categories: [String]? var isOfferDeals: Bool = false var radius: Double? func getFormatFilters() -> [String] { var filters: [String] = [] if !term.isEmpty { filters.append("Search: \(term)") } if isOfferDeals { filters.append("Offer Deals") } if let sortByString = sortModeAsString() { filters.append("Sort by: \(sortByString)") } filters.append("Distance: \(distanceAsString())") if let categories = categories { let ctgString = categories.joined(separator: ", ") filters.append("Categories: \(ctgString)") } return filters } func sortModeAsString() -> String? { switch sortBy { case .bestMatched: return "Best Matched" case .distance: return "Distance" case .highestRated: return "Highest Rated" } } func distanceAsString() -> String { guard let value = radius else { return "Auto" } return String(format: "%.2f miles", Constants.MilesPerMeter * value) } }
apache-2.0
399b5b17cf0df2e3828b1942ac733f0d
22.363636
76
0.514267
4.70122
false
false
false
false
vector-im/riot-ios
Riot/Modules/KeyVerification/Device/SelfVerifyWait/KeyVerificationSelfVerifyWaitCoordinator.swift
1
3549
// File created from ScreenTemplate // $ createScreen.sh KeyVerification KeyVerificationSelfVerifyWait /* Copyright 2020 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 import UIKit final class KeyVerificationSelfVerifyWaitCoordinator: KeyVerificationSelfVerifyWaitCoordinatorType { // MARK: - Properties // MARK: Private private let session: MXSession private var keyVerificationSelfVerifyWaitViewModel: KeyVerificationSelfVerifyWaitViewModelType private let keyVerificationSelfVerifyWaitViewController: KeyVerificationSelfVerifyWaitViewController // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: KeyVerificationSelfVerifyWaitCoordinatorDelegate? // MARK: - Setup init(session: MXSession, isNewSignIn: Bool) { self.session = session let keyVerificationSelfVerifyWaitViewModel = KeyVerificationSelfVerifyWaitViewModel(session: self.session, isNewSignIn: isNewSignIn) let keyVerificationSelfVerifyWaitViewController = KeyVerificationSelfVerifyWaitViewController.instantiate(with: keyVerificationSelfVerifyWaitViewModel) self.keyVerificationSelfVerifyWaitViewModel = keyVerificationSelfVerifyWaitViewModel self.keyVerificationSelfVerifyWaitViewController = keyVerificationSelfVerifyWaitViewController } // MARK: - Public methods func start() { self.keyVerificationSelfVerifyWaitViewModel.coordinatorDelegate = self } func toPresentable() -> UIViewController { return self.keyVerificationSelfVerifyWaitViewController } } // MARK: - KeyVerificationSelfVerifyWaitViewModelCoordinatorDelegate extension KeyVerificationSelfVerifyWaitCoordinator: KeyVerificationSelfVerifyWaitViewModelCoordinatorDelegate { func keyVerificationSelfVerifyWaitViewModel(_ viewModel: KeyVerificationSelfVerifyWaitViewModelType, didAcceptKeyVerificationRequest keyVerificationRequest: MXKeyVerificationRequest) { self.delegate?.keyVerificationSelfVerifyWaitCoordinator(self, didAcceptKeyVerificationRequest: keyVerificationRequest) } func keyVerificationSelfVerifyWaitViewModel(_ viewModel: KeyVerificationSelfVerifyWaitViewModelType, didAcceptIncomingSASTransaction incomingSASTransaction: MXIncomingSASTransaction) { self.delegate?.keyVerificationSelfVerifyWaitCoordinator(self, didAcceptIncomingSASTransaction: incomingSASTransaction) } func keyVerificationSelfVerifyWaitViewModelDidCancel(_ viewModel: KeyVerificationSelfVerifyWaitViewModelType) { self.delegate?.keyVerificationSelfVerifyWaitCoordinatorDidCancel(self) } func keyVerificationSelfVerifyWaitViewModel(_ coordinator: KeyVerificationSelfVerifyWaitViewModelType, wantsToRecoverSecretsWith secretsRecoveryMode: SecretsRecoveryMode) { self.delegate?.keyVerificationSelfVerifyWaitCoordinator(self, wantsToRecoverSecretsWith: secretsRecoveryMode) } }
apache-2.0
51401bcc7c3f3ad665305b533a11df9a
43.924051
188
0.798535
6.417722
false
false
false
false
upLynk/Sample-Players
ios/fairplay/swift/PlayerViewController.swift
1
20095
/* Copyright (C) 2015 Apple Inc. All Rights Reserved. See the Apple Developer Program License Agreement for this file's licensing information. All use of these materials is subject to the terms of the Apple Developer Program License Agreement. Abstract: PlayerViewController.swift: Sample player view controller. Illustrates how to implement and install an AVAssetResourceLoader delegate that will handle FairPlay Streaming key requests. */ import Foundation import UIKit import AVFoundation // MARK: ADAPT: Your media stream URL. // Playlists are not hardcoded in a real app. Modify this to suit your app design. // This URL will NOT work with your public certficate, but it left here to show // an example of what a fairplay protected uplynk URL will look like. let playlistURL = "https://content.uplynk.com/7b5fcaf81b204808a66b2d855802260c.m3u8?rmt=fps" // MARK: ADAPT: Replace with a URL path to your Apple signed FairPlay Certificate // If you are including a cert file in your app you will need to further adapt // the code to load your certificate from file instead of from URL. let defaultCertURL = "http://example.com/certs/public.der" // MARK: AVAssetResourceLoaderDelegate class AssetLoaderDelegate: NSObject, AVAssetResourceLoaderDelegate { // MARK: Properties /** Your custom scheme name that indicates how to obtain the content key. This value is specified in the URI attribute in the EXT-X-KEY tag in the playlist. */ static let URLScheme = "skd" /// The application certificate that is retrieved from the server. var fetchedCertificate: Data? // MARK: Functions /** ADAPT: YOU MUST IMPLEMENT THIS METHOD. - returns: Content Key Context (CKC) message data specific to this request. */ var ckcData: Data? /** ADAPT: YOU MUST IMPLEMENT THIS METHOD. Sends the SPC to a Key Server that contains your Key Security Module (KSM). The KSM decrypts the SPC and gets the requested CK from the Key Server. The KSM wraps the CK inside an encrypted Content Key Context (CKC) message, which it sends to the app. The application may use whatever transport forms and protocols it needs to send the SPC to the Key Server. - returns: The CKC from the server. */ func contentKeyFromKeyServerModuleWithRequestData(_ requestBytes: Data, assetString: String, expiryDuration: TimeInterval, skdURL: URL) throws -> Data { //format message to b64 + json and post let spc = requestBytes.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) let postBody = String(format: "{\"spc\":\"%@\"}", spc) let urlRequest: NSMutableURLRequest = NSMutableURLRequest(url: skdURL) urlRequest.httpBody = postBody.data(using: String.Encoding.utf8, allowLossyConversion: true) urlRequest.httpMethod = "POST" urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") var response: URLResponse? do { let urlData = try NSURLConnection.sendSynchronousRequest(urlRequest as URLRequest, returning: &response) let object = try JSONSerialization.jsonObject(with: urlData, options: .allowFragments) if let dictionary = object as? [String: AnyObject] { let ckc = dictionary["ckc"]! return Data(base64Encoded: ckc as! String, options:NSData.Base64DecodingOptions(rawValue: 0))! } } catch { // Handle Error } // If the key server provided a CKC, return it. if let ckcData = ckcData { return ckcData } /* Otherwise, the CKC was not provided by key server. Fail with bogus error. Generate an error describing the failure. */ throw NSError(domain: "com.example.apple-samplecode", code: 0, userInfo: [ NSLocalizedDescriptionKey: NSLocalizedString("Item cannot be played.", comment: "Item cannot be played."), NSLocalizedFailureReasonErrorKey: NSLocalizedString("Could not get the content key from the Key Server.", comment: "Failure to successfully send the SPC to the Key Server and get the content key from the returned Content Key Context (CKC) message.") ]) } /** ADAPT: YOU MUST IMPLEMENT THIS METHOD: Get the application certificate from the server in DER format. */ func fetchAppCertificateDataWithCompletionHandler(_ handler: (Data?) -> Void) { /* This needs to be implemented to conform to your protocol with the backend/key security module. At a high level, this function gets the application certificate from the server in DER format. */ // If the server provided an application certificate, return it. let url = URL(string: defaultCertURL) fetchedCertificate = try? Data(contentsOf: url!) if let fetchedCertificate = fetchedCertificate { handler(fetchedCertificate) return } // Otherwise, failed to get application certificate from the server. fetchedCertificate = nil // If the server provided an application certificate, return it. handler(fetchedCertificate) } /* resourceLoader:shouldWaitForLoadingOfRequestedResource: When iOS asks the app to provide a CK, the app invokes the AVAssetResourceLoader delegate’s implementation of its -resourceLoader:shouldWaitForLoadingOfRequestedResource: method. This method provides the delegate with an instance of AVAssetResourceLoadingRequest, which accesses the underlying NSURLRequest for the requested resource together with support for responding to the request. */ func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest) -> Bool { // Get the URL request object for the requested resource. /* Your URI scheme must be a non-standard scheme for AVFoundation to invoke your AVAssetResourceLoader delegate for help in loading it. */ guard let url = loadingRequest.request.url, url.scheme == AssetLoaderDelegate.URLScheme else { print("URI scheme name does not match our scheme.") return false } //We're going to request the key over https(not skd) so change the scheme var skdurl = URLComponents(url: url, resolvingAgainstBaseURL: false) skdurl?.scheme = "https" // Get the URI for the content key. guard let assetString = skdurl!.queryItems![0].value, let assetID = assetString.data(using: String.Encoding.utf8) else { return false } // Get the application certificate from the server. guard let fetchedCertificate = fetchedCertificate else { print("Failed to get Application Certificate from key server.") return false } do { // MARK: ADAPT: YOU MUST CALL: `streamingContentKeyRequestDataForApp(_:options:)` /* ADAPT: YOU MUST CALL : `streamingContentKeyRequestDataForApp(_:options:)`. to obtain the SPC message from iOS to send to the Key Server. */ let requestedBytes = try loadingRequest.streamingContentKeyRequestData(forApp: fetchedCertificate, contentIdentifier: assetID, options: nil) let expiryDuration: TimeInterval = 0.0 let responseData = try contentKeyFromKeyServerModuleWithRequestData(requestedBytes, assetString: assetString, expiryDuration: expiryDuration, skdURL: (skdurl?.url)!) guard let dataRequest = loadingRequest.dataRequest else { print("Failed to get instance of AVAssetResourceLoadingDataRequest (loadingRequest.dataRequest).") return false } /* The Key Server returns the CK inside an encrypted Content Key Context (CKC) message in response to the app’s SPC message. This CKC message, containing the CK, was constructed from the SPC by a Key Security Module in the Key Server’s software. */ // Provide the CKC message (containing the CK) to the loading request. dataRequest.respond(with: responseData) // Get the CK expiration time from the CKC. This is used to enforce the expiration of the CK. if let infoRequest = loadingRequest.contentInformationRequest, expiryDuration != 0.0 { /* Set the date at which a renewal should be triggered. Before you finish loading an AVAssetResourceLoadingRequest, if the resource is prone to expiry you should set the value of this property to the date at which a renewal should be triggered. This value should be set sufficiently early enough to allow an AVAssetResourceRenewalRequest, delivered to your delegate via -resourceLoader:shouldWaitForRenewalOfRequestedResource:, to finish before the actual expiry time. Otherwise media playback may fail. */ infoRequest.renewalDate = Date(timeIntervalSinceNow: expiryDuration) infoRequest.contentType = "application/octet-stream" infoRequest.contentLength = Int64(responseData.count) infoRequest.isByteRangeAccessSupported = false } // Treat the processing of the requested resource as complete. loadingRequest.finishLoading() // The resource request has been handled regardless of whether the server returned an error. return true } catch let error as NSError { // Resource loading failed with an error. print("streamingContentKeyRequestDataForApp failure: \(error.localizedDescription)") loadingRequest.finishLoading(with: error) return false } } /* resourceLoader: shouldWaitForRenewalOfRequestedResource: Delegates receive this message when assistance is required of the application to renew a resource previously loaded by resourceLoader:shouldWaitForLoadingOfRequestedResource:. For example, this method is invoked to renew decryption keys that require renewal, as indicated in a response to a prior invocation of resourceLoader:shouldWaitForLoadingOfRequestedResource:. If the result is YES, the resource loader expects invocation, either subsequently or immediately, of either -[AVAssetResourceRenewalRequest finishLoading] or -[AVAssetResourceRenewalRequest finishLoadingWithError:]. If you intend to finish loading the resource after your handling of this message returns, you must retain the instance of AVAssetResourceRenewalRequest until after loading is finished. If the result is NO, the resource loader treats the loading of the resource as having failed. Note that if the delegate's implementation of -resourceLoader:shouldWaitForRenewalOfRequestedResource: returns YES without finishing the loading request immediately, it may be invoked again with another loading request before the prior request is finished; therefore in such cases the delegate should be prepared to manage multiple loading requests. */ func resourceLoader(_ resourceLoader: AVAssetResourceLoader, shouldWaitForRenewalOfRequestedResource renewalRequest: AVAssetResourceRenewalRequest) -> Bool { return self.resourceLoader(resourceLoader, shouldWaitForLoadingOfRequestedResource: renewalRequest) } } /** KVO context used to differentiate KVO callbacks for this class versus other classes in its class hierarchy. */ private var playerViewControllerKVOContext = 0 // MARK: - View Controller class PlayerViewController: UIViewController { // MARK: Properties let player = AVPlayer() var playerLayer: AVPlayerLayer? { return playerView.playerLayer } var playerItem: AVPlayerItem? { didSet { /* If needed, configure player item here before associating it with a player. (example: adding outputs, setting text style rules, selecting media options) */ player.replaceCurrentItem(with: playerItem) } } /// Dispatch queue to use with the resource loader. let resourceRequestDispatchQueue = DispatchQueue(label: "com.example.apple-samplecode.resourcerequests", attributes: []) var loaderDelegate = AssetLoaderDelegate() var asset: AVURLAsset? { didSet { guard let newAsset = asset else { return } // Sets the delegate and dispatch queue to use with the resource loader. newAsset.resourceLoader.setDelegate(loaderDelegate, queue: resourceRequestDispatchQueue) asynchronouslyLoadURLAsset(newAsset) } } // Must load and test these asset keys before playing. static let assetKeysRequiredToPlay = [ "playable" ] static let playerItemStatusKey = "player.currentItem.status" @IBOutlet weak var playerView: PlayerView! // MARK: Functions func asynchronouslyLoadURLAsset(_ newAsset: AVURLAsset) { /* Using AVAsset now runs the risk of blocking the current thread (the main UI thread) whilst I/O happens to populate the properties. It's prudent to defer our work until the properties we need have been loaded. */ newAsset.loadValuesAsynchronously(forKeys: PlayerViewController.assetKeysRequiredToPlay) { /* The asset invokes its completion handler on an arbitrary queue. To avoid multiple threads using our internal state at the same time we'll elect to use the main thread at all times, let's dispatch our handler to the main queue. */ DispatchQueue.main.async { /* `self.asset` has already changed! No point continuing because another `newAsset` will come along in a moment. */ guard newAsset == self.asset else { return } /* Test whether the values of each of the keys we need have been successfully loaded. */ for key in PlayerViewController.assetKeysRequiredToPlay { var error: NSError? if newAsset.statusOfValue(forKey: key, error: &error) == .failed { let stringFormat = NSLocalizedString("error.asset_key_%@_failed.description", comment: "Can't use this AVAsset because one of it's keys failed to load") let message = String.localizedStringWithFormat(stringFormat, key) self.handleErrorWithMessage(message, error: error) return } } // We can't play this asset. if !newAsset.isPlayable { let message = NSLocalizedString("error.asset_not_playable.description", comment: "Can't use this AVAsset because it isn't playable") self.handleErrorWithMessage(message) return } /* We can play this asset. Create a new `AVPlayerItem` and make it our player's current item. */ self.playerItem = AVPlayerItem(asset: newAsset) } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Observe the player item "status" property to determine when it is ready to play. addObserver(self, forKeyPath: PlayerViewController.playerItemStatusKey, options: [.new, .initial], context: &playerViewControllerKVOContext) /* When an iOS device is in AirPlay mode, FPS content will not play on an attached AppleTV unless AirPlay playback is set to full screen. */ player.usesExternalPlaybackWhileExternalScreenIsActive = true playerView.playerLayer.player = player loaderDelegate.fetchAppCertificateDataWithCompletionHandler { _ in /* Create an asset for the media specified by the playlist url. Calling the setter for the asset property will then invoke a method to load and test the necessary asset keys before playback. */ if let playlistURL = URL(string: playlistURL) { self.asset = AVURLAsset(url: playlistURL, options: nil) } } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) player.pause() removeObserver(self, forKeyPath: PlayerViewController.playerItemStatusKey, context: &playerViewControllerKVOContext) } // MARK: - KVO Observation /* observeValueForKeyPath:ofObject:change:context Called when the value at the specified key path relative to the given object has changed. Start movie playback when the AVPlayerItem is ready to play. Report and error if the AVPlayerItem cannot be played. NOTE: this method is invoked on the main queue. */ override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) { // Make sure the this KVO callback was intended for this view controller. guard context == &playerViewControllerKVOContext else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) return } if playerItem?.status == .failed { handleErrorWithMessage(player.currentItem?.error?.localizedDescription, error: player.currentItem?.error as NSError?) } else if playerItem?.status == .readyToPlay { /* Once the AVPlayerItem becomes ready to play, i.e. playerItem.status == .ReadyToPlay, we can start playback using the associated player object. */ player.play() } } // MARK: - Error Handling func handleErrorWithMessage(_ message: String?, error: NSError? = nil) { NSLog("Error occured with message: \(String(describing: message)), error: \(String(describing: error)).") let alertTitle = NSLocalizedString("alert.error.title", comment: "Alert title for errors") let defaultAlertMessage = NSLocalizedString("error.default.description", comment: "Default error message when no NSError provided") let alert = UIAlertController(title: alertTitle, message: message == nil ? defaultAlertMessage : message, preferredStyle: .alert) let alertActionTitle = NSLocalizedString("alert.error.actions.OK", comment: "OK on error alert") let alertAction = UIAlertAction(title: alertActionTitle, style: .default, handler: nil) alert.addAction(alertAction) present(alert, animated: true, completion: nil) } }
mit
089d281bad40975bee296215b1a1fefc
43.44469
261
0.643984
5.488798
false
false
false
false
Dwarven/ShadowsocksX-NG
ShadowsocksX-NG/ShareServerProfilesWindowController.swift
2
6832
// // ShareServerProfilesWindowController.swift // ShadowsocksX-NG // // Created by 邱宇舟 on 2018/9/16. // Copyright © 2018年 qiuyuzhou. All rights reserved. // import Cocoa class ShareServerProfilesWindowController: NSWindowController , NSTableViewDataSource, NSTableViewDelegate { @IBOutlet weak var profilesTableView: NSTableView! @IBOutlet weak var qrCodeImageView: NSImageView! @IBOutlet weak var copyAllServerURLsButton: NSButton! @IBOutlet weak var saveAllServerURLsAsFileButton: NSButton! @IBOutlet weak var copyURLButton: NSButton! @IBOutlet weak var copyQRCodeButton: NSButton! @IBOutlet weak var saveQRCodeAsFileButton: NSButton! var defaults: UserDefaults! var profileMgr: ServerProfileManager! override func windowDidLoad() { super.windowDidLoad() defaults = UserDefaults.standard profileMgr = ServerProfileManager.instance profilesTableView.reloadData() if !profileMgr.profiles.isEmpty { let index = IndexSet(integer: 0) profilesTableView.selectRowIndexes(index, byExtendingSelection: false) } else { copyAllServerURLsButton.isEnabled = false saveAllServerURLsAsFileButton.isEnabled = false copyURLButton.isEnabled = false copyQRCodeButton.isEnabled = false saveQRCodeAsFileButton.isEnabled = false } } @IBAction func copyURL(_ sender: NSButton) { let profile = getSelectedProfile() if profile.isValid(), let url = profile.URL() { let pb = NSPasteboard.general pb.clearContents() if pb.writeObjects([url.absoluteString as NSPasteboardWriting]) { NSLog("Copy URL to clipboard") } else { NSLog("Failed to copy URL to clipboard") } } } @IBAction func copyQRCode(_ sender: NSButton) { if let img = qrCodeImageView.image { let pb = NSPasteboard.general pb.clearContents() if pb.writeObjects([img as NSPasteboardWriting]) { NSLog("Copy QRCode to clipboard") } else { NSLog("Failed to copy QRCode to clipboard") } } } @IBAction func saveQRCodeAsFile(_ sender: NSButton) { if let img = qrCodeImageView.image { let savePanel = NSSavePanel() savePanel.title = "Save QRCode As File".localized savePanel.canCreateDirectories = true savePanel.allowedFileTypes = ["gif"] savePanel.isExtensionHidden = false let profile = getSelectedProfile() if profile.remark.isEmpty { savePanel.nameFieldStringValue = "shadowsocks_qrcode.gif" } else { savePanel.nameFieldStringValue = "shadowsocks_qrcode_\(profile.remark).gif" } savePanel.becomeKey() let result = savePanel.runModal() if (result.rawValue == NSFileHandlingPanelOKButton && (savePanel.url) != nil) { let imgRep = NSBitmapImageRep(data: img.tiffRepresentation!) let data = imgRep?.representation(using: NSBitmapImageRep.FileType.gif, properties: [:]) try! data?.write(to: savePanel.url!) } } } @IBAction func copyAllServerURLs(_ sender: NSButton) { let pb = NSPasteboard.general pb.clearContents() if pb.writeObjects([getAllServerURLs() as NSPasteboardWriting]) { NSLog("Copy all server URLs to clipboard") } else { NSLog("Failed to all server URLs to clipboard") } } @IBAction func saveAllServerURLsAsFile(_ sender: NSButton) { let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd" let date_string = formatter.string(from: Date()) let savePanel = NSSavePanel() savePanel.title = "Save All Server URLs To File".localized savePanel.canCreateDirectories = true savePanel.allowedFileTypes = ["txt"] savePanel.isExtensionHidden = false savePanel.nameFieldStringValue = "shadowsocks_profiles_\(date_string).txt" savePanel.becomeKey() let result = savePanel.runModal() if (result.rawValue == NSFileHandlingPanelOKButton && (savePanel.url) != nil) { let urls = getAllServerURLs() try! urls.write(to: (savePanel.url)!, atomically: true, encoding: String.Encoding.utf8) } } func getAllServerURLs() -> String { let urls = profileMgr.profiles.filter({ (profile) -> Bool in return profile.isValid() }).map { (profile) -> String in return profile.URL()!.absoluteString } return urls.joined(separator: "\n") } func getSelectedProfile() -> ServerProfile { let i = profilesTableView.selectedRow return profileMgr.profiles[i] } func getDataAtRow(_ index:Int) -> String { let profile = profileMgr.profiles[index] if !profile.remark.isEmpty { return profile.remark } else { return profile.serverHost } } //-------------------------------------------------- // For NSTableViewDataSource func numberOfRows(in tableView: NSTableView) -> Int { if let mgr = profileMgr { return mgr.profiles.count } return 0 } //-------------------------------------------------- // For NSTableViewDelegate func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { let colId = NSUserInterfaceItemIdentifier(rawValue: "cellTitle") if let cell = tableView.makeView(withIdentifier: colId, owner: self) as? NSTableCellView { cell.textField?.stringValue = getDataAtRow(row) return cell } return nil } func tableViewSelectionDidChange(_ notification: Notification) { if profilesTableView.selectedRow >= 0 { let profile = getSelectedProfile() if profile.isValid(), let url = profile.URL() { let img = createQRImage(url.absoluteString, NSMakeSize(250, 250)) qrCodeImageView.image = img copyURLButton.isEnabled = true copyQRCodeButton.isEnabled = true saveQRCodeAsFileButton.isEnabled = true return } } qrCodeImageView.image = nil copyURLButton.isEnabled = false copyQRCodeButton.isEnabled = false saveQRCodeAsFileButton.isEnabled = false } }
gpl-3.0
4366c3544f2be42f874dcde5e038e144
34.910526
104
0.596219
5.272798
false
false
false
false
insidegui/AppleEvents
Dependencies/ChromeCastCore/ChromeCastCore/CastMediaStatus.swift
1
1412
// // CastMediaStatus.swift // ChromeCastCore // // Created by Guilherme Rambo on 21/10/16. // Copyright © 2016 Guilherme Rambo. All rights reserved. // import Foundation public enum CastMediaPlayerState: String, Codable { case idle = "IDLE" case buffering = "BUFFERING" case playing = "PLAYING" case paused = "PAUSED" case stopped = "STOPPED" } final class CastMediaStatusPayload: NSObject, Codable { var type: CastMessageType = CastMessageType.mediaStatus var requestId: Int? var mediaStatus: [CastMediaStatus]? enum CodingKeys: String, CodingKey { case type case requestId case mediaStatus = "status" } } @objcMembers public final class CastMediaStatus: NSObject, Codable { public var mediaSessionId: Int = 0 public var playbackRate: Int = 1 public var playerState: CastMediaPlayerState? = .buffering public var currentTime: Double = 0 public var state: String? { return playerState?.rawValue } public override var description: String { return "MediaStatus(mediaSessionId: \(mediaSessionId), playbackRate: \(playbackRate), playerState: \(String(describing: playerState)), currentTime: \(currentTime))" } public enum CodingKeys: String, CodingKey { case mediaSessionId case playbackRate case playerState case currentTime } }
bsd-2-clause
832978678df43b35dba0cea6c25f4c77
24.654545
172
0.677534
4.522436
false
false
false
false
plivesey/SwiftGen
Pods/Commander/Sources/CommandRunner.swift
3
1326
#if os(Linux) import Glibc #else import Darwin.libc #endif /// Extensions to CommandType to provide convinience running methods for CLI tools extension CommandType { /// Run the command using the `Process.argument`, removing the executable name public func run(_ version:String? = nil) -> Never { let parser = ArgumentParser(arguments: CommandLine.arguments) if parser.hasOption("version") && !parser.hasOption("help") { if let version = version { print(version) exit(0) } } let executableName = parser.shift()! // Executable Name do { try run(parser) } catch let error as Help { let help = error.reraise("$ \(executableName)") help.print() exit(1) } catch GroupError.noCommand(let path, let group) { var usage = "$ \(executableName)" if let path = path { usage += " \(path)" } let help = Help([], command: usage, group: group) help.print() exit(1) } catch let error as ANSIConvertible { error.print() exit(1) } catch let error as CustomStringConvertible { fputs("\(ANSI.red)\(error.description)\(ANSI.reset)\n", stderr) exit(1) } catch { fputs("\(ANSI.red)Unknown error occurred.\(ANSI.reset)\n", stderr) exit(1) } exit(0) } }
mit
5309d5541de27bd0b408b73b5564b5db
25.52
82
0.607843
4.018182
false
false
false
false
galv/reddift
reddift/Network/Session+CAPTCHA.swift
1
6555
// // Session+CAPTCHA.swift // reddift // // Created by sonson on 2015/05/19. // Copyright (c) 2015年 sonson. All rights reserved. // import Foundation #if os(iOS) import UIKit public typealias CAPTCHAImage = UIImage #elseif os(OSX) import Cocoa public typealias CAPTCHAImage = NSImage #endif /** Parse simple string response for "/api/needs_captcha" - parameter data: Binary data is returned from reddit. - returns: Result object. If data is "true" or "false", Result object has boolean, otherwise error object. */ func data2Bool(data: NSData) -> Result<Bool> { let decoded = NSString(data:data, encoding:NSUTF8StringEncoding) if let decoded = decoded { if decoded == "true" { return Result(value:true) } else if decoded == "false" { return Result(value:false) } } return Result(error:ReddiftError.CheckNeedsCAPTHCA.error) } /** Parse simple string response for "/api/needs_captcha" - parameter data: Binary data is returned from reddit. - returns: Result object. If data is "true" or "false", Result object has boolean, otherwise error object. */ func data2Image(data: NSData) -> Result<CAPTCHAImage> { #if os(iOS) let captcha = UIImage(data: data) #elseif os(OSX) let captcha = NSImage(data: data) #endif return resultFromOptional(captcha, error: ReddiftError.GetCAPTCHAImage.error) } /** Parse JSON contains "iden" for CAPTHA. {"json": {"data": {"iden": "<code>"},"errors": []}} - parameter json: JSON object, like above sample. - returns: Result object. When parsing is succeeded, object contains iden as String. */ func idenJSON2String(json: JSON) -> Result<String> { if let json = json as? JSONDictionary { if let j = json["json"] as? JSONDictionary { if let data = j["data"] as? JSONDictionary { if let iden = data["iden"] as? String { return Result(value:iden) } } } } return Result(error:ReddiftError.GetCAPTCHAIden.error) } extension Session { /** Check whether CAPTCHAs are needed for API methods that define the "captcha" and "iden" parameters. - parameter completion: The completion handler to call when the load request is complete. - returns: Data task which requests search to reddit.com. */ public func checkNeedsCAPTCHA(completion:(Result<Bool>) -> Void) -> NSURLSessionDataTask? { guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/needs_captcha", method:"GET", token:token) else { return nil } let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in self.updateRateLimitWithURLResponse(response) let result = resultFromOptionalError(Response(data: data, urlResponse: response), optionalError:error) .flatMap(response2Data) .flatMap(data2Bool) completion(result) }) task.resume() return task } /** Responds with an iden of a new CAPTCHA. Use this endpoint if a user cannot read a given CAPTCHA, and wishes to receive a new CAPTCHA. To request the CAPTCHA image for an iden, use /captcha/iden. - parameter completion: The completion handler to call when the load request is complete. - returns: Data task which requests search to reddit.com. */ public func getIdenForNewCAPTCHA(completion:(Result<String>) -> Void) -> NSURLSessionDataTask? { let parameter:[String:String] = ["api_type":"json"] guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/api/new_captcha", parameter:parameter, method:"POST", token:token) else { return nil } let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in self.updateRateLimitWithURLResponse(response) let result = resultFromOptionalError(Response(data: data, urlResponse: response), optionalError:error) .flatMap(response2Data) .flatMap(data2Json) .flatMap(idenJSON2String) completion(result) }) task.resume() return task } /** Request a CAPTCHA image for given an iden. An iden is given as the captcha field with a BAD_CAPTCHA error, you should use this endpoint if you get a BAD_CAPTCHA error response. Responds with a 120x50 image/png which should be displayed to the user. The user's response to the CAPTCHA should be sent as captcha along with your request. To request a new CAPTCHA, Session.getIdenForNewCAPTCHA. - parameter iden: Code to get a new CAPTCHA. Use Session.getIdenForNewCAPTCHA. - parameter completion: The completion handler to call when the load request is complete. - returns: Data task which requests search to reddit.com. */ public func getCAPTCHA(iden:String, completion:(Result<CAPTCHAImage>) -> Void) -> NSURLSessionDataTask? { guard let request = NSMutableURLRequest.mutableOAuthRequestWithBaseURL(baseURL, path:"/captcha/" + iden, method:"GET", token:token) else { return nil } let task = URLSession.dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in self.updateRateLimitWithURLResponse(response) let result = resultFromOptionalError(Response(data: data, urlResponse: response), optionalError:error) .flatMap(response2Data) .flatMap(data2Image) completion(result) }) task.resume() return task } /** Request a CAPTCHA image Responds with a 120x50 image/png which should be displayed to the user. The user's response to the CAPTCHA should be sent as captcha along with your request. - parameter completion: The completion handler to call when the load request is complete. - returns: Data task which requests search to reddit.com. */ public func getCAPTCHA(completion:(Result<CAPTCHAImage>) -> Void) -> NSURLSessionDataTask? { return getIdenForNewCAPTCHA { (result) -> Void in switch result { case .Failure(let error): print(error.description) case .Success(let iden): self.getCAPTCHA(iden, completion:completion) } } } }
mit
5dab0108b6bf78a666d449c71c9f7716
39.9625
181
0.670533
4.397987
false
false
false
false
eduresende/ios-nd-swift-syntax-swift-3
Lesson2/L2_Exercises.playground/Contents.swift
1
3153
import UIKit //: # Lesson 2 Exercises //: ## Optionals //: ### Exercise 1 //: When retrieving a value from a dictionary, Swift returns an optional. //: //: 1a) The variable, director, is an optional type. Its value cannot be used until it is unwrapped. Use `if let` to carefully unwrap the value returned by `moviesDict[movie]` var moviesDict:Dictionary = [ "Star Wars":"George Lucas", "Point Break":"Kathryn Bigelow"] var movie = "Point Break" var director = moviesDict[movie] //: 1b) Test your code by inserting different values for the variable `movie`. //: ### Exercise 2 //: The LoginViewController class below needs a UITextField to hold a user's name. Declare a variable for this text field as a property of the class LoginViewController. Keep in mind that the textfield property will not be initialized until after the view controller is constructed. class LoginViewController: UIViewController { } //: ### Exercise 3 //: The Swift Int type has an initializer that takes a string as a parameter and returns an optional of type Int?. //: //: 3a) Finish the code below by safely unwrapping the constant, `number`. var numericalString = "3" var number = Int(numericalString) //TODO: Unwrap number to make the following print statement more readable. print("\(number) is the magic number.") //: 3b) Change the value of numericalString to "three" and execute the playground again. //: ### Exercise 4 //: The class UIViewController has a property called tabBarController. The tabBarController property is an optional of type UITabBarController?. The tabBarController itself holds a tabBar as a property. Complete the code below by filling in the appropriate use of optional chaining to access the tab bar property. var viewController = UIViewController() //if let tabBar = //TODO: Optional chaining here { // print("Here's the tab bar.") //} else { // print("No tab bar controller found.") //} //: ### Exercise 5 //: Below is a dictionary of paintings and artists. //: //: 5a) The variable, artist, is an optional type. Its value cannot be used until it is unwrapped. Use `if let` to carefully unwrap the value returned by `paintingDict[painting]`. var paintingDict:Dictionary = [ "Guernica":"Picasso", "Mona Lisa": "da Vinci", "No. 5": "Pollock"] var painting = "Mona Lisa" var artist = paintingDict[painting] //: 5b) Test your code by inserting different values for the variable `painting`. //: ### Exercise 6 //: Set the width of the cancel button below. Notice that the cancelButton variable is declared as an implicitly unwrapped optional. var anotherViewController = UIViewController() var cancelButton: UIBarButtonItem! cancelButton = UIBarButtonItem() // TODO: Set the width of the cancel button. //: ### Exercise 7 //: The class UIViewController has a property called parentViewController. The parentViewController property is an optional of type UIViewController?. We can't always be sure that a given view controller has a parentViewController. Safely unwrap the parentViewController property below using if let. var childViewController = UIViewController() // TODO: Safely unwrap childViewController.parentViewController
mit
70fea01ee879a48ccd1c263a867baec0
53.362069
314
0.755471
4.51073
false
false
false
false
Railsreactor/json-data-sync-swift
JDSKit/Core/RegistryService.swift
1
8125
// // AbstractRegistryService.swift // JDSKit // // Created by Igor Reshetnikov on 3/2/16. // Copyright © 2016 RailsReactor. All rights reserved. // import UIKit open class AbstractRegistryService: NSObject { // Setup here your implementation of RegistryService open static var mainRegistryService: AbstractRegistryService! // JSON-API url string open var apiURLString: String { fatalError("Var 'apiURLString' should be overriden") } open var apiToken: String { fatalError("Var 'apiToken' should be overriden") } open var apiSecret: String { fatalError("Var 'apiSecret' should be overriden") } // Path to Core Data store file open var storeModelURL: URL { fatalError("Var 'storeModelURL' should be overriden") } // Path to Core Data Managed Object Model open var storeURL: URL { fatalError("Var 'storeURL' should be overriden") } // open func createRemoteManager() -> BaseJSONAPIManager { return BaseJSONAPIManager(urlString: "http://\(apiURLString)/", clientToken: apiToken, clientSecret: apiSecret) } open func createLocalManager() -> BaseDBService { return BaseDBService(modelURL: AbstractRegistryService.mainRegistryService.storeModelURL, storeURL: AbstractRegistryService.mainRegistryService.storeURL) } // ********************************************* Model ********************************************* // // Registered representations for models. WARNING! Model Protocol should be always the first one! // In most cases you only need to register your models and reps here. Other stuff like DB Gateways or JSON Manager will handle if out of the box. open var _modelRepresentations: [[ManagedEntity.Type]] { return [ [ManagedEntity.self, DummyManagedEntity.self, JSONManagedEntity.self, CDManagedEntity.self], [Attachment.self, DummyAttachment.self, JSONAttachment.self, CDAttachment.self], [Event.self, JSONEvent.self] ] } // ********************************************* Services ********************************************* // // List of predefined enitity services. open var _predefinedEntityServices: [String: EntityService] { return [ String(describing: Attachment.self) : AttachmentService() ] } internal var _sharedEntityServices: [String: EntityService] = [:] // This function returns registered entity service or creates GenericService for requested entity type open func entityService<T: ManagedEntity>() -> GenericService<T> { let key = String(describing: T.self) var service = (_sharedEntityServices[key]) as? GenericService<T> if service == nil { service = GenericService<T>() _sharedEntityServices[key] = service } return service! } open func entityService(_ type: ManagedEntity.Type) -> EntityService { let key = String(describing: type) var service = _sharedEntityServices[key] if service == nil { service = EntityService(entityType: type) _sharedEntityServices[key] = service } return service! } open func entityServiceByKey(_ key: String) -> EntityService { return entityService(ExtractModel(key)) } internal func performServiceIndexation() { for (key, service) in _predefinedEntityServices { _sharedEntityServices[key] = service } } // ****************************************** EntityGateways ************************************************** // // List of predefined entity gateways. Other gateways will be dynamycaly initialized when requested. open var _predefinedEntityGateways: [GenericEntityGateway] { return [ LinkableEntitiyGateway(CDAttachment.self) ] } // ************************************************************************************************************ // internal func performRepresentationsIndexation() { for modelReps in _modelRepresentations { for i in 1 ... modelReps.count-1 { _ = RegisterRepresenation(modelReps.first!, repType: modelReps[i]) } } } public override init() { super.init() if AbstractRegistryService.mainRegistryService == nil { AbstractRegistryService.mainRegistryService = self } performRepresentationsIndexation() performServiceIndexation() } } class ModelRegistry: NSObject { static let sharedRegistry = ModelRegistry() var registeredModelByType = [String : ManagedEntity.Type]() var registeredModelByKey = [String : ManagedEntity.Type]() var registeredKeyByModel = [String : String]() var registeredModelByRep = [String : ManagedEntity.Type]() var registeredRepsByModel = [String : [ManagedEntity.Type]]() func register(_ modelType: ManagedEntity.Type, key inKey: String? = nil) -> Bool { let key = inKey ?? String(describing: modelType) let typeKey = String(describing: modelType) registeredModelByType[typeKey] = modelType registeredKeyByModel[typeKey] = key registeredModelByKey[key] = modelType return true } func registerRep(_ modelType: ManagedEntity.Type, repType: ManagedEntity.Type, modelKey: String?=nil) -> Bool { let typeKey = String(describing: modelType) if registeredModelByType[typeKey] == nil { _ = register(modelType, key: modelKey) } registeredModelByRep[String(describing: repType)] = modelType if registeredRepsByModel[typeKey] == nil { registeredRepsByModel[typeKey] = [ManagedEntity.Type]() } registeredRepsByModel[typeKey]! += [repType] return true } func extractModel(_ repType: ManagedEntity.Type) -> ManagedEntity.Type { let key = String(describing: repType) if registeredRepsByModel[key] != nil { return repType } return registeredModelByRep[key]! } func extractModelByKey(_ key: String) -> ManagedEntity.Type { return registeredModelByKey[key]! } func extractRep<R>(_ modelType: ManagedEntity.Type, subclassOf: R.Type?=nil) -> ManagedEntity.Type { let key = String(describing: modelType) let reps: [ManagedEntity.Type] = registeredRepsByModel[key]! if subclassOf != nil { for repClass in reps { if let _ = repClass as? R.Type { return repClass } } } return reps.first! } func extractAllReps<R>(_ subclassOf: R.Type) -> [ManagedEntity.Type] { var result = [ManagedEntity.Type]() for (_, reps) in registeredRepsByModel { for repClass in reps { if let _ = repClass as? R.Type { result.append(repClass) } } } return result } } func RegisterRepresenation(_ modelType: ManagedEntity.Type, repType: ManagedEntity.Type) -> Bool { return ModelRegistry.sharedRegistry.registerRep(modelType, repType: repType) } func ExtractModel(_ repType: ManagedEntity.Type) -> ManagedEntity.Type { return ModelRegistry.sharedRegistry.extractModel(repType) } func ExtractModel(_ key: String) -> ManagedEntity.Type { return ModelRegistry.sharedRegistry.extractModelByKey(key) } func ExtractRep<R>(_ modelType: ManagedEntity.Type, subclassOf: R.Type?=nil) -> ManagedEntity.Type { return ModelRegistry.sharedRegistry.extractRep(modelType, subclassOf: subclassOf) } func ExtractAllReps<R>(_ subclassOf: R.Type) -> [ManagedEntity.Type] { return ModelRegistry.sharedRegistry.extractAllReps(subclassOf) }
mit
50072d529a40629282ce0ad280b6237c
34.321739
161
0.601551
4.764809
false
false
false
false
llxyls/DYTV
DYTV/DYTV/Classes/Tools/Common.swift
1
326
// // Common.swift // DYTV // // Created by liuqi on 16/10/9. // Copyright © 2016年 liuqi. All rights reserved. // import UIKit let kStatusBarH : CGFloat = 20 let kNavigationBarH : CGFloat = 44 let kTabBarH : CGFloat = 44 let kScreenW = UIScreen.main.bounds.size.width let kScreenH = UIScreen.main.bounds.size.height
mit
e047a5b011cbf492fb6fd48a736b4dd4
19.1875
49
0.712074
3.329897
false
false
false
false
gokselkoksal/Lightning
Lightning/Sources/Components/CollectionChange.swift
1
4908
// // CollectionChange.swift // Lightning // // Created by Göksel Köksal on 19/11/2016. // Copyright © 2016 GK. All rights reserved. // import Foundation /// Represents a change in a collection like table view, array, etc. /// /// - reload: Data source got reloaded. /// - update: Data source updated given index path set. /// - insertion: Data source inserted new items at given index path set. /// - deletion: Data source deleted items from given index path set. /// - move: Data source moved items from index path to another index path. /// /// `IndexPathSetConvertible` lets you construct the `CollectionChange` however you want. /// /// Some constructor examples: /// ``` /// // Using `Int`, `UInt` or `IndexPath`: /// CollectionChange.insertion(Int(2)) /// CollectionChange.insertion(UInt(1)) /// CollectionChange.insertion(IndexPath(row: 1, section: 0)) /// CollectionChange.move(from: 0, to: 1) /// CollectionChange.move(from: IndexPath(row: 0, section: 0), to: IndexPath(row: 1, section: 0)) /// // Using `IndexSet`: /// CollectionChange.insertion(IndexSet(arrayLiteral: 1, 2, 3)) /// // Using `Array`: /// CollectionChange.insertion([1, 2, 3]) /// CollectionChange.insertion([IndexPath(row: 0, section: 0), IndexPath(row: 1, section: 0)]) /// // Using `Set`: /// CollectionChange.insertion(Set(arrayLiteral: 1, 2, 3)) /// CollectionChange.insertion(Set(arrayLiteral: IndexPath(row: 0, section: 0), IndexPath(row: 1, section: 0))) /// ``` /// /// Example 1: /// ``` /// let change = CollectionChange.insertion(1) /// /// switch change { /// case .insertion(let indexes): /// for indexPath in indexes.asIndexPathSet() { /// print("\(indexPath)") // Prints "[1]" /// print("\(indexPath.first)") // Prints "Optional(1)" /// } /// default: /// break /// } /// ``` /// /// Example 2: /// ``` /// let indexPath = IndexPath(row: 1, section: 0) /// let change = CollectionChange.insertion(indexPath) /// /// switch change { /// case .insertion(let indexes): /// for indexPath in indexes.asIndexPathSet() { /// print("\(indexPath)") // Prints "[0, 1]" /// } /// default: /// break /// } /// ``` public enum CollectionChange { case reload case update(IndexPathSetConvertible) case insertion(IndexPathSetConvertible) case deletion(IndexPathSetConvertible) case move(from: IndexPathConvertible, to: IndexPathConvertible) } // MARK: - IndexPathConvertible /// Anything that is convertible to an index path. public protocol IndexPathConvertible { func asIndexPath() -> IndexPath } extension IndexPath: IndexPathConvertible { public func asIndexPath() -> IndexPath { return self } } extension UInt: IndexPathConvertible { public func asIndexPath() -> IndexPath { return IndexPath(index: Int(self)) } } extension Int: IndexPathConvertible { public func asIndexPath() -> IndexPath { return IndexPath(index: self) } } // MARK: - IndexPathSetConvertible /// Anything that is convertible to an index path set. public protocol IndexPathSetConvertible { func asIndexPathSet() -> Set<IndexPath> } extension Array: IndexPathSetConvertible where Element: IndexPathConvertible { public func asIndexPathSet() -> Set<IndexPath> { return Set<IndexPath>(self.map({ $0.asIndexPath() })) } } extension Set: IndexPathSetConvertible where Element: IndexPathConvertible { public func asIndexPathSet() -> Set<IndexPath> { return Set<IndexPath>(self.map({ $0.asIndexPath() })) } } extension IndexSet: IndexPathSetConvertible { public func asIndexPathSet() -> Set<IndexPath> { return Set<IndexPath>(self.map({ $0.asIndexPath() })) } } extension IndexPath: IndexPathSetConvertible { public func asIndexPathSet() -> Set<IndexPath> { return Set<IndexPath>(arrayLiteral: self.asIndexPath()) } } extension Int: IndexPathSetConvertible { public func asIndexPathSet() -> Set<IndexPath> { return Set<IndexPath>(arrayLiteral: self.asIndexPath()) } } extension UInt: IndexPathSetConvertible { public func asIndexPathSet() -> Set<IndexPath> { return Set<IndexPath>(arrayLiteral: self.asIndexPath()) } } // MARK: Equatable extension CollectionChange: Equatable { public static func ==(lhs: CollectionChange, rhs: CollectionChange) -> Bool { switch (lhs, rhs) { case (.reload, .reload): return true case (.insertion(let indexes1), .insertion(let indexes2)): return indexes1.asIndexPathSet() == indexes2.asIndexPathSet() case (.deletion(let indexes1), .deletion(let indexes2)): return indexes1.asIndexPathSet() == indexes2.asIndexPathSet() case (.update(let indexes1), .update(let indexes2)): return indexes1.asIndexPathSet() == indexes2.asIndexPathSet() case (.move(let from1, let to1), .move(let from2, let to2)): return from1.asIndexPath() == from2.asIndexPath() && to1.asIndexPath() == to2.asIndexPath() default: return false } } }
mit
06cd13bf22e75552b9f991f9c9d21f04
28.908537
111
0.686442
3.892857
false
false
false
false
thedistance/TheDistanceCore
TDCore/Classes/ParallaxScrollable.swift
1
7286
// // ParallaxScrollable.swift // TDCore // // Created by Josh Campion on 02/11/2015. // Copyright © 2015 The Distance. All rights reserved. // import UIKit /** Protocol extending `UIScrollViewDelegate` to adjust the scrolling of a given view to mimic a parallax motion between the two views. Default implementations are given for `parallaxScrollViewDidScroll(_:)` on all adopters, and for `configureParallaxScrollInset(_:)` for `UIViewController`s. */ public protocol ParallaxScrollable: UIScrollViewDelegate { /// The reference view that the `UIScrollView` will scroll over, whose position is adjusted on scrolling the `UIScrollView`. var parallaxHeaderView: UIView! { get } /// The `UIScrollView` whose offset drives the parallax motion of the `headerView`. var parallaxScrollView: UIScrollView! { get set } /// The mask applied to the `parallaxHeaderView` that provides clipping of `parallaxHeaderView` if the content of a `parallaxScrollView` is short enough for the `parallaxHeaderView` to be visible underneath the scrollable content. var parallaxHeaderMask: CAShapeLayer { get } /// The parallax motion of the `headerView` is implemented by setting the `constant` property of this constraint. var parallaxHeaderViewTopConstraint : NSLayoutConstraint! { get set } /// Should set the `contentInset` of the `parallaxScrollView` to allow the `headerView` to be seen above the content of `parallaxScrollView`. func configureParallaxScrollInset(_ minimumHeight:CGFloat) /// Should update `headerViewTopConstraint.constant` to mimic a parallax motion. With the given parameter. A default implementation is given. func parallaxScrollViewDidScroll(_ scrollView:UIScrollView, scrollRate:CGFloat, bouncesHeader:Bool, maskingHeader:Bool) } public extension ParallaxScrollable where Self:UIViewController { /// - returns: The intersection of `the bottomLayoutGuide` and `parallaxScrollView` in the frame of `parallaxScrollView.superview`. public func parallaxBottomOverlap() -> CGRect { guard let superview = parallaxScrollView.superview else { return CGRect.zero } let bottomInView = CGRect(x: 0, y: view.frame.size.height - bottomLayoutGuide.length, width: view.frame.size.width, height: bottomLayoutGuide.length) let bottomInSuper = superview.convert(bottomInView, from: view) let intersection = parallaxScrollView.frame.intersection(bottomInSuper) return intersection.integral } /** Default implementation of `configureParallaxScrollInset(_:)` for `UIViewController`s. Sets the content inset of `parallaxScrollView` to allow the `headerView` to be fully visible above the content of the `parallaxScrollView`. The bottom inset of the `parallaxScrollView` is adjusted to allow the content to be visible above the `bottomLayoutGuide`. This will typically by called from `viewDidLayoutSubviews()`, to reset the `contentInset` as the size of other content changes. `headerOverlap()` and `bottomOverlap()` are used to calculate the necessary values. - parameter miniumHeight: The maximum of this and the value necessary for `headerView` to be fully visible above the content of the `parallaxScrollView` is the value assigned to `contentInset.top` on the `parallaxScrollView`. */ public func configureParallaxScrollInset(_ minimumHeight:CGFloat = 0) { let intersect = parallaxHeaderView.frame // parallaxHeaderOverlap() let topInset = max(intersect.size.height, minimumHeight) if parallaxScrollView.contentInset.top != topInset { var newInsets = parallaxScrollView.contentInset newInsets.top = topInset parallaxScrollView.contentInset = newInsets } // bottom inset is only increased, not set so that the content is visible over the bottom layout guide but the inset isn't decreased for things such as a keyboard being onscreen. let bottomIntersect = parallaxBottomOverlap() let bottomInset = max(0, bottomIntersect.size.height) if parallaxScrollView.contentInset.bottom <= bottomInset { var insets = parallaxScrollView.contentInset insets.bottom = bottomInset parallaxScrollView.contentInset = insets } updateParallaxHeaderMask() } } public extension ParallaxScrollable { /// - returns: The intersection of `headerView` and `parallaxScrollView` in the frame of `parallaxScrollView.superview`. public func parallaxHeaderOverlap() -> CGRect { guard let superview = parallaxScrollView.superview else { return CGRect.zero } let headerInSuper = superview.convert(parallaxHeaderView.frame, from: parallaxHeaderView.superview) let intersection = parallaxScrollView.frame.intersection(headerInSuper) return intersection.integral } /** Default implementation for parallax scrolling a header view. Typically this will be called from `scrollViewDidScroll:`. - parameter scrollView: The `UIScrollView` that has scrolled. - parameter scrollRate: The factor to mulitply the amount `scrollView` has scrolled by to get the parallax scroll amount. The default is 0.5. - parameter bouncesHeader: Flag to determine whether `headerView` should 'bounce' when `parallaxScrollView` bounces. This is achieved by setting negative values for `headerViewTopConstraint.constant`. The default value is `false`. - parameter maskingHeader: Flag to determine whether `headerView` should be masked by `parallaxScrollView`'s `contentOffset`. The default value is `true`. */ public func parallaxScrollViewDidScroll(_ scrollView:UIScrollView, scrollRate:CGFloat = 0.5, bouncesHeader:Bool = false, maskingHeader:Bool = true) { if scrollView == parallaxScrollView { let offset = scrollView.contentOffset.y + scrollView.contentInset.top let upScroll = bouncesHeader ? offset : max(offset, 0) var headerTop = scrollRate * upScroll headerTop = -floor(headerTop) if parallaxHeaderViewTopConstraint.constant != headerTop { parallaxHeaderViewTopConstraint.constant = headerTop } updateParallaxHeaderMask() } } /// Updates `parallaxHeaderMask` to clip the `parallaxHeaderView`, preventing it being seen beneath short content. public func updateParallaxHeaderMask() { // mask the header view by the scroll view let absOffset = -parallaxHeaderViewTopConstraint.constant let headerSize = parallaxHeaderView.frame.size let visibleRect = CGRect(x: 0, y: absOffset, width: headerSize.width, height: headerSize.height - 2.0 * absOffset) parallaxHeaderMask.frame = parallaxHeaderView.bounds parallaxHeaderMask.path = UIBezierPath(rect: visibleRect).cgPath parallaxHeaderMask.fillColor = UIColor.black.cgColor if parallaxHeaderView.layer.mask == nil { parallaxHeaderView.layer.mask = parallaxHeaderMask } } }
mit
bd38dd45ec5985b5857e793635c11249
50.302817
395
0.713109
5.271346
false
false
false
false
jianwoo/WordPress-iOS
WordPress/Classes/ViewRelated/Notifications/RichTextView/RichTextView.swift
1
8802
import Foundation @objc public protocol RichTextViewDataSource { optional func textView(textView: UITextView, viewForTextAttachment attachment: NSTextAttachment) -> UIView? } @objc public protocol RichTextViewDelegate : UITextViewDelegate { optional func textView(textView: UITextView, didPressLink link: NSURL) } @objc public class RichTextView : UIView, UITextViewDelegate { public var dataSource: RichTextViewDataSource? public var delegate: RichTextViewDelegate? // MARK: - Initializers public override init() { super.init() setupSubviews() } public override init(frame: CGRect) { super.init(frame: frame) setupSubviews() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSubviews() } // MARK: - Properties public var contentInset: UIEdgeInsets { set { textView.contentInset = newValue } get { return textView.contentInset } } public var textContainerInset: UIEdgeInsets { set { textView.textContainerInset = newValue } get { return textView.textContainerInset } } public var attributedText: NSAttributedString! { set { textView.attributedText = newValue renderAttachments() } get { return textView.attributedText } } public var editable: Bool { set { textView.editable = newValue } get { return textView.editable } } public var selectable: Bool { set { textView.selectable = newValue } get { return textView.selectable } } public var dataDetectorTypes: UIDataDetectorTypes { set { textView.dataDetectorTypes = newValue } get { return textView.dataDetectorTypes } } public override var backgroundColor: UIColor? { didSet { textView?.backgroundColor = backgroundColor } } public var linkTextAttributes: [NSObject : AnyObject]! { set { textView.linkTextAttributes = newValue } get { return textView.linkTextAttributes } } // MARK: - TextKit Getters public var layoutManager: NSLayoutManager { get { return textView.layoutManager } } public var textStorage: NSTextStorage { get { return textView.textStorage } } public var textContainer: NSTextContainer { get { return textView.textContainer } } // MARK: - Autolayout Helpers public var preferredMaxLayoutWidth: CGFloat = 0 { didSet { invalidateIntrinsicContentSize() } } public override func intrinsicContentSize() -> CGSize { // Fix: Let's add 1pt extra size. There are few scenarios in which text gets clipped by 1 point let bottomPadding = CGFloat(1) let maxWidth = (preferredMaxLayoutWidth != 0) ? preferredMaxLayoutWidth : frame.width let maxSize = CGSize(width: maxWidth, height: CGFloat.max) let requiredSize = textView!.sizeThatFits(maxSize) let roundedSize = CGSize(width: ceil(requiredSize.width), height: ceil(requiredSize.height) + bottomPadding) return roundedSize } // MARK: - Private Methods private func setupSubviews() { gesturesRecognizer = UITapGestureRecognizer() gesturesRecognizer.addTarget(self, action: "handleTextViewTap:") textView = UITextView(frame: bounds) textView.backgroundColor = backgroundColor textView.contentInset = UIEdgeInsetsZero textView.textContainerInset = UIEdgeInsetsZero textView.textContainer.lineFragmentPadding = 0 textView.layoutManager.allowsNonContiguousLayout = false textView.editable = editable textView.dataDetectorTypes = dataDetectorTypes textView.delegate = self textView.gestureRecognizers = [gesturesRecognizer] addSubview(textView) // Setup Layout textView.setTranslatesAutoresizingMaskIntoConstraints(false) pinSubviewToAllEdges(textView) } private func renderAttachments() { // Nuke old attachments attachmentViews.map { $0.removeFromSuperview() } attachmentViews.removeAll(keepCapacity: false) // Proceed only if needed if attributedText == nil { return } // Load new attachments attributedText.enumerateAttachments { (attachment: NSTextAttachment, range: NSRange) -> () in let attachmentView = self.dataSource?.textView?(self.textView, viewForTextAttachment: attachment) if attachmentView == nil { return } let unwrappedView = attachmentView! unwrappedView.frame.origin = self.textView.frameForTextInRange(range).integerRect.origin self.textView.addSubview(unwrappedView) self.attachmentViews.append(unwrappedView) } } // MARK: - UITapGestureRecognizer Helpers public func handleTextViewTap(recognizer: UITapGestureRecognizer) { // NOTE: Why do we need this? // Because this mechanism allows us to disable DataDetectors, and yet, detect taps on links. // let textStorage = textView.textStorage let layoutManager = textView.layoutManager let textContainer = textView.textContainer let locationInTextView = recognizer.locationInView(textView) let characterIndex = layoutManager.characterIndexForPoint(locationInTextView, inTextContainer: textContainer, fractionOfDistanceBetweenInsertionPoints: nil) if characterIndex >= textStorage.length { return } // Load the NSURL instance, if any let rawURL = textStorage.attribute(NSLinkAttributeName, atIndex: characterIndex, effectiveRange: nil) as? NSURL if let unwrappedURL = rawURL { delegate?.textView?(textView, didPressLink: unwrappedURL) } } // MARK: - UITextViewDelegate Wrapped Methods public func textViewShouldBeginEditing(textView: UITextView) -> Bool { return delegate?.textViewShouldBeginEditing?(textView) ?? true } public func textViewShouldEndEditing(textView: UITextView) -> Bool { return delegate?.textViewShouldEndEditing?(textView) ?? true } public func textViewDidBeginEditing(textView: UITextView) { delegate?.textViewDidBeginEditing?(textView) } public func textViewDidEndEditing(textView: UITextView) { delegate?.textViewDidEndEditing?(textView) } public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { return delegate?.textView?(textView, shouldChangeTextInRange: range, replacementText: text) ?? true } public func textViewDidChange(textView: UITextView) { delegate?.textViewDidChange?(textView) } public func textViewDidChangeSelection(textView: UITextView) { delegate?.textViewDidChangeSelection?(textView) } public func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { return delegate?.textView?(textView, shouldInteractWithURL: URL, inRange: characterRange) ?? true } public func textView(textView: UITextView, shouldInteractWithTextAttachment textAttachment: NSTextAttachment, inRange characterRange: NSRange) -> Bool { return delegate?.textView?(textView, shouldInteractWithTextAttachment: textAttachment, inRange: characterRange) ?? true } // MARK: - Private Properites private var textView: UITextView! private var gesturesRecognizer: UITapGestureRecognizer! private var attachmentViews: [UIView] = [] }
gpl-2.0
c92f19b4bc881ba337d37b36c087d804
31.966292
156
0.601454
6.194229
false
false
false
false
benlangmuir/swift
test/decl/protocol/override.swift
19
3718
// RUN: %target-typecheck-verify-swift -dump-ast > %t.ast // RUN: %FileCheck %s < %t.ast // Test overriding of protocol members. // CHECK: protocol{{.*}}"P0" protocol P0 { associatedtype A // expected-note@+1{{potential overridden instance method 'foo()' here}} func foo() // expected-note@+1{{attempt to override property here}} var prop: A { get } } // CHECK: protocol{{.*}}"P1" protocol P1: P0 { // CHECK: associated_type_decl // CHECK-SAME: overridden=P0 associatedtype A // CHECK: func_decl{{.*}}foo(){{.*}}Self : P1{{.*}}override={{.*}}P0.foo func foo() // CHECK: var_decl // CHECK-SAME: "prop" // CHECK-SAME: override=override.(file).P0.prop var prop: A { get } } // CHECK: protocol{{.*}}"P2" protocol P2 { associatedtype A func foo() var prop: A { get } } // CHECK: protocol{{.*}}"P3" protocol P3: P1, P2 { // CHECK: associated_type_decl // CHECK-SAME: "A" // CHECK-SAME: override=override.(file).P1.A // CHECK-SAME: override.(file).P2.A associatedtype A // CHECK: func_decl{{.*}}foo(){{.*}}Self : P3{{.*}}override={{.*}}P2.foo{{.*,.*}}P1.foo func foo() // CHECK: var_decl // CHECK-SAME: "prop" // CHECK-SAME: override=override.(file).P2.prop // CHECK-SAME: override.(file).P1.prop var prop: A { get } } // CHECK: protocol{{.*}}"P4" protocol P4: P0 { // CHECK: func_decl{{.*}}foo(){{.*}}Self : P4 // CHECK-NOT: override= // CHECK-SAME: ) func foo() -> Int // CHECK: var_decl // CHECK-SAME: "prop" // CHECK-NOT: override= // CHECK-SAME: immutable var prop: Int { get } } // CHECK: protocol{{.*}}"P5" protocol P5: P0 where Self.A == Int { // CHECK: func_decl{{.*}}foo(){{.*}}Self : P5 // CHECK-NOT: override= // CHECK-SAME: ) func foo() -> Int // CHECK: var_decl // CHECK-SAME: "prop" // CHECK-SAME: override=override.(file).P0.prop var prop: Int { get } } // Allow the 'override' keyword on protocol members (it is not required). // CHECK: protocol{{.*}}"P6" protocol P6: P0 { // CHECK: func_decl{{.*}}foo(){{.*}}Self : P6{{.*}}override={{.*}}P0.foo override func foo() // CHECK: var_decl // CHECK-SAME: "prop" // CHECK-SAME: override=override.(file).P0.prop override var prop: A { get } } // Complain if 'override' is present but there is no overridden declaration. protocol P7: P0 { // expected-error@+1{{method does not override any method from its parent protocol}} override func foo() -> Int // expected-error@+1{{property 'prop' with type 'Int' cannot override a property with type 'Self.A'}} override var prop: Int { get } } // Suppress overrides. // CHECK: protocol{{.*}}"P8" protocol P8: P0 { // CHECK: associated_type_decl // CHECK-SAME: "A" // CHECK-NOT: override // CHECK-SAME: ) @_nonoverride associatedtype A // CHECK: func_decl{{.*}}foo(){{.*}}Self : P8 // CHECK-NOT: override= // CHECK-SAME: ) @_nonoverride func foo() // CHECK: var_decl // CHECK-SAME: "prop" // CHECK-NOT: override= // CHECK-SAME: immutable @_nonoverride var prop: A { get } } class Base { } class Derived : Base { } // Protocol overrides require exact type matches. protocol SubtypingP0 { init?() func foo() -> Base } // CHECK: protocol{{.*}}"SubtypingP1" protocol SubtypingP1: SubtypingP0 { // CHECK: constructor_decl{{.*}}Self : SubtypingP1 // CHECK-NOT: override= // CHECK-SAME: designated init() // CHECK: func_decl{{.*}}foo(){{.*}}Self : SubtypingP1 // CHECK-NOT: override= // CHECK-SAME: ) func foo() -> Derived } // CHECK: protocol{{.*}}"SubtypingP2" protocol SubtypingP2: SubtypingP0 { // CHECK: constructor_decl{{.*}}Self : SubtypingP2 // CHECK: override={{.*}}SubtypingP0.init // CHECK-SAME: designated init?() }
apache-2.0
3d98906b421f0dcfa8b8edf32b16b13a
22.383648
103
0.61135
3.272887
false
false
false
false
groue/GRDB.swift
Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS/AppDatabase.swift
1
4552
import GRDB /// AppDatabase lets the application access the database. /// /// It applies the pratices recommended at /// <https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md> final class AppDatabase { /// Creates an `AppDatabase`, and make sure the database schema is ready. init(_ dbWriter: any DatabaseWriter) throws { self.dbWriter = dbWriter try migrator.migrate(dbWriter) } /// Provides access to the database. /// /// Application can use a `DatabasePool`, and tests can use a fast /// in-memory `DatabaseQueue`. /// /// See <https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections> private let dbWriter: any DatabaseWriter /// The DatabaseMigrator that defines the database schema. /// /// See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations> private var migrator: DatabaseMigrator { var migrator = DatabaseMigrator() #if DEBUG // Speed up development by nuking the database when migrations change // See <https://swiftpackageindex.com/groue/grdb.swift/documentation/grdb/migrations> migrator.eraseDatabaseOnSchemaChange = true #endif migrator.registerMigration("createPlayer") { db in // Create a table // See https://github.com/groue/GRDB.swift#create-tables try db.create(table: "player") { t in t.autoIncrementedPrimaryKey("id") t.column("name", .text).notNull() t.column("score", .integer).notNull() } } // Migrations for future application versions will be inserted here: // migrator.registerMigration(...) { db in // ... // } return migrator } } // MARK: - Database Access: Writes extension AppDatabase { /// Saves (inserts or updates) a player. When the method returns, the /// player is present in the database, and its id is not nil. func savePlayer(_ player: inout Player) throws { try dbWriter.write { db in try player.save(db) } } /// Delete the specified players func deletePlayers(ids: [Int64]) throws { try dbWriter.write { db in _ = try Player.deleteAll(db, ids: ids) } } /// Delete all players func deleteAllPlayers() throws { try dbWriter.write { db in _ = try Player.deleteAll(db) } } /// Refresh all players (by performing some random changes, for demo purpose). func refreshPlayers() throws { try dbWriter.write { db in if try Player.all().isEmpty(db) { // When database is empty, insert new random players try createRandomPlayers(db) } else { // Insert a player if Bool.random() { _ = try Player.makeRandom().inserted(db) // insert but ignore inserted id } // Delete a random player if Bool.random() { try Player.order(sql: "RANDOM()").limit(1).deleteAll(db) } // Update some players for var player in try Player.fetchAll(db) where Bool.random() { try player.updateChanges(db) { $0.score = Player.randomScore() } } } } } /// Create random players if the database is empty. func createRandomPlayersIfEmpty() throws { try dbWriter.write { db in if try Player.all().isEmpty(db) { try createRandomPlayers(db) } } } /// Support for `createRandomPlayersIfEmpty()` and `refreshPlayers()`. private func createRandomPlayers(_ db: Database) throws { for _ in 0..<8 { _ = try Player.makeRandom().inserted(db) // insert but ignore inserted id } } } // MARK: - Database Access: Reads // This demo app does not provide any specific reading method, and instead // gives an unrestricted read-only access to the rest of the application. // In your app, you are free to choose another path, and define focused // reading methods. extension AppDatabase { /// Provides a read-only access to the database var databaseReader: DatabaseReader { dbWriter } }
mit
dc66968a652b8651c1f1f847d1b8033b
33.225564
107
0.580624
4.78654
false
false
false
false
halawata13/Golf
Golf/model/Card.swift
1
770
import Foundation class Card { let suit: PlayingCard.Suit let number: UInt var column: Int? var row: Int? var imageName: String { return suit.rawValue + String(number) } init?(suit: PlayingCard.Suit, number: UInt?) { switch suit { case .spade: fallthrough case .club: fallthrough case .heart: fallthrough case .diamond: guard let number = number else { return nil } if number == 0 || number > 13 { return nil } self.suit = suit self.number = number case .joker: self.suit = .joker self.number = 0 } } }
mit
0a7343b0fc18291c9900af84ffacc2c3
18.74359
50
0.47013
4.723926
false
false
false
false
AgtLucas/lets-realm
RWRealmStarterProject/AddNewEntryController.swift
1
2759
// // AddNewEntryController.swift // RWRealmStarterProject // // Created by Bill Kastanakis on 8/6/14. // Copyright (c) 2014 Bill Kastanakis. All rights reserved. // import UIKit import Realm class AddNewEntryController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var categoryTextField: UITextField! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var descriptionTextField: UITextView! var selectedAnnotation: SpecimenAnnotation! var selectedCategory: Category! var specimen: Specimen! //MARK: - Validation func validateFields() -> Bool { if (nameTextField.text.isEmpty || descriptionTextField.text.isEmpty || selectedCategory == nil) { let alertController = UIAlertController(title: "Validation Error", message: "All fields must be filled", preferredStyle: .Alert) let alertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Destructive, handler: {(alert : UIAlertAction!) in alertController.dismissViewControllerAnimated(true, completion: nil) }) alertController.addAction(alertAction) presentViewController(alertController, animated: true, completion: nil) return false } else { return true } } //MARK: - UITextFieldDelegate func textFieldDidBeginEditing(textField: UITextField) { performSegueWithIdentifier("Categories", sender: self) } //MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func unwindFromCategories(segue: UIStoryboardSegue) { let categoriesController = segue.sourceViewController as! CategoriesTableViewController selectedCategory = categoriesController.selectedCategory categoryTextField.text = selectedCategory.name } func addNewSpecimen() { let realm = RLMRealm.defaultRealm() realm.beginWriteTransaction() let newSpecimen = Specimen() newSpecimen.name = nameTextField.text newSpecimen.category = selectedCategory newSpecimen.specimenDescription = descriptionTextField.text newSpecimen.latitude = selectedAnnotation.coordinate.latitude newSpecimen.longitude = selectedAnnotation.coordinate.longitude realm.addObject(newSpecimen) realm.commitWriteTransaction() specimen = newSpecimen } //MARK: - Actions override func shouldPerformSegueWithIdentifier(identifier: String?, sender: AnyObject!) -> Bool { if validateFields() { if specimen == nil { addNewSpecimen() } return true } else { return false } } }
isc
d1429417178426003635efeea37b31c3
27.153061
134
0.719826
5.255238
false
false
false
false
mightydeveloper/swift
validation-test/compiler_crashers_fixed/1170-getselftypeforcontainer.swift
10
829
// RUN: not %target-swift-frontend %s -parse // REQUIRES: asserts // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing class k<g>: d { var f: g init(f: g) { l. d { typealias j = je: Int -> Int = { } let d: Int = { c, b in }(f, e) } class d { func l<j where j: h, j: d>(l: j) { } func i(k: b) -> <j>(() -> j) -> b { } class j { func y((Any, j))(v: (Any, AnyObject)) { } } func w(j: () -> ()) { } class v { l _ = w() { } } func v<x>() -> (x, x -> x) -> x { l y j s<q : l, y: l m y.n == q.n> { } o l { } y q<x> { } o n { } class r { func s() -> p { } } class w: r, n { } func b<c { enum b { } } } class d<j : i, f : i where j.i == f> : e { } class d<j, f> { } protocol i { } protocol e { } protocol i : d { func d
apache-2.0
4163a7151a00eb1a916afd2fb4e360fb
12.816667
87
0.512666
2.234501
false
false
false
false
or1onsli/Calculator
Calculator/CalculatorBrain.swift
1
3707
// // CalculatorBrain.swift // Calculator // // Created by Andrea Vultaggio on 17/10/2017. // Copyright © 2017 Andrea Vultaggio. All rights reserved. // import Foundation struct CalculatorBrain { //MARK: Variables private var accumulator: Double? private var pendingBinaryOperation: PendingBinaryOperation? private var resultIsPending = false var description = "" var result: Double? { get { return accumulator } } //MARK: Enumerations private enum Operation { case constant(Double) case unaryOperation((Double) -> Double) case binaryOperation((Double, Double) -> Double) case result } private var operations: Dictionary<String, Operation> = [ "+" : .binaryOperation({ $0 + $1 }), "﹣" : .binaryOperation({ $0 - $1 }), "×" : .binaryOperation({ $0 * $1 }), "÷" : .binaryOperation({ $0 / $1 }), "√" : .unaryOperation({ sqrt($0) }), "±" : .unaryOperation({ -$0 }), "﹪" : .unaryOperation({ $0 / 100 }), "AC": .constant(0), "=" : .result ] //MARK: Embedded struct private struct PendingBinaryOperation { let function: (Double, Double) -> Double let firstOperand: Double func perform(with secondOperand: Double) -> Double { return function(firstOperand, secondOperand) } } //MARK: Functions private mutating func performPendingBinaryOperation() { if pendingBinaryOperation != nil && accumulator != nil { accumulator = pendingBinaryOperation?.perform(with: accumulator!) pendingBinaryOperation = nil resultIsPending = false } } mutating func performOperation(_ symbol: String) { if let operation = operations[symbol] { switch operation { case .constant(let value): accumulator = value description = "" case .unaryOperation(let function): if accumulator != nil { let value = String(describing: accumulator!).removeAfterPointIfZero() description = symbol + "(" + value.setMaxLength(of: 5) + ")" + "=" accumulator = function(accumulator!) } case .binaryOperation(let function): performPendingBinaryOperation() if accumulator != nil { if description.last == "=" { description = String(describing: accumulator!).removeAfterPointIfZero().setMaxLength(of: 5) + symbol } else { description += symbol } pendingBinaryOperation = PendingBinaryOperation(function: function, firstOperand: accumulator!) resultIsPending = true accumulator = nil } case .result: performPendingBinaryOperation() if !resultIsPending { description += "=" } } } } mutating func setOperand(_ operand: Double?) { accumulator = operand ?? 0.0 if !resultIsPending { description = String(describing: operand!).removeAfterPointIfZero().setMaxLength(of: 5) } else { description += String(describing: operand!).removeAfterPointIfZero().setMaxLength(of: 5) } } }
mit
747a043f182b783bd6dcd304715f8dfc
33.212963
128
0.517456
5.465976
false
false
false
false
salesforce-ux/design-system-ios
Demo-Swift/slds-sample-app/library/model/ColorObject.swift
1
2840
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license import UIKit //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– enum ColorObjectType : String { case background = "Background" case border = "Border" case fill = "Fill" case text = "Text" } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– struct ColorObject { var type : ColorObjectType var index : NSInteger //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var color : UIColor? { switch self.type { case .background : if let value = SLDSBackgroundColorType.init(rawValue: self.index) { return UIColor.sldsBackgroundColor(value) } case .border : if let value = SLDSBorderColorType.init(rawValue: self.index) { return UIColor.sldsBorderColor(value) } case .fill : if let value = SLDSFillType.init(rawValue: self.index) { return UIColor.sldsFill(value) } case .text : if let value = SLDSTextColorType.init(rawValue: self.index) { return UIColor.sldsTextColor(value) } } return nil } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var method : String { switch self.type { case .background : return "sldsBackgroundColor" case .border : return "sldsBorderColor" case .fill : return "sldsFill" case .text : return "sldsTextColor" } } //–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––– var name : String { return NSString.sldsColorName(self.index) } }
bsd-3-clause
d276be223c89ad2b013fd67e9bb155ec
26.466667
84
0.417961
5.75419
false
false
false
false
gewill/Feeyue
Feeyue/Model/WeiboAccount.swift
1
574
// // WeiboAccount.swift // Feeyue // // Created by Will on 2/1/16. // Copyright © 2016 gewill.org. All rights reserved. // import Foundation import RealmSwift /* //v0 class WeiboAccount: Object { dynamic var accountId: Int = 0 dynamic var token: String? dynamic var user: User? } */ //v1 class WeiboAccount: BaseModel { @objc dynamic var accountId: String = "" @objc dynamic var accessToken: String = "" @objc dynamic var userName: String = "" @objc dynamic var avatar: String = "" @objc dynamic var isActive: Bool = false }
mit
c0b2a3d6de0b367c8db4a48cda730ca5
16.90625
53
0.65096
3.649682
false
false
false
false
siejkowski/160
onesixty/Source/Control/Injection.swift
2
3192
import Foundation import RxSwift import UIKit import Swinject struct Injection { var provider: DependencyProvider { get { return container } } private let container = Container() init() { setupContainer(self.container) } private func setupContainer(container: Container) { // todo: extract injection categories to separate methods container.register(FlowController.self) { r in return FlowController(provider: r as! DependencyProvider) }.inObjectScope(.Container) container.register(ViewController.self) { _ in return ViewController() } container.register(NavigationController.self) { (r: Resolvable) in return NavigationController(flowController: r.provide(FlowController.self)) } container.register(UIWindow.self) { (r: Resolvable) in let window = UIWindow() window.rootViewController = r.provide(NavigationController.self) return window }.inObjectScope(.Container) } } struct InjectionError : ErrorType { let message: String init(_ message: String) { self.message = message } } protocol DependencyProvider { func resolveWithError<Service>(serviceType: Service.Type) throws -> Service func resolveWithError<Service>(serviceType: Service.Type, name: String?) throws -> Service func resolveWithError<Service, Arg1>(serviceType: Service.Type, argument: Arg1) throws -> Service func provide<Service>(serviceType: Service.Type) -> Service func provide<Service>(serviceType: Service.Type, name: String?) -> Service func provide<Service, Arg1>(serviceType: Service.Type, argument: Arg1) -> Service } extension Container : DependencyProvider {} extension Resolvable { //where Self : DependencyProvider { private func provideWithError<Service>( @autoclosure serviceClosure: () -> Service?, serviceType: Service.Type ) throws -> Service { guard let service = serviceClosure() else { throw InjectionError("Couldn't resolve service. Type: \(serviceType).") } return service } func resolveWithError<Service>(serviceType: Service.Type) throws -> Service { return try provideWithError(self.resolve(serviceType), serviceType: serviceType) } func resolveWithError<Service>(serviceType: Service.Type, name: String?) throws -> Service { return try provideWithError(self.resolve(serviceType, name: name), serviceType: serviceType) } func resolveWithError<Service, Arg1>(serviceType: Service.Type, argument: Arg1) throws -> Service { return try provideWithError(self.resolve(serviceType, argument: argument), serviceType: serviceType) } func provide<Service>(serviceType: Service.Type) -> Service { return try! resolveWithError(serviceType) } func provide<Service>(serviceType: Service.Type, name: String?) -> Service { return try! resolveWithError(serviceType, name: name) } func provide<Service, Arg1>(serviceType: Service.Type, argument: Arg1) -> Service { return try! resolveWithError(serviceType, argument: argument) } }
mit
67e795fcefa6bfb25281f7d30260fe96
35.689655
108
0.692669
4.81448
false
false
false
false
nakau1/Formations
Formations/Sources/Modules/Formation/Models/FormationModel.swift
1
1053
// ============================================================================= // Formations // Copyright 2017 yuichi.nakayasu All rights reserved. // ============================================================================= import Foundation class FormationModel { typealias Entity = Formation // MARK: - CRUD func create() -> Entity { return Entity() } func load(teamID id: String) -> Entity { guard let jsonString = Json.formation(teamId: id).load() else { return create() } return try! JSONDecoder().decode(Formation.self, from: jsonString.data(using: .utf8)!) } func save(entity: Entity, toTeamID id: String) { let data = try! JSONEncoder().encode(entity) let jsonString = String(data: data, encoding: .utf8) Json.formation(teamId: id).save(jsonString) } func delete(teamID id: String) { Json.formation(teamId: id).delete() } } extension Realm { static let Formation = FormationModel() }
apache-2.0
224186af1b66523f0ff6e9717f78222b
27.459459
94
0.51472
4.68
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/FeatureTransaction/Sources/FeatureTransactionUI/FiatAccountTransactions/PaymentMethod/PaymentMethodBuilder.swift
1
859
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RIBs // MARK: - Builder protocol PaymentMethodBuildable: Buildable { func build(withListener listener: PaymentMethodListener) -> PaymentMethodRouting } final class PaymentMethodBuilder: PaymentMethodBuildable { // TODO: Consider injecting an `AssetAction` as the action may dictate // what payment methods are available to the user. init() {} func build(withListener listener: PaymentMethodListener) -> PaymentMethodRouting { let viewController = PaymentMethodViewController() let interactor = PaymentMethodInteractor(presenter: viewController) interactor.listener = listener let router = PaymentMethodRouter(interactor: interactor, viewController: viewController) interactor.router = router return router } }
lgpl-3.0
a84f12fb3c79ccc69a90b3700b1f5e07
33.32
96
0.742424
5.5
false
false
false
false
kstaring/swift
stdlib/private/StdlibUnittest/StdlibCoreExtras.swift
1
7238
//===--- StdlibCoreExtras.swift -------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftPrivate import SwiftPrivateLibcExtras #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) import Glibc #endif #if _runtime(_ObjC) import Foundation #endif // // These APIs don't really belong in a unit testing library, but they are // useful in tests, and stdlib does not have such facilities yet. // func findSubstring(_ string: String, _ substring: String) -> String.Index? { if substring.isEmpty { return string.startIndex } #if _runtime(_ObjC) return string.range(of: substring)?.lowerBound #else // FIXME(performance): This is a very non-optimal algorithm, with a worst // case of O((n-m)*m). When non-objc String has a match function that's better, // this should be removed in favor of using that. // Operate on unicode scalars rather than codeunits. let haystack = string.unicodeScalars let needle = substring.unicodeScalars for matchStartIndex in haystack.indices { var matchIndex = matchStartIndex var needleIndex = needle.startIndex while true { if needleIndex == needle.endIndex { // if we hit the end of the search string, we found the needle return matchStartIndex.samePosition(in: string) } if matchIndex == haystack.endIndex { // if we hit the end of the string before finding the end of the needle, // we aren't going to find the needle after that. return nil } if needle[needleIndex] == haystack[matchIndex] { // keep advancing through both the string and search string on match matchIndex = haystack.index(after: matchIndex) needleIndex = haystack.index(after: needleIndex) } else { // no match, go back to finding a starting match in the string. break } } } return nil #endif } public func createTemporaryFile( _ fileNamePrefix: String, _ fileNameSuffix: String, _ contents: String ) -> String { #if _runtime(_ObjC) let tempDir: NSString = NSTemporaryDirectory() as NSString var fileName = tempDir.appendingPathComponent( fileNamePrefix + "XXXXXX" + fileNameSuffix) #else var fileName = fileNamePrefix + "XXXXXX" + fileNameSuffix #endif let fd = _stdlib_mkstemps( &fileName, CInt(fileNameSuffix.utf8.count)) if fd < 0 { fatalError("mkstemps() returned an error") } var stream = _FDOutputStream(fd: fd) stream.write(contents) if close(fd) != 0 { fatalError("close() return an error") } return fileName } public final class Box<T> { public init(_ value: T) { self.value = value } public var value: T } infix operator <=> public func <=> <T: Comparable>(lhs: T, rhs: T) -> ExpectedComparisonResult { return lhs < rhs ? .lt : lhs > rhs ? .gt : .eq } public struct TypeIdentifier : Hashable, Comparable { public init(_ value: Any.Type) { self.value = value } public var hashValue: Int { return objectID.hashValue } public var value: Any.Type internal var objectID : ObjectIdentifier { return ObjectIdentifier(value) } } public func < (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool { return lhs.objectID < rhs.objectID } public func == (lhs: TypeIdentifier, rhs: TypeIdentifier) -> Bool { return lhs.objectID == rhs.objectID } extension TypeIdentifier : CustomStringConvertible, CustomDebugStringConvertible { public var description: String { return String(describing: value) } public var debugDescription: String { return "TypeIdentifier(\(description))" } } enum FormNextPermutationResult { case success case formedFirstPermutation } extension MutableCollection where Self : BidirectionalCollection, Iterator.Element : Comparable { mutating func _reverseSubrange(_ subrange: Range<Index>) { if subrange.isEmpty { return } var f = subrange.lowerBound var l = index(before: subrange.upperBound) while f < l { swap(&self[f], &self[l]) formIndex(after: &f) formIndex(before: &l) } } mutating func formNextPermutation() -> FormNextPermutationResult { if isEmpty { // There are 0 elements, only one permutation is possible. return .formedFirstPermutation } do { var i = startIndex formIndex(after: &i) if i == endIndex { // There is only element, only one permutation is possible. return .formedFirstPermutation } } var i = endIndex formIndex(before: &i) var beforeI = i formIndex(before: &beforeI) var elementAtI = self[i] var elementAtBeforeI = self[beforeI] while true { if elementAtBeforeI < elementAtI { // Elements at `i..<endIndex` are in non-increasing order. To form the // next permutation in lexicographical order we need to replace // `self[i-1]` with the next larger element found in the tail, and // reverse the tail. For example: // // i-1 i endIndex // V V V // 6 2 8 7 4 1 [ ] // Input. // 6 (4) 8 7 (2) 1 [ ] // Exchanged self[i-1] with the // ^--------^ // next larger element // // from the tail. // 6 4 (1)(2)(7)(8)[ ] // Reversed the tail. // <--------> var j = endIndex repeat { formIndex(before: &j) } while !(elementAtBeforeI < self[j]) swap(&self[beforeI], &self[j]) _reverseSubrange(i..<endIndex) return .success } if beforeI == startIndex { // All elements are in non-increasing order. Reverse to form the first // permutation, where all elements are sorted (in non-increasing order). reverse() return .formedFirstPermutation } i = beforeI formIndex(before: &beforeI) elementAtI = elementAtBeforeI elementAtBeforeI = self[beforeI] } } } /// Generate all permutations. public func forAllPermutations(_ size: Int, _ body: ([Int]) -> Void) { var data = Array(0..<size) repeat { body(data) } while data.formNextPermutation() != .formedFirstPermutation } /// Generate all permutations. public func forAllPermutations<S : Sequence>( _ sequence: S, _ body: ([S.Iterator.Element]) -> Void ) { let data = Array(sequence) forAllPermutations(data.count) { (indices: [Int]) in body(indices.map { data[$0] }) return () } } public func cartesianProduct<C1 : Collection, C2 : Collection>( _ c1: C1, _ c2: C2 ) -> [(C1.Iterator.Element, C2.Iterator.Element)] { var result: [(C1.Iterator.Element, C2.Iterator.Element)] = [] for e1 in c1 { for e2 in c2 { result.append((e1, e2)) } } return result }
apache-2.0
02d6b9921a25e3330835294f1a9c4489
28.303644
81
0.632357
4.091577
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/PeerMediaBlockRowItem.swift
1
9588
// // PeerMediaBlockRowItem.swift // Telegram // // Created by Mikhail Filimonov on 19.03.2020. // Copyright © 2020 Telegram. All rights reserved. // import Cocoa import TGUIKit import Postbox import TelegramCore import SwiftSignalKit import CoreGraphics class PeerMediaBlockRowItem: GeneralRowItem { fileprivate var temporaryHeight: CGFloat? fileprivate let listener: TableScrollListener fileprivate let controller: PeerMediaController fileprivate let isMediaVisible: Bool init(_ initialSize: NSSize, stableId: AnyHashable, controller: PeerMediaController, isVisible: Bool, viewType: GeneralViewType) { self.controller = controller self.isMediaVisible = isVisible self.listener = TableScrollListener(dispatchWhenVisibleRangeUpdated: false, { _ in }) super.init(initialSize, height: initialSize.height, stableId: stableId, viewType: viewType) } deinit { if self.controller.isLoaded(), let table = self.table { // let view = self.controller.genericView // view.removeFromSuperview() if controller.frame.minY == 0 { table.scroll(to: .up(true)) if self.controller.genericView.superview != nil { controller.viewWillDisappear(true) self.controller.genericView.removeFromSuperview() controller.viewDidDisappear(true) } } } } override var instantlyResize: Bool { return false } override var height: CGFloat { // return 10000 if !isMediaVisible { return 1 } else { if let temporaryHeight = temporaryHeight { return temporaryHeight } else { return table?.frame.height ?? initialSize.height } } } override func makeSize(_ width: CGFloat, oldWidth: CGFloat = 0) -> Bool { _ = super.makeSize(width, oldWidth: oldWidth) return true } override func viewClass() -> AnyClass { return PeerMediaBlockRowView.self } } private final class PeerMediaBlockRowView : TableRowView { required init(frame frameRect: NSRect) { super.init(frame: frameRect) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var backdorColor: NSColor { return theme.colors.listBackground } private func updateOrigin() { guard let item = item as? PeerMediaBlockRowItem, let table = item.table else { return } item.controller.view.frame = NSMakeRect(0, max(0, self.frame.minY - table.documentOffset.y), self.frame.width, table.frame.height) } override func layout() { super.layout() self.updateOrigin() } override func setFrameOrigin(_ newOrigin: NSPoint) { super.setFrameOrigin(newOrigin) self.updateOrigin() } override func removeFromSuperview() { super.removeFromSuperview() } override func scrollWheel(with event: NSEvent) { guard let item = item as? PeerMediaBlockRowItem else { super.scrollWheel(with: event) return } item.controller.view.enclosingScrollView?.scrollWheel(with: event) } override func set(item: TableRowItem, animated: Bool = false) { super.set(item: item, animated: animated) guard let item = item as? PeerMediaBlockRowItem else { return } item.controller.bar = .init(height: 0) item.controller._frameRect = bounds var scrollInner: Bool = false var scrollingInMediaTable: Bool = false if item.isMediaVisible { item.listener.handler = { [weak self, weak item] _ in guard let `self` = self, let table = item?.table, let item = item else { return } scrollInner = table.documentOffset.y >= self.frame.minY let mediaTable = item.controller.genericView.mainTable if let mediaTable = mediaTable { let offset = table.documentOffset.y - self.frame.minY var updated = max(0, offset) if mediaTable.documentSize.height <= table.frame.height, updated > 0 { updated = max(updated - 30, 0) } if !scrollingInMediaTable, updated != mediaTable.documentOffset.y { mediaTable.clipView.scroll(to: NSMakePoint(0, updated)) mediaTable.reflectScrolledClipView(mediaTable.clipView) } if scrollInner { } else { if mediaTable.documentOffset.y > 0 { scrollInner = true } } NotificationCenter.default.post(name: NSView.boundsDidChangeNotification, object: mediaTable.clipView) let previousY = item.controller.view.frame.minY if item.temporaryHeight != mediaTable.documentSize.height { item.temporaryHeight = max(mediaTable.documentSize.height, table.frame.height) table.noteHeightOfRow(item.index, false) } item.controller.view.frame = NSMakeRect(0, max(0, self.frame.minY - table.documentOffset.y), self.frame.width, table.frame.height) let currentY = item.controller.view.frame.minY if previousY != currentY { if currentY == 0, previousY != 0 { item.controller.viewWillAppear(true) item.controller.viewDidAppear(true) } else if previousY == 0 { item.controller.viewWillDisappear(true) item.controller.viewDidDisappear(true) } } } } item.table?.addScroll(listener: item.listener) item.table?.hasVerticalScroller = false item.table?._scrollWillStartLiveScrolling = { scrollingInMediaTable = false } item.controller.genericView.mainTable?.reloadData() } else { needsLayout = true } if item.controller.view.superview != item.table { item.controller.view.removeFromSuperview() item.table?.addSubview(item.controller.view) } if let table = item.table { item.controller.genericView.change(pos: NSMakePoint(0, max(0, table.rectOf(item: item).minY - table.documentOffset.y)), animated: animated) } if item.isMediaVisible { item.controller.genericView.isHidden = false } item.controller.genericView.change(opacity: item.isMediaVisible ? 1 : 0, animated: animated, completion: { [weak item] _ in guard let item = item else { return } item.controller.genericView.isHidden = !item.isMediaVisible }) if item.isMediaVisible { item.controller.currentMainTableView = { [weak item, weak self] mainTable, animated, updated in if let item = item, animated { if item.table?.documentOffset.y == self?.frame.minY { if !updated { mainTable?.scroll(to: .up(true)) } } else if updated { item.table?.scroll(to: .top(id: item.stableId, innerId: nil, animated: animated, focus: .init(focus: false), inset: 0)) } } mainTable?.applyExternalScroll = { [weak self, weak item] event in guard let `self` = self, let item = item else { return false } if scrollInner { if event.scrollingDeltaY > 0 { if let tableView = item.controller.genericView.mainTable, tableView.documentOffset.y <= 0 { if !item.controller.unableToHide { scrollInner = false item.table?.clipView.scroll(to: NSMakePoint(0, self.frame.minY)) item.table?.scrollWheel(with: event) scrollingInMediaTable = false return true } } } scrollingInMediaTable = true return false } else { scrollingInMediaTable = false item.table?.scrollWheel(with: event) return true } } } } else { item.controller.currentMainTableView = nil } } deinit { } }
gpl-2.0
17d55a7e29a88d305a0ea910a119a560
36.015444
151
0.521435
5.401127
false
false
false
false
tjw/swift
stdlib/public/core/Flatten.swift
1
17398
//===--- Flatten.swift ----------------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A sequence consisting of all the elements contained in each segment /// contained in some `Base` sequence. /// /// The elements of this view are a concatenation of the elements of /// each sequence in the base. /// /// The `joined` method is always lazy, but does not implicitly /// confer laziness on algorithms applied to its result. In other /// words, for ordinary sequences `s`: /// /// * `s.joined()` does not create new storage /// * `s.joined().map(f)` maps eagerly and returns a new array /// * `s.lazy.joined().map(f)` maps lazily and returns a `LazyMapSequence` /// /// - See also: `FlattenCollection` @_fixed_layout // FIXME(sil-serialize-all) public struct FlattenSequence<Base: Sequence> where Base.Element: Sequence { @usableFromInline // FIXME(sil-serialize-all) internal var _base: Base /// Creates a concatenation of the elements of the elements of `base`. /// /// - Complexity: O(1) @inlinable // FIXME(sil-serialize-all) internal init(_base: Base) { self._base = _base } } extension FlattenSequence { @_fixed_layout // FIXME(sil-serialize-all) public struct Iterator { @usableFromInline // FIXME(sil-serialize-all) internal var _base: Base.Iterator @usableFromInline // FIXME(sil-serialize-all) internal var _inner: Base.Element.Iterator? /// Construct around a `base` iterator. @inlinable // FIXME(sil-serialize-all) internal init(_base: Base.Iterator) { self._base = _base } } } extension FlattenSequence.Iterator: IteratorProtocol { public typealias Element = Base.Element.Element /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. @inlinable // FIXME(sil-serialize-all) public mutating func next() -> Element? { repeat { if _fastPath(_inner != nil) { let ret = _inner!.next() if _fastPath(ret != nil) { return ret } } let s = _base.next() if _slowPath(s == nil) { return nil } _inner = s!.makeIterator() } while true } } extension FlattenSequence: Sequence { /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator()) } } extension Sequence where Element : Sequence { /// Returns the elements of this sequence of sequences, concatenated. /// /// In this example, an array of three ranges is flattened so that the /// elements of each range can be iterated in turn. /// /// let ranges = [0..<3, 8..<10, 15..<17] /// /// // A for-in loop over 'ranges' accesses each range: /// for range in ranges { /// print(range) /// } /// // Prints "0..<3" /// // Prints "8..<10" /// // Prints "15..<17" /// /// // Use 'joined()' to access each element of each range: /// for index in ranges.joined() { /// print(index, terminator: " ") /// } /// // Prints: "0 1 2 8 9 15 16" /// /// - Returns: A flattened view of the elements of this /// sequence of sequences. @inlinable // FIXME(sil-serialize-all) public func joined() -> FlattenSequence<Self> { return FlattenSequence(_base: self) } } extension LazySequenceProtocol where Element : Sequence { /// Returns a lazy sequence that concatenates the elements of this sequence of /// sequences. @inlinable // FIXME(sil-serialize-all) public func joined() -> LazySequence<FlattenSequence<Elements>> { return FlattenSequence(_base: elements).lazy } } /// A flattened view of a base collection of collections. /// /// The elements of this view are a concatenation of the elements of /// each collection in the base. /// /// The `joined` method is always lazy, but does not implicitly /// confer laziness on algorithms applied to its result. In other /// words, for ordinary collections `c`: /// /// * `c.joined()` does not create new storage /// * `c.joined().map(f)` maps eagerly and returns a new array /// * `c.lazy.joined().map(f)` maps lazily and returns a `LazyMapCollection` /// /// - Note: The performance of accessing `startIndex`, `first`, any methods /// that depend on `startIndex`, or of advancing an `Index` /// depends on how many empty subcollections are found in the base /// collection, and may not offer the usual performance given by `Collection` /// or `Index`. Be aware, therefore, that general operation on /// `FlattenCollection` instances may not have the documented complexity. /// /// - See also: `FlattenSequence` @_fixed_layout // FIXME(sil-serialize-all) public struct FlattenCollection<Base> where Base : Collection, Base.Element : Collection { @usableFromInline // FIXME(sil-serialize-all) internal var _base: Base /// Creates a flattened view of `base`. @inlinable // FIXME(sil-serialize-all) public init(_ base: Base) { self._base = base } } extension FlattenCollection { /// A position in a FlattenCollection @_fixed_layout // FIXME(sil-serialize-all) public struct Index { /// The position in the outer collection of collections. @usableFromInline // FIXME(sil-serialize-all) internal let _outer: Base.Index /// The position in the inner collection at `base[_outer]`, or `nil` if /// `_outer == base.endIndex`. /// /// When `_inner != nil`, `_inner!` is a valid subscript of `base[_outer]`; /// when `_inner == nil`, `_outer == base.endIndex` and this index is /// `endIndex` of the `FlattenCollection`. @usableFromInline // FIXME(sil-serialize-all) internal let _inner: Base.Element.Index? @inlinable // FIXME(sil-serialize-all) internal init(_ _outer: Base.Index, _ inner: Base.Element.Index?) { self._outer = _outer self._inner = inner } } } extension FlattenCollection.Index : Equatable { @inlinable // FIXME(sil-serialize-all) public static func == ( lhs: FlattenCollection<Base>.Index, rhs: FlattenCollection<Base>.Index ) -> Bool { return lhs._outer == rhs._outer && lhs._inner == rhs._inner } } extension FlattenCollection.Index : Comparable { @inlinable // FIXME(sil-serialize-all) public static func < ( lhs: FlattenCollection<Base>.Index, rhs: FlattenCollection<Base>.Index ) -> Bool { // FIXME: swift-3-indexing-model: tests. if lhs._outer != rhs._outer { return lhs._outer < rhs._outer } if let lhsInner = lhs._inner, let rhsInner = rhs._inner { return lhsInner < rhsInner } // When combined, the two conditions above guarantee that both // `_outer` indices are `_base.endIndex` and both `_inner` indices // are `nil`, since `_inner` is `nil` iff `_outer == base.endIndex`. _precondition(lhs._inner == nil && rhs._inner == nil) return false } } extension FlattenCollection.Index : Hashable where Base.Index : Hashable, Base.Element.Index : Hashable { @inlinable // FIXME(sil-serialize-all) public var hashValue: Int { return _hashValue(for: self) } @inlinable // FIXME(sil-serialize-all) public func _hash(into hasher: inout _Hasher) { hasher.combine(_outer) hasher.combine(_inner) } } extension FlattenCollection : Sequence { public typealias Iterator = FlattenSequence<Base>.Iterator public typealias SubSequence = Slice<FlattenCollection> /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable // FIXME(sil-serialize-all) public func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator()) } // To return any estimate of the number of elements, we have to start // evaluating the collections. That is a bad default for `flatMap()`, so // just return zero. public var underestimatedCount: Int { return 0 } @inlinable // FIXME(sil-serialize-all) public func _copyToContiguousArray() -> ContiguousArray<Base.Element.Element> { // The default implementation of `_copyToContiguousArray` queries the // `count` property, which materializes every inner collection. This is a // bad default for `flatMap()`. So we treat `self` as a sequence and only // rely on underestimated count. return _copySequenceToContiguousArray(self) } // TODO: swift-3-indexing-model - add docs @inlinable // FIXME(sil-serialize-all) public func forEach( _ body: (Base.Element.Element) throws -> Void ) rethrows { // FIXME: swift-3-indexing-model: tests. for innerCollection in _base { try innerCollection.forEach(body) } } } extension FlattenCollection : Collection { /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. @inlinable // FIXME(sil-serialize-all) public var startIndex: Index { let end = _base.endIndex var outer = _base.startIndex while outer != end { let innerCollection = _base[outer] if !innerCollection.isEmpty { return Index(outer, innerCollection.startIndex) } _base.formIndex(after: &outer) } return endIndex } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `index(after:)`. @inlinable // FIXME(sil-serialize-all) public var endIndex: Index { return Index(_base.endIndex, nil) } @inlinable // FIXME(sil-serialize-all) internal func _index(after i: Index) -> Index { let innerCollection = _base[i._outer] let nextInner = innerCollection.index(after: i._inner!) if _fastPath(nextInner != innerCollection.endIndex) { return Index(i._outer, nextInner) } var nextOuter = _base.index(after: i._outer) while nextOuter != _base.endIndex { let nextInnerCollection = _base[nextOuter] if !nextInnerCollection.isEmpty { return Index(nextOuter, nextInnerCollection.startIndex) } _base.formIndex(after: &nextOuter) } return endIndex } @inlinable // FIXME(sil-serialize-all) internal func _index(before i: Index) -> Index { var prevOuter = i._outer if prevOuter == _base.endIndex { prevOuter = _base.index(prevOuter, offsetBy: -1) } var prevInnerCollection = _base[prevOuter] var prevInner = i._inner ?? prevInnerCollection.endIndex while prevInner == prevInnerCollection.startIndex { prevOuter = _base.index(prevOuter, offsetBy: -1) prevInnerCollection = _base[prevOuter] prevInner = prevInnerCollection.endIndex } return Index(prevOuter, prevInnerCollection.index(prevInner, offsetBy: -1)) } // TODO: swift-3-indexing-model - add docs @inlinable // FIXME(sil-serialize-all) public func index(after i: Index) -> Index { return _index(after: i) } @inlinable // FIXME(sil-serialize-all) public func formIndex(after i: inout Index) { i = index(after: i) } @inlinable // FIXME(sil-serialize-all) public func distance(from start: Index, to end: Index) -> Int { // The following check makes sure that distance(from:to:) is invoked on the // _base at least once, to trigger a _precondition in forward only // collections. if end < start { _ = _base.distance(from: _base.endIndex, to: _base.startIndex) } var _start: Index let _end: Index let step: Int if start > end { _start = end _end = start step = -1 } else { _start = start _end = end step = 1 } var count = 0 while _start != _end { count += step formIndex(after: &_start) } return count } @inline(__always) @inlinable // FIXME(sil-serialize-all) internal func _advanceIndex(_ i: inout Index, step: Int) { _sanityCheck(-1...1 ~= step, "step should be within the -1...1 range") i = step < 0 ? _index(before: i) : _index(after: i) } @inline(__always) @inlinable // FIXME(sil-serialize-all) internal func _ensureBidirectional(step: Int) { // FIXME: This seems to be the best way of checking whether _base is // forward only without adding an extra protocol requirement. // index(_:offsetBy:limitedBy:) is chosen becuase it is supposed to return // nil when the resulting index lands outside the collection boundaries, // and therefore likely does not trap in these cases. if step < 0 { _ = _base.index( _base.endIndex, offsetBy: step, limitedBy: _base.startIndex) } } @inlinable // FIXME(sil-serialize-all) public func index(_ i: Index, offsetBy n: Int) -> Index { var i = i let step = n.signum() _ensureBidirectional(step: step) for _ in 0 ..< abs(n) { _advanceIndex(&i, step: step) } return i } @inlinable // FIXME(sil-serialize-all) public func formIndex(_ i: inout Index, offsetBy n: Int) { i = index(i, offsetBy: n) } @inlinable // FIXME(sil-serialize-all) public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { var i = i let step = n.signum() // The following line makes sure that index(_:offsetBy:limitedBy:) is // invoked on the _base at least once, to trigger a _precondition in // forward only collections. _ensureBidirectional(step: step) for _ in 0 ..< abs(n) { if i == limit { return nil } _advanceIndex(&i, step: step) } return i } @inlinable // FIXME(sil-serialize-all) public func formIndex( _ i: inout Index, offsetBy n: Int, limitedBy limit: Index ) -> Bool { if let advancedIndex = index(i, offsetBy: n, limitedBy: limit) { i = advancedIndex return true } i = limit return false } /// Accesses the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. @inlinable // FIXME(sil-serialize-all) public subscript(position: Index) -> Base.Element.Element { return _base[position._outer][position._inner!] } @inlinable // FIXME(sil-serialize-all) public subscript(bounds: Range<Index>) -> SubSequence { return Slice(base: self, bounds: bounds) } } extension FlattenCollection : BidirectionalCollection where Base : BidirectionalCollection, Base.Element : BidirectionalCollection { // FIXME(performance): swift-3-indexing-model: add custom advance/distance // methods that skip over inner collections when random-access // TODO: swift-3-indexing-model - add docs @inlinable // FIXME(sil-serialize-all) public func index(before i: Index) -> Index { return _index(before: i) } @inlinable // FIXME(sil-serialize-all) public func formIndex(before i: inout Index) { i = index(before: i) } } extension Collection where Element : Collection { /// Returns the elements of this collection of collections, concatenated. /// /// In this example, an array of three ranges is flattened so that the /// elements of each range can be iterated in turn. /// /// let ranges = [0..<3, 8..<10, 15..<17] /// /// // A for-in loop over 'ranges' accesses each range: /// for range in ranges { /// print(range) /// } /// // Prints "0..<3" /// // Prints "8..<10" /// // Prints "15..<17" /// /// // Use 'joined()' to access each element of each range: /// for index in ranges.joined() { /// print(index, terminator: " ") /// } /// // Prints: "0 1 2 8 9 15 16" /// /// - Returns: A flattened view of the elements of this /// collection of collections. @inlinable // FIXME(sil-serialize-all) public func joined() -> FlattenCollection<Self> { return FlattenCollection(self) } } extension LazyCollectionProtocol where Self : Collection, Element : Collection { /// A concatenation of the elements of `self`. @inlinable // FIXME(sil-serialize-all) public func joined() -> LazyCollection<FlattenCollection<Elements>> { return FlattenCollection(elements).lazy } } // @available(*, deprecated, renamed: "FlattenCollection.Index") public typealias FlattenCollectionIndex<T> = FlattenCollection<T>.Index where T : Collection, T.Element : Collection @available(*, deprecated, renamed: "FlattenCollection.Index") public typealias FlattenBidirectionalCollectionIndex<T> = FlattenCollection<T>.Index where T : BidirectionalCollection, T.Element : BidirectionalCollection @available(*, deprecated, renamed: "FlattenCollection") public typealias FlattenBidirectionalCollection<T> = FlattenCollection<T> where T : BidirectionalCollection, T.Element : BidirectionalCollection
apache-2.0
568a531a9ed856e49028a0aa4fd29f17
31.580524
155
0.651742
3.990367
false
false
false
false
hwj4477/CustomPickerDialog-Swift
CustomPickerDialog/CustomPickerDialog.swift
1
9020
// // CustomPickerDialog.swift // // Created by hwj4477 on 2016. 3. 16.. // import UIKit class CustomPickerDialog<T>: UIView, UIPickerViewDataSource, UIPickerViewDelegate { typealias CustomPickerCallback = (_ result: T) -> Void typealias CustomDataSourceFormat = (T) -> String // constants fileprivate let componentNum: Int = 1 fileprivate let titleHeight: CGFloat = 30 fileprivate let buttonHeight: CGFloat = 50 fileprivate let doneButtonTag: Int = 1 // view fileprivate var dialogView: UIView! fileprivate var titleLabel: UILabel! fileprivate var pickerView: UIPickerView! fileprivate var cancelButton: UIButton! fileprivate var doneButton: UIButton! // callback fileprivate var callback: CustomPickerCallback? fileprivate var dataSourceFormat: CustomDataSourceFormat? // data fileprivate var dataSelcted: T? fileprivate var dataSource: [T]? init() { super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)) initView() } init(dataSource: [T], dataSourceFormat: @escaping CustomDataSourceFormat) { super.init(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height)) initView() setDataSource(dataSource) self.dataSourceFormat = dataSourceFormat } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } fileprivate func initView() { self.frame = CGRect(x: 0, y: 0, width: UIScreen.main.applicationFrame.size.width, height: UIScreen.main.bounds.size.height) self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.main.scale self.dialogView = createDialogView() self.addSubview(self.dialogView!) } fileprivate func createDialogView() -> UIView { let dialogSize = CGSize(width: 300, height: 250 + buttonHeight) let dialogContainer = UIView(frame: CGRect(x: (self.frame.size.width - dialogSize.width) / 2, y: (self.frame.size.height - dialogSize.height) / 2, width: dialogSize.width, height: dialogSize.height)) dialogContainer.backgroundColor = UIColor.white dialogContainer.layer.shouldRasterize = true dialogContainer.layer.rasterizationScale = UIScreen.main.scale dialogContainer.layer.cornerRadius = 7 dialogContainer.layer.borderColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1).cgColor dialogContainer.layer.borderWidth = 1 dialogContainer.layer.shadowRadius = 12 dialogContainer.layer.shadowOpacity = 0.1 dialogContainer.layer.shadowOffset = CGSize(width: -6, height: -6) dialogContainer.layer.shadowColor = UIColor.black.cgColor dialogContainer.layer.shadowPath = UIBezierPath(roundedRect: dialogContainer.bounds, cornerRadius: dialogContainer.layer.cornerRadius).cgPath //Title self.titleLabel = UILabel(frame: CGRect(x: 10, y: 10, width: 280, height: titleHeight)) self.titleLabel.textAlignment = NSTextAlignment.center self.titleLabel.font = UIFont.boldSystemFont(ofSize: 17) dialogContainer.addSubview(self.titleLabel) // PickerView pickerView = UIPickerView.init(frame: CGRect(x: 0, y: titleHeight, width: dialogSize.width, height: dialogSize.height - buttonHeight - 10)) pickerView.delegate = self dialogContainer.addSubview(pickerView) // Line let lineView = UIView(frame: CGRect(x: 0, y: dialogContainer.bounds.size.height - buttonHeight, width: dialogContainer.bounds.size.width, height: 1)) lineView.backgroundColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1) dialogContainer.addSubview(lineView) // Button let buttonWidth = dialogContainer.bounds.size.width / 2 self.cancelButton = UIButton(type: UIButtonType.custom) as UIButton self.cancelButton.frame = CGRect(x: 0, y: dialogContainer.bounds.size.height - buttonHeight, width: buttonWidth, height: buttonHeight) self.cancelButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), for: UIControlState()) self.cancelButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), for: UIControlState.highlighted) self.cancelButton.titleLabel!.font = UIFont.boldSystemFont(ofSize: 14) self.cancelButton.layer.cornerRadius = 7 self.cancelButton.addTarget(self, action: #selector(CustomPickerDialog.clickButton(_:)), for: UIControlEvents.touchUpInside) dialogContainer.addSubview(self.cancelButton) self.doneButton = UIButton(type: UIButtonType.custom) as UIButton self.doneButton.tag = doneButtonTag self.doneButton.frame = CGRect(x: buttonWidth, y: dialogContainer.bounds.size.height - buttonHeight, width: buttonWidth, height: buttonHeight) self.doneButton.setTitleColor(UIColor(red: 0, green: 0.5, blue: 1, alpha: 1), for: UIControlState()) self.doneButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 0.5), for: UIControlState.highlighted) self.doneButton.titleLabel!.font = UIFont.boldSystemFont(ofSize: 14) self.doneButton.layer.cornerRadius = 7 self.doneButton.addTarget(self, action: #selector(CustomPickerDialog.clickButton(_:)), for: UIControlEvents.touchUpInside) dialogContainer.addSubview(self.doneButton) self.doneButton.setTitle("OK", for: UIControlState()) self.cancelButton.setTitle("Cancel", for: UIControlState()) return dialogContainer } // MARK: public func func setDataSource(_ source: [T]) { self.dataSource = source self.dataSelcted = self.dataSource?.first } func selectRow(_ row: Int) { self.dataSelcted = self.dataSource?[row] self.pickerView.selectRow(row, inComponent: 0, animated: true) } func showDialog(_ title: String, doneButtonTitle: String = "OK", cancelButtonTitle: String = "Cancel", callback: @escaping CustomPickerCallback) { self.titleLabel.text = title self.doneButton.setTitle(doneButtonTitle, for: UIControlState()) self.cancelButton.setTitle(cancelButtonTitle, for: UIControlState()) self.callback = callback UIApplication.shared.windows.first!.addSubview(self) UIApplication.shared.windows.first!.endEditing(true) // Animation self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.0) self.dialogView!.layer.opacity = 0.5 self.dialogView!.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1) UIView.animate( withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.4) self.dialogView!.layer.opacity = 1 self.dialogView!.layer.transform = CATransform3DMakeScale(1, 1, 1) }, completion: nil ) } func close() { // Animation UIView.animate( withDuration: 0.2, delay: 0, options: UIViewAnimationOptions(), animations: { () -> Void in self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.0) self.dialogView!.layer.opacity = 0.1 self.dialogView!.layer.transform = CATransform3DMakeScale(0.1, 0.1, 1) }) { (finished: Bool) -> Void in self.removeFromSuperview() } } // MARK: Button Event func clickButton(_ sender: UIButton!) { if sender.tag == doneButtonTag { self.callback?(dataSelcted!) } close() } // UIPickerView Delegate func numberOfComponents(in pickerView: UIPickerView) -> Int { return componentNum } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if let count = self.dataSource?.count { return count } return 0 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if let data = self.dataSource?[row], let dataFormat = dataSourceFormat { return dataFormat(data) } return nil } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { self.selectRow(row) } }
mit
8f0b9ba060b44dd612491ab04c4435ce
38.388646
207
0.637472
4.742376
false
false
false
false
DMuckerman/tldr-swift
tldr/Markdown.swift
1
79147
/* Markdown.swift Copyright (c) 2014 Kristopher Johnson 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. */ /* Markdown.swift is based on MarkdownSharp, whose licenses and history are enumerated in the following sections. */ /* * MarkdownSharp * ------------- * a C# Markdown processor * * Markdown is a text-to-HTML conversion tool for web writers * Copyright (c) 2004 John Gruber * http://daringfireball.net/projects/markdown/ * * Markdown.NET * Copyright (c) 2004-2009 Milan Negovan * http://www.aspnetresources.com * http://aspnetresources.com/blog/markdown_announced.aspx * * MarkdownSharp * Copyright (c) 2009-2011 Jeff Atwood * http://stackoverflow.com * http://www.codinghorror.com/blog/ * http://code.google.com/p/markdownsharp/ * * History: Milan ported the Markdown processor to C#. He granted license to me so I can open source it * and let the community contribute to and improve MarkdownSharp. * */ /* Copyright (c) 2009 - 2010 Jeff Atwood http://www.opensource.org/licenses/mit-license.php 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. Copyright (c) 2003-2004 John Gruber <http://daringfireball.net/> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name "Markdown" nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. */ import Foundation public struct MarkdownOptions { /// when true, (most) bare plain URLs are auto-hyperlinked /// WARNING: this is a significant deviation from the markdown spec public var autoHyperlink: Bool = false /// when true, RETURN becomes a literal newline /// WARNING: this is a significant deviation from the markdown spec public var autoNewlines: Bool = false /// use ">" for HTML output, or " />" for XHTML output public var emptyElementSuffix: String = " />" /// when true, problematic URL characters like [, ], (, and so forth will be encoded /// WARNING: this is a significant deviation from the markdown spec public var encodeProblemUrlCharacters: Bool = false /// when false, email addresses will never be auto-linked /// WARNING: this is a significant deviation from the markdown spec public var linkEmails: Bool = true /// when true, bold and italic require non-word characters on either side /// WARNING: this is a significant deviation from the markdown spec public var strictBoldItalic: Bool = false public init() {} } /// Markdown is a text-to-HTML conversion tool for web writers. /// /// Markdown allows you to write using an easy-to-read, easy-to-write plain text format, /// then convert it to structurally valid XHTML (or HTML). public struct Markdown { // The MarkdownRegex, MarkdownRegexOptions, and MarkdownRegexMatch types // provide interfaces similar to .NET's Regex, RegexOptions, and Match. private typealias Regex = MarkdownRegex private typealias RegexOptions = MarkdownRegexOptions private typealias Match = MarkdownRegexMatch private typealias MatchEvaluator = (Match) -> String /// MarkdownSharp version on which this implementation is based private let _version = "1.13" /// Create a new Markdown instance and set the options from the MarkdownOptions object. public init(options: MarkdownOptions? = nil) { if Markdown.staticsInitialized { if let options = options { _autoHyperlink = options.autoHyperlink _autoNewlines = options.autoNewlines _emptyElementSuffix = options.emptyElementSuffix _encodeProblemUrlCharacters = options.encodeProblemUrlCharacters _linkEmails = options.linkEmails _strictBoldItalic = options.strictBoldItalic } } } /// use ">" for HTML output, or " />" for XHTML output public var emptyElementSuffix: String { get { return _emptyElementSuffix } set(value) { _emptyElementSuffix = value } } private var _emptyElementSuffix = " />" /// when false, email addresses will never be auto-linked /// WARNING: this is a significant deviation from the markdown spec public var linkEmails: Bool { get { return _linkEmails } set(value) { _linkEmails = value } } private var _linkEmails = true /// when true, bold and italic require non-word characters on either side /// WARNING: this is a significant deviation from the markdown spec public var strictBoldItalic: Bool { get { return _strictBoldItalic } set(value) { _strictBoldItalic = value } } private var _strictBoldItalic = false /// when true, RETURN becomes a literal newline /// WARNING: this is a significant deviation from the markdown spec public var autoNewLines: Bool { get { return _autoNewlines } set(value) { _autoNewlines = value } } private var _autoNewlines = false /// when true, (most) bare plain URLs are auto-hyperlinked /// WARNING: this is a significant deviation from the markdown spec public var autoHyperlink: Bool { get { return _autoHyperlink } set(value) { _autoHyperlink = value } } private var _autoHyperlink = false /// when true, problematic URL characters like [, ], (, and so forth will be encoded /// WARNING: this is a significant deviation from the markdown spec public var encodeProblemUrlCharacters: Bool { get { return _encodeProblemUrlCharacters } set(value) { _encodeProblemUrlCharacters = value } } private var _encodeProblemUrlCharacters = false private enum TokenType { case Text case Tag } private struct Token { private init(type: TokenType, value: String) { self.type = type self.value = value } private var type: TokenType private var value: String } /// maximum nested depth of [] and () supported by the transform; implementation detail private static let _nestDepth = 6 /// Tabs are automatically converted to spaces as part of the transform /// this constant determines how "wide" those tabs become in spaces private static let _tabWidth = 4 private static let _markerUL = "[*+-]" private static let _markerOL = "\\d+[.]" private static var _escapeTable = Dictionary<String, String>() private static var _invertedEscapeTable = Dictionary<String, String>() private static var _backslashEscapeTable = Dictionary<String, String>() private var _urls = Dictionary<String, String>() private var _titles = Dictionary<String, String>() private var _htmlBlocks = Dictionary<String, String>() private var _listLevel: Int = 0 private static let autoLinkPreventionMarker = "\u{1A}P" // temporarily replaces "://" where auto-linking shouldn't happen; /// Swift doesn't have static initializers, so our trick is to /// define this static property with an initializer, and use the /// property in init() to force initialization. private static let staticsInitialized: Bool = { // Table of hash values for escaped characters: _escapeTable = Dictionary<String, String>() _invertedEscapeTable = Dictionary<String, String>() // Table of hash value for backslash escaped characters: _backslashEscapeTable = Dictionary<String, String>() var backslashPattern = "" for c in "\\`*_{}[]()>#+-.!/".characters { let key = String(c) let hash = Markdown.getHashKey(key, isHtmlBlock: false) _escapeTable[key] = hash _invertedEscapeTable[hash] = key _backslashEscapeTable["\\" + key] = hash if !backslashPattern.isEmpty { backslashPattern += "|" } backslashPattern += Regex.escape("\\" + key) } _backslashEscapes = Regex(backslashPattern) return true }() /// current version of MarkdownSharp; /// see http://code.google.com/p/markdownsharp/ for the latest code or to contribute public var version: String { get { return _version } } /// Transforms the provided Markdown-formatted text to HTML; /// see http://en.wikipedia.org/wiki/Markdown /// /// - parameter text: Markdown-format text to be transformed to HTML /// /// - returns: HTML-format text public mutating func transform(text: String) -> String { // The order in which other subs are called here is // essential. Link and image substitutions need to happen before // EscapeSpecialChars(), so that any *'s or _'s in the a // and img tags get encoded. if text.isEmpty { return "" } setup() var text = normalize(text) text = hashHTMLBlocks(text) text = stripLinkDefinitions(text) text = runBlockGamut(text) text = unescape(text) cleanup() return text + "\n" } /// Perform transformations that form block-level tags like paragraphs, headers, and list items. private mutating func runBlockGamut(text: String, unhash: Bool = true) -> String { var text = doHeaders(text) text = doHorizontalRules(text) text = doLists(text) text = doCodeBlocks(text) text = doBlockQuotes(text) // We already ran HashHTMLBlocks() before, in Markdown(), but that // was to escape raw HTML in the original Markdown source. This time, // we're escaping the markup we've just created, so that we don't wrap // <p> tags around block-level tags. text = hashHTMLBlocks(text) text = formParagraphs(text, unhash: unhash) return text } /// Perform transformations that occur *within* block-level tags like paragraphs, headers, and list items. private func runSpanGamut(text: String) -> String { var text = doCodeSpans(text) text = escapeSpecialCharsWithinTagAttributes(text) text = escapeBackslashes(text) // Images must come first, because ![foo][f] looks like an anchor. text = doImages(text) text = doAnchors(text) // Must come after DoAnchors(), because you can use < and > // delimiters in inline links like [this](<url>). text = doAutoLinks(text) text = text.stringByReplacingOccurrencesOfString(Markdown.autoLinkPreventionMarker, withString: "://") text = encodeAmpsAndAngles(text) text = doItalicsAndBold(text) text = doHardBreaks(text) return text } private static let _newlinesLeadingTrailing = Regex("^\\n+|\\n+\\z") private static let _newlinesMultiple = Regex("\\n{2,}") private static let _leadingWhitespace = Regex("^\\p{Z}*") private static let _htmlBlockHash = Regex("\u{1A}H\\d+H") /// splits on two or more newlines, to form "paragraphs"; /// each paragraph is then unhashed (if it is a hash and unhashing isn't turned off) or wrapped in HTML p tag private func formParagraphs(text: String, unhash: Bool = true) -> String { // split on two or more newlines var grafs = Markdown._newlinesMultiple.split( Markdown._newlinesLeadingTrailing.replace(text, "")) let grafsLength = grafs.count for i in 0..<grafsLength { if (grafs[i].hasPrefix("\u{1A}H")) { // unhashify HTML blocks if unhash { var sanityCheck = 50 // just for safety, guard against an infinite loop var keepGoing = true // as long as replacements where made, keep going while keepGoing && sanityCheck > 0 { keepGoing = false let graf = grafs[i] grafs[i] = Markdown._htmlBlockHash.replace(graf) { match in if let replacementValue = self._htmlBlocks[match.value as String] { keepGoing = true return replacementValue } return graf } sanityCheck -= 1 } /* if (keepGoing) { // Logging of an infinite loop goes here. // If such a thing should happen, please open a new issue on http://code.google.com/p/markdownsharp/ // with the input that caused it. }*/ } } else { // do span level processing inside the block, then wrap result in <p> tags let paragraph = Markdown._leadingWhitespace.replace(runSpanGamut(grafs[i]), "<p>") + "</p>" grafs[i] = paragraph } } return grafs.joinWithSeparator("\n\n") } private mutating func setup() { // Clear the global hashes. If we don't clear these, you get conflicts // from other articles when generating a page which contains more than // one article (e.g. an index page that shows the N most recent // articles): _urls.removeAll(keepCapacity: false) _titles.removeAll(keepCapacity: false) _htmlBlocks.removeAll(keepCapacity: false) _listLevel = 0 } private mutating func cleanup() { setup() } private static var _nestedBracketsPattern = "" /// Reusable pattern to match balanced [brackets]. See Friedl's /// "Mastering Regular Expressions", 2nd Ed., pp. 328-331. private static func getNestedBracketsPattern() -> String { // in other words [this] and [this[also]] and [this[also[too]]] // up to _nestDepth if (_nestedBracketsPattern.isEmpty) { _nestedBracketsPattern = repeatString([ "(?> # Atomic matching", "[^\\[\\]]+ # Anything other than brackets", "|", "\\[" ].joinWithSeparator("\n"), _nestDepth) + repeatString(" \\])*", _nestDepth) } return _nestedBracketsPattern } private static var _nestedParensPattern = "" /// Reusable pattern to match balanced (parens). See Friedl's /// "Mastering Regular Expressions", 2nd Ed., pp. 328-331. private static func getNestedParensPattern() -> String { // in other words (this) and (this(also)) and (this(also(too))) // up to _nestDepth if (_nestedParensPattern.isEmpty) { _nestedParensPattern = repeatString([ "(?> # Atomic matching", "[^()\\s]+ # Anything other than parens or whitespace", "|", "\\(" ].joinWithSeparator("\n"), _nestDepth) + repeatString(" \\))*", _nestDepth) } return _nestedParensPattern } private static var _linkDef = Regex([ "^\\p{Z}{0,\(Markdown._tabWidth - 1)}\\[([^\\[\\]]+)\\]: # id = $1", " \\p{Z}*", " \\n? # maybe *one* newline", " \\p{Z}*", "<?(\\S+?)>? # url = $2", " \\p{Z}*", " \\n? # maybe one newline", " \\p{Z}*", "(?:", " (?<=\\s) # lookbehind for whitespace", " [\"(]", " (.+?) # title = $3", " [\")]", " \\p{Z}*", ")? # title is optional", "(?:\\n+|\\Z)" ].joinWithSeparator("\n"), options: RegexOptions.Multiline.union(RegexOptions.IgnorePatternWhitespace)) /// Strips link definitions from text, stores the URLs and titles in hash references. /// /// ^[id]: url "optional title" private mutating func stripLinkDefinitions(text: String) -> String { return Markdown._linkDef.replace(text) { self.linkEvaluator($0) } } private mutating func linkEvaluator(match: Match) -> String { let linkID = match.valueOfGroupAtIndex(1) as String _urls[linkID] = encodeAmpsAndAngles(match.valueOfGroupAtIndex(2) as String) let group3Value = match.valueOfGroupAtIndex(3) if group3Value.length != 0 { _titles[linkID] = group3Value.stringByReplacingOccurrencesOfString("\"", withString: "&quot") } return "" } private static let _blocksHtml = Regex(Markdown.getBlockPattern(), options: RegexOptions.Multiline.union(RegexOptions.IgnorePatternWhitespace)) /// derived pretty much verbatim from PHP Markdown private static func getBlockPattern() -> String { // Hashify HTML blocks: // We only want to do this for block-level HTML tags, such as headers, // lists, and tables. That's because we still want to wrap <p>s around // "paragraphs" that are wrapped in non-block-level tags, such as anchors, // phrase emphasis, and spans. The list of tags we're looking for is // hard-coded: // // * List "a" is made of tags which can be both inline or block-level. // These will be treated block-level when the start tag is alone on // its line, otherwise they're not matched here and will be taken as // inline later. // * List "b" is made of tags which are always block-level; // let blockTagsA = "ins|del" let blockTagsB = "p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|script|noscript|form|fieldset|iframe|math" // Regular expression for the content of a block tag. let attr = [ "(?> # optional tag attributes", " \\s # starts with whitespace", " (?>", " [^>\"/]+ # text outside quotes", " |", " /+(?!>) # slash not followed by >", " |", " \"[^\"]*\" # text inside double quotes (tolerate >)", " |", " '[^']*' # text inside single quotes (tolerate >)", " )*", ")?" ].joinWithSeparator("\n") let content = repeatString([ "(?>", " [^<]+ # content without tag", "|", " <\\2 # nested opening tag", attr, "(?>", " />", "|", " >"].joinWithSeparator("\n"), _nestDepth) + // end of opening tag ".*?" + // last level nested tag content repeatString([ " </\\2\\s*> # closing nested tag", " )", " | ", " <(?!/\\2\\s*> # other tags with a different name", " )", ")*"].joinWithSeparator("\n"), _nestDepth) let content2 = content.stringByReplacingOccurrencesOfString("\\2", withString: "\\3") // First, look for nested blocks, e.g.: // <div> // <div> // tags for inner block must be indented. // </div> // </div> // // The outermost tags must start at the left margin for this to match, and // the inner nested divs must be indented. // We need to do this before the next, more liberal match, because the next // match will start at the first `<div>` and stop at the first `</div>`. var pattern = [ "(?>", " (?>", " (?<=\\n) # Starting at the beginning of a line", " | # or", " \\A\\n? # the beginning of the doc", " )", " ( # save in $1", "", " # Match from `\\n<tag>` to `</tag>\\n`, handling nested tags ", " # in between.", " ", " <($block_tags_b_re) # start tag = $2", " $attr> # attributes followed by > and \\n", " $content # content, support nesting", " </\\2> # the matching end tag", " \\p{Z}* # trailing spaces", " (?=\\n+|\\Z) # followed by a newline or end of document", "", " | # Special version for tags of group a.", "", " <($block_tags_a_re) # start tag = $3", " $attr>\\p{Z}*\\n # attributes followed by >", " $content2 # content, support nesting", " </\\3> # the matching end tag", " \\p{Z}* # trailing spaces", " (?=\\n+|\\Z) # followed by a newline or end of document", " ", " | # Special case just for <hr />. It was easier to make a special ", " # case than to make the other regex more complicated.", " ", " \\p{Z}{0,$less_than_tab}", " <hr", " $attr # attributes", " /?> # the matching end tag", " \\p{Z}*", " (?=\\n{2,}|\\Z) # followed by a blank line or end of document", " ", " | # Special case for standalone HTML comments:", " ", " (?<=\\n\\n|\\A) # preceded by a blank line or start of document", " \\p{Z}{0,$less_than_tab}", " (?s:", " <!--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)-->", " )", " \\p{Z}*", " (?=\\n{2,}|\\Z) # followed by a blank line or end of document", " ", " | # PHP and ASP-style processor instructions (<? and <%)", " ", " \\p{Z}{0,$less_than_tab}", " (?s:", " <([?%]) # $4", " .*?", " \\4>", " )", " \\p{Z}*", " (?=\\n{2,}|\\Z) # followed by a blank line or end of document", " ", " )", ")" ].joinWithSeparator("\n") pattern = pattern.stringByReplacingOccurrencesOfString("$less_than_tab", withString: String(_tabWidth - 1)) pattern = pattern.stringByReplacingOccurrencesOfString("$block_tags_b_re", withString: blockTagsB) pattern = pattern.stringByReplacingOccurrencesOfString("$block_tags_a_re", withString: blockTagsA) pattern = pattern.stringByReplacingOccurrencesOfString("$attr", withString: attr) pattern = pattern.stringByReplacingOccurrencesOfString("$content2", withString: content2) pattern = pattern.stringByReplacingOccurrencesOfString("$content", withString: content) return pattern } /// replaces any block-level HTML blocks with hash entries private mutating func hashHTMLBlocks(text: String) -> String { return Markdown._blocksHtml.replace(text) { self.htmlEvaluator($0) } } private mutating func htmlEvaluator(match: Match) -> String { let text: String = match.valueOfGroupAtIndex(1) as String ?? "" let key = Markdown.getHashKey(text, isHtmlBlock: true) _htmlBlocks[key] = text return "\n\n\(key)\n\n" } private static func getHashKey(s: String, isHtmlBlock: Bool) -> String { let delim = isHtmlBlock ? "H" : "E" return "\u{1A}" + delim + String(abs(s.hashValue)) + delim } // TODO: C# code uses RegexOptions.ExplicitCapture here. Need to figure out // how/whether to emulate that with NSRegularExpression. private static let _htmlTokens = Regex([ "(<!--(?:|(?:[^>-]|-[^>])(?:[^-]|-[^-])*)-->)| # match <!-- foo -->", "(<\\?.*?\\?>)| # match <?foo?>" ].joinWithSeparator("\n") + Markdown.repeatString("(<[A-Za-z\\/!$](?:[^<>]|", _nestDepth) + Markdown.repeatString(")*>)", _nestDepth) + " # match <tag> and </tag>", options: RegexOptions.Multiline.union(RegexOptions.Singleline).union(RegexOptions.IgnorePatternWhitespace)) /// returns an array of HTML tokens comprising the input string. Each token is /// either a tag (possibly with nested, tags contained therein, such /// as &lt;a href="&lt;MTFoo&gt;"&gt;, or a run of text between tags. Each element of the /// array is a two-element array; the first is either 'tag' or 'text'; the second is /// the actual value. private func tokenizeHTML(text: String) -> [Token] { var pos = 0 var tagStart = 0 var tokens = Array<Token>() let str = text as NSString // this regex is derived from the _tokenize() subroutine in Brad Choate's MTRegex plugin. // http://www.bradchoate.com/past/mtregex.php for match in Markdown._htmlTokens.matches(text) { tagStart = match.index if pos < tagStart { let range = NSMakeRange(pos, tagStart - pos) tokens.append(Token(type: .Text, value: str.substringWithRange(range))) } tokens.append(Token(type: .Tag, value: match.value as String)) pos = tagStart + match.length } if pos < str.length { tokens.append(Token(type: .Text, value: str.substringWithRange(NSMakeRange(pos, Int(str.length) - pos)))) } return tokens } private static let _anchorRef = Regex([ "( # wrap whole match in $1", " \\[", " (\(Markdown.getNestedBracketsPattern())) # link text = $2", " \\]", "", " \\p{Z}? # one optional space", " (?:\\n\\p{Z}*)? # one optional newline followed by spaces", "", " \\[", " (.*?) # id = $3", " \\]", ")" ].joinWithSeparator("\n"), options: RegexOptions.Singleline.union(RegexOptions.IgnorePatternWhitespace)) private static let _anchorInline = Regex([ "( # wrap whole match in $1", " \\[", " (\(Markdown.getNestedBracketsPattern())) # link text = $2", " \\]", " \\( # literal paren", " \\p{Z}*", " (\(Markdown.getNestedParensPattern())) # href = $3", " \\p{Z}*", " ( # $4", " (['\"]) # quote char = $5", " (.*?) # title = $6", " \\5 # matching quote", " \\p{Z}* # ignore any spaces between closing quote and )", " )? # title is optional", " \\)", ")" ].joinWithSeparator("\n"), options: RegexOptions.Singleline.union(RegexOptions.IgnorePatternWhitespace)) private static let _anchorRefShortcut = Regex([ "( # wrap whole match in $1", " \\[", " ([^\\[\\]]+) # link text = $2; can't contain [ or ]", " \\]", ")" ].joinWithSeparator("\n"), options: RegexOptions.Singleline.union(RegexOptions.IgnorePatternWhitespace)) /// Turn Markdown link shortcuts into HTML anchor tags /// /// - [link text](url "title") /// - [link text][id] /// - [id] private func doAnchors(text: String) -> String { // First, handle reference-style links: [link text] [id] var text = Markdown._anchorRef.replace(text) { self.anchorRefEvaluator($0) } // Next, inline-style links: [link text](url "optional title") or [link text](url "optional title") text = Markdown._anchorInline.replace(text) { self.anchorInlineEvaluator($0) } // Last, handle reference-style shortcuts: [link text] // These must come last in case you've also got [link test][1] // or [link test](/foo) text = Markdown._anchorRefShortcut.replace(text) { self.anchorRefShortcutEvaluator($0) } return text } private func saveFromAutoLinking(s: String) -> String { return s.stringByReplacingOccurrencesOfString("://", withString: Markdown.autoLinkPreventionMarker) } private func anchorRefEvaluator(match: Match) -> String { let wholeMatch = match.valueOfGroupAtIndex(1) let linkText = saveFromAutoLinking(match.valueOfGroupAtIndex(2) as String) var linkID = match.valueOfGroupAtIndex(3).lowercaseString var result: String // for shortcut links like [this][]. if linkID.isEmpty { linkID = linkText.lowercaseString } if var url = _urls[linkID] { url = encodeProblemUrlChars(url) url = escapeBoldItalic(url) result = "<a href=\"\(url)\"" if var title = _titles[linkID] { title = Markdown.attributeEncode(title) title = Markdown.attributeEncode(escapeBoldItalic(title)) result += " title=\"\(title)\"" } result += ">\(linkText)</a>" } else { result = wholeMatch as String } return result } private func anchorRefShortcutEvaluator(match: Match) -> String { let wholeMatch = match.valueOfGroupAtIndex(1) let linkText = saveFromAutoLinking(match.valueOfGroupAtIndex(2) as String) let linkID = Regex.replace(linkText.lowercaseString, pattern: "\\p{Z}*\\n\\p{Z}*", replacement: " ") // lower case and remove newlines / extra spaces var result: String if var url = _urls[linkID] { url = encodeProblemUrlChars(url) url = escapeBoldItalic(url) result = "<a href=\"\(url)\"" if var title = _titles[linkID] { title = Markdown.attributeEncode(title) title = escapeBoldItalic(title) result += " title=\"\(title)\"" } result += ">\(linkText)</a>" } else { result = wholeMatch as String } return result } private func anchorInlineEvaluator(match: Match) -> String { let linkText = saveFromAutoLinking(match.valueOfGroupAtIndex(2) as String) var url = match.valueOfGroupAtIndex(3) var title = match.valueOfGroupAtIndex(6) var result: String url = encodeProblemUrlChars(url as String) url = escapeBoldItalic(url as String) if url.hasPrefix("<") && url.hasSuffix(">") { url = url.substringWithRange(NSMakeRange(1, url.length - 2)) // remove <>'s surrounding URL, if present } result = "<a href=\"\(url)\"" if title.length != 0 { title = Markdown.attributeEncode(title as String) title = escapeBoldItalic(title as String) result += " title=\"\(title)\"" } result += ">\(linkText)</a>" return result } private static let _imagesRef = Regex([ "( # wrap whole match in $1", "!\\[", " (.*?) # alt text = $2", "\\]", "", "\\p{Z}? # one optional space", "(?:\\n\\p{Z}*)? # one optional newline followed by spaces", "", "\\[", " (.*?) # id = $3", "\\]", "", ")" ].joinWithSeparator("\n"), options: RegexOptions.IgnorePatternWhitespace.union(RegexOptions.Singleline)) private static let _imagesInline = Regex([ "( # wrap whole match in $1", " !\\[", " (.*?) # alt text = $2", " \\]", " \\s? # one optional whitespace character", " \\( # literal paren", " \\p{Z}*", " (\(Markdown.getNestedParensPattern())) # href = $3", " \\p{Z}*", " ( # $4", " (['\"]) # quote char = $5", " (.*?) # title = $6", " \\5 # matching quote", " \\p{Z}*", " )? # title is optional", " \\)", ")" ].joinWithSeparator("\n"), options: RegexOptions.IgnorePatternWhitespace.union(RegexOptions.Singleline)) /// Turn Markdown image shortcuts into HTML img tags. /// /// - ![alt text][id] /// - ![alt text](url "optional title") private func doImages(text: String) -> String { // First, handle reference-style labeled images: ![alt text][id] var text = Markdown._imagesRef.replace(text) { self.imageReferenceEvaluator($0) } // Next, handle inline images: ![alt text](url "optional title") // Don't forget: encode * and _ text = Markdown._imagesInline.replace(text) { self.imageInlineEvaluator($0) } return text } // This prevents the creation of horribly broken HTML when some syntax ambiguities // collide. It likely still doesn't do what the user meant, but at least we're not // outputting garbage. private func escapeImageAltText(s: String) -> String { var s = escapeBoldItalic(s) s = Regex.replace(s, pattern: "[\\[\\]()]") { Markdown._escapeTable[$0.value as String]! } return s } private func imageReferenceEvaluator(match: Match) -> String { let wholeMatch = match.valueOfGroupAtIndex(1) let altText = match.valueOfGroupAtIndex(2) var linkID = match.valueOfGroupAtIndex(3).lowercaseString // for shortcut links like ![this][]. if linkID.isEmpty { linkID = altText.lowercaseString } if let url = _urls[linkID] { var title: String? = nil if let t = _titles[linkID] { title = t } return imageTag(url, altText: altText as String, title: title) } else{ // If there's no such link ID, leave intact: return wholeMatch as String } } private func imageInlineEvaluator(match: Match) -> String { let alt = match.valueOfGroupAtIndex(2) var url = match.valueOfGroupAtIndex(3) let title = match.valueOfGroupAtIndex(6) if url.hasPrefix("<") && url.hasSuffix(">") { url = url.substringWithRange(NSMakeRange(1, url.length - 2)) // Remove <>'s surrounding URL, if present } return imageTag(url as String, altText: alt as String, title: title as String) } private func imageTag(url: String, altText: String, title: String?) -> String { let altText = escapeImageAltText(Markdown.attributeEncode(altText)) var url = encodeProblemUrlChars(url) url = escapeBoldItalic(url) var result = "<img src=\"\(url)\" alt=\"\(altText)\"" if var title = title { if !title.isEmpty { title = Markdown.attributeEncode(escapeBoldItalic(title)) result += " title=\"\(title)\"" } } result += _emptyElementSuffix return result } private static let _headerSetext = Regex([ "^(.+?)", "\\p{Z}*", "\\n", "(=+|-+) # $1 = string of ='s or -'s", "\\p{Z}*", "\\n+" ].joinWithSeparator("\n"), options: RegexOptions.Multiline.union(RegexOptions.IgnorePatternWhitespace)) private static let _headerAtx = Regex([ "^(\\#{1,6}) # $1 = string of #'s", "\\p{Z}*", "(.+?) # $2 = Header text", "\\p{Z}*", "\\#* # optional closing #'s (not counted)", "\\n+" ].joinWithSeparator("\n"), options: RegexOptions.Multiline.union(RegexOptions.IgnorePatternWhitespace)) /// Turn Markdown headers into HTML header tags /// /// Header 1 /// ======== /// /// Header 2 /// -------- /// /// # Header 1 /// /// ## Header 2 /// /// ## Header 2 with closing hashes ## /// /// ... /// /// ###### Header 6 private func doHeaders(text: String) -> String { var text = Markdown._headerSetext.replace(text) { self.setextHeaderEvaluator($0) } text = Markdown._headerAtx.replace(text) { self.atxHeaderEvaluator($0) } return text } private func setextHeaderEvaluator(match: Match) -> String { let header = match.valueOfGroupAtIndex(1) let level = match.valueOfGroupAtIndex(2).hasPrefix("=") ? 1 : 2 return "<h\(level)>\(runSpanGamut(header as String))</h\(level)>\n\n" } private func atxHeaderEvaluator(match: Match) -> String { let header = match.valueOfGroupAtIndex(2) let level = match.valueOfGroupAtIndex(1).length return "<h\(level)>\(runSpanGamut(header as String))</h\(level)>\n\n" } private static let _horizontalRules = Regex([ "^\\p{Z}{0,3} # Leading space", " ([-*_]) # $1: First marker", " (?> # Repeated marker group", " \\p{Z}{0,2} # Zero, one, or two spaces.", " \\1 # Marker character", " ){2,} # Group repeated at least twice", " \\p{Z}* # Trailing spaces", " $ # End of line." ].joinWithSeparator("\n"), options: RegexOptions.Multiline.union(RegexOptions.IgnorePatternWhitespace)) /// Turn Markdown horizontal rules into HTML hr tags /// /// *** /// /// * * * /// /// --- /// /// - - - private func doHorizontalRules(text: String) -> String { return Markdown._horizontalRules.replace(text, "<hr" + _emptyElementSuffix + "\n") } private static let _listMarker = "(?:\(_markerUL)|\(_markerOL))" private static let _wholeList = [ "( # $1 = whole list", " ( # $2", " \\p{Z}{0,\(_tabWidth - 1)}", " (\(_listMarker)) # $3 = first list item marker", " \\p{Z}+", " )", " (?s:.+?)", " ( # $4", " \\z", " |", " \\n{2,}", " (?=\\S)", " (?! # Negative lookahead for another list item marker", " \\p{Z}*", " \(_listMarker)\\p{Z}+", " )", " )", ")" ].joinWithSeparator("\n") private static let _listNested = Regex("^" + _wholeList, options: RegexOptions.Multiline.union(RegexOptions.IgnorePatternWhitespace)) private static let _listTopLevel = Regex("(?:(?<=\\n\\n)|\\A\\n?)" + _wholeList, options: RegexOptions.Multiline.union(RegexOptions.IgnorePatternWhitespace)) /// Turn Markdown lists into HTML ul and ol and li tags private mutating func doLists(text: String, isInsideParagraphlessListItem: Bool = false) -> String { // We use a different prefix before nested lists than top-level lists. // See extended comment in _ProcessListItems(). var text = text if _listLevel > 0 { let evaluator = getListEvaluator(isInsideParagraphlessListItem) text = Markdown._listNested.replace(text) { evaluator($0) } } else { let evaluator = getListEvaluator(false) text = Markdown._listTopLevel.replace(text) { evaluator($0) } } return text } private mutating func getListEvaluator(isInsideParagraphlessListItem: Bool = false) -> MatchEvaluator { return { match in let list = match.valueOfGroupAtIndex(1) as String let listType = Regex.isMatch(match.valueOfGroupAtIndex(3) as String, pattern: Markdown._markerUL) ? "ul" : "ol" var result: String result = self.processListItems(list, marker: listType == "ul" ? Markdown._markerUL : Markdown._markerOL, isInsideParagraphlessListItem: isInsideParagraphlessListItem) result = "<\(listType)>\n\(result)</\(listType)>\n" return result } } /// Process the contents of a single ordered or unordered list, splitting it /// into individual list items. private mutating func processListItems(list: String, marker: String, isInsideParagraphlessListItem: Bool = false) -> String { // The listLevel global keeps track of when we're inside a list. // Each time we enter a list, we increment it; when we leave a list, // we decrement. If it's zero, we're not in a list anymore. // We do this because when we're not inside a list, we want to treat // something like this: // I recommend upgrading to version // 8. Oops, now this line is treated // as a sub-list. // As a single paragraph, despite the fact that the second line starts // with a digit-period-space sequence. // Whereas when we're inside a list (or sub-list), that line will be // treated as the start of a sub-list. What a kludge, huh? This is // an aspect of Markdown's syntax that's hard to parse perfectly // without resorting to mind-reading. Perhaps the solution is to // change the syntax rules such that sub-lists must start with a // starting cardinal number; e.g. "1." or "a.". _listLevel += 1 // Trim trailing blank lines: var list = Regex.replace(list, pattern: "\\n{2,}\\z", replacement: "\n") let pattern = [ "(^\\p{Z}*) # leading whitespace = $1", "(\(marker)) \\p{Z}+ # list marker = $2", "((?s:.+?) # list item text = $3", "(\\n+))", "(?= (\\z | \\1 (\(marker)) \\p{Z}+))" ].joinWithSeparator("\n") var lastItemHadADoubleNewline = false // has to be a closure, so subsequent invocations can share the bool let listItemEvaluator: MatchEvaluator = { match in var item = match.valueOfGroupAtIndex(3) let endsWithDoubleNewline = item.hasSuffix("\n\n") let containsDoubleNewline = endsWithDoubleNewline || Markdown.doesString(item, containSubstring: "\n\n") if containsDoubleNewline || lastItemHadADoubleNewline { // we could correct any bad indentation here.. item = self.runBlockGamut(self.outdent(item as String) + "\n", unhash: false) } else { // recursion for sub-lists item = self.doLists(self.outdent(item as String), isInsideParagraphlessListItem: true) item = Markdown.trimEnd(item, "\n") if (!isInsideParagraphlessListItem) { // only the outer-most item should run this, otherwise it's run multiple times for the inner ones item = self.runSpanGamut(item as String) } } lastItemHadADoubleNewline = endsWithDoubleNewline return "<li>\(item)</li>\n" } list = Regex.replace(list, pattern: pattern, evaluator: listItemEvaluator, options: RegexOptions.IgnorePatternWhitespace.union(RegexOptions.Multiline)) _listLevel -= 1 return list } private static let _codeBlock = Regex([ "(?:\\n\\n|\\A\\n?)", "( # $1 = the code block -- one or more lines, starting with a space", "(?:", " (?:\\p{Z}{\(_tabWidth)}) # Lines must start with a tab-width of spaces", " .*\\n+", ")+", ")", "((?=^\\p{Z}{0,\(_tabWidth)}[^ \\t\\n])|\\Z) # Lookahead for non-space at line-start, or end of doc" ].joinWithSeparator("\n"), options: RegexOptions.Multiline.union(RegexOptions.IgnorePatternWhitespace)) /// Turn Markdown 4-space indented code into HTML pre code blocks private func doCodeBlocks(text: String) -> String { let text = Markdown._codeBlock.replace(text) { self.codeBlockEvaluator($0) } return text } private func codeBlockEvaluator(match: Match) -> String { var codeBlock = match.valueOfGroupAtIndex(1) codeBlock = encodeCode(outdent(codeBlock as String)) codeBlock = Markdown._newlinesLeadingTrailing.replace(codeBlock as String, "") return "\n\n<pre><code>\(codeBlock)\n</code></pre>\n\n" } private static let _codeSpan = Regex([ "(?<![\\\\`]) # Character before opening ` can't be a backslash or backtick", "(`+) # $1 = Opening run of `", "(?!`) # and no more backticks -- match the full run", "(.+?) # $2 = The code block", "(?<!`)", "\\1", "(?!`)" ].joinWithSeparator("\n"), options: RegexOptions.IgnorePatternWhitespace.union(RegexOptions.Singleline)) /// Turn Markdown `code spans` into HTML code tags private func doCodeSpans(text: String) -> String { // * You can use multiple backticks as the delimiters if you want to // include literal backticks in the code span. So, this input: // // Just type ``foo `bar` baz`` at the prompt. // // Will translate to: // // <p>Just type <code>foo `bar` baz</code> at the prompt.</p> // // There's no arbitrary limit to the number of backticks you // can use as delimters. If you need three consecutive backticks // in your code, use four for delimiters, etc. // // * You can use spaces to get literal backticks at the edges: // // ... type `` `bar` `` ... // // Turns to: // // ... type <code>`bar`</code> ... // return Markdown._codeSpan.replace(text) { self.codeSpanEvaluator($0) } } private func codeSpanEvaluator(match: Match) -> String { var span = match.valueOfGroupAtIndex(2) span = Regex.replace(span as String, pattern: "^\\p{Z}*", replacement: "") // leading whitespace span = Regex.replace(span as String, pattern: "\\p{Z}*$", replacement: "") // trailing whitespace span = encodeCode(span as String) span = saveFromAutoLinking(span as String) // to prevent auto-linking. Not necessary in code *blocks*, but in code spans. return "<code>\(span)</code>" } private static let _bold = Regex("(\\*\\*|__) (?=\\S) (.+?[*_]*) (?<=\\S) \\1", options: RegexOptions.IgnorePatternWhitespace.union(RegexOptions.Singleline)) private static let _strictBold = Regex("(^|[\\W_])(?:(?!\\1)|(?=^))(\\*|_)\\2(?=\\S)(.*?\\S)\\2\\2(?!\\2)(?=[\\W_]|$)", options: RegexOptions.Singleline) private static let _italic = Regex("(\\*|_) (?=\\S) (.+?) (?<=\\S) \\1", options: RegexOptions.IgnorePatternWhitespace.union(RegexOptions.Singleline)) private static let _strictItalic = Regex("(^|[\\W_])(?:(?!\\1)|(?=^))(\\*|_)(?=\\S)((?:(?!\\2).)*?\\S)\\2(?!\\2)(?=[\\W_]|$)", options: RegexOptions.Singleline) /// Turn Markdown *italics* and **bold** into HTML strong and em tags private func doItalicsAndBold(text: String) -> String { // <strong> must go first, then <em> var text = text if (_strictBoldItalic) { text = Markdown._strictBold.replace(text, "$1<strong>$3</strong>") text = Markdown._strictItalic.replace(text, "$1<em>$3</em>") } else { text = Markdown._bold.replace(text, "<strong>$2</strong>") text = Markdown._italic.replace(text, "<em>$2</em>") } return text } /// Turn markdown line breaks (two space at end of line) into HTML break tags private func doHardBreaks(text: String) -> String { var text = text if (_autoNewlines) { text = Regex.replace(text, pattern: "\\n", replacement: "<br\(_emptyElementSuffix)\n") } else { text = Regex.replace(text, pattern: " {2,}\n", replacement: "<br\(_emptyElementSuffix)\n") } return text } private static let _blockquote = Regex([ "( # Wrap whole match in $1", " (", " ^\\p{Z}*>\\p{Z}? # '>' at the start of a line", " .+\\n # rest of the first line", " (.+\\n)* # subsequent consecutive lines", " \\n* # blanks", " )+", ")" ].joinWithSeparator("\n"), options: RegexOptions.IgnorePatternWhitespace.union(RegexOptions.Multiline)) /// Turn Markdown > quoted blocks into HTML blockquote blocks private mutating func doBlockQuotes(text: String) -> String { return Markdown._blockquote.replace(text) { self.blockQuoteEvaluator($0) } } private mutating func blockQuoteEvaluator(match: Match) -> String { var bq = match.valueOfGroupAtIndex(1) as String bq = Regex.replace(bq, pattern: "^\\p{Z}*>\\p{Z}?", replacement: "", options: RegexOptions.Multiline) // trim one level of quoting bq = Regex.replace(bq, pattern: "^\\p{Z}+$", replacement: "", options: RegexOptions.Multiline) // trim whitespace-only lines bq = runBlockGamut(bq) // recurse bq = Regex.replace(bq, pattern: "^", replacement: " ", options: RegexOptions.Multiline) // These leading spaces screw with <pre> content, so we need to fix that: bq = Regex.replace(bq, pattern: "(\\s*<pre>.+?</pre>)", evaluator: { self.blockQuoteEvaluator2($0) }, options: RegexOptions.IgnorePatternWhitespace.union(RegexOptions.Singleline)) bq = "<blockquote>\n\(bq)\n</blockquote>" let key = Markdown.getHashKey(bq, isHtmlBlock: true) _htmlBlocks[key] = bq return "\n\n\(key)\n\n" } private func blockQuoteEvaluator2(match: Match) -> String { return Regex.replace(match.valueOfGroupAtIndex(1) as String, pattern: "^ ", replacement: "", options: RegexOptions.Multiline) } private static let _charInsideUrl = "[-A-Z0-9+&@#/%?=~_|\\[\\]\\(\\)!:,\\.;\u{1a}]" private static let _charEndingUrl = "[-A-Z0-9+&@#/%=~_|\\[\\])]" private static let _autolinkBare = Regex("(<|=\")?\\b(https?|ftp)(://\(_charInsideUrl)*\(_charEndingUrl))(?=$|\\W)", options: RegexOptions.IgnoreCase) private static let _endCharRegex = Regex(_charEndingUrl, options: RegexOptions.IgnoreCase) private static func handleTrailingParens(match: Match) -> String { // The first group is essentially a negative lookbehind -- if there's a < or a =", we don't touch this. // We're not using a *real* lookbehind, because of links with in links, like <a href="http://web.archive.org/web/20121130000728/http://www.google.com/"> // With a real lookbehind, the full link would never be matched, and thus the http://www.google.com *would* be matched. // With the simulated lookbehind, the full link *is* matched (just not handled, because of this early return), causing // the google link to not be matched again. if !Markdown.isNilOrEmpty(match.valueOfGroupAtIndex(1)) { return match.value as String } let proto = match.valueOfGroupAtIndex(2) var link: NSString = match.valueOfGroupAtIndex(3) if !link.hasSuffix(")") { return "<\(proto)\(link)>" } var level = 0 for c in Regex.matches(link as String, pattern: "[()]") { if c.value == "(" { if (level <= 0) { level = 1 } else { level += 1 } } else { level -= 1 } } var tail: NSString = "" if level < 0 { link = Regex.replace(link as String, pattern: "\\){1,\(-level)}$", evaluator: { m in tail = m.value return "" }) } if tail.length > 0 { let lastChar = link.substringFromIndex(link.length - 1) if !_endCharRegex.isMatch(lastChar) { tail = "\(lastChar)\(tail)" link = link.substringToIndex(link.length - 1) } } return "<\(proto)\(link)>\(tail)" } /// Turn angle-delimited URLs into HTML anchor tags /// /// &lt;http://www.example.com&gt; private func doAutoLinks(text: String) -> String { var text = text if (_autoHyperlink) { // fixup arbitrary URLs by adding Markdown < > so they get linked as well // note that at this point, all other URL in the text are already hyperlinked as <a href=""></a> // *except* for the <http://www.foo.com> case text = Markdown._autolinkBare.replace(text) { Markdown.handleTrailingParens($0) } } // Hyperlinks: <http://foo.com> text = Regex.replace(text, pattern: "<((https?|ftp):[^'\">\\s]+)>", evaluator: { self.hyperlinkEvaluator($0) }) if (_linkEmails) { // Email addresses: <address@domain.foo> let pattern = [ "<", "(?:mailto:)?", "(", " [-.\\w]+", " \\@", " [-a-z0-9]+(\\.[-a-z0-9]+)*\\.[a-z]+", ")", ">" ].joinWithSeparator("\n") text = Regex.replace(text, pattern: pattern, evaluator: { self.emailEvaluator($0) }, options: RegexOptions.IgnoreCase.union(RegexOptions.IgnorePatternWhitespace)) } return text } private func hyperlinkEvaluator(match: Match) -> String { let link = match.valueOfGroupAtIndex(1) return "<a href=\"\(escapeBoldItalic(encodeProblemUrlChars(link as String)))\">\(link)</a>" } private func emailEvaluator(match: Match) -> String { var email = unescape(match.valueOfGroupAtIndex(1) as String) // // Input: an email address, e.g. "foo@example.com" // // Output: the email address as a mailto link, with each character // of the address encoded as either a decimal or hex entity, in // the hopes of foiling most address harvesting spam bots. E.g.: // // <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101; // x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111; // &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a> // // Based by a filter by Matthew Wickline, posted to the BBEdit-Talk // mailing list: <http://tinyurl.com/yu7ue> // email = "mailto:" + email // leave ':' alone (to spot mailto: later) email = encodeEmailAddress(email) email = "<a href=\"\(email)\">\(email)</a>" // strip the mailto: from the visible part email = Regex.replace(email, pattern: "\">.+?:", replacement: "\">") return email } private static let _outDent = Regex("^\\p{Z}{1,\(_tabWidth)}", options: RegexOptions.Multiline) /// Remove one level of line-leading spaces private func outdent(block: String) -> String { return Markdown._outDent.replace(block, "") } /// encodes email address randomly /// roughly 10% raw, 45% hex, 45% dec /// note that @ is always encoded and : never is private func encodeEmailAddress(addr: String) -> String { var sb = "" let colon: UInt8 = 58 // ':' let at: UInt8 = 64 // '@' for c in addr.utf8 { let r = arc4random_uniform(99) + 1 // TODO: verify that the following stuff works as expected in Swift if (r > 90 || c == colon) && c != at { sb += String(count: 1, repeatedValue: UnicodeScalar(UInt32(c))) // m } else if r < 45 { sb += NSString(format:"&#x%02x;", UInt(c)) as String // &#x6D } else { sb += "&#\(c);" // &#109 } } return sb } private static let _codeEncoder = Regex("&|<|>|\\\\|\\*|_|\\{|\\}|\\[|\\]") /// Encode/escape certain Markdown characters inside code blocks and spans where they are literals private func encodeCode(code: String) -> String { return Markdown._codeEncoder.replace(code) { self.encodeCodeEvaluator($0) } } private func encodeCodeEvaluator(match: Match) -> String { switch (match.value) { // Encode all ampersands; HTML entities are not // entities within a Markdown code span. case "&": return "&amp;" // Do the angle bracket song and dance case "<": return "&lt;" case ">": return "&gt;" // escape characters that are magic in Markdown default: return Markdown._escapeTable[match.value as String]! } } // TODO: C# code uses RegexOptions.ExplicitCapture here. Need to figure out // how/whether to emulate that with NSRegularExpression. private static let _amps = Regex("&(?!((#[0-9]+)|(#[xX][a-fA-F0-9]+)|([a-zA-Z][a-zA-Z0-9]*));)") private static let _angles = Regex("<(?![A-Za-z/?\\$!])") /// Encode any ampersands (that aren't part of an HTML entity) and left or right angle brackets private func encodeAmpsAndAngles(s: String) -> String { var s = Markdown._amps.replace(s, "&amp;") s = Markdown._angles.replace(s, "&lt;") return s } private static var _backslashEscapes: Regex! /// Encodes any escaped characters such as \`, \*, \[ etc private func escapeBackslashes(s: String) -> String { return Markdown._backslashEscapes.replace(s) { self.escapeBackslashesEvaluator($0) } } private func escapeBackslashesEvaluator(match: Match) -> String { return Markdown._backslashEscapeTable[match.value as String]! } private static let _unescapes = Regex("\u{1A}E\\d+E") /// swap back in all the special characters we've hidden private func unescape(s: String) -> String { return Markdown._unescapes.replace(s) { self.unescapeEvaluator($0) } } private func unescapeEvaluator(match: Match) -> String { return Markdown._invertedEscapeTable[match.value as String]! } /// this is to emulate what's evailable in PHP private static func repeatString(text: String, _ count: Int) -> String { return Array(count: count, repeatedValue: text).reduce("", combine: +) } /// escapes Bold [ * ] and Italic [ _ ] characters private func escapeBoldItalic(s: String) -> String { var str = s as NSString str = str.stringByReplacingOccurrencesOfString("*", withString: Markdown._escapeTable["*"]!) str = str.stringByReplacingOccurrencesOfString("_", withString: Markdown._escapeTable["_"]!) return str as String } private static let _problemUrlChars = NSCharacterSet(charactersInString: "\"'*()[]$:") /// hex-encodes some unusual "problem" chars in URLs to avoid URL detection problems private func encodeProblemUrlChars(url: String) -> String { if (!_encodeProblemUrlCharacters) { return url } var sb = "" var encode = false let str = url as NSString for i in 0..<str.length { let c = str.characterAtIndex(i) encode = Markdown._problemUrlChars.characterIsMember(c) if (encode && c == U16_COLON && i < str.length - 1) { encode = !(str.characterAtIndex(i + 1) == U16_SLASH) && !(str.characterAtIndex(i + 1) >= U16_ZERO && str.characterAtIndex(i + 1) <= U16_NINE) } if (encode) { sb += "%" sb += NSString(format:"%2x", UInt(c)) as String } else { sb += String(count: 1, repeatedValue: UnicodeScalar(c)) } } return sb } /// Within tags -- meaning between &lt; and &gt; -- encode [\ ` * _] so they /// don't conflict with their use in Markdown for code, italics and strong. /// We're replacing each such character with its corresponding hash /// value; this is likely overkill, but it should prevent us from colliding /// with the escape values by accident. private func escapeSpecialCharsWithinTagAttributes(text: String) -> String { let tokens = tokenizeHTML(text) // now, rebuild text from the tokens var sb = "" for token in tokens { var value = token.value if token.type == TokenType.Tag { value = value.stringByReplacingOccurrencesOfString("\\", withString: Markdown._escapeTable["\\"]!) if _autoHyperlink && value.hasPrefix("<!") { // escape slashes in comments to prevent autolinking there -- http://meta.stackoverflow.com/questions/95987/html-comment-containing-url-breaks-if-followed-by-another-html-comment value = value.stringByReplacingOccurrencesOfString("/", withString: Markdown._escapeTable["/"]!) } value = Regex.replace(value, pattern: "(?<=.)</?code>(?=.)", replacement: Markdown._escapeTable["`"]!) value = escapeBoldItalic(value) } sb += value } return sb } /// convert all tabs to _tabWidth spaces; /// standardizes line endings from DOS (CR LF) or Mac (CR) to UNIX (LF); /// makes sure text ends with a couple of newlines; /// removes any blank lines (only spaces) in the text private func normalize(text: String) -> String { var output = "" var line = "" var valid = false for i in text.startIndex..<text.endIndex { let c = text[i] switch (c) { case "\n": if (valid) { output += line } output += "\n" line = "" valid = false case "\r": if (valid) { output += line } output += "\n" line = "" valid = false case "\r\n": if (valid) { output += line } output += "\n" line = "" valid = false case "\t": let width = Markdown._tabWidth - line.characters.count % Markdown._tabWidth for _ in 0..<width { line += " " } default: if !valid && c != " " /* ' ' */ { valid = true } line += String(count: 1, repeatedValue: c) break } } if (valid) { output += line } output += "\n" // add two newlines to the end before return return output + "\n\n" } private static func attributeEncode(s: String) -> String { return s.stringByReplacingOccurrencesOfString(">", withString: "&gt;") .stringByReplacingOccurrencesOfString("<", withString: "&lt;") .stringByReplacingOccurrencesOfString("\"", withString: "&quot;") } private static func doesString(string: NSString, containSubstring substring: NSString) -> Bool { let range = string.rangeOfString(substring as String) return !(NSNotFound == range.location) } private static func trimEnd(string: NSString, _ suffix: NSString) -> String { var string = string while string.hasSuffix(suffix as String) { string = string.substringToIndex(string.length - suffix.length) } return string as String } private static func isNilOrEmpty(s: String?) -> Bool { switch s { case .Some(let nonNilString): return nonNilString.isEmpty default: return true } } private static func isNilOrEmpty(s: NSString?) -> Bool { switch s { case .Some(let nonNilString): return nonNilString.length == 0 default: return true } } /// Convert UnicodeScalar to a 16-bit unichar value private static func unicharForUnicodeScalar(unicodeScalar: UnicodeScalar) -> unichar { let u32 = UInt32(unicodeScalar) if u32 <= UInt32(UINT16_MAX) { return unichar(u32) } else { assert(false, "value must be representable in 16 bits") return 0 } } // unichar constants // (Unfortunate that Swift doesn't provide easy single-character literals) private let U16_COLON = Markdown.unicharForUnicodeScalar(":" as UnicodeScalar) private let U16_SLASH = Markdown.unicharForUnicodeScalar("/" as UnicodeScalar) private let U16_ZERO = Markdown.unicharForUnicodeScalar("0" as UnicodeScalar) private let U16_NINE = Markdown.unicharForUnicodeScalar("9" as UnicodeScalar) private let U16_NEWLINE = Markdown.unicharForUnicodeScalar("\n" as UnicodeScalar) private let U16_RETURN = Markdown.unicharForUnicodeScalar("\r" as UnicodeScalar) private let U16_TAB = Markdown.unicharForUnicodeScalar("\t" as UnicodeScalar) private let U16_SPACE = Markdown.unicharForUnicodeScalar(" " as UnicodeScalar) } /// Private wrapper for NSRegularExpression that provides interface /// similar to that of .NET's Regex class. /// /// This is intended only for use by the Markdown parser. It is not /// a general-purpose regex utility. private struct MarkdownRegex { private let regularExpresson: NSRegularExpression! #if MARKINGBIRD_DEBUG // These are not used, but can be helpful when debugging private var initPattern: NSString private var initOptions: NSRegularExpressionOptions #endif private init(_ pattern: String, options: NSRegularExpressionOptions = NSRegularExpressionOptions(rawValue: 0)) { #if MARKINGBIRD_DEBUG self.initPattern = pattern self.initOptions = options #endif var error: NSError? let re: NSRegularExpression? do { re = try NSRegularExpression(pattern: pattern, options: options) } catch let error1 as NSError { error = error1 re = nil } // If re is nil, it means NSRegularExpression didn't like // the pattern we gave it. All regex patterns used by Markdown // should be valid, so this probably means that a pattern // valid for .NET Regex is not valid for NSRegularExpression. if re == nil { if let error = error { print("Regular expression error: \(error.userInfo)") } assert(re != nil) } self.regularExpresson = re } private func replace(input: String, _ replacement: String) -> String { let s = input as NSString let result = regularExpresson.stringByReplacingMatchesInString(s as String, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, s.length), withTemplate: replacement) return result } private static func replace(input: String, pattern: String, replacement: String) -> String { let regex = MarkdownRegex(pattern) return regex.replace(input, replacement) } private func replace(input: String, evaluator: (MarkdownRegexMatch) -> String) -> String { // Get list of all replacements to be made var replacements = Array<(NSRange, String)>() let s = input as NSString let options = NSMatchingOptions(rawValue: 0) let range = NSMakeRange(0, s.length) regularExpresson.enumerateMatchesInString(s as String, options: options, range: range, usingBlock: { (result, flags, stop) -> Void in if result!.range.location == NSNotFound { return } let match = MarkdownRegexMatch(textCheckingResult: result!, string: s) let range = result!.range let replacementText = evaluator(match) let replacement = (range, replacementText) replacements.append(replacement) }) // Make the replacements from back to front var result = s for (range, replacementText) in Array(replacements.reverse()) { result = result.stringByReplacingCharactersInRange(range, withString: replacementText) } return result as String } private static func replace(input: String, pattern: String, evaluator: (MarkdownRegexMatch) -> String) -> String { let regex = MarkdownRegex(pattern) return regex.replace(input, evaluator: evaluator) } private static func replace(input: String, pattern: String, evaluator: (MarkdownRegexMatch) -> String, options: NSRegularExpressionOptions) -> String { let regex = MarkdownRegex(pattern, options: options) return regex.replace(input, evaluator: evaluator) } private static func replace(input: String, pattern: String, replacement: String, options: NSRegularExpressionOptions) -> String { let regex = MarkdownRegex(pattern, options: options) return regex.replace(input, replacement) } private func matches(input: String) -> [MarkdownRegexMatch] { var matchArray = Array<MarkdownRegexMatch>() let s = input as NSString let options = NSMatchingOptions(rawValue: 0) let range = NSMakeRange(0, s.length) regularExpresson.enumerateMatchesInString(s as String, options: options, range: range, usingBlock: { (result, flags, stop) -> Void in let match = MarkdownRegexMatch(textCheckingResult: result!, string: s) matchArray.append(match) }) return matchArray } private static func matches(input: String, pattern: String) -> [MarkdownRegexMatch] { let regex = MarkdownRegex(input) return regex.matches(pattern) } private func isMatch(input: String) -> Bool { let s = input as NSString let firstMatchRange = regularExpresson.rangeOfFirstMatchInString(s as String, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, s.length)) return !(NSNotFound == firstMatchRange.location) } private static func isMatch(input: String, pattern: String) -> Bool { let regex = MarkdownRegex(pattern) return regex.isMatch(input) } private func split(input: String) -> [String] { var stringArray: [String] = Array<String>() var nextStartIndex = 0 let s = input as NSString let options = NSMatchingOptions(rawValue: 0) let range = NSMakeRange(0, s.length) regularExpresson.enumerateMatchesInString(input, options: options, range: range, usingBlock: { (result, flags, stop) -> Void in let range = result!.range if range.location > nextStartIndex { let runRange = NSMakeRange(nextStartIndex, range.location - nextStartIndex) let run = s.substringWithRange(runRange) as String stringArray.append(run) nextStartIndex = range.location + range.length } }) if nextStartIndex < s.length { let lastRunRange = NSMakeRange(nextStartIndex, s.length - nextStartIndex) let lastRun = s.substringWithRange(lastRunRange) as String stringArray.append(lastRun) } return stringArray } private static func escape(input: String) -> String { return NSRegularExpression.escapedPatternForString(input) } } /// Provides interface similar to that of .NET's Match class for an NSTextCheckingResult private struct MarkdownRegexMatch { let textCheckingResult: NSTextCheckingResult let string: NSString init(textCheckingResult: NSTextCheckingResult, string: NSString) { self.textCheckingResult = textCheckingResult self.string = string } var value: NSString { return string.substringWithRange(textCheckingResult.range) } var index: Int { return textCheckingResult.range.location } var length: Int { return textCheckingResult.range.length } func valueOfGroupAtIndex(idx: Int) -> NSString { if 0 <= idx && idx < textCheckingResult.numberOfRanges { let groupRange = textCheckingResult.rangeAtIndex(idx) if (groupRange.location == NSNotFound) { return "" } assert(groupRange.location + groupRange.length <= string.length, "range must be contained within string") return string.substringWithRange(groupRange) } return "" } } /// Defines .NET-style synonyms for NSRegularExpressionOptions values /// /// - Multiline /// - IgnorePatternWhitespace /// - Singleline /// - IgnoreCase /// - None /// /// Note: NSRegularExpressionOptions does not provide equivalents to /// these .NET RegexOptions values used in the original C# source: /// /// - Compile /// - ExplicitCapture private struct MarkdownRegexOptions { /// Allow ^ and $ to match the start and end of lines. static let Multiline = NSRegularExpressionOptions.AnchorsMatchLines /// Ignore whitespace and #-prefixed comments in the pattern. static let IgnorePatternWhitespace = NSRegularExpressionOptions.AllowCommentsAndWhitespace /// Allow . to match any character, including line separators. static let Singleline = NSRegularExpressionOptions.DotMatchesLineSeparators /// Match letters in the pattern independent of case. static let IgnoreCase = NSRegularExpressionOptions.CaseInsensitive /// Default options static let None = NSRegularExpressionOptions(rawValue: 0) }
mit
bfc972267961144df94708a01bd53446
38.533966
239
0.561398
4.45773
false
false
false
false