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
rob-brown/Atoms
Atoms/DataSourceCombinators/ChainableDataSource.swift
1
4678
// ~MMMMMMMM,. .,MMMMMMM .. // DNMMDMMMMMMMM,. ..MMMMNMMMNMMM, // MMM.. ...NMMM MMNMM ,MMM // NMM, , MMND MMMM .MM // MMN MMMMM MMM // .MM , MMMMMM , MMM // .MM MMM. MMMM MMM // .MM~ .MMM. NMMN. MMM // MMM MMMM: .M ..MMM .MM, // MMM.NNMMMMMMMMMMMMMMMMMMMMMMMMMM:MMM, // ,,MMMMMMMMMMMMMMM NMMDNMMMMMMMMN~, // MMMMMMMMM,, OMMM NMM . ,MMNMMMMN. // ,MMMND .,MM= NMM~ MMMMMM+. MMM. NMM. .:MMMMM. // MMMM NMM,MMMD MMM$ZZZMMM: .NMN.MMM NMMM // MMNM MMMMMM MMZO~:ZZZZMM~ MMNMMN .MMM // MMM MMMMM MMNZ~~:ZZZZZNM, MMMM MMN. // MM. .MMM. MMZZOZZZZZZZMM. MMMM MMM. // MMN MMMMN MMMZZZZZZZZZNM. MMMM MMM. // NMMM .MMMNMN .MM$ZZZZZZZMMN ..NMMMMM MMM // MMMMM MMM.MMM~ .MNMZZZZMMMD MMM MMM . . NMMN, // NMMMM: ..MM8 MMM, . MNMMMM: .MMM: NMM ..MMMMM // ...MMMMMMNMM MMM .. MMM. MNDMMMMM. // .: MMMMMMMMMMDMMND MMMMMMMMNMMMMM // NMM8MNNMMMMMMMMMMMMMMMMMMMMMMMMMMNMM // ,MMM NMMMDMMMMM NMM.,. ,MM // MMO ..MMM NMMM MMD // .MM. ,,MMM+.MMMM= ,MMM // .MM. MMMMMM~. MMM // MM= MMMMM.. .MMN // MMM MMM8 MMMN. MM, // +MMO MMMN, MMMMM, MMM // ,MMMMMMM8MMMMM, . MMNMMMMMMMMM. // .NMMMMNMM DMDMMMMMM import UIKit open class ChainableDataSource: BaseDataSource { open fileprivate(set) var dataSource: ChainableDataSource? override public init(_ collection: [[Element]], cellCreator: @escaping CellCreator) { super.init(collection, cellCreator: cellCreator) } public init(dataSource: ChainableDataSource) { self.dataSource = dataSource super.init(dataSource.collection, cellCreator: dataSource.cellCreator) } // MARK: Forwarded UITableViewDataSource open func sectionIndexTitlesForTableView(_ tableView: UITableView) -> [Element]! { if let dataSource = dataSource { return dataSource.sectionIndexTitlesForTableView(tableView) } return [] } open func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { if let dataSource = dataSource { return dataSource.tableView(tableView, sectionForSectionIndexTitle: title, atIndex: index) } return 0 } open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let dataSource = dataSource { return dataSource.tableView(tableView, titleForHeaderInSection: section) } return nil } open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { if let dataSource = dataSource { return dataSource.tableView(tableView, titleForFooterInSection: section) } return nil } open func tableView(_ tableView: UITableView, canEditRowAtIndexPath indexPath: IndexPath) -> Bool { if let dataSource = dataSource { return dataSource.tableView(tableView, canEditRowAtIndexPath: indexPath) } return false } open func tableView(_ tableView: UITableView, canMoveRowAtIndexPath indexPath: IndexPath) -> Bool { if let dataSource = dataSource { return dataSource.tableView(tableView, canMoveRowAtIndexPath: indexPath) } return false } open func tableView(_ tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: IndexPath) { if let dataSource = dataSource { dataSource.tableView(tableView, commitEditingStyle: editingStyle, forRowAtIndexPath: indexPath) } } open func tableView(_ tableView: UITableView, moveRowAtIndexPath sourceIndexPath: IndexPath, toIndexPath destinationIndexPath: IndexPath) { if let dataSource = dataSource { dataSource.tableView(tableView, moveRowAtIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath) } } }
mit
ad6b5d54ae4a05b9102b38f9de2d7eb7
41.527273
153
0.555152
4.650099
false
false
false
false
urbn/URBNSwiftAlert
URBNSwiftAlert/Classes/AlertConfiguration.swift
1
1462
// // AlertConfiguration.swift // Pods // // Created by Kevin Taniguchi on 5/22/17. // // import Foundation public struct AlertConfiguration { /** * Title text for the alert */ public var title: String? /** * Message text for the alert */ public var message: String? /** * The view to present from when using showInView: */ public var presentationView: UIView? /** * Duration of a passive alert (no buttons added) */ public var duration: CGFloat? /** * When set to true, you can touch outside of an alert to dismiss it */ public var touchOutsideToDismiss = false /** * When set to true, you can touch the alert's view (custom or standard) to dismiss it */ public var tapInsideToDismiss = false /** * When set to true, you can touch outside of an alert to dismiss it */ public var alertViewButtonContainer: AlertButtonContainer? // Internal Variables var type = URBNSwAlertType.fullStandard var styler = AlertController.shared.alertStyler var textFields = [UITextField]() var customView: UIView? var customButtons: AlertButtonContainer? var actions = [AlertAction]() var textFieldInputs = [UITextField]() var isActiveAlert: Bool { let hasActiveAction = !actions.filter{$0.type != .passive}.isEmpty return hasActiveAction } }
mit
344a1fbf9422b2b906b2d01b97f83a49
23.366667
91
0.626539
4.498462
false
false
false
false
syxc/ZhihuDaily
ZhihuDaily/Classes/Controllers/MainVC.swift
1
4225
// // RootViewController.swift // ZhihuDaily // // Created by syxc on 15/12/5. // Copyright © 2015年 syxc. All rights reserved. // import UIKit import PromiseKit /** 首页 */ class MainVC: BaseTableViewController { private var topStories: [TopStory]? private var stories: [Story]? override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "app_name".localized self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Search, target: self, action: #selector(self.searchTap)) self.hud.show() self.setupView() self.loadData() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return super.preferredStatusBarStyle() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Setup view func setupView() { // Default self.automaticallyAdjustsScrollViewInsets = true tableView.estimatedRowHeight = 97.0 tableView.rowHeight = UITableViewAutomaticDimension tableView.registerClass(HomeTopBannerCell.self, forCellReuseIdentifier: "BannerCell") tableView.registerNib(UINib(nibName: "StoryCell", bundle: nil), forCellReuseIdentifier: "StoryCell") } override func mj_headerRefresh() { self.loadData() } // MARK: Load data func loadData() { let client = AppClient.shareClient weak var weakSelf = self firstly { client.fetchLatestNews() }.then { news -> Void in log.info("news=\(news.top_stories)") if let topStories = news.top_stories { weakSelf!.topStories = topStories } if let stories = news.stories { weakSelf!.stories = stories } weakSelf!.reloadData() }.always { self.hud.dismiss() self.setNetworkActivityIndicatorVisible(false) self.mj_endRefreshing() }.error { error in log.error("error=\(error)") } } // MARK: UITableViewDataSource override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 1 { guard let stories = stories else { return 0 } return stories.count } return 1 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { let bannerCell = tableView.dequeueReusableCellWithIdentifier("BannerCell", forIndexPath: indexPath) as! HomeTopBannerCell bannerCell.hideSeparatorLine() bannerCell.setupBannerData(topStories) return bannerCell } if indexPath.section == 1 { let cell = tableView.dequeueReusableCellWithIdentifier("StoryCell", forIndexPath: indexPath) as! StoryCell cell.setupStory(stories![indexPath.row]) return cell } return UITableViewCell() } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.section == 0 { return AppConstants.HomeTopBannerHeight } return 97.0 } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 1 { guard let story: Story = stories![indexPath.row] else { return } guard let scheme_detail: String = scheme(FYScheme.News_Detail, params: ["id" : "\(story.id!)"]) else { return } UIApplication.sharedApplication().openURL(NSURL(string: scheme_detail)!) } tableView.deselectRowAtIndexPath(indexPath, animated: true) } // MARK: Other methods func searchTap() { log.info("searchTap...") let scheme_about = scheme(FYScheme.About) UIApplication.sharedApplication().openURL(NSURL(string: scheme_about)!) } // MARK: deinit deinit { tableView.dataSource = nil tableView.delegate = nil } }
mit
4be3d489a079cd9bb0a820aa51c9aade
25.3625
139
0.66311
4.881944
false
false
false
false
AgentFeeble/pgoapi
Pods/ProtocolBuffers-Swift/Source/ExtendableMessage.swift
2
18206
// Protocol Buffers for Swift // // Copyright 2014 Alexey Khohklov(AlexeyXo). // Copyright 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation typealias ExtensionsValueType = Hashable & Equatable open class ExtendableMessage : GeneratedMessage { fileprivate var extensionMap:[Int32:Any] = [Int32:Any]() public var extensionRegistry:[Int32:ConcreateExtensionField] = [Int32:ConcreateExtensionField]() required public init() { super.init() } //Override override open class func className() -> String { return "ExtendableMessage" } override open func className() -> String { return "ExtendableMessage" } // public func isInitialized(object:Any) -> Bool { switch object { case let array as Array<Any>: for child in array { if (!isInitialized(object: child)) { return false } } case let array as Array<GeneratedMessage>: for child in array { if (!isInitialized(object: child)) { return false } } case let message as GeneratedMessage: return message.isInitialized() default: return true } return true } open func extensionsAreInitialized() -> Bool { let arr = Array(extensionMap.values) return isInitialized(object:arr) } internal func ensureExtensionIsRegistered(extensions:ConcreateExtensionField) { extensionRegistry[extensions.fieldNumber] = extensions } public func getExtension(extensions:ConcreateExtensionField) -> Any { ensureExtensionIsRegistered(extensions: extensions) if let value = extensionMap[extensions.fieldNumber] { return value } return extensions.defaultValue } public func hasExtension(extensions:ConcreateExtensionField) -> Bool { guard (extensionMap[extensions.fieldNumber] != nil) else { return false } return true } public func writeExtensionsTo(codedOutputStream:CodedOutputStream, startInclusive:Int32, endExclusive:Int32) throws { var keys = Array(extensionMap.keys) keys.sort(by: { $0 < $1 }) for fieldNumber in keys { if (fieldNumber >= startInclusive && fieldNumber < endExclusive) { let extensions = extensionRegistry[fieldNumber]! let value = extensionMap[fieldNumber]! try extensions.writeValueIncludingTagToCodedOutputStream(value: value, output: codedOutputStream) } } } public func getExtensionDescription(startInclusive:Int32 ,endExclusive:Int32, indent:String) throws -> String { var output = "" var keys = Array(extensionMap.keys) keys.sort(by: { $0 < $1 }) for fieldNumber in keys { if (fieldNumber >= startInclusive && fieldNumber < endExclusive) { let extensions = extensionRegistry[fieldNumber]! let value = extensionMap[fieldNumber]! output += try extensions.getDescription(value: value, indent: indent) } } return output } public func isEqualExtensionsInOther(otherMessage:ExtendableMessage, startInclusive:Int32, endExclusive:Int32) -> Bool { var keys = Array(extensionMap.keys) keys.sort(by: { $0 < $1 }) for fieldNumber in keys { if (fieldNumber >= startInclusive && fieldNumber < endExclusive) { let value = extensionMap[fieldNumber]! let otherValue = otherMessage.extensionMap[fieldNumber]! return compare(lhs: value, rhs: otherValue) } } return true } private func compare(lhs:Any, rhs:Any) -> Bool { switch (lhs,rhs) { case (let value as Int32, let value2 as Int32): return value == value2 case (let value as Int64, let value2 as Int64): return value == value2 case (let value as Double, let value2 as Double): return value == value2 case (let value as Float, let value2 as Float): return value == value2 case (let value as Bool, let value2 as Bool): return value == value2 case (let value as String, let value2 as String): return value == value2 case (let value as Data, let value2 as Data): return value == value2 case (let value as UInt32, let value2 as UInt32): return value == value2 case (let value as UInt64, let value2 as UInt64): return value == value2 case (let value as GeneratedMessage, let value2 as GeneratedMessage): return value == value2 case (let value as [Int32], let value2 as [Int32]): return value == value2 case (let value as [Int64], let value2 as [Int64]): return value == value2 case (let value as [Double], let value2 as [Double]): return value == value2 case (let value as [Float], let value2 as [Float]): return value == value2 case (let value as [Bool], let value2 as [Bool]): return value == value2 case (let value as [String], let value2 as [String]): return value == value2 case (let value as Array<Data>, let value2 as Array<Data>): return value == value2 case (let value as [UInt32], let value2 as [UInt32]): return value == value2 case (let value as [UInt64], let value2 as [UInt64]): return value == value2 case (let value as [GeneratedMessage], let value2 as [GeneratedMessage]): return value == value2 default: return false } } private func getHash<T>(lhs:T) -> Int! { switch lhs { case let value as Int32: return getHashValue(lhs: value) case let value as Int64: return getHashValue(lhs: value) case let value as UInt32: return getHashValue(lhs: value) case let value as UInt64: return getHashValue(lhs: value) case let value as Float: return getHashValue(lhs: value) case let value as Double: return getHashValue(lhs: value) case let value as Bool: return getHashValue(lhs: value) case let value as String: return getHashValue(lhs: value) case let value as GeneratedMessage: return getHashValue(lhs: value) case let value as Data: return value.hashValue case let value as [Int32]: return getHashValueRepeated(lhs: value) case let value as [Int64]: return getHashValueRepeated(lhs: value) case let value as [UInt32]: return getHashValueRepeated(lhs: value) case let value as [UInt64]: return getHashValueRepeated(lhs: value) case let value as [Float]: return getHashValueRepeated(lhs: value) case let value as [Double]: return getHashValueRepeated(lhs: value) case let value as [Bool]: return getHashValueRepeated(lhs: value) case let value as [String]: return getHashValueRepeated(lhs: value) case let value as Array<Data>: return getHashValueRepeated(lhs: value) case let value as [GeneratedMessage]: return getHashValueRepeated(lhs: value) default: return nil } } private func getHashValueRepeated<T>(lhs:T) -> Int! where T:Collection, T.Iterator.Element:Hashable & Equatable { var hashCode:Int = 0 for vv in lhs { hashCode = (hashCode &* 31) &+ vv.hashValue } return hashCode } private func getHashValue<T>(lhs:T) -> Int! where T:Hashable & Equatable { return lhs.hashValue } public func hashExtensionsFrom(startInclusive:Int32, endExclusive:Int32) -> Int { var hashCode:Int = 0 var keys = Array(extensionMap.keys) keys.sort(by: { $0 < $1 }) for fieldNumber in keys { if (fieldNumber >= startInclusive && fieldNumber < endExclusive) { let value = extensionMap[fieldNumber]! hashCode = (hashCode &* 31) &+ getHash(lhs: value)! } } return hashCode } public func extensionsSerializedSize() ->Int32 { var size:Int32 = 0 for fieldNumber in extensionMap.keys { let extensions = extensionRegistry[fieldNumber]! let value = extensionMap[fieldNumber]! size += extensions.computeSerializedSizeIncludingTag(value: value) } return size } } open class ExtendableMessageBuilder:GeneratedMessageBuilder { override open var internalGetResult:ExtendableMessage { get { return ExtendableMessage() } } override open func checkInitialized() throws { let result = internalGetResult if (!result.isInitialized()) { throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") } } override open func checkInitializedParsed() throws { let result = internalGetResult if (!result.isInitialized()) { throw ProtocolBuffersError.invalidProtocolBuffer("Uninitialized Message") } } override open func isInitialized() -> Bool { return internalGetResult.isInitialized() } override open func merge(unknownField: UnknownFieldSet) throws -> Self { let result:GeneratedMessage = internalGetResult result.unknownFields = try UnknownFieldSet.builderWithUnknownFields(copyFrom: result.unknownFields).merge(unknownFields: unknownField).build() return self } override public func parse(codedInputStream:CodedInputStream ,unknownFields:UnknownFieldSet.Builder, extensionRegistry:ExtensionRegistry, tag:Int32) throws -> Bool { let message = internalGetResult let wireType = WireFormat.getTagWireType(tag: tag) let fieldNumber:Int32 = WireFormat.getTagFieldNumber(tag: tag) let extensions = extensionRegistry.getExtension(clName: type(of: message), fieldNumber: fieldNumber) if extensions != nil { if extensions!.wireType.rawValue == wireType { try extensions!.mergeFrom(codedInputStream: codedInputStream, unknownFields:unknownFields, extensionRegistry:extensionRegistry, builder:self, tag:tag) return true } } return try super.parse(codedInputStream: codedInputStream, unknownFields: unknownFields, extensionRegistry: extensionRegistry, tag: tag) } public func getExtension(extensions:ConcreateExtensionField) -> Any { return internalGetResult.getExtension(extensions: extensions) } public func hasExtension(extensions:ConcreateExtensionField) -> Bool { return internalGetResult.hasExtension(extensions: extensions) } public func setExtension(extensions:ConcreateExtensionField, value:Any) throws -> Self { let message = internalGetResult message.ensureExtensionIsRegistered(extensions: extensions) guard !extensions.isRepeated else { throw ProtocolBuffersError.illegalArgument("Must call addExtension() for repeated types.") } message.extensionMap[extensions.fieldNumber] = value return self } public func addExtension<T>(extensions:ConcreateExtensionField, value:T) throws -> ExtendableMessageBuilder { let message = internalGetResult message.ensureExtensionIsRegistered(extensions: extensions) guard extensions.isRepeated else { throw ProtocolBuffersError.illegalArgument("Must call addExtension() for repeated types.") } let fieldNumber = extensions.fieldNumber if let val = value as? GeneratedMessage { var list:[GeneratedMessage]! = message.extensionMap[fieldNumber] as? [GeneratedMessage] ?? [] list.append(val) message.extensionMap[fieldNumber] = list } else { var list:[T]! = message.extensionMap[fieldNumber] as? [T] ?? [] list.append(value) message.extensionMap[fieldNumber] = list } return self } public func setExtension<T>(extensions:ConcreateExtensionField, index:Int32, value:T) throws -> Self { let message = internalGetResult message.ensureExtensionIsRegistered(extensions: extensions) guard extensions.isRepeated else { throw ProtocolBuffersError.illegalArgument("Must call setExtension() for singular types.") } let fieldNumber = extensions.fieldNumber if let val = value as? GeneratedMessage { var list:[GeneratedMessage]! = message.extensionMap[fieldNumber] as? [GeneratedMessage] ?? [] list[Int(index)] = val message.extensionMap[fieldNumber] = list } else { var list:[T]! = message.extensionMap[fieldNumber] as? [T] ?? [] list[Int(index)] = value message.extensionMap[fieldNumber] = list } return self } public func clearExtension(extensions:ConcreateExtensionField) -> Self { let message = internalGetResult message.ensureExtensionIsRegistered(extensions: extensions) message.extensionMap.removeValue(forKey: extensions.fieldNumber) return self } private func mergeRepeatedExtensionFields<T>(otherList:T, extensionMap:[Int32:Any], fieldNumber:Int32) -> [T.Iterator.Element] where T:Collection { var list:[T.Iterator.Element]! = extensionMap[fieldNumber] as? [T.Iterator.Element] ?? [] list! += otherList return list! } public func mergeExtensionFields(other:ExtendableMessage) throws { let thisMessage = internalGetResult guard thisMessage.className() == other.className() else { throw ProtocolBuffersError.illegalArgument("Cannot merge extensions from a different type") } if other.extensionMap.count > 0 { var registry = other.extensionRegistry for fieldNumber in other.extensionMap.keys { let thisField = registry[fieldNumber]! let value = other.extensionMap[fieldNumber]! if thisField.isRepeated { switch value { case let values as [Int32]: thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber) case let values as [Int64]: thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber) case let values as [UInt64]: thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber) case let values as [UInt32]: thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber) case let values as [Bool]: thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber) case let values as [Float]: thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber) case let values as [Double]: thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber) case let values as [String]: thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber) case let values as Array<Data>: thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber) case let values as [GeneratedMessage]: thisMessage.extensionMap[fieldNumber] = mergeRepeatedExtensionFields(otherList: values, extensionMap: thisMessage.extensionMap, fieldNumber: fieldNumber) default: break } } else { thisMessage.extensionMap[fieldNumber] = value } } } } }
apache-2.0
f2420351cc04b669dd0f71243452c018
37.490486
177
0.614413
5.518642
false
false
false
false
milseman/swift
test/SILGen/conditionally_unreachable.swift
10
1660
// RUN: %target-swift-frontend -enable-sil-ownership -emit-silgen -parse-stdlib -primary-file %s | %FileCheck %s -check-prefix=RAW // RUN: %target-swift-frontend -enable-sil-ownership -emit-sil -assert-config Debug -parse-stdlib -primary-file %s | %FileCheck -check-prefix=DEBUG %s // RUN: %target-swift-frontend -enable-sil-ownership -emit-sil -O -assert-config Debug -parse-stdlib -primary-file %s | %FileCheck -check-prefix=DEBUG %s // RUN: %target-swift-frontend -enable-sil-ownership -emit-sil -assert-config Release -parse-stdlib -primary-file %s | %FileCheck -check-prefix=RELEASE %s // RUN: %target-swift-frontend -enable-sil-ownership -emit-sil -O -assert-config Release -parse-stdlib -primary-file %s | %FileCheck -check-prefix=RELEASE %s import Swift @_silgen_name("foo") func foo() func condUnreachable() { if Int32(Builtin.assert_configuration()) == 0 { foo() } else { Builtin.conditionallyUnreachable() } } // RAW-LABEL: sil hidden @_T025conditionally_unreachable15condUnreachableyyF // RAW: cond_br {{%.*}}, [[YEA:bb[0-9]+]], [[NAY:bb[0-9]+]] // RAW: [[YEA]]: // RAW: function_ref @foo // RAW: [[NAY]]: // RAW: builtin "conditionallyUnreachable" // DEBUG-LABEL: sil hidden @_T025conditionally_unreachable15condUnreachableyyF // DEBUG-NOT: cond_br // DEBUG: function_ref @foo // DEBUG-NOT: {{ unreachable}} // DEBUG: return // RELEASE-LABEL: sil hidden @_T025conditionally_unreachable15condUnreachableyyF // RELEASE-NOT: cond_br // RELEASE-NOT: function_ref @foo // RELEASE-NOT: return // RELEASE-NOT: builtin // RELEASE: {{ unreachable}}
apache-2.0
4dd8d5d4d9db985dcbff3b7ec7b971ad
43.864865
157
0.675904
3.42268
false
true
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/BuySellUIKit/Core/PaymentMethods/Link Bank Flow/Yodlee Screen/YodleeScreenViewController.swift
1
4613
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import RIBs import RxCocoa import RxSwift import UIKit import WebKit final class YodleeScreenViewController: BaseScreenViewController, YodleeScreenPresentable, YodleeScreenViewControllable { private let disposeBag = DisposeBag() private let closeTriggerred = PublishSubject<Bool>() private let backTriggerred = PublishSubject<Void>() private let webview: WKWebView private let pendingView: YodleePendingView init(webConfiguration: WKWebViewConfiguration) { webview = WKWebView(frame: .zero, configuration: webConfiguration) pendingView = YodleePendingView() super.init(nibName: nil, bundle: nil) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white // so that we'll be able to listen for system dismissal methods navigationController?.presentationController?.delegate = self setupUI() } override func navigationBarTrailingButtonPressed() { closeTriggerred.onNext(false) } override func navigationBarLeadingButtonPressed() { backTriggerred.onNext(()) } // MARK: - YodleeScreenPresentable func connect(action: Driver<YodleeScreen.Action>) -> Driver<YodleeScreen.Effect> { let requestAction = action .compactMap(\.request) let contentAction = action .compactMap(\.content) .distinctUntilChanged() requestAction .drive(weak: self) { (self, request) in self.webview.load(request) } .disposed(by: disposeBag) contentAction .drive(pendingView.rx.content) .disposed(by: disposeBag) contentAction .drive(weak: self) { (self, _) in self.toggle(visibility: true, of: self.pendingView) self.toggle(visibility: false, of: self.webview) } .disposed(by: disposeBag) webview.rx.observeWeakly(Bool.self, "loading", options: [.new]) .compactMap { $0 } .observe(on: MainScheduler.asyncInstance) .subscribe(onNext: { [weak self] loading in guard let self = self else { return } self.toggle(visibility: loading, of: self.pendingView) self.toggle(visibility: !loading, of: self.webview) }) .disposed(by: disposeBag) let closeTapped = closeTriggerred .map { isInteractive in YodleeScreen.Effect.closeFlow(isInteractive) } .asDriverCatchError() let backTapped = backTriggerred .map { _ in YodleeScreen.Effect.back } .asDriverCatchError() let linkTapped = contentAction .flatMap { content -> Driver<TitledLink> in content.subtitleLinkTap .asDriver(onErrorDriveWith: .empty()) } .map { link -> YodleeScreen.Effect in .link(url: link.url) } return .merge(closeTapped, backTapped, linkTapped) } // MARK: - Private private func setupUI() { titleViewStyle = .text(value: LocalizationConstants.SimpleBuy.YodleeWebScreen.title) set( barStyle: .darkContent(), leadingButtonStyle: .back, trailingButtonStyle: .close ) view.addSubview(webview) view.addSubview(pendingView) webview.layoutToSuperview(axis: .vertical) webview.layoutToSuperview(axis: .horizontal) pendingView.layoutToSuperview(.top) pendingView.layoutToSuperview(.leading) pendingView.layoutToSuperview(.trailing) pendingView.layoutToSuperview(.bottom) } private func toggle(visibility: Bool, of view: UIView) { let alpha: CGFloat = visibility ? 1.0 : 0.0 let hidden = !visibility UIView.animate( withDuration: 0.2, animations: { view.alpha = alpha }, completion: { _ in view.isHidden = hidden } ) } } extension YodleeScreenViewController: UIAdaptivePresentationControllerDelegate { /// Called when a pull-down dismissal happens func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { closeTriggerred.onNext(true) } }
lgpl-3.0
d0dd7d4dc9cc35e985f6af4756938d2d
30.162162
95
0.620121
5.013043
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Components/SelectionButtonView/SelectionButtonView.swift
1
11008
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxCocoa import RxRelay import RxSwift public final class SelectionButtonView: UIView { // MARK: - Injected /// Injected in a manner that would enable `SelectionButtonView` to /// be a part of a queue mechanism. public var viewModel: SelectionButtonViewModel! { willSet { disposeBag = DisposeBag() } didSet { guard let viewModel = viewModel else { return } viewModel.leadingContent .drive(weak: self) { (self, content) in switch content { case .badgeImage(let viewModel): self.leadingBadgeImageView.viewModel = viewModel self.leadingLabel.content = .empty self.stackViewToLabelConstraint.priority = .penultimateLow self.stackViewToBadgeConstraint.priority = .penultimateHigh self.stackViewToSuperviewConstraint.priority = .penultimateLow case .label(let content): self.leadingLabel.content = content self.leadingBadgeImageView.viewModel = .empty self.stackViewToLabelConstraint.priority = .penultimateHigh self.stackViewToBadgeConstraint.priority = .penultimateLow self.stackViewToSuperviewConstraint.priority = .penultimateLow case .none: self.leadingLabel.content = .empty self.leadingBadgeImageView.viewModel = .empty self.stackViewToLabelConstraint.priority = .penultimateLow self.stackViewToBadgeConstraint.priority = .penultimateLow self.stackViewToSuperviewConstraint.priority = .penultimateHigh } } .disposed(by: disposeBag) viewModel.title .drive(titleLabel.rx.content) .disposed(by: disposeBag) viewModel.subtitle .map { $0 ?? .empty } .drive(subtitleLabel.rx.content) .disposed(by: disposeBag) viewModel.subtitle .map { $0 != nil } .distinctUntilChanged() .drive(onNext: { [weak self] shouldDisplay in self?.relayoutToDisplaySubtitle(shouldDisplay: shouldDisplay) }) .disposed(by: disposeBag) viewModel.horizontalOffset .drive(onNext: { [weak self] offset in self?.leadingConstraint.constant = offset self?.trailingConstraint.constant = -offset }) .disposed(by: disposeBag) viewModel.verticalOffset .drive(onNext: { [weak self] offset in self?.verticalConstraints.set(offset: offset) }) .disposed(by: disposeBag) viewModel.isButtonEnabled .drive(button.rx.isEnabled) .disposed(by: disposeBag) button.rx .controlEvent(.touchUpInside) .bindAndCatch(to: viewModel.tapRelay) .disposed(by: disposeBag) viewModel.accessibility .drive(button.rx.accessibility) .disposed(by: disposeBag) viewModel.shouldShowSeparator .map { !$0 } .drive(separatorView.rx.isHidden) .disposed(by: disposeBag) viewModel.leadingImageViewSize .drive(onNext: { [weak self] size in self?.badgeImageViewSizeConstraints.setConstant( horizontal: size.width, vertical: size.height ) }) .disposed(by: disposeBag) // Trailing Content viewModel.trailingContent .drive(weak: self) { (self, content) in switch content { case .image(let content): self.transactionDescriptorView.viewModel = nil self.trailingImageView.set(content) self.stackViewToImageConstraint.priority = .penultimateHigh self.stackViewToTransactionConstraint.priority = .penultimateLow case .transaction(let viewModel): self.transactionDescriptorView.viewModel = viewModel self.trailingImageView.set(nil) self.stackViewToImageConstraint.priority = .penultimateLow self.stackViewToTransactionConstraint.priority = .penultimateHigh case .empty: self.transactionDescriptorView.viewModel = nil self.trailingImageView.set(nil) self.stackViewToImageConstraint.priority = .penultimateHigh self.stackViewToTransactionConstraint.priority = .penultimateLow } } .disposed(by: disposeBag) viewModel.trailingContent .map { $0.image == nil } .map { $0 ? .hidden : .visible } .drive(transactionDescriptorView.rx.visibility) .disposed(by: disposeBag) viewModel.trailingContent .map { $0.transaction == nil } .map { $0 ? .hidden : .visible } .drive(transactionDescriptorView.rx.visibility) .disposed(by: disposeBag) } } // MARK: - UI Properties private let transactionDescriptorView = TransactionDescriptorView() private let leadingBadgeImageView = BadgeImageView() private let leadingLabel = UILabel() private let separatorView = UIView() private let labelsStackView = UIStackView() private let titleLabel = UILabel() private let subtitleLabel = UILabel() private let trailingImageView = UIImageView() private let button = UIButton() private var leadingConstraint: NSLayoutConstraint! private var stackViewToBadgeConstraint: NSLayoutConstraint! private var stackViewToLabelConstraint: NSLayoutConstraint! private var stackViewToSuperviewConstraint: NSLayoutConstraint! private var stackViewToImageConstraint: NSLayoutConstraint! private var stackViewToTransactionConstraint: NSLayoutConstraint! private var trailingConstraint: NSLayoutConstraint! private var verticalConstraints: Axis.Constraints! private var badgeImageViewSizeConstraints: LayoutForm.Constraints! // MARK: - Accessors private var disposeBag = DisposeBag() // MARK: - Setup override public init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder: NSCoder) { super.init(coder: coder) setup() } private func relayoutToDisplaySubtitle(shouldDisplay: Bool) { if shouldDisplay { labelsStackView.addArrangedSubview(subtitleLabel) } else { labelsStackView.removeArrangedSubview(subtitleLabel) } } private func setup() { // General setup backgroundColor = .white clipsToBounds = true separatorView.backgroundColor = .lightBorder // Subviews hierarchy setup addSubview(leadingBadgeImageView) addSubview(leadingLabel) addSubview(labelsStackView) addSubview(trailingImageView) addSubview(transactionDescriptorView) addSubview(button) labelsStackView.addArrangedSubview(titleLabel) addSubview(separatorView) labelsStackView.distribution = .fillProportionally labelsStackView.axis = .vertical labelsStackView.spacing = 6 // Layout the view leading to trailing separatorView.layout(edges: .leading, .trailing, .bottom, to: self) separatorView.layout(dimension: .height, to: 1) button.fillSuperview() button.addTargetForTouchDown(self, selector: #selector(touchDown)) button.addTargetForTouchUp(self, selector: #selector(touchUp)) leadingBadgeImageView.layoutToSuperview(.centerY) badgeImageViewSizeConstraints = leadingBadgeImageView.layout( size: .init(edge: 32), priority: .penultimateHigh ) leadingConstraint = leadingBadgeImageView.layoutToSuperview(.leading, offset: 24) leadingLabel.layout(to: .leading, of: leadingBadgeImageView) leadingLabel.layout(to: .centerY, of: leadingBadgeImageView) leadingLabel.horizontalContentHuggingPriority = .required verticalConstraints = labelsStackView.layoutToSuperview(axis: .vertical) stackViewToBadgeConstraint = labelsStackView.layout( edge: .leading, to: .trailing, of: leadingBadgeImageView, offset: 16, priority: .penultimateLow ) stackViewToLabelConstraint = labelsStackView.layout( edge: .leading, to: .trailing, of: leadingLabel, offset: 16, priority: .penultimateLow ) stackViewToSuperviewConstraint = labelsStackView.layout( edge: .leading, to: .leading, of: self, offset: 24, priority: .penultimateHigh ) titleLabel.verticalContentHuggingPriority = .required titleLabel.verticalContentCompressionResistancePriority = .required subtitleLabel.verticalContentHuggingPriority = .required subtitleLabel.verticalContentCompressionResistancePriority = .required trailingConstraint = trailingImageView.layoutToSuperview(.trailing, offset: -24) trailingImageView.layoutToSuperview(.centerY) trailingImageView.maximizeResistanceAndHuggingPriorities() transactionDescriptorView.layoutToSuperview(.trailing, offset: -24) transactionDescriptorView.layoutToSuperview(.centerY) transactionDescriptorView.maximizeResistanceAndHuggingPriorities() stackViewToImageConstraint = labelsStackView.layout( edge: .trailing, to: .leading, of: trailingImageView, offset: -8, priority: .penultimateHigh ) stackViewToTransactionConstraint = labelsStackView.layout( edge: .trailing, to: .leading, of: transactionDescriptorView, offset: -8, priority: .penultimateLow ) } @objc private func touchDown() { backgroundColor = .hightlightedBackground } @objc private func touchUp() { backgroundColor = .white } }
lgpl-3.0
946258a5306336c60e73efcd482f813c
36.311864
89
0.597256
5.756799
false
false
false
false
Daij-Djan/DDUtils
swift/ddutils-common/model/EWSProfileImage [ios+osx + demo]/EWSProfileImageDemo/ViewController.swift
1
2156
// // ViewController.swift // EWSProfileImageDemo // // Created by Dominik Pich on 7/9/16. // Copyright © 2016 Dominik Pich. All rights reserved. // import UIKit class ViewController: UIViewController, UICollectionViewDataSource { let emails = ["dpich@sapient.com", "mroehl@sapient.com", "shabeeb2@sapient.com", "dpich@sapient.com", "mroehl@sapient.com", "shabeeb2@sapient.com", "dpich@sapient.com", "mroehl@sapient.com", "shabeeb2@sapient.com", "dpich@sapient.com", "mroehl@sapient.com", "shabeeb2@sapient.com", "dpich@sapient.com", "mroehl@sapient.com", "shabeeb2@sapient.com", "dpich@sapient.com", "mroehl@sapient.com", "shabeeb2@sapient.com", "dpich@sapient.com", "mroehl@sapient.com", "shabeeb2@sapient.com"] func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return emails.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "profileImage", for: indexPath) let email = emails[(indexPath as NSIndexPath).item]; let profileImage = try! EWSProfileImages.shared.get(email) { (loadedProfileImage) in guard let cellToUpdate = collectionView.cellForItem(at: indexPath) , cellToUpdate.tag == loadedProfileImage.email.hash else { return } guard let imageView = cellToUpdate.contentView.subviews.first as? UIImageView else { return } imageView.image = loadedProfileImage.image } cell.tag = email.hash if let imageView = cell.contentView.subviews.first as? UIImageView { imageView.image = profileImage.image imageView.contentMode = .scaleAspectFit } return cell; } }
mit
9d5885c8dfdf400764b49e41a84e1a60
38.907407
137
0.625522
4.104762
false
false
false
false
fruitcoder/ReplaceAnimation
ReplaceAnimation/ViewController.swift
1
8235
// // ViewController.swift // ReplaceAnimation // // Created by Alexander Hüllmandel on 05/03/16. // Copyright © 2016 Alexander Hüllmandel. All rights reserved. // import UIKit import MessageUI private let reuseIdentifier = "Cell" struct Joke { let question : String let answer : String } extension Joke { init?(json : [String : AnyObject]) { if let joke = json["joke"] { var separatedJoke = joke.components(separatedBy: "?") if separatedJoke.count >= 2 { self.init(question: separatedJoke[0]+"?", answer: separatedJoke[1]) } else if separatedJoke.count == 1 { separatedJoke = joke.components(separatedBy: ". ") if separatedJoke.count >= 2 { self.init(question: separatedJoke[0]+".", answer: separatedJoke[1]) } else { return nil } } else { return nil } } else { return nil } } } class ViewController: UICollectionViewController { private var threshold : CGFloat = -95 private var animateNewCell = false private var jokes = [ Joke(question: "What's red and bad for your teeth?", answer: "A Brick."), Joke(question: "What do you call a chicken crossing the road?", answer: "Poultry in moton."), Joke(question: "Why did the fireman wear red, white, and blue suspenders?", answer: "To hold his pants up."), Joke(question: "How did Darth Vader know what Luke was getting for Christmas?", answer: "He felt his presents."), Joke(question: "My friend's bakery burned down last night.", answer: "Now his business is toast."), Joke(question: "What's funnier than a monkey dancing with an elephant?", answer: "Two monkeys dancing with an elephant.") ] private let emoticons = ["😂","😅","😆","😊","😬","🙃","🙂"] private let jokeService = JokeWebService() override func viewDidLoad() { super.viewDidLoad() // Register cell classes let headerNib = UINib(nibName: "PullToRefreshHeader", bundle: Bundle.main) self.collectionView!.register(headerNib, forSupplementaryViewOfKind: PullToRefreshHeader.Kind, withReuseIdentifier: "header") let cellNib = UINib(nibName: "CollectionViewCell", bundle: Bundle.main) self.collectionView!.register(cellNib, forCellWithReuseIdentifier: reuseIdentifier) let screenBounds = UIScreen.main.bounds // setup layout if let layout: StickyHeaderLayout = self.collectionView?.collectionViewLayout as? StickyHeaderLayout { layout.parallaxHeaderReferenceSize = CGSize(width: screenBounds.width, height: 0.56 * screenBounds.width) layout.parallaxHeaderMinimumReferenceSize = CGSize(width: UIScreen.main.bounds.size.width, height: 60) layout.itemSize = CGSize(width: UIScreen.main.bounds.size.width, height: layout.itemSize.height) layout.parallaxHeaderAlwaysOnTop = true layout.disableStickyHeaders = true self.collectionView?.collectionViewLayout = layout self.collectionView?.panGestureRecognizer.addTarget(self, action: #selector(ViewController.handlePan(pan:))) } threshold = -floor(0.3 * screenBounds.width) } override var prefersStatusBarHidden: Bool { return true } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return jokes.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? CollectionViewCell { cell.backgroundColor = UIColor.white cell.titleLabel.text = jokes[indexPath.row].question cell.subtitleLabel.text = jokes[indexPath.row].answer cell.leftLabel.text = emoticons[Int(arc4random()) % emoticons.count] return cell } return UICollectionViewCell() } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if let header = collectionView.dequeueReusableSupplementaryView(ofKind: PullToRefreshHeader.Kind, withReuseIdentifier: "header", for: indexPath) as? PullToRefreshHeader { header.onRefresh = { self.jokeService.getJoke() { (joke) -> Void in DispatchQueue.main.async { header.finishRefreshAnimation() { if let joke = joke { self.animateNewCell = true self.jokes.insert(joke, at: 0) self.collectionView?.insertItems(at: [IndexPath(item: 0, section: 0)]) } } } } } header.onCancel = { self.jokeService.cancelFetch() } header.onMailButtonPress = { // write email guard MFMailComposeViewController.canSendMail() else { return } let picker = MFMailComposeViewController() picker.mailComposeDelegate = self picker.setSubject("Replace Animation") picker.setMessageBody("Any questions on the implementation?", isHTML: false) picker.setToRecipients(["alexhue91gmail.com"]) self.present(picker, animated: true, completion: nil) } return header } return UICollectionReusableView() } override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if animateNewCell { let animation = CABasicAnimation(keyPath: "transform.scale") animation.toValue = 1.0 animation.fromValue = 0.5 animation.duration = 0.3 cell.layer.add(animation, forKey: nil) animateNewCell = false } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { if let layout: StickyHeaderLayout = self.collectionView?.collectionViewLayout as? StickyHeaderLayout { layout.parallaxHeaderMinimumReferenceSize = CGSize(width: size.width, height: 60) layout.parallaxHeaderReferenceSize = CGSize(width: size.width, height: 0.56 * size.width) layout.itemSize = CGSize(width: size.width, height: layout.itemSize.height) coordinator.animate(alongsideTransition: { (context) -> Void in layout.invalidateLayout() }, completion: nil) } } @objc func handlePan(pan : UIPanGestureRecognizer) { switch pan.state { case .ended, .failed, .cancelled: if self.collectionView!.contentOffset.y <= threshold { // load items if let refreshHeader = collectionView!.visibleSupplementaryViews(ofKind: PullToRefreshHeader.Kind).first as? PullToRefreshHeader { if !refreshHeader.isLoading { refreshHeader.startRefreshAnimation() } } } default: break } } } extension ViewController : MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { dismiss(animated: true, completion: nil) } }
mit
881ada7ed1e4b7c43c2101faf02583b2
41.107692
178
0.607721
5.44496
false
false
false
false
uasys/swift
stdlib/public/core/ObjectIdentifier.swift
1
3318
//===----------------------------------------------------------------------===// // // 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 unique identifier for a class instance or metatype. /// /// In Swift, only class instances and metatypes have unique identities. There /// is no notion of identity for structs, enums, functions, or tuples. public struct ObjectIdentifier : Hashable { internal let _value: Builtin.RawPointer // FIXME: Better hashing algorithm /// The identifier's hash value. /// /// The hash value is not guaranteed to be stable across different /// invocations of the same program. Do not persist the hash value across /// program runs. public var hashValue: Int { return Int(Builtin.ptrtoint_Word(_value)) } /// Creates an instance that uniquely identifies the given class instance. /// /// The following example creates an example class `A` and compares instances /// of the class using their object identifiers and the identical-to /// operator (`===`): /// /// class IntegerRef { /// let value: Int /// init(_ value: Int) { /// self.value = value /// } /// } /// /// let x = IntegerRef(10) /// let y = x /// /// print(ObjectIdentifier(x) == ObjectIdentifier(y)) /// // Prints "true" /// print(x === y) /// // Prints "true" /// /// let z = IntegerRef(10) /// print(ObjectIdentifier(x) == ObjectIdentifier(z)) /// // Prints "false" /// print(x === z) /// // Prints "false" /// /// - Parameter x: An instance of a class. public init(_ x: AnyObject) { self._value = Builtin.bridgeToRawPointer(x) } /// Creates an instance that uniquely identifies the given metatype. /// /// - Parameter: A metatype. public init(_ x: Any.Type) { self._value = unsafeBitCast(x, to: Builtin.RawPointer.self) } } extension ObjectIdentifier : CustomDebugStringConvertible { /// A textual representation of the identifier, suitable for debugging. public var debugDescription: String { return "ObjectIdentifier(\(_rawPointerToString(_value)))" } } extension ObjectIdentifier : Comparable { public static func < (lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool { return UInt(bitPattern: lhs) < UInt(bitPattern: rhs) } public static func == (x: ObjectIdentifier, y: ObjectIdentifier) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(x._value, y._value)) } } extension UInt { /// Creates an integer that captures the full value of the given object /// identifier. public init(bitPattern objectID: ObjectIdentifier) { self.init(Builtin.ptrtoint_Word(objectID._value)) } } extension Int { /// Creates an integer that captures the full value of the given object /// identifier. public init(bitPattern objectID: ObjectIdentifier) { self.init(bitPattern: UInt(bitPattern: objectID)) } }
apache-2.0
fc47b20c69d126d4d3434365d634de4e
31.851485
80
0.628391
4.447721
false
false
false
false
abunur/quran-ios
Quran/QuranFoundation+Extensions.swift
1
2370
// // QuranFoundation+Extensions.swift // Quran // // Created by Mohamed Afifi on 6/11/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import Foundation private let alpha: CGFloat = 0.25 extension QuranHighlightType { var color: UIColor { switch self { case .reading : return UIColor.appIdentity().withAlphaComponent(alpha) case .share : return UIColor.selection().withAlphaComponent(alpha) case .bookmark : return UIColor.bookmark().withAlphaComponent(alpha) case .search : return #colorLiteral(red: 0.5741485357, green: 0.5741624236, blue: 0.574154973, alpha: 1).withAlphaComponent(alpha) case .wordByWord: return UIColor.appIdentity().withAlphaComponent(alpha) } } } extension Quran { static func range(forPage page: Int) -> VerseRange { let lowerBound = startAyahForPage(page) let finder = PageBasedLastAyahFinder() let upperBound = finder.findLastAyah(startAyah: lowerBound, page: page) return VerseRange(lowerBound: lowerBound, upperBound: upperBound) } } extension AyahNumber { var localizedName: String { let ayahNumberString = String.localizedStringWithFormat(NSLocalizedString("quran_ayah", tableName: "Android", comment: ""), ayah) let suraName = Quran.nameForSura(sura) return "\(suraName), \(ayahNumberString)" } } extension Quran { static func nameForSura(_ sura: Int, withPrefix: Bool = false) -> String { let suraName = NSLocalizedString("sura_names[\(sura - 1)]", tableName: "Suras", comment: "") if !withPrefix { return suraName } let suraFormat = NSLocalizedString("quran_sura_title", tableName: "Android", comment: "") return String(format: suraFormat, suraName) } }
gpl-3.0
23ebde48a74f2e43a9e2cc79d951707b
35.461538
141
0.687764
4.27027
false
false
false
false
jcheng77/missfit-ios
missfit/missfit/ClassDetailPriceTableViewCell.swift
1
1088
// // ClassDetailPriceTableViewCell.swift // missfit // // Created by Hank Liang on 6/27/15. // Copyright (c) 2015 Hank Liang. All rights reserved. // import UIKit class ClassDetailPriceTableViewCell: UITableViewCell { @IBOutlet weak var memberPrice: UILabel! @IBOutlet weak var nonMemberPrice: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func setData(missfitClass: MissFitClass) { if missfitClass.memberPrice?.floatValue == 0 { self.memberPrice.text = "免费" } else { self.memberPrice.text = "¥ " + missfitClass.memberPrice!.stringValue } if missfitClass.price?.floatValue == 0 { self.nonMemberPrice.text = "免费" } else { self.nonMemberPrice.text = "¥ " + missfitClass.price!.stringValue } } }
mit
47f94d9a85e1c99f656496c81948c4fe
25.292683
80
0.624304
4.210938
false
false
false
false
ndleon09/SwiftSample500px
pictures/PictureModel.swift
1
1914
// // PictureModel.swift // pictures // // Created by Nelson on 05/11/15. // Copyright © 2015 Nelson Dominguez. All rights reserved. // import UIKit struct UserModel { let image : String? let name : String? } class PictureModel { var id : Double? var image : String? var name : String? var detailText : String? var rating : Double? var user : UserModel? var camera : String? var latitude : Double? var longitude : Double? init(dictionary: NSDictionary) { id = dictionary["id"] as? Double image = dictionary["image_url"] as? String name = dictionary["name"] as? String detailText = dictionary["description"] as? String rating = dictionary["rating"] as? Double camera = dictionary["camera"] as? String latitude = dictionary["latitude"] as? Double longitude = dictionary["longitude"] as? Double let userName = dictionary.value(forKeyPath: "user.fullname") as? String let userImageName = dictionary.value(forKeyPath: "user.avatars.large.https") as? String user = UserModel(image: userImageName, name: userName) } init(coreDataDictionary: [String: Any]) { id = coreDataDictionary["id"] as? Double image = coreDataDictionary["image"] as? String name = coreDataDictionary["name"] as? String detailText = coreDataDictionary["detailText"] as? String rating = coreDataDictionary["rating"] as? Double camera = coreDataDictionary["camera"] as? String latitude = coreDataDictionary["latitude"] as? Double longitude = coreDataDictionary["longitude"] as? Double let userName = coreDataDictionary["userName"] as? String let userImage = coreDataDictionary["userImage"] as? String user = UserModel(image: userImage, name: userName) } }
mit
780d2047a718b35190b985b724b40aaa
30.883333
95
0.634605
4.620773
false
false
false
false
NSManchester/nsmanchester-app-ios
NSManchester/EventViewController.swift
1
2418
// // EventViewController.swift // NSManchester // // Created by Ross Butler on 30/01/2016. // Copyright © 2016 Ross Butler. All rights reserved. // import UIKit import SafariServices import SVProgressHUD struct EventCell { static let TalkLabelId = 1 static let AuthorLabelId = 2 } class EventViewController: UIViewController { // Outlets @IBOutlet weak var tableView: UITableView! @IBOutlet weak var titleLabel: UILabel! // Services private let dataService: DataService = ServicesFactory.dataService() var titleText: String! var menuOptions: [MenuOption]? var eventID: Int! var backgroundColour: UIColor? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) NotificationCenter.default.addObserver(self, selector: #selector(EventViewController.reload(_:)), name: NSNotification.Name.FeedDataUpdated, object: nil) } override func viewDidLoad() { self.view.backgroundColor = backgroundColour titleLabel?.text = titleText dataService.eventMenuOptions(eventID, callback: { [weak self] results in switch results { case .success(let menuOptions): self?.menuOptions = menuOptions self?.tableView.reloadData() case .failure( _): // TODO: Provide feedback e.g. stop activity indicator, present alert view etc. print("Unable to retrieve menu options.") } }) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let tableView = tableView, let selectedIndex = tableView.indexPathForSelectedRow { tableView.deselectRow(at: selectedIndex, animated: true) } } deinit { NotificationCenter.default.removeObserver(self) } // Notifications @objc func reload(_ notification: Notification) { DispatchQueue.main.async { [unowned self] in self.tableView?.reloadData() } } }
mit
724797bf2b6bcc82e077493b782e1e26
25.855556
100
0.551096
5.796163
false
false
false
false
anthonypuppo/GDAXSwift
GDAXSwift/Classes/GDAXRequestAuthenticator.swift
1
2567
// // GDAXRequestAuthenticator.swift // GDAXSwift // // Created by Anthony on 6/4/17. // Copyright © 2017 Anthony Puppo. All rights reserved. // import CryptoSwift public class GDAXRequestAuthenticator { public let gdaxClient: GDAXClient public init(gdaxClient: GDAXClient) { self.gdaxClient = gdaxClient } public func authenticate(request: inout URLRequest) throws { let baseURLString = gdaxClient.baseURLString guard let urlString = request.url?.absoluteString, urlString.hasPrefix(baseURLString) else { throw GDAXError.authenticationBuilderError("Attempted to authenticate a non GDAX endpoint request") } guard let apiKey = gdaxClient.apiKey, let secret64 = gdaxClient.secret64, let passphrase = gdaxClient.passphrase else { throw GDAXError.authenticationBuilderError("A GDAX API key, secret and passphrase must be defined") } guard let method = request.httpMethod else { throw GDAXError.authenticationBuilderError("Attempted to authenticate a request with no HTTP method") } let timestamp = Int64(Date().timeIntervalSince1970) let relativeURL = "\(urlString.replacingOccurrences(of: baseURLString, with: ""))" let hmac = try generateSignature(secret64: secret64, timestamp: timestamp, method: method, relativeURL: relativeURL, body: request.httpBody) request.setValue(apiKey, forHTTPHeaderField: "CB-ACCESS-KEY") request.setValue(hmac, forHTTPHeaderField: "CB-ACCESS-SIGN") request.setValue(String(timestamp), forHTTPHeaderField: "CB-ACCESS-TIMESTAMP") request.setValue(passphrase, forHTTPHeaderField: "CB-ACCESS-PASSPHRASE") } private func generateSignature(secret64: String, timestamp: Int64, method: String, relativeURL: String, body: Data? = nil) throws -> String { var preHash = "\(timestamp)\(method.uppercased())\(relativeURL)" if let body = body { guard let bodyString = String(data: body, encoding: .utf8) else { throw GDAXError.authenticationBuilderError("Failed to UTF8 encode the request body") } preHash += bodyString } guard let secret = Data(base64Encoded: secret64) else { throw GDAXError.authenticationBuilderError("Failed to base64 decode secret") } guard let preHashData = preHash.data(using: .utf8) else { throw GDAXError.authenticationBuilderError("Failed to convert preHash into data") } guard let hmac = try HMAC(key: secret.bytes, variant: .sha256).authenticate(preHashData.bytes).toBase64() else { throw GDAXError.authenticationBuilderError("Failed to generate HMAC from preHash") } return hmac } }
mit
c18b158155d12d31cc5ac4cc277836c8
35.657143
142
0.750195
4.015649
false
false
false
false
fqhuy/minimind
minimind/optimisation/scg.swift
1
5105
// // scaled_conjugate_gradient.swift // minimind // // Created by Phan Quoc Huy on 5/28/17. // Copyright © 2017 Phan Quoc Huy. All rights reserved. // import Foundation //import Surge public class SCG<F: ObjectiveFunction>: Optimizer where F.ScalarT == Float { public typealias ObjectiveFunctionT = F public typealias ScalarT = Float typealias T = ScalarT public var objective: F var initX: MatrixT public var Xs: [MatrixT] = [] var maxIters: Int var verbose: Bool = false public init(objective: F, learningRate: Float, initX: MatrixT, maxIters: Int = 200) { self.objective = objective self.initX = initX self.maxIters = maxIters } public func optimize(verbose: Bool = false) -> (MatrixT, [Float], Int) { let xtol: T = 1e-12 let ftol: T = 1e-12 let gtol: T = 1e-12 let max_f_eval = 10000 let sigma0: T = 1.0e-7 var fold: T = self.objective.compute(self.initX) var function_eval = 1 var fnow = fold var gradnew: MatrixT = self.objective.gradient(self.initX) function_eval += 1 var current_grad = (gradnew * gradnew.t)[0, 0] // NEED TO COPY ! var gradold: MatrixT = gradnew var d = -1 * gradnew var success = true var nsuccess = 0 let betamin: T = 1.0e-10 let betamax: T = 1.0e10 var status = "Not Converged" var flog = [Float]() var iteration = 0 var delta: T = 0.0 var theta: T = 0.0 var kappa: T = 0.0 var sigma: T = 0.0 var alpha: T = 0.0 var beta: T = 1.0 var Gamma: T = 0.0 var mu: T = 0.0 var x = self.initX var xnew: MatrixT var fnew: T = 0.0 Xs.append(x) while iteration < self.maxIters { if success { mu = (d * gradnew.t)[0, 0] if mu >= 0 { d = -gradnew mu = (d * gradnew.t)[0, 0] } kappa = (d * d.t)[0, 0] sigma = sigma0 / sqrt(kappa) let xplus = x + sigma * d let gplus = self.objective.gradient(xplus) function_eval += 1 theta = (d * (gplus - gradnew).t / sigma)[0, 0] } delta = theta + beta * kappa if delta <= 0 { delta = beta * kappa beta = beta - theta / kappa } alpha = -mu / delta xnew = x + alpha * d fnew = self.objective.compute(xnew) function_eval += 1 if function_eval >= max_f_eval{ print("max_f_eval reached") return (x, flog, function_eval) } let Delta = 2.0 * (fnew - fold) / (alpha * mu) if Delta >= 0 { success = true nsuccess += 1 x = xnew Xs.append(x) fnow = fnew } else { success = false fnow = fold } flog.append(fnow) iteration += 1 if verbose { // show current values print("iter: ", iteration, fnow) } if success { if abs(fnew - fold) < ftol { status = "converged - relative reduction in objective" break } else if max(abs(alpha * d)) < xtol { status = "converged - relative stepsize" break } else { gradold = gradnew gradnew = self.objective.gradient(x) function_eval += 1 current_grad = (gradnew * gradnew.t)[0, 0] fold = fnew if current_grad <= gtol { status = "converged - relative reduction in gradients" break } } } if Delta < 0.25 { beta = min([4.0 * beta, betamax]) } if Delta > 0.75 { beta = max([025 * beta, betamin]) } if nsuccess == x.size { d = -gradnew beta = 1.0 nsuccess = 0 } else if success { Gamma = ((gradold - gradnew) * gradnew.t)[0, 0] / mu d = Gamma * d - gradnew } } if iteration == maxIters { status = "maxiter exceeded" } if verbose { print("iter: ", iteration, fnow) print(status) } return (x, flog, function_eval) } public func getCost() -> Double { return 0.0 } }
mit
fec759bb43ccbdb70c3abab07e482216
28.50289
89
0.423002
4.246256
false
false
false
false
dipen30/Qmote
KodiRemote/Pods/UPnAtom/Source/Management/UPnPRegistry.swift
1
14396
// // UPnPRegistry.swift // // Copyright (c) 2015 David Robles // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import AFNetworking /// TODO: For now rooting to NSObject to expose to Objective-C, see Github issue #16 open class UPnPRegistry: NSObject { fileprivate enum UPnPObjectNotificationType { case device case service func notificationComponents() -> (objectAddedNotificationName: String, objectRemoveNotificationName: String, objectKey: String) { switch self { case .device: return ("UPnPDeviceAddedNotification", "UPnPDeviceRemovedNotification", "UPnPDeviceKey") case .service: return ("UPnPServiceAddedNotification", "UPnPServiceRemovedNotification", "UPnPServiceKey") } } } // private fileprivate let _concurrentUPnPObjectQueue = DispatchQueue(label: "com.upnatom.upnp-registry.upnp-object-queue", attributes: DispatchQueue.Attributes.concurrent) /// Must be accessed within dispatch_sync() or dispatch_async() and updated within dispatch_barrier_async() to the concurrent queue lazy fileprivate var _upnpObjects = [UniqueServiceName: AbstractUPnP]() lazy fileprivate var _upnpObjectsMainThreadCopy = [UniqueServiceName: AbstractUPnP]() // main thread safe copy /// Must be accessed within dispatch_sync() or dispatch_async() and updated within dispatch_barrier_async() to the concurrent queue lazy fileprivate var _ssdpDiscoveryCache = [SSDPDiscovery]() fileprivate let _upnpObjectDescriptionSessionManager = AFHTTPSessionManager() fileprivate var _upnpClasses = [String: AbstractUPnP.Type]() fileprivate let _ssdpDiscoveryAdapter: SSDPDiscoveryAdapter init(ssdpDiscoveryAdapter: SSDPDiscoveryAdapter) { _upnpObjectDescriptionSessionManager.requestSerializer = AFHTTPRequestSerializer() _upnpObjectDescriptionSessionManager.responseSerializer = AFHTTPResponseSerializer() _ssdpDiscoveryAdapter = ssdpDiscoveryAdapter super.init() ssdpDiscoveryAdapter.delegate = self } /// Safe to call from any thread open func upnpDevices(completionQueue: OperationQueue, completion: @escaping (_ upnpDevices: [AbstractUPnPDevice]) -> Void) { upnpObjects { (upnpObjects: [UniqueServiceName: AbstractUPnP]) -> Void in let upnpDevices = Array(upnpObjects.values).filter({$0 is AbstractUPnPDevice}) completionQueue.addOperation({ () -> Void in completion(upnpDevices as! [AbstractUPnPDevice]) }) } } /// Safe to call from any thread open func upnpServices(completionQueue: OperationQueue, completion: @escaping (_ upnpServices: [AbstractUPnPService]) -> Void) { upnpObjects { (upnpObjects: [UniqueServiceName: AbstractUPnP]) -> Void in let upnpServices = Array(upnpObjects.values).filter({$0 is AbstractUPnPService}) completionQueue.addOperation({ () -> Void in completion(upnpServices as! [AbstractUPnPService]) }) } } open func register(upnpClass: AbstractUPnP.Type, forURN urn: String) { _upnpClasses[urn] = upnpClass } open func createUPnPObject(upnpArchivable: UPnPArchivable, callbackQueue: OperationQueue, success: @escaping ((_ upnpObject: AbstractUPnP) -> Void), failure: @escaping ((_ error: NSError) -> Void)) { let failureCase = { (error: NSError) -> Void in LogError("Unable to fetch UPnP object description for archivable: \(upnpArchivable.usn) at \(upnpArchivable.descriptionURL): \(error)") callbackQueue.addOperation({ () -> Void in failure(error) }) } _upnpObjectDescriptionSessionManager.get(upnpArchivable.descriptionURL.absoluteString, parameters: nil, success: { (task: URLSessionDataTask!, responseObject: Any?) -> Void in DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async(execute: { () -> Void in guard let xmlData = responseObject as? Data, let usn = UniqueServiceName(rawValue: upnpArchivable.usn), let upnpObject = self.createUPnPObject(usn: usn, descriptionURL: upnpArchivable.descriptionURL, descriptionXML: xmlData) else { failureCase(createError("Unable to create UPnP object")) return } callbackQueue.addOperation({ () -> Void in success(upnpObject) }) }) } ) } /// Safe to call from any thread, closure called on background thread fileprivate func upnpObjects(_ closure: @escaping (_ upnpObjects: [UniqueServiceName: AbstractUPnP]) -> Void) { // only reading upnp objects, so distpach_async is appropriate to allow for concurrent reads _concurrentUPnPObjectQueue.async(execute: { () -> Void in let upnpObjects = self._upnpObjects DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.default).async(execute: { () -> Void in closure(upnpObjects) }) }) } /// Should be called on the background thread as every instance it creates parses XML fileprivate func createUPnPObject(usn: UniqueServiceName, descriptionURL: URL, descriptionXML: Data) -> AbstractUPnP? { let upnpClass: AbstractUPnP.Type let urn = usn.urn! // checked for nil earlier if let registeredClass = _upnpClasses[urn] { upnpClass = registeredClass } else if urn.range(of: "urn:schemas-upnp-org:device") != nil { upnpClass = AbstractUPnPDevice.self } else if urn.range(of: "urn:schemas-upnp-org:service") != nil { upnpClass = AbstractUPnPService.self } else { upnpClass = AbstractUPnP.self } return upnpClass.init(usn: usn, descriptionURL: descriptionURL, descriptionXML: descriptionXML) } } /// Extension used for defining notification constants. Functions are used since class constants are not supported in swift yet public extension UPnPRegistry { class func UPnPDeviceAddedNotification() -> String { return UPnPObjectNotificationType.device.notificationComponents().objectAddedNotificationName } class func UPnPDeviceRemovedNotification() -> String { return UPnPObjectNotificationType.device.notificationComponents().objectRemoveNotificationName } class func UPnPDeviceKey() -> String { return UPnPObjectNotificationType.device.notificationComponents().objectKey } class func UPnPServiceAddedNotification() -> String { return UPnPObjectNotificationType.service.notificationComponents().objectAddedNotificationName } class func UPnPServiceRemovedNotification() -> String { return UPnPObjectNotificationType.service.notificationComponents().objectRemoveNotificationName } class func UPnPServiceKey() -> String { return UPnPObjectNotificationType.service.notificationComponents().objectKey } class func UPnPDiscoveryErrorNotification() -> String { return "UPnPDiscoveryErrorNotification" } class func UPnPDiscoveryErrorKey() -> String { return "UPnPDiscoveryErrorKey" } } extension UPnPRegistry: SSDPDiscoveryAdapterDelegate { func ssdpDiscoveryAdapter(_ adapter: SSDPDiscoveryAdapter, didUpdateSSDPDiscoveries ssdpDiscoveries: [SSDPDiscovery]) { _concurrentUPnPObjectQueue.async(flags: .barrier, execute: { () -> Void in self._ssdpDiscoveryCache = ssdpDiscoveries var upnpObjectsToKeep = [AbstractUPnP]() for ssdpDiscovery in ssdpDiscoveries { // only concerned with objects with a device or service type urn if ssdpDiscovery.usn.urn != nil { switch ssdpDiscovery.type { case .device, .service: if let foundObject = self._upnpObjects[ssdpDiscovery.usn] { upnpObjectsToKeep.append(foundObject) } else { self.getUPnPDescription(forSSDPDiscovery: ssdpDiscovery) } default: LogVerbose("Discovery type will not be handled") } } } self.process(upnpObjectsToKeep: upnpObjectsToKeep, upnpObjects: &self._upnpObjects) }) } func ssdpDiscoveryAdapter(_ adapter: SSDPDiscoveryAdapter, didFailWithError error: NSError) { LogError("SSDP discovery did fail with error: \(error)") DispatchQueue.main.async(execute: { () -> Void in NotificationCenter.default.post(name: Notification.Name(rawValue: UPnPRegistry.UPnPDiscoveryErrorNotification()), object: self, userInfo: [UPnPRegistry.UPnPDiscoveryErrorKey(): error]) }) } fileprivate func getUPnPDescription(forSSDPDiscovery ssdpDiscovery: SSDPDiscovery) { self._upnpObjectDescriptionSessionManager.get(ssdpDiscovery.descriptionURL.absoluteString, parameters: nil, success: { (task: URLSessionDataTask!, responseObject: Any?) -> Void in self._concurrentUPnPObjectQueue.async(flags: .barrier, execute: { () -> Void in if let xmlData = responseObject as? Data { // if ssdp object is not in cache then discard guard self._ssdpDiscoveryCache.index(of: ssdpDiscovery) != nil else { return } self.addUPnPObject(forSSDPDiscovery: ssdpDiscovery, descriptionXML: xmlData, upnpObjects: &self._upnpObjects) } }) } ) } /// Must be called within dispatch_barrier_async() to the UPnP object queue since the upnpObjects dictionary is being updated fileprivate func addUPnPObject(forSSDPDiscovery ssdpDiscovery: SSDPDiscovery, descriptionXML: Data, upnpObjects: inout [UniqueServiceName: AbstractUPnP]) { let usn = ssdpDiscovery.usn // ignore if already in db guard upnpObjects[usn] == nil else { return } if let newObject = createUPnPObject(usn: usn, descriptionURL: ssdpDiscovery.descriptionURL as URL, descriptionXML: descriptionXML) { guard newObject is AbstractUPnPDevice || newObject is AbstractUPnPService else { return } if newObject is AbstractUPnPDevice { (newObject as! AbstractUPnPDevice).serviceSource = self } else { (newObject as! AbstractUPnPService).deviceSource = self } upnpObjects[usn] = newObject let upnpObjectsCopy = upnpObjects // create a copy for safe use on the main thread let notificationType: UPnPObjectNotificationType = newObject is AbstractUPnPDevice ? .device : .service let notificationComponents = notificationType.notificationComponents() DispatchQueue.main.async(execute: { () -> Void in self._upnpObjectsMainThreadCopy = upnpObjectsCopy NotificationCenter.default.post(name: Notification.Name(rawValue: notificationComponents.objectAddedNotificationName), object: self, userInfo: [notificationComponents.objectKey: newObject]) }) } } /// Must be called within dispatch_barrier_async() to the UPnP object queue since the upnpObjects dictionary is being updated fileprivate func process(upnpObjectsToKeep: [AbstractUPnP], upnpObjects: inout [UniqueServiceName: AbstractUPnP]) { let upnpObjectsSet = Set(Array(upnpObjects.values)) let upnpObjectsToRemove = upnpObjectsSet.subtracting(Set(upnpObjectsToKeep)) for upnpObjectToRemove in upnpObjectsToRemove { upnpObjects.removeValue(forKey: upnpObjectToRemove.usn) let upnpObjectsCopy = upnpObjects // create a copy for safe use on the main thread let notificationType: UPnPObjectNotificationType = upnpObjectToRemove is AbstractUPnPDevice ? .device : .service let notificationComponents = notificationType.notificationComponents() DispatchQueue.main.async(execute: { () -> Void in self._upnpObjectsMainThreadCopy = upnpObjectsCopy NotificationCenter.default.post(name: Notification.Name(rawValue: notificationComponents.objectRemoveNotificationName), object: self, userInfo: [notificationComponents.objectKey: upnpObjectToRemove]) }) } } } extension UPnPRegistry: UPnPServiceSource { public func service(forUSN usn: UniqueServiceName) -> AbstractUPnPService? { return _upnpObjectsMainThreadCopy[usn] as? AbstractUPnPService } } extension UPnPRegistry: UPnPDeviceSource { public func device(forUSN usn: UniqueServiceName) -> AbstractUPnPDevice? { return _upnpObjectsMainThreadCopy[usn] as? AbstractUPnPDevice } }
apache-2.0
c5f67a40423009b3248acdb0d1218567
48.986111
215
0.667408
4.660408
false
false
false
false
yaozongchao/ComplicateTableDemo
ComplicateUI/KDDetailViewController.swift
1
2468
// // KDDetailViewController.swift // ComplicateUI // // Created by 姚宗超 on 2017/3/9. // Copyright © 2017年 姚宗超. All rights reserved. // import UIKit class KDDetailViewController: UIViewController { var originRect: CGRect? let animatePop = AnimateTransitionPop() lazy var textLabel: UILabel = { let label = UILabel.init(frame: CGRect.zero) return label }() var detail: String? convenience init(detail: String?, originRect: CGRect?) { self.init() self.detail = detail self.originRect = originRect } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.white self.view.addSubview(self.textLabel) self.textLabel.snp.makeConstraints { (make) in make.center.equalTo(self.view) } self.textLabel.text = self.detail } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.navigationController?.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension KDDetailViewController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == UINavigationControllerOperation.pop { self.animatePop.originRect = self.originRect return self.animatePop } return nil } }
mit
a0a05588765f639e1e46ef89d24ac0a7
28.554217
246
0.664085
5.186047
false
false
false
false
HTWDD/HTWDresden-iOS
HTWDD/Components/Onboarding/Studygroup/OnboardStudygroupViewController.swift
1
7656
// // OnboardStudygroupViewController.swift // HTWDD // // Created by Fabian Ehlert on 12.10.17. // Copyright © 2017 HTW Dresden. All rights reserved. // import UIKit import RxSwift import RxCocoa class OnboardStudygroupViewController: OnboardDetailViewController<ScheduleService.Auth>, AnimatedViewControllerTransitionDataSource { private struct State { var years: [StudyYear]? var majors: [StudyCourse]? { guard let year = self.year, let studyYear = self.years?.first(where: { $0.studyYear == year.studyYear }) else { return nil } return studyYear.studyCourses } var groups: [StudyGroup]? { guard let major = self.major, let studyMajor = self.majors?.first(where: { $0.studyCourse == major.studyCourse }) else { return nil } return studyMajor.studyGroups } var year: StudyYear? { didSet { if oldValue?.studyYear != year?.studyYear { self.major = nil self.group = nil } } } var major: StudyCourse? { didSet { if oldValue?.studyCourse != major?.studyCourse { self.group = nil } } } var group: StudyGroup? var completed: Bool { return self.year != nil && self.major != nil && self.group != nil } } private var state = BehaviorRelay(value: State()) private lazy var yearButton = ReactiveButton() private lazy var majorButton = ReactiveButton() private lazy var groupButton = ReactiveButton() private let network = Network() private let disposeBag = DisposeBag() // MARK: - ViewController lifecycle override func initialSetup() { let configureButton: (ReactiveButton) -> Void = { $0.isEnabled = false $0.setTitle("config.continueButtonText", for: .normal) $0.titleLabel?.font = .systemFont(ofSize: 20, weight: .semibold) $0.backgroundColor = UIColor.htw.blue $0.layer.cornerRadius = 12 } let buttons = [self.yearButton, self.majorButton, self.groupButton] buttons.forEach(configureButton) self.config = .init(title: Loca.Onboarding.Studygroup.title, description: Loca.Onboarding.Studygroup.body, contentViews: buttons, contentViewsStackViewAxis: NSLayoutConstraint.Axis.horizontal, notNowText: Loca.Onboarding.Studygroup.notnow, continueButtonText: Loca.nextStep) super.initialSetup() } override func viewDidLoad() { super.viewDidLoad() let stateObservable = self.state.asObservable() stateObservable .map({ $0.years != nil }) .bind(to: self.yearButton.rx.isEnabled) .disposed(by: self.disposeBag) stateObservable .map({ $0.year != nil }) .bind(to: self.majorButton.rx.isEnabled) .disposed(by: self.disposeBag) stateObservable .map({ $0.major != nil }) .bind(to: self.groupButton.rx.isEnabled) .disposed(by: self.disposeBag) stateObservable .map({ $0.year?.studyYear.description ?? Loca.Onboarding.Studygroup.year }) .bind(to: self.yearButton.rx.title()) .disposed(by: self.disposeBag) stateObservable .map({ $0.major?.studyCourse ?? Loca.Onboarding.Studygroup.major }) .bind(to: self.majorButton.rx.title()) .disposed(by: self.disposeBag) stateObservable .map({ $0.group?.studyGroup ?? Loca.Onboarding.Studygroup.group }) .bind(to: self.groupButton.rx.title()) .disposed(by: self.disposeBag) stateObservable .map({ $0.completed }) .observeOn(MainScheduler.instance) .subscribe(onNext: { [weak self] _ in self?.checkState() }) .disposed(by: self.disposeBag) StudyYear.get(network: self.network).subscribe(onNext: { years in var mutableState = self.state.value mutableState.years = years self.state.accept(mutableState) }, onError: { [weak self] _ in self?.dismissOrPopViewController() }).disposed(by: self.disposeBag) self.yearButton.rx .controlEvent(.touchUpInside) .flatMap({ [weak self] _ -> Observable<StudyYear> in guard let `self` = self, let years = self.state.value.years else { return Observable.empty() } return OnboardStudygroupSelectionController.show(controller: self, data: years) }) .subscribe(onNext: { [weak self] studyYear in guard let self = self else { return } var mutableState = self.state.value mutableState.year = studyYear self.state.accept(mutableState) }) .disposed(by: self.disposeBag) self.majorButton.rx .controlEvent(.touchUpInside) .flatMap({ [weak self] _ -> Observable<StudyCourse> in guard let `self` = self, let majors = self.state.value.majors else { return Observable.empty() } return OnboardStudygroupSelectionController.show(controller: self, data: majors) }) .subscribe(onNext: { major in var mutableState = self.state.value mutableState.major = major self.state.accept(mutableState) }) .disposed(by: self.disposeBag) self.groupButton.rx .controlEvent(.touchUpInside) .flatMap({ [weak self] _ -> Observable<StudyGroup> in guard let `self` = self, let groups = self.state.value.groups else { return Observable.empty() } return OnboardStudygroupSelectionController.show(controller: self, data: groups) }) .subscribe(onNext: { group in var mutableState = self.state.value mutableState.group = group self.state.accept(mutableState) }) .disposed(by: self.disposeBag) } // MARK: - Overridden @objc override func continueBoarding() { let currentState = self.state.value guard let y = currentState.year?.studyYear.description, let m = currentState.major?.studyCourse, let g = currentState.group?.studyGroup, let d = currentState.group?.degree else { self.onFinish?(nil) return } let degree: ScheduleService.Auth.Degree switch d { case .bachelor: degree = .bachelor case .diplom: degree = .diplom case .master: degree = .master } let group = ScheduleService.Auth(year: y, major: m, group: g, degree: degree) self.onFinish?(group) } override func shouldContinue() -> Bool { return self.state.value.completed } }
gpl-2.0
134dc3e580aeefff6715b89ba7985af0
34.114679
134
0.54017
4.869593
false
false
false
false
payjp/payjp-ios
Sources/Views/BorderView.swift
1
1459
// // BorderView.swift // PAYJP // // Created by Tadashi Wakayanagi on 2020/04/13. // Copyright © 2020 PAY, Inc. All rights reserved. // import UIKit @IBDesignable class BorderView: UIView { @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor? { didSet { layer.borderColor = borderColor?.cgColor } } @IBInspectable var isHighlighted: Bool = false { didSet { if oldValue != isHighlighted { updateHighlight() } } } override func layoutSubviews() { super.layoutSubviews() updateHighlight() } private func updateHighlight() { if isHighlighted { highlightOn() } else { highlightOff() } } private func highlightOn() { layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 layer.borderWidth = borderWidth layer.borderColor = borderColor?.cgColor } private func highlightOff() { layer.cornerRadius = 0 layer.masksToBounds = false layer.borderWidth = 0 layer.borderColor = nil } }
mit
cd6fcf4aac8fe9bceb813069941846cd
21.78125
52
0.571331
5.0625
false
false
false
false
joalbright/Inlinit
Example/Inlinit/ViewController.swift
1
1466
// // ViewController.swift // Inlinit // // Created by Jo Albright on 01/06/2016. // Copyright (c) 2016 Jo Albright. All rights reserved. // import UIKit extension UIView: Inlinit { } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let label: UILabel = UILabel { $0.text = "This is Awesome!" $0.textColor = UIColor.cyan $0.frame = CGRect(x: 20, y: 20, width: view.frame.width - 40, height: 40) view.addSubview($0) } view.addSubview(label) view.addSubview(UIButton { $0.setTitle("Submit", for: UIControlState()) $0.setTitleColor(UIColor.white, for: UIControlState()) $0.backgroundColor = UIColor.magenta $0.frame = CGRect(x: 20, y: 60, width: view.frame.width - 40, height: 40) }) // initialize & set properties var me = Person { $0.name = "Jo" $0.age = 32 } print(me) // update properties only works on classes me <- { $0.name = "John" $0.age = 30 } print(me) } } class Person: Inlinit { var age: Int = 0 var name: String? required init() { } }
mit
427e9500a575dc23fe96956889c1ff1f
19.942857
85
0.466576
4.402402
false
false
false
false
WSDOT/wsdot-ios-app
wsdot/MountainPassesViewController.swift
1
6419
// // MountainPassesViewController.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import UIKit import Foundation import GoogleMobileAds class MountainPassesViewController: RefreshViewController, UITableViewDelegate, UITableViewDataSource, GADBannerViewDelegate { let cellIdentifier = "PassCell" let segueMountainPassDetailsViewController = "MountainPassDetailsViewController" var passItems = [MountainPassItem]() @IBOutlet weak var bannerView: GAMBannerView! let refreshControl = UIRefreshControl() @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() // refresh controller refreshControl.addTarget(self, action: #selector(MountainPassesViewController.refreshAction(_:)), for: .valueChanged) tableView.addSubview(refreshControl) showOverlay(self.view) self.passItems = MountainPassStore.getPasses() self.tableView.reloadData() refresh(false) tableView.rowHeight = UITableView.automaticDimension // Ad Banner bannerView.adUnitID = ApiKeys.getAdId() bannerView.adSize = getFullWidthAdaptiveAdSize() bannerView.rootViewController = self let request = GAMRequest() request.customTargeting = ["wsdotapp":"passes"] bannerView.load(request) bannerView.delegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) MyAnalytics.screenView(screenName: "PassReports") } func refresh(_ force: Bool){ DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { [weak self] in MountainPassStore.updatePasses(force, completion: { error in if (error == nil) { // Reload tableview on UI thread DispatchQueue.main.async { [weak self] in if let selfValue = self{ selfValue.passItems = MountainPassStore.getPasses() selfValue.tableView.reloadData() selfValue.refreshControl.endRefreshing() selfValue.hideOverlayView() UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: selfValue.tableView) } } } else { DispatchQueue.main.async { [weak self] in if let selfValue = self{ selfValue.refreshControl.endRefreshing() selfValue.hideOverlayView() AlertMessages.getConnectionAlert(backupURL: WsdotURLS.passes, message: WSDOTErrorStrings.passReports) } } } }) } } @objc func refreshAction(_ sender: UIRefreshControl) { refresh(true) } // MARK: Table View Data Source Methods func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return passItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! MountainPassCell let passItem = passItems[indexPath.row] cell.nameLabel.text = passItem.name cell.forecastLabel.text = "" if (passItem.weatherCondition != ""){ cell.forecastLabel.text = passItem.weatherCondition } if (passItem.forecast.count > 0){ if (cell.forecastLabel.text == "") { cell.forecastLabel.text = WeatherUtils.getForecastBriefDescription(passItem.forecast[0].forecastText) } cell.weatherImage.image = UIImage(named: WeatherUtils.getIconName(passItem.forecast[0].forecastText, title: passItem.forecast[0].day)) } else { cell.forecastLabel.text = "" cell.weatherImage.image = nil } if passItem.dateUpdated as Date == Date.init(timeIntervalSince1970: 0){ cell.updatedLabel.text = "Not Available" }else { cell.updatedLabel.text = TimeUtils.timeAgoSinceDate(date: passItem.dateUpdated, numericDates: true) } return cell } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } // MARK: Table View Delegate Methods func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Perform Segue performSegue(withIdentifier: segueMountainPassDetailsViewController, sender: self) tableView.deselectRow(at: indexPath, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == segueMountainPassDetailsViewController { if let indexPath = tableView.indexPathForSelectedRow { let passItem = self.passItems[indexPath.row] as MountainPassItem let destinationViewController = segue.destination as! MountainPassTabBarViewController destinationViewController.passItem = passItem let backItem = UIBarButtonItem() backItem.title = "Back" navigationItem.backBarButtonItem = backItem } } } }
gpl-3.0
28a52e4709ca0da121323ef0b70bfcd3
37.90303
146
0.629537
5.572049
false
false
false
false
Adorkable/Eunomia
Source/Core/UtilityExtensions/CoreData/NSFetchedResultsController+Utility.swift
1
2300
// // NSFetchedResultsController+Utility.swift // Eunomia // // Created by Ian Grossberg on 7/29/15. // Copyright (c) 2015 Adorkable. All rights reserved. // import Foundation import CoreData // Currently bugged: https://bugs.swift.org/browse/SR-2708 //extension NSFetchedResultsController { // // convenience init(fetchObjectType : NSManagedObject.Type, managedObjectContext context : NSManagedObjectContext, sectionNameKeyPath : String? = nil, cacheName : String? = nil) { // // let useFetchRequest = fetchObjectType.guaranteeFetchRequest(nil) // self.init(fetchRequest: useFetchRequest as! NSFetchRequest<_>, managedObjectContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) // } // // public func firstResultOfPerformFetch() throws -> AnyObject? { // var result : AnyObject? // // try self.performFetch() // // if let fetchedObjects = self.fetchedObjects // { // result = fetchedObjects.first // } // // return result // } // // public class func firstResult(_ fetchRequest : NSFetchRequest<NSFetchRequestResult>, context : NSManagedObjectContext, sectionNameKeyPath : String? = nil, cacheName : String? = nil) throws -> AnyObject? { // // let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest as! NSFetchRequest<NSFetchRequestResult>, managedObjectContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) // return try fetchedResultsController.firstResultOfPerformFetch() // } // // public var fetchedObjectsCount : Int { // return guarantee(self.fetchedObjects?.count, fallback: 0) // } // // public class func fetchedObjectsCount(_ fetchObjectType : NSManagedObject.Type, context : NSManagedObjectContext, sectionNameKeyPath : String? = nil, cacheName : String? = nil) throws -> Int { // // let fetchedResultsController = NSFetchedResultsController(fetchObjectType: fetchObjectType, managedObjectContext: context, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName) // try fetchedResultsController.performFetch() // // return fetchedResultsController.fetchedObjectsCount // } //}
mit
e91c52e01c52800a0080583b765dc2cc
43.230769
229
0.699565
4.946237
false
false
false
false
wuzhenli/MyDailyTestDemo
swiftTest/swifter-tips+swift+3.0/Swifter.playground/Pages/enumerate.xcplaygroundpage/Contents.swift
1
357
import Foundation let arr: NSArray = [1,2,3,4,5] var result = 0 arr.enumerateObjects ({ (num, idx, stop) -> Void in result += num as! Int if idx == 2 { stop.pointee = true } }) print(result) // 输出:6 result = 0 for (idx, num) in [1,2,3,4,5].enumerated() { result += num if idx == 2 { break } } print(result)
apache-2.0
eb8befc00ff28e994014a888a451c0ab
14.26087
51
0.547009
2.830645
false
false
false
false
rcach/Layers
Layers/Layers/RainforestCollectionViewLayout.swift
1
7051
// // RainforestCollectionViewLayout.swift // LayersCollectionViewPlayground // // Created by René Cacheaux on 10/1/14. // Copyright (c) 2014 Razeware LLC. All rights reserved. // import Foundation // NOTE: This custom layout is built specifically for the AsyncDisplayKit tutorial. If you would like // to use this layout outside this project you may end up needing to make modifications. // However, this code is a good starting point. protocol RainforestLayoutMetrics { func numberOfRowsForNumberOfItems(numberOfItems: Int) -> Int func rowForItemAtIndex(index: Int) -> Int func columnForItemAtIndex(index: Int) -> Int func indexForItemAboveItemAtIndex(index: Int) -> Int func numberOfColumns() -> Int } class TwoColumnLayoutMetrics: RainforestLayoutMetrics { func numberOfRowsForNumberOfItems(numberOfItems: Int) -> Int { var isOdd: Bool = numberOfItems%2 > 0 var numberOfRows = numberOfItems/2 if isOdd { numberOfRows++ } return numberOfRows } func rowForItemAtIndex(index: Int) -> Int { return ((index + 1)/2 + (index + 1)%2) - 1 } func columnForItemAtIndex(index: Int) -> Int { return index%2 } func indexForItemAboveItemAtIndex(index: Int) -> Int { var aboveItemIndex = index - 2 return aboveItemIndex >= 0 ? aboveItemIndex : index } func numberOfColumns() -> Int { return 2 } } class OneColumnLayoutMetrics: RainforestLayoutMetrics { func numberOfRowsForNumberOfItems(numberOfItems: Int) -> Int { return numberOfItems } func rowForItemAtIndex(index: Int) -> Int { return index } func columnForItemAtIndex(index: Int) -> Int { return 0 } func indexForItemAboveItemAtIndex(index: Int) -> Int { var aboveItemIndex = index - 1 return aboveItemIndex >= 0 ? aboveItemIndex : index } func numberOfColumns() -> Int { return 1 } } enum RainforestLayoutType { case OneColumn case TwoColumn func metrics() -> RainforestLayoutMetrics { switch self { case OneColumn: return OneColumnLayoutMetrics() case TwoColumn: return TwoColumnLayoutMetrics() } } } class RainforestCollectionViewLayout: UICollectionViewLayout { var allLayoutAttributes = [UICollectionViewLayoutAttributes]() let cellDefaultHeight = 300 let cellWidth = Int(FrameCalculator.cardWidth) let interCellVerticalSpacing = 10 let interCellHorizontalSpacing = 10 var contentMaxY: CGFloat = 0 var layoutType: RainforestLayoutType var layoutMetrics: RainforestLayoutMetrics init(type: RainforestLayoutType) { layoutType = type layoutMetrics = type.metrics() super.init() } override init() { layoutType = .TwoColumn layoutMetrics = layoutType.metrics() super.init() } required init(coder aDecoder: NSCoder) { layoutType = .TwoColumn layoutMetrics = layoutType.metrics() super.init(coder: aDecoder) } override func prepareLayout() { super.prepareLayout() if allLayoutAttributes.count == 0 { if let collectionView = self.collectionView { if collectionView.frame.size.width < CGFloat((self.cellWidth * 2) + interCellHorizontalSpacing) { layoutType = .OneColumn layoutMetrics = layoutType.metrics() } } populateLayoutAttributes() } } func populateLayoutAttributes() { if self.collectionView == nil { return } let collectionView = self.collectionView! // Calculate left margin max x. let totalWidthOfCellsInARow = layoutMetrics.numberOfColumns() * cellWidth let totalSpaceBetweenCellsInARow = interCellHorizontalSpacing * max(0, layoutMetrics.numberOfColumns() - 1) let totalCellAndSpaceWidth = totalWidthOfCellsInARow + totalSpaceBetweenCellsInARow let totalHorizontalMargin = collectionView.frame.size.width - CGFloat(totalCellAndSpaceWidth) let leftMarginMaxX = totalHorizontalMargin / CGFloat(2.0) allLayoutAttributes.removeAll(keepCapacity: true) for i in 0 ..< collectionView.numberOfItemsInSection(0) { let la = UICollectionViewLayoutAttributes(forCellWithIndexPath: NSIndexPath(forItem: i, inSection: 0)) let row = layoutMetrics.rowForItemAtIndex(i) let column = layoutMetrics.columnForItemAtIndex(i) let x = ((cellWidth + interCellHorizontalSpacing) * column) + Int(leftMarginMaxX) let y = (row * cellDefaultHeight) + (interCellVerticalSpacing * (row + 1)) la.frame = CGRect(x: x, y: y, width: cellWidth, height: cellDefaultHeight) allLayoutAttributes.append(la) if la.frame.maxY > contentMaxY { contentMaxY = ceil(la.frame.maxY) } } } override func collectionViewContentSize() -> CGSize { if self.collectionView == nil { return CGSizeZero } let collectionView = self.collectionView! return CGSize(width: collectionView.frame.size.width, height: contentMaxY) } override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { var layoutAttributes = [UICollectionViewLayoutAttributes]() for i in 0 ..< allLayoutAttributes.count { let la = allLayoutAttributes[i] if rect.contains(la.frame) { layoutAttributes.append(la) } } return allLayoutAttributes } override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { if indexPath.item >= allLayoutAttributes.count { return nil } return allLayoutAttributes[indexPath.item] } override func shouldInvalidateLayoutForPreferredLayoutAttributes(preferredAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes originalAttributes: UICollectionViewLayoutAttributes) -> Bool { return true } override func invalidationContextForPreferredLayoutAttributes(preferredAttributes: UICollectionViewLayoutAttributes, withOriginalAttributes originalAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutInvalidationContext { let indexForItemAbove = layoutMetrics.indexForItemAboveItemAtIndex(originalAttributes.indexPath.item) let layoutAttributesForItemAbove = allLayoutAttributes[indexForItemAbove] if originalAttributes.indexPath.item != indexForItemAbove { preferredAttributes.frame.origin.y = layoutAttributesForItemAbove.frame.maxY + CGFloat(interCellVerticalSpacing) } else { preferredAttributes.frame.origin.y = 0 } allLayoutAttributes[originalAttributes.indexPath.item] = preferredAttributes let invalidationContext = super.invalidationContextForPreferredLayoutAttributes(preferredAttributes, withOriginalAttributes: originalAttributes) invalidationContext.invalidateItemsAtIndexPaths([originalAttributes.indexPath]) if preferredAttributes.frame.maxY > contentMaxY { invalidationContext.contentSizeAdjustment = CGSize(width: 0, height: preferredAttributes.frame.maxY - contentMaxY) contentMaxY = ceil(preferredAttributes.frame.maxY) } return invalidationContext } }
apache-2.0
663a57cefa0e8702ed8c88d41cd3440d
32.254717
148
0.730638
4.832077
false
false
false
false
MrZoidberg/metapp
metapp/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift
17
5343
// // CompositeDisposable.swift // RxSwift // // Created by Krunoslav Zaher on 2/20/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /// Represents a group of disposable resources that are disposed together. public final class CompositeDisposable : DisposeBase, Disposable, Cancelable { public typealias DisposeKey = BagKey private var _lock = SpinLock() // state private var _disposables: Bag<Disposable>? = Bag() public var isDisposed: Bool { _lock.lock(); defer { _lock.unlock() } return _disposables == nil } public override init() { } /// Initializes a new instance of composite disposable with the specified number of disposables. public init(_ disposable1: Disposable, _ disposable2: Disposable) { // This overload is here to make sure we are using optimized version up to 4 arguments. let _ = _disposables!.insert(disposable1) let _ = _disposables!.insert(disposable2) } /// Initializes a new instance of composite disposable with the specified number of disposables. public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) { // This overload is here to make sure we are using optimized version up to 4 arguments. let _ = _disposables!.insert(disposable1) let _ = _disposables!.insert(disposable2) let _ = _disposables!.insert(disposable3) } /// Initializes a new instance of composite disposable with the specified number of disposables. public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposable4: Disposable, _ disposables: Disposable...) { // This overload is here to make sure we are using optimized version up to 4 arguments. let _ = _disposables!.insert(disposable1) let _ = _disposables!.insert(disposable2) let _ = _disposables!.insert(disposable3) let _ = _disposables!.insert(disposable4) for disposable in disposables { let _ = _disposables!.insert(disposable) } } /// Initializes a new instance of composite disposable with the specified number of disposables. public init(disposables: [Disposable]) { for disposable in disposables { let _ = _disposables!.insert(disposable) } } /** Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. - parameter disposable: Disposable to add. - returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already disposed `nil` will be returned. */ public func insert(_ disposable: Disposable) -> DisposeKey? { let key = _insert(disposable) if key == nil { disposable.dispose() } return key } private func _insert(_ disposable: Disposable) -> DisposeKey? { _lock.lock(); defer { _lock.unlock() } return _disposables?.insert(disposable) } /// - returns: Gets the number of disposables contained in the `CompositeDisposable`. public var count: Int { _lock.lock(); defer { _lock.unlock() } return _disposables?.count ?? 0 } /// Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable. /// /// - parameter disposeKey: Key used to identify disposable to be removed. public func remove(for disposeKey: DisposeKey) { _remove(for: disposeKey)?.dispose() } private func _remove(for disposeKey: DisposeKey) -> Disposable? { _lock.lock(); defer { _lock.unlock() } return _disposables?.removeKey(disposeKey) } /// Disposes all disposables in the group and removes them from the group. public func dispose() { if let disposables = _dispose() { disposeAll(in: disposables) } } private func _dispose() -> Bag<Disposable>? { _lock.lock(); defer { _lock.unlock() } let disposeBag = _disposables _disposables = nil return disposeBag } } extension Disposables { /// Creates a disposable with the given disposables. public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) -> Cancelable { return CompositeDisposable(disposable1, disposable2, disposable3) } /// Creates a disposable with the given disposables. public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposables: Disposable ...) -> Cancelable { var disposables = disposables disposables.append(disposable1) disposables.append(disposable2) disposables.append(disposable3) return CompositeDisposable(disposables: disposables) } /// Creates a disposable with the given disposables. public static func create(_ disposables: [Disposable]) -> Cancelable { switch disposables.count { case 2: return Disposables.create(disposables[0], disposables[1]) default: return CompositeDisposable(disposables: disposables) } } }
mpl-2.0
ebceaa17985c261bd1c451ad51dc9041
35.589041
157
0.650505
5.001873
false
false
false
false
superk589/DereGuide
DereGuide/Card/Detail/View/CardDetailSourceCell.swift
2
3762
// // CardDetailSourceCell.swift // DereGuide // // Created by zzk on 2017/6/26. // Copyright © 2017 zzk. All rights reserved. // import UIKit import TTGTagCollectionView class CardDetailSourceCell: UITableViewCell { var types: [CGSSAvailableTypes] = [CGSSAvailableTypes.event, .normal, .limit, .fes] var titles: [String] { return types.map { $0.description } } let collectionView = TTGTagCollectionView() var tagViews = [CheckBox]() let leftLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) leftLabel.font = .systemFont(ofSize: 16) leftLabel.text = NSLocalizedString("获得途径", comment: "卡片详情页") contentView.addSubview(leftLabel) leftLabel.snp.makeConstraints { (make) in make.left.equalTo(readableContentGuide) make.top.equalTo(10) } for i in 0..<types.count { let checkBox = CheckBox() checkBox.tintColor = .parade checkBox.label.textColor = .darkGray checkBox.label.text = titles[i] checkBox.isChecked = false tagViews.append(checkBox) } collectionView.contentInset = .zero collectionView.verticalSpacing = 5 collectionView.horizontalSpacing = 15 contentView.addSubview(collectionView) collectionView.dataSource = self collectionView.delegate = self collectionView.snp.makeConstraints { (make) in make.top.equalTo(leftLabel.snp.bottom).offset(5) make.left.equalTo(readableContentGuide) make.right.equalTo(readableContentGuide) make.bottom.equalTo(-10) } selectionStyle = .none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize { layoutIfNeeded() collectionView.invalidateIntrinsicContentSize() return super.systemLayoutSizeFitting(targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority) } } extension CardDetailSourceCell: TTGTagCollectionViewDelegate, TTGTagCollectionViewDataSource { func numberOfTags(in tagCollectionView: TTGTagCollectionView!) -> UInt { return UInt(types.count) } func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, tagViewFor index: UInt) -> UIView! { return tagViews[Int(index)] } func tagCollectionView(_ tagCollectionView: TTGTagCollectionView!, sizeForTagAt index: UInt) -> CGSize { let tagView = tagViews[Int(index)] return tagView.intrinsicContentSize } } extension CardDetailSourceCell: CardDetailSetable { func setup(with card: CGSSCard) { var types: CGSSAvailableTypes = .free if card.evolutionId == 0 { leftLabel.text = NSLocalizedString("获得途径(进化前)", comment: "卡片详情页") if let cardFrom = CGSSDAO.shared.findCardById(card.id - 1) { types = cardFrom.gachaType } } else { leftLabel.text = NSLocalizedString("获得途径", comment: "卡片详情页") types = card.gachaType } for i in 0..<self.types.count { let view = tagViews[i] view.isChecked = types.contains(self.types[i]) } collectionView.reload() } }
mit
d77b9a43b538fc5862931030c5d43bf8
34.932039
193
0.654148
4.812744
false
false
false
false
team-supercharge/boa
lib/boa/module/templates/swift/ViewInterface.swift
1
191
// // <%= @prefixed_module %>View.h // <%= @project %> // // Created by <%= @author %> on <%= @date %>. // // import Foundation protocol <%= @prefixed_module %>ViewInterface: class { }
mit
822a40517eae30b14dc94a909551298b
12.642857
52
0.539267
3.031746
false
false
false
false
alexking124/Picture-Map
Picture Map/DatabaseInterface.swift
1
2163
// // DatabaseInterface.swift // Picture Map // // Created by Alex King on 12/21/16. // Copyright © 2016 Alex King. All rights reserved. // import Foundation import FirebaseAuth import FirebaseDatabase class DatabaseInterface { static let shared = DatabaseInterface() private var currentUserID: String { let currentUser = FIRAuth.auth()?.currentUser guard let userID = currentUser?.uid else { fatalError("Couldn't get the current user!") } return userID } private var databaseReference: FIRDatabaseReference { return FIRDatabase.database().reference() } private var pinsDatabaseReference: FIRDatabaseReference { return databaseReference.child("pins").child(currentUserID) } private var usageDatabaseReference: FIRDatabaseReference { return databaseReference.child("limit").child(currentUserID) } func insertNewPin() -> FIRDatabaseReference { let pinReference = pinsDatabaseReference.childByAutoId() self.decrementLimit() return pinReference } func updatePin(_ pinID: String, metadata: Any?) { let pinReference = pinsDatabaseReference.child(pinID) pinReference.setValue(metadata) } func deletePin(_ pinID: String) { let pinReference = pinsDatabaseReference.child(pinID) pinReference.removeValue() self.incrementLimit() } private func decrementLimit() { usageDatabaseReference.observeSingleEvent(of: .value, with: { [unowned self] (snapshot) in guard let value = snapshot.value else { return } self.usageDatabaseReference.setValue((value as AnyObject).integerValue - 1) }) } private func incrementLimit() { usageDatabaseReference.observeSingleEvent(of: .value, with: { [unowned self] (snapshot) in guard let value = snapshot.value else { return } self.usageDatabaseReference.setValue((value as AnyObject).integerValue + 1) }) } }
mit
9475677ec7834464ae189395b963e37d
27.077922
98
0.631822
5.099057
false
false
false
false
tejen/codepath-instagram
Instagram/Instagram/ProfileCollectionRowTableViewCell.swift
1
4653
// // ProfileCollectionRowTableViewCell.swift // Instagram // // Created by Tejen Hasmukh Patel on 3/6/16. // Copyright © 2016 Tejen. All rights reserved. // import UIKit class ProfileCollectionRowTableViewCell: UITableViewCell { weak var profileTableController: ProfileTableViewController?; @IBOutlet weak var activityOne: UIActivityIndicatorView! @IBOutlet weak var activityTwo: UIActivityIndicatorView! @IBOutlet weak var activityThree: UIActivityIndicatorView! var postOne: Post? { didSet { if(postOne != nil) { activityOne.startAnimating(); imageOne.setImageWithURLRequest(NSURLRequest(URL: postOne!.mediaURL!), placeholderImage: nil, success: { (req: NSURLRequest, res: NSHTTPURLResponse?, img: UIImage) -> Void in self.activityOne.stopAnimating(); self.imageOne.image = img; }, failure: nil); } else { activityOne.stopAnimating(); } } } var postTwo: Post? { didSet { if(postTwo != nil) { activityTwo.startAnimating(); imageTwo.setImageWithURLRequest(NSURLRequest(URL: postTwo!.mediaURL!), placeholderImage: nil, success: { (req: NSURLRequest, res: NSHTTPURLResponse?, img: UIImage) -> Void in self.activityTwo.stopAnimating(); self.imageTwo.image = img; }, failure: nil); } else { activityTwo.stopAnimating(); imageTwo.hidden = true; } } } var postThree: Post? { didSet { if(postThree != nil) { activityThree.startAnimating(); imageThree.setImageWithURLRequest(NSURLRequest(URL: postThree!.mediaURL!), placeholderImage: nil, success: { (req: NSURLRequest, res: NSHTTPURLResponse?, img: UIImage) -> Void in self.activityThree.stopAnimating(); self.imageThree.image = img; }, failure: nil); } else { activityThree.stopAnimating(); imageThree.hidden = true; } } } @IBOutlet var imageOne: UIImageView!; @IBOutlet var imageTwo: UIImageView!; @IBOutlet var imageThree: UIImageView!; override func awakeFromNib() { super.awakeFromNib() // Initialization code var taps = [ UITapGestureRecognizer(target: self, action: Selector("onTappedLeftPhoto")), UITapGestureRecognizer(target: self, action: Selector("onTappedCenterPhoto")), UITapGestureRecognizer(target: self, action: Selector("onTappedRightPhoto")), ]; [imageOne, imageTwo, imageThree].map { imageView in taps[0].delegate = self; imageView.addGestureRecognizer(taps[0]); taps.removeAtIndex(0); } } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func onTappedLeftPhoto() { profileTableController?.detailPost = postOne; UIView.animateWithDuration(0.05) { () -> Void in self.imageOne.alpha = 0.25; } delay(0.2) { () -> () in UIView.animateWithDuration(0.2) { () -> Void in self.imageOne.alpha = 1; } self.profileTableController?.performSegueWithIdentifier("toDetails", sender: self.profileTableController); } } func onTappedCenterPhoto() { profileTableController?.detailPost = postTwo; UIView.animateWithDuration(0.05) { () -> Void in self.imageTwo.alpha = 0.25; } delay(0.2) { () -> () in UIView.animateWithDuration(0.2) { () -> Void in self.imageTwo.alpha = 1; } self.profileTableController?.performSegueWithIdentifier("toDetails", sender: self.profileTableController); } } func onTappedRightPhoto() { profileTableController?.detailPost = postThree; UIView.animateWithDuration(0.05) { () -> Void in self.imageThree.alpha = 0.25; } delay(0.2) { () -> () in UIView.animateWithDuration(0.2) { () -> Void in self.imageThree.alpha = 1; } self.profileTableController?.performSegueWithIdentifier("toDetails", sender: self.profileTableController); } } }
apache-2.0
10467d523d3a73e21d1caa7460453411
34.51145
194
0.573302
4.991416
false
false
false
false
morizotter/SwiftRefresher
SwiftRefresher/SimpleRefreshView.swift
1
3378
// // SimpleRefreshView.swift // Demo // // Created by MORITANAOKI on 2015/12/31. // Copyright © 2015年 molabo. All rights reserved. // import UIKit private let DEFAULT_ACTIVITY_INDICATOR_VIEW_STYLE: UIActivityIndicatorViewStyle = .gray private let DEFAULT_PULLING_IMAGE: UIImage? = { if let imagePath = Bundle(for: SimpleRefreshView.self).path(forResource: "pull", ofType: "png") { return UIImage(contentsOfFile: imagePath) } return nil }() open class SimpleRefreshView: UIView, SwfitRefresherEventReceivable { fileprivate weak var activityIndicatorView: UIActivityIndicatorView! fileprivate weak var pullingImageView: UIImageView! fileprivate var activityIndicatorViewStyle = DEFAULT_ACTIVITY_INDICATOR_VIEW_STYLE fileprivate var pullingImage: UIImage? public convenience init(activityIndicatorViewStyle: UIActivityIndicatorViewStyle, pullingImage: UIImage? = DEFAULT_PULLING_IMAGE) { self.init(frame: CGRect.zero) self.activityIndicatorViewStyle = activityIndicatorViewStyle self.pullingImage = pullingImage commonInit() } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } fileprivate func commonInit() { let aView = UIActivityIndicatorView(activityIndicatorStyle: activityIndicatorViewStyle) aView.hidesWhenStopped = true addSubview(aView) aView.translatesAutoresizingMaskIntoConstraints = false addConstraints( [ NSLayoutConstraint(item: aView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: aView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0) ] ) self.activityIndicatorView = aView let pView = UIImageView(frame: CGRect.zero) pView.contentMode = .scaleAspectFit pView.image = pullingImage addSubview(pView) pView.translatesAutoresizingMaskIntoConstraints = false addConstraints( [ NSLayoutConstraint(item: pView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: pView, attribute: .centerY, relatedBy: .equal, toItem: self, attribute: .centerY, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: pView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1.0, constant: 22.0), NSLayoutConstraint(item: pView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 22.0), ] ) self.pullingImageView = pView } open func didReceiveEvent(_ event: SwiftRefresherEvent) { switch event { case .pull: pullingImageView.isHidden = false case .startRefreshing: pullingImageView.isHidden = true activityIndicatorView.startAnimating() case .endRefreshing: activityIndicatorView.stopAnimating() case .recoveredToInitialState: break } } }
mit
4ef579e2630f530b94be6c9075af1c69
38.244186
155
0.674963
4.891304
false
false
false
false
LinkRober/RBRefresh
RBRefresh/TestViewController.swift
1
5680
// // TestViewController.swift // RBRefresh // // Created by 夏敏 on 20/01/2017. // Copyright © 2017 夏敏. All rights reserved. // import UIKit class TestViewController: UIViewController,UITableViewDelegate,UITableViewDataSource{ lazy var tableview:UITableView = { let tableview = UITableView.init(frame: CGRect(x:0,y:0,width:self.view.frame.size.width,height:self.view.frame.size.height - 64), style: .plain) return tableview }() var type:Type = .Normal var datasource = [1,2,3,4,5] override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = [] self.tableview.delegate = self self.tableview.dataSource = self self.tableview.tableFooterView = UIView() view.addSubview(self.tableview) if type == .Normal { self.tableview.rb_addHeaderRefreshBlock({ DispatchQueue.main.asyncAfter(deadline:.now() + 1) { self.datasource.removeAll() self.tableview.reloadData() for _ in 0 ..< 10 { self.datasource.append(self.randNumber()) } self.tableview.rb_resetNoMoreData() self.tableview.rb_endHeaderRefresh() self.tableview.reloadData() } }, animator:RBNormalHeader.init(frame: CGRect(x:0,y:0,width:0,height:50))) }else if type == .Gif{ self.tableview.rb_addHeaderRefreshBlock({ DispatchQueue.main.asyncAfter(deadline:.now() + 1) { self.datasource.removeAll() self.tableview.reloadData() for _ in 0 ..< 10 { self.datasource.append(self.randNumber()) } self.tableview.rb_resetNoMoreData() self.tableview.rb_endHeaderRefresh() self.tableview.reloadData() } }, animator:RBGifHeader.init(frame: CGRect(x:0,y:0,width:0,height:80))) } else if type == .BallRoateChase { self.tableview.rb_addHeaderRefreshBlock({ DispatchQueue.main.asyncAfter(deadline:.now() + 1) { self.datasource.removeAll() self.tableview.reloadData() for _ in 0 ..< 10 { self.datasource.append(self.randNumber()) } self.tableview.rb_resetNoMoreData() self.tableview.rb_endHeaderRefresh() self.tableview.reloadData() } }, animator:RBBallRoateChaseHeader.init(frame: CGRect(x:0,y:0,width:kScreenWidth,height:50))) } else if type == .BallClipRotate { self.tableview.rb_addHeaderRefreshBlock({ DispatchQueue.main.asyncAfter(deadline:.now() + 1) { self.datasource.removeAll() self.tableview.reloadData() for _ in 0 ..< 10 { self.datasource.append(self.randNumber()) } self.tableview.rb_resetNoMoreData() self.tableview.rb_endHeaderRefresh() self.tableview.reloadData() } }, animator:RBBallClipRoateHeader.init(frame: CGRect(x:0,y:0,width:kScreenWidth,height:50))) }else if type == .BallScale { self.tableview.rb_addHeaderRefreshBlock({ DispatchQueue.main.asyncAfter(deadline:.now() + 1) { self.datasource.removeAll() self.tableview.reloadData() for _ in 0 ..< 10 { self.datasource.append(self.randNumber()) } self.tableview.rb_resetNoMoreData() self.tableview.rb_endHeaderRefresh() self.tableview.reloadData() } }, animator:RBBallScaleHeader.init(frame: CGRect(x:0,y:0,width:kScreenWidth,height:50))) } self.tableview.rb_addFooterRefreshBlock({ OperationQueue().addOperation { sleep(1) OperationQueue.main.addOperation { self.tableview.rb_endFooterRefresh() self.datasource.append(contentsOf: [24,25].map({ (n:Int) -> Int in return self.randNumber() })) self.tableview.reloadData() } } }, animator: RBNormalFooter.init(frame: CGRect(x:0,y:0,width:0,height:50))) self.tableview.rb_beginHeaderRefresh() } func randNumber() -> Int { return Int(arc4random_uniform(100)) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datasource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell.init(style: .default, reuseIdentifier: "") cell.textLabel?.text = "\(datasource[indexPath.row])" return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } }
mit
d98e5a8457fec9ce3b900a7a52638f99
37.317568
152
0.536766
4.92702
false
false
false
false
cuba/NetworkKit
Example/Example/AlamofireDispatcher.swift
1
1931
// // AlamofireDispatcher.swift // Example // // Created by Jacob Sikorski on 2019-04-12. // Copyright © 2019 Jacob Sikorski. All rights reserved. // import Foundation import NetworkKit import Alamofire class AlamofireDispatcher: Dispatcher { weak var serverProvider: ServerProvider? var sessionManager: SessionManager /// Initialize this `Dispatcher` with a `ServerProvider`. /// /// - Parameter serverProvider: The server provider that will give the dispatcher the `baseURL`. init(serverProvider: ServerProvider) { self.serverProvider = serverProvider self.sessionManager = SessionManager() } func future(from request: NetworkKit.Request) -> ResponseFuture<Response<Data?>> { return ResponseFuture<Response<Data?>>() { promise in guard let serverProvider = self.serverProvider else { throw RequestError.missingServerProvider } let urlRequest = try serverProvider.urlRequest(from: request) self.sessionManager.request(urlRequest).response(completionHandler: { dataResponse in // Ensure there is an http response guard let httpResponse = dataResponse.response else { let error = ResponseError.unknown(cause: dataResponse.error) promise.fail(with: error) return } // Create the response let error = dataResponse.error let statusCode = StatusCode(rawValue: httpResponse.statusCode) let responseError = statusCode.makeError(cause: error) let response = Response(data: dataResponse.data, httpResponse: httpResponse, urlRequest: urlRequest, statusCode: statusCode, error: responseError) promise.succeed(with: response) }) } } }
mit
459d780128a9875fc27dbeb86bc5d671
37.6
162
0.628497
5.482955
false
false
false
false
willowtreeapps/PinkyPromise
Sources/PromiseQueue.swift
1
3998
// // PromiseQueue.swift // PinkyPromise // // Created by Kevin Conner on 8/19/16. // // The MIT License (MIT) // Copyright © 2016 WillowTree, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // import Foundation /// A simple queue that runs one Promise at a time in the order they're added. public final class PromiseQueue<Value> { /// The promise that is currently executing, if any. private var runningPromise: Promise<Value>? /// Promises that are waiting to begin. private var remainingPromises: [Promise<Value>] = [] /// Creates a queue. public init() {} /** Creates a promise that enqueues an array of promises and unifies their results. - parameter promises: The array of promises to run. - returns: A promise whose task runs all the given promises and produces either an array of all the given promises' success values, or the first error among them. */ public func batch(promises: [Promise<Value>]) -> Promise<[Value]> { return Promise { fulfill in var results: [Result<Value, Error>] = [] guard let lastPromise = promises.last else { fulfill(zipArray(results)) return } for promise in promises.dropLast() { promise .onResult { result in results.append(result) } .enqueue(in: self) } lastPromise .onResult { result in results.append(result) fulfill(zipArray(results)) } .enqueue(in: self) } } // MARK: Helpers /** Adds a promise to the queue. - parameter promise: The promise to be enqueued. The promise will begin when all the previously enqueued promises have completed. If the queue was empty, the promise will begin immediately. */ fileprivate func add(_ promise: Promise<Value>) { remainingPromises.append(promise) continueIfIdle() } /// Begins the next promise, provided that no promise is running and the queue is not empty. private func continueIfIdle() { guard runningPromise == nil, let promise = remainingPromises.first else { return } remainingPromises.removeFirst() runningPromise = promise promise.call { _ in self.runningPromise = nil self.continueIfIdle() } } } public extension Promise { /** Adds a promise to a queue. - parameter queue: A queue that will run the promise. In order to work with a `PromiseQueue`, use `enqueue` instead of `call`. The queue will invoke `call` when all its previously enqueued promises have completed. */ func enqueue(in queue: PromiseQueue<Value>) { queue.add(self) } }
mit
87cdfd92f3c5c0c5bf1ade00c9978594
31.762295
167
0.638979
4.663944
false
false
false
false
CodeDrunkard/OYE
OYE/Player/PlayerView.swift
1
6625
// // PlayerView.swift // OYE // // Created by JT Ma on 30/09/2017. // Copyright © 2017 JiangtaoMa<majt@hiscene.com>. All rights reserved. // import UIKit import AVFoundation class PlayerView: UIView { public override init(frame: CGRect) { super.init(frame: frame) setupUI() makeConstraints() preview.player = player.player player.delegate = self } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() makeConstraints() preview.player = player.player player.delegate = self } func play(url: URL?) { guard let url = url else { return } player.playerItem = AVPlayerItem(url: url) } @objc func playOrPause(_ sender: UIButton) { if !sender.isSelected { pause() } else { play() } } @objc func durationSliderBegan(_ sender: UISlider) { pause() } @objc func durationSliderMove(_ sender: UISlider) { uiCurrentDurationLabel.text = convert(duration: sender.value * player.duration) player.seek(to: Double(sender.value * player.duration), completionHandler: nil) } @objc func durationSliderEnd(_ sender: UISlider) { player.seek(to: Double(sender.value * totalDuration)) { finished in if finished { self.play() } } } func play() { player.play() uiPlayButton.isSelected = false } func pause() { player.pause() uiPlayButton.isSelected = true } // MARK: UI private let player = Player() private let preview = PlayerPreview() private let uiView = UIView() private let uiCurrentDurationLabel = UILabel() private let uiDurationLabel = UILabel() private let uiDurationSlider = UISlider() private let uiDurationProgressView = UIProgressView() private let uiPlayButton = UIButton(type: UIButtonType.custom) private var totalDuration: Float = 0 } extension PlayerView: PlayerDurationProtocol { func playerTotalDuration(duration: Float) { totalDuration = duration uiDurationLabel.text = convert(duration: duration) } func playerDidLoadedDuration(duration: Float) { uiDurationProgressView.setProgress(Float(duration), animated: true) } func playerCurrentDuration(duration: Float) { guard totalDuration > 0 else { return } uiCurrentDurationLabel.text = convert(duration: duration) uiDurationSlider.value = duration / totalDuration } } extension PlayerView { func convert(duration: Float) -> String { let min = Int(duration / 60) let sec = Int(duration.truncatingRemainder(dividingBy: 60)) return String(format: "%02d:%02d", min, sec) } } extension PlayerView { func setupUI() { // uiView.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4) uiCurrentDurationLabel.text = "00:00" uiCurrentDurationLabel.textColor = .white uiCurrentDurationLabel.textAlignment = .center uiCurrentDurationLabel.font = UIFont.systemFont(ofSize: 15) uiDurationLabel.text = "00:00" uiDurationLabel.textColor = .white uiDurationLabel.textAlignment = .center uiDurationLabel.font = UIFont.systemFont(ofSize: 15) uiDurationSlider.maximumValue = 1.0 uiDurationSlider.minimumValue = 0.0 uiDurationSlider.value = 0.0 uiDurationSlider.setThumbImage(UIImage(named: "Player_slider_thumb"), for: .normal) uiDurationSlider.maximumTrackTintColor = UIColor.clear uiDurationSlider.minimumTrackTintColor = UIColor.green uiDurationSlider.addTarget(self, action: #selector(self.durationSliderBegan(_:)), for: .touchDown) uiDurationSlider.addTarget(self, action: #selector(self.durationSliderMove(_:)), for: .valueChanged) uiDurationSlider.addTarget(self, action: #selector(self.durationSliderEnd(_:)), for: [.touchUpInside, .touchUpOutside, .touchCancel]) uiDurationProgressView.tintColor = UIColor (red: 1.0, green: 1.0, blue: 1.0, alpha: 0.6) uiDurationProgressView.trackTintColor = UIColor (red: 1.0, green: 1.0, blue: 1.0, alpha: 0.3) uiPlayButton.setImage(UIImage(named: "Player_play"), for: .selected) uiPlayButton.setImage(UIImage(named: "Player_pause"), for: .normal) uiPlayButton.addTarget(self, action: #selector(self.playOrPause(_:)), for: .touchUpInside) } func makeConstraints() { addSubview(preview) preview.snp.makeConstraints { $0.bottom.right.top.left.equalTo(self) } addSubview(uiView) uiView.snp.makeConstraints { $0.top.bottom.right.left.equalTo(self) } uiView.addSubview(uiCurrentDurationLabel) uiCurrentDurationLabel.snp.makeConstraints { $0.left.equalTo(uiView).offset(15) $0.bottom.equalTo(-20) $0.width.equalTo(60) $0.height.equalTo(20) } uiView.addSubview(uiDurationLabel) uiDurationLabel.snp.makeConstraints { $0.centerY.equalTo(uiCurrentDurationLabel) $0.right.equalTo(uiView).offset(-15) $0.width.equalTo(uiCurrentDurationLabel) $0.height.equalTo(uiCurrentDurationLabel) } uiView.addSubview(uiDurationSlider) uiDurationSlider.snp.makeConstraints { $0.centerY.equalTo(uiCurrentDurationLabel) $0.left.equalTo(uiCurrentDurationLabel.snp.right).offset(10) $0.right.equalTo(uiDurationLabel.snp.left).offset(-10) $0.height.equalTo(20) } uiView.addSubview(uiDurationProgressView) uiDurationProgressView.snp.makeConstraints { $0.left.right.equalTo(uiDurationSlider) $0.centerY.equalTo(uiDurationSlider).offset(1) $0.height.equalTo(2) } // uiView.addSubview(uiBottomMaskView) // uiBottomMaskView.snp.makeConstraints { // $0.left.bottom.right.equalTo(uiView) // $0.height.equalTo(50) // } uiView.addSubview(uiPlayButton) uiPlayButton.snp.makeConstraints { $0.center.equalTo(uiView) $0.width.height.equalTo(80) } } }
mit
4d61b8c63ab2e2e82280cbdb7f68fd53
31.792079
141
0.614583
4.375165
false
false
false
false
ByteriX/BxInputController
BxInputController/Example/Controllers/SelectionController.swift
1
3360
// // SelectionController.swift // BxInputController // // Created by Sergey Balalaev on 12/01/17. // Copyright © 2017 Byterix. All rights reserved. // import UIKit class SelectionController : BxInputController { private var dateValue = BxInputSelectorDateRow(title: "date selector", value: Date().addingTimeInterval(300000)) private var emptyDateValue = BxInputSelectorDateRow(title: "empty date", placeholder: "SELECT") private var autoselectedDateValue = BxInputSelectorDateRow(title: "autoselected", placeholder: "SELECT") private var fromCurrentValue = BxInputSelectorDateRow(title: "from current", value: Date()) private var standartSuggestionsValue = BxInputSelectorSuggestionsRow<BxInputChildSelectorSuggestionsRow>(title: "standart", placeholder: "SELECT") private var justValue = BxInputTextRow(title: "just", placeholder: "for keyboard opening") private var filledVariantValue = BxInputSelectorVariantRow<BxInputVariantItem>(title: "variant") private var emptyVariantValue = BxInputSelectorVariantRow<BxInputVariantItem>(title: "empty variant", placeholder: "SELECT") private var autoselectedVariantValue = BxInputSelectorVariantRow<BxInputVariantItem>(title: "autoselected", placeholder: "SELECT") private var variants : [BxInputVariantItem] = [ BxInputVariantItem(id: "1", name: "first"), BxInputVariantItem(id: "2", name: "second"), BxInputVariantItem(id: "3", name: "last"), ] private var otherVariants : [BxInputVariantItem] = [ BxInputVariantItem(id: "1", name: "value1"), BxInputVariantItem(id: "2", name: "value2"), BxInputVariantItem(id: "3", name: "value3"), BxInputVariantItem(id: "4", name: "value4"), ] override func viewDidLoad() { super.viewDidLoad() autoselectedDateValue.timeForAutoselection = 3 fromCurrentValue.minimumDate = Date() standartSuggestionsValue.children = [ BxInputChildSelectorSuggestionsRow(title: "value 1"), BxInputChildSelectorSuggestionsRow(title: "value 2"), BxInputChildSelectorSuggestionsRow(title: "value 3"), BxInputChildSelectorSuggestionsRow(title: "value 4"), BxInputChildSelectorSuggestionsRow(title: "value 5"), BxInputChildSelectorSuggestionsRow(title: "value 6"), BxInputChildSelectorSuggestionsRow(title: "value 7"), BxInputChildSelectorSuggestionsRow(title: "value 8"), BxInputChildSelectorSuggestionsRow(title: "value 9") ] emptyVariantValue.items = variants filledVariantValue.items = variants filledVariantValue.value = variants.first filledVariantValue.child.height = 120 autoselectedVariantValue.items = otherVariants autoselectedVariantValue.timeForAutoselection = 2 self.sections = [ BxInputSection(headerText: "Date", rows: [dateValue, emptyDateValue, autoselectedDateValue, fromCurrentValue], footerText: "all variants of dates"), BxInputSection(headerText: "Suggestions", rows: [standartSuggestionsValue, justValue]), BxInputSection(headerText: "Variant", rows: [filledVariantValue, emptyVariantValue, autoselectedVariantValue]), ] } }
mit
570f523c204e10252c7f57129c3c0088
45.652778
160
0.696338
4.737659
false
false
false
false
LionWY/MoveView
Model.swift
1
4536
// // Model.swift // AlipaySwift // // Created by FOODING on 17/1/41. // Copyright © 2017年 Noohle. All rights reserved. // import UIKit extension UIImage { static func bundlePath(_ name: String) -> UIImage { let bundlePath = Bundle.main.path(forResource: "My", ofType: "bundle") let bundle = Bundle(path: bundlePath!) let imgPath = bundle?.path(forResource: name, ofType: "png") return UIImage(contentsOfFile: imgPath!)! } } class Model: UIButton { let width = Int(UIScreen.main.bounds.size.width / 4) let height = 80 var _isCheck: Bool = false { didSet { self.isSelected = _isCheck self.handleBtn.isHidden = !_isCheck UIView.animate(withDuration: 0.2) { self.transform = self._isCheck ? CGAffineTransform(scaleX: 1.2, y: 1.2) : CGAffineTransform.identity } self.superview?.bringSubview(toFront: self) } } var delegate: ModelDelegate? var title: String! var handleBtn: UIButton! override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init(frame: CGRect, tag: Int, isNextPage: Bool, isMore: Bool) { super.init(frame: frame) // print("==========\(tag)") self.tag = tag self.layer.cornerRadius = 8.0 self.layer.borderColor = UIColor.init(colorLiteralRed: 235/255.0, green: 235/255.0, blue: 235/255.0, alpha: 1).cgColor self.layer.masksToBounds = true self.setBackgroundImage(UIImage.bundlePath("app_item_bg"), for: .normal) self.setBackgroundImage(UIImage.bundlePath("app_item_pressed_bg"), for: .selected) self.setTitleColor(UIColor.darkGray, for: .normal) if !isMore { handleBtn = UIButton(type: .custom) handleBtn.frame = CGRect(x: frame.size.width - 16, y: 2, width: 16, height: 16) handleBtn.setBackgroundImage(UIImage.bundlePath("app_item_minus"), for: .normal) if isNextPage { handleBtn.setBackgroundImage(UIImage.bundlePath("app_item_plus"), for: .normal) handleBtn.addTarget(self, action: #selector(plusBtnClick), for: .touchUpInside) } else { handleBtn.addTarget(self, action: #selector(minusBtnClick), for: .touchUpInside) } self.addSubview(handleBtn) handleBtn.isHidden = true let gesture = UILongPressGestureRecognizer(target: self, action: #selector(gestureLongPress)) self.addGestureRecognizer(gesture) } } func resetModelFrame() { let index = self.tag - 100 let i = index / 4 let j = index % 4 UIView.animate(withDuration: 0.2) { self.frame = CGRect(x: j * self.width, y: i * self.height, width: self.width, height: self.height) } } func gestureLongPress(gesture: UILongPressGestureRecognizer) { switch gesture.state { case .began: self.delegate?.longPressBegin(model: self, gesture: gesture) break case .changed: self.delegate?.longPressChange(model: self, gesture: gesture) break case .ended: self.delegate?.longPressEnd(model: self, gesture: gesture) break default: print("default") } } func plusBtnClick() { self.delegate?.add(model: self) } func minusBtnClick(){ self.delegate?.delete(model: self) } override func setTitle(_ title: String?, for state: UIControlState) { super.setTitle(title, for: state) self.titleLabel?.font = UIFont.systemFont(ofSize: 16.0) self.title = title } }
mit
584f4823bd7aad7043b98c88832597ef
23.770492
126
0.510038
4.863734
false
false
false
false
Noobish1/KeyedMapper
KeyedMapperTests/Extensions/KeyedMapper/KeyedMapper+NilConvertibleSpec.swift
1
2114
import Foundation import Quick import Nimble @testable import KeyedMapper private enum NilConvertibleEnum: NilConvertible { case nothing case something fileprivate static func fromMap(_ value: Any?) throws -> NilConvertibleEnum { return value.map { _ in .something } ?? .nothing } } extension NilConvertibleEnum: Equatable { fileprivate static func == (lhs: NilConvertibleEnum, rhs: NilConvertibleEnum) -> Bool { switch lhs { case .nothing: switch rhs { case .nothing: return true case .something: return false } case .something: switch rhs { case .nothing: return false case .something: return true } } } } private struct Model: Mappable { fileprivate enum Key: String, JSONKey { case enumProperty } fileprivate let enumProperty: NilConvertibleEnum fileprivate init(map: KeyedMapper<Model>) throws { try self.enumProperty = map.from(.enumProperty) } } class KeyedMapper_NilConvertibleSpec: QuickSpec { override func spec() { describe("KeyedMapper+NilConvertible") { describe("from<T: NilConvertible>") { context("when the given JSON does not contain the value") { it("should map correctly to the nothing case") { let JSON: NSDictionary = [:] let model = try! Model.from(JSON) expect(model.enumProperty) == NilConvertibleEnum.nothing } } context("when the given JSON does contain the value") { it("should map correctly to the something case") { let JSON: NSDictionary = [Model.Key.enumProperty.stringValue: ""] let model = try! Model.from(JSON) expect(model.enumProperty) == NilConvertibleEnum.something } } } } } }
mit
44eb31c0e523b16a3dc89ac41d624509
30.088235
91
0.547304
5.258706
false
false
false
false
normand1/SpriteKit-InventorySystem
InventoryTestApp/GameViewController.swift
1
1249
// // ViewController.swift // InventoryTestApp // // Created by David Norman on 9/17/15. // Copyright © 2015 David Norman. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { var scene: InventoryScene? @IBOutlet weak var inventoryMenuView: SKView! //MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() //Configure the game state for this demo! GameState.inititialSetup() //setup view self.view.backgroundColor = UIColor.blackColor() //setup scene self.scene = InventoryScene(size: self.view.bounds.size) inventoryMenuView.showsFPS = true inventoryMenuView.showsNodeCount = true inventoryMenuView.ignoresSiblingOrder = true self.scene!.scaleMode = .ResizeFill inventoryMenuView.presentScene(scene) } @IBAction func addSword(sender: AnyObject) { let foundItem = GameState.findInventoryItemInEitherStorage(InventoryItemName.sword_silver) foundItem?.numberInStack++ NSNotificationCenter.defaultCenter().postNotification(NSNotification(name:"com.davidwnorman.updateEquippedSlots", object: nil)) } }
mit
e1ad31b276782906ab172fb190e1f005
26.130435
135
0.683494
4.818533
false
false
false
false
xilosada/TravisViewerIOS
TVModel/User+CoreDataProperties.swift
1
1233
// // User+CoreDataProperties.swift // TravisViewerIOS // // Created by X.I. Losada on 13/02/16. // Copyright © 2016 XiLosada. All rights reserved. // // import Foundation import CoreData class User: NSManagedObject{ @NSManaged var name: String @NSManaged var avatarUrl: String? @NSManaged var repos : NSOrderedSet? override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) } init(name:String, avatarUrl: String, context: NSManagedObjectContext){ let entity = NSEntityDescription.entityForName("User", inManagedObjectContext: context)! super.init(entity: entity,insertIntoManagedObjectContext: context) self.name = name self.avatarUrl = avatarUrl } } extension User { func toEntity() -> UserEntity { var user = UserEntity(name: name, avatarUrl:avatarUrl!) var reposAux = [RepositoryEntity]() repos?.forEach{ anyObjectNSSet in let repo = anyObjectNSSet as! Repo reposAux.append(repo.toEntity()) } user.repos = reposAux return user } }
mit
ad3d82006a9a03d8ddcf06b03e4dea46
27
113
0.672078
4.738462
false
false
false
false
ketoo/actor-platform
actor-apps/app-ios/Actor/Controllers/Dialogs/DialogsSearchSource.swift
55
1231
// // Copyright (c) 2015 Actor LLC. <https://actor.im> // import UIKit class DialogsSearchSource: SearchSource { // MARK: - // MARK: Private vars private let DialogsListSearchCellIdentifier = "DialogsListSearchCellIdentifier" // MARK: - // MARK: UITableView override func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier(DialogsListSearchCellIdentifier) as! DialogsSearchCell? if cell == nil { cell = DialogsSearchCell(reuseIdentifier: DialogsListSearchCellIdentifier) } return cell!; } override func bindCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, item: AnyObject?, cell: UITableViewCell) { var searchEntity = item as! AMSearchEntity let isLast = indexPath.row == tableView.numberOfRowsInSection(indexPath.section) - 1; (cell as? DialogsSearchCell)?.bindSearchEntity(searchEntity, isLast: isLast) } override func buildDisplayList() -> AMBindedDisplayList { return MSG.buildSearchList() } }
mit
527c67d5ee1eed31d10df4baa37e8b67
31.394737
139
0.679123
5.150628
false
false
false
false
Instagram/IGListKit
Examples/Examples-iOS/IGListKitExamples/Models/User.swift
1
814
/* * Copyright (c) Meta Platforms, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import IGListKit final class User: ListDiffable { let pk: Int let name: String let handle: String init(pk: Int, name: String, handle: String) { self.pk = pk self.name = name self.handle = handle } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { return pk as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { guard self !== object else { return true } guard let object = object as? User else { return false } return name == object.name && handle == object.handle } }
mit
e4242624c841dbdf1d675e7a4edb3c2d
22.941176
66
0.633907
4.4
false
false
false
false
SoneeJohn/WWDC
WWDC/MainWindowController.swift
1
1970
// // MainWindowController.swift // WWDC // // Created by Guilherme Rambo on 19/04/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa enum MainWindowTab: Int { case schedule case videos func stringValue() -> String { var name = "" debugPrint(self, separator: "", terminator: "", to: &name) return name } } extension Notification.Name { static let MainWindowWantsToSelectSearchField = Notification.Name("MainWindowWantsToSelectSearchField") } final class MainWindowController: NSWindowController { static var defaultRect: NSRect { return NSScreen.main?.visibleFrame.insetBy(dx: 50, dy: 120) ?? NSRect(x: 0, y: 0, width: 1200, height: 600) } public var sidebarInitWidth: CGFloat? init() { let mask: NSWindow.StyleMask = [NSWindow.StyleMask.titled, NSWindow.StyleMask.resizable, NSWindow.StyleMask.miniaturizable, NSWindow.StyleMask.closable] let window = WWDCWindow(contentRect: MainWindowController.defaultRect, styleMask: mask, backing: .buffered, defer: false) super.init(window: window) window.title = "WWDC" window.appearance = WWDCAppearance.appearance() window.center() window.titleVisibility = .hidden window.toolbar = NSToolbar(identifier: NSToolbar.Identifier(rawValue: "WWDC")) window.identifier = NSUserInterfaceItemIdentifier(rawValue: "main") window.setFrameAutosaveName(NSWindow.FrameAutosaveName(rawValue: "main")) window.minSize = NSSize(width: 1060, height: 700) windowDidLoad() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func windowDidLoad() { super.windowDidLoad() } @IBAction func performFindPanelAction(_ sender: Any) { NotificationCenter.default.post(name: .MainWindowWantsToSelectSearchField, object: nil) } }
bsd-2-clause
f4e3ef32bd38a9dc855ccfa626a1edcf
27.128571
160
0.679533
4.505721
false
false
false
false
ahoppen/swift
test/SILOptimizer/move_function_kills_copyable_addressonly_lets.swift
4
12509
// RUN: %target-swift-frontend -enable-experimental-move-only -verify %s -parse-stdlib -emit-sil -o /dev/null // REQUIRES: optimized_stdlib import Swift ////////////////// // Declarations // ////////////////// public class Klass {} public protocol P {} public protocol SubP1 : P {} public protocol SubP2 : P {} func consumingUse<T>(_ k: __owned T) {} var booleanValue: Bool { false } func nonConsumingUse<T>(_ k: T) {} /////////// // Tests // /////////// //===--- // Let + Non Consuming Use // public func simpleLinearUse<T>(_ x: T) { let y = x // expected-error {{'y' used after being moved}} let _ = _move(y) // expected-note {{move here}} nonConsumingUse(y) // expected-note {{use here}} } // We just emit an error today for the first error in a block. public func simpleLinearUse2<T>(_ x: T) { let y = x // expected-error {{'y' used after being moved}} let _ = _move(y) // expected-note {{move here}} nonConsumingUse(y) // expected-note {{use here}} nonConsumingUse(y) } public func conditionalUse1<T>(_ x: T) { let y = x if booleanValue { let _ = _move(y) } else { nonConsumingUse(y) } } public func loopUse1<T>(_ x: T) { let y = x // expected-error {{'y' used after being moved}} let _ = _move(y) // expected-note {{move here}} for _ in 0..<1024 { nonConsumingUse(y) // expected-note {{use here}} } } //===--- // Let + Consuming Use // public func simpleLinearConsumingUse<T>(_ x: T) { let y = x // expected-error {{'y' used after being moved}} let _ = _move(y) // expected-note {{move here}} consumingUse(y) // expected-note {{use here}} } public func conditionalUseOk1<T>(_ x: T) { let y = x if booleanValue { let _ = _move(y) } else { consumingUse(y) } } // This test makes sure that in the case where we have two consuming uses, with // different first level copies, we emit a single diagnostic. public func conditionalBadConsumingUse<T>(_ x: T) { let y = x // expected-error {{'y' used after being moved}} if booleanValue { let _ = _move(y) // expected-note {{move here}} consumingUse(y) // expected-note {{use here}} } else { // We shouldn't get any diagnostic on this use. consumingUse(y) } // But this one and the first consumingUse should get a diagnostic. But // since this is a later error, we require the user to recompile for now. consumingUse(y) } public func conditionalBadConsumingUse2<T>(_ x: T) { let y = x // expected-error {{'y' used after being moved}} if booleanValue { let _ = _move(y) // expected-note {{move here}} } else { // We shouldn't get any diagnostic on this use. consumingUse(y) } consumingUse(y) // expected-note {{use here}} } // This test makes sure that in the case where we have two consuming uses, with // different first level copies, we emit a single diagnostic. public func conditionalBadConsumingUseLoop<T>(_ x: T) { let y = x // expected-error {{'y' used after being moved}} if booleanValue { let _ = _move(y) // expected-note {{move here}} consumingUse(y) // expected-note {{use here}} } else { // We shouldn't get any diagnostic on this use. consumingUse(y) } // But this one and the first consumingUse should get a diagnostic. // // We do not actually emit the diagnostic here since we emit only one // diagnostic per move at a time. for _ in 0..<1024 { consumingUse(y) } } // This test makes sure that in the case where we have two consuming uses, with // different first level copies, we emit a single diagnostic. public func conditionalBadConsumingUseLoop2<T>(_ x: T) { let y = x // expected-error {{'y' used after being moved}} if booleanValue { let _ = _move(y) // expected-note {{move here}} } else { // We shouldn't get any diagnostic on this use. consumingUse(y) } for _ in 0..<1024 { consumingUse(y) // expected-note {{use here}} } } //=== // Parameters // This is ok, no uses after. public func simpleMoveOfParameter<T>(_ x: T) -> () { let _ = _move(x) // expected-error {{_move applied to value that the compiler does not support checking}} } public func simpleMoveOfOwnedParameter<T>(_ x: __owned T) -> () { let _ = _move(x) } public func errorSimpleMoveOfParameter<T>(_ x: __owned T) -> () { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} let _ = _move(x) // expected-note {{use here}} } public func errorSimple2MoveOfParameter<T>(_ x: __owned T) -> () { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} let _ = consumingUse(x) // expected-note {{use here}} } // TODO: I wonder if we could do better for the 2nd error. At least we tell the // user it is due to the loop. public func errorLoopMultipleMove<T>(_ x: __owned T) -> () { // expected-error {{'x' used after being moved}} // expected-error @-1 {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} for _ in 0..<1024 { let _ = _move(x) // expected-note {{move here}} // expected-note @-1 {{use here}} // expected-note @-2 {{use here}} } } public func errorLoopMoveOfParameter<T>(_ x: __owned T) -> () { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} for _ in 0..<1024 { consumingUse(x) // expected-note {{use here}} } } public func errorLoop2MoveOfParameter<T>(_ x: __owned T) -> () { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} for _ in 0..<1024 { nonConsumingUse(x) // expected-note {{use here}} } } public func errorSimple2MoveOfParameterNonConsume<T>(_ x: __owned T) -> () { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} let _ = nonConsumingUse(x) // expected-note {{use here}} } public func errorLoopMoveOfParameterNonConsume<T>(_ x: __owned T) -> () { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} for _ in 0..<1024 { nonConsumingUse(x) // expected-note {{use here}} } } //////////////////////// // Pattern Match Lets // //////////////////////// public func patternMatchIfCaseLet<T>(_ x: T?) { if case let .some(y) = x { // expected-error {{'y' used after being moved}} let _ = _move(y) // expected-note {{move here}} nonConsumingUse(y) // expected-note {{use here}} } } public func patternMatchSwitchLet<T>(_ x: T?) { switch x { case .none: break case .some(let y): // expected-error {{'y' used after being moved}} let _ = _move(y) // expected-note {{move here}} nonConsumingUse(y) // expected-note {{use here}} } } public func patternMatchSwitchLet2<T>(_ x: (T?, T?)?) { switch x { case .some((.some(let y), _)): // expected-error {{'y' used after being moved}} let _ = _move(y) // expected-note {{move here}} nonConsumingUse(y) // expected-note {{use here}} default: break } } public func patternMatchSwitchLet3<T>(_ x: __owned (T?, T?)?) { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} switch x { // expected-note {{use here}} case .some((.some(_), .some(let z))): // expected-error {{'z' used after being moved}} let _ = _move(z) // expected-note {{move here}} nonConsumingUse(z) // expected-note {{use here}} default: break } } //////////////// // Aggregates // //////////////// public struct Pair<T> { var x: T var y: T var z: Int } // Current semantics is that we error on any use of any part of pair once we // have invalidated a part of pair. We can be less restrictive in the future. // // TODO: Why are we emitting two uses here. public func performMoveOnOneEltOfPair<T>(_ p: __owned Pair<T>) { // expected-error {{'p' used after being moved}} let _ = p.z // Make sure we don't crash when we access a trivial value from Pair. let _ = _move(p) // expected-note {{move here}} nonConsumingUse(p.y) // expected-note {{use here}} } public class TPair<T> { var x: T? = nil var y: T? = nil } // TODO: Emit a better error here! We should state that we are applying _move to // a class field and that is illegal. public func performMoveOnOneEltOfTPair<T>(_ p: TPair<T>) { let _ = _move(p.x) // expected-error {{_move applied to value that the compiler does not support checking}} nonConsumingUse(p.y) } public func performMoveOnOneEltOfTPair2<T>(_ p: __owned TPair<T>) { let _ = _move(p.x) // expected-error {{_move applied to value that the compiler does not support checking}} nonConsumingUse(p.y) } public func multipleVarsWithSubsequentBorrows<T : Equatable>(_ p: T) -> Bool { let k = p let k2 = k let k3 = _move(k) return k2 == k3 } //////////////// // Cast Tests // //////////////// public func castTest0<T : SubP1>(_ x: __owned T) -> P { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} return x as P // expected-note {{use here}} } public func castTest1<T : P>(_ x: __owned T) -> SubP2 { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} return x as! SubP2 // expected-note {{use here}} } public func castTest2<T : P>(_ x: __owned T) -> SubP1? { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} return x as? SubP1 // expected-note {{use here}} } public func castTestSwitch1<T : P>(_ x: __owned T) { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} switch x { // expected-note {{use here}} case let k as SubP1: print(k) default: print("Nope") } } public func castTestSwitch2<T : P>(_ x: __owned T) { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} switch x { // expected-note {{use here}} case let k as SubP1: print(k) case let k as SubP2: print(k) default: print("Nope") } } public func castTestSwitchInLoop<T : P>(_ x: __owned T) { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} for _ in 0..<1024 { switch x { // expected-note {{use here}} case let k as SubP1: print(k) default: print("Nope") } } } public func castTestIfLet<T : P>(_ x: __owned T) { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} if case let k as SubP1 = x { // expected-note {{use here}} print(k) } else { print("no") } } public func castTestIfLetInLoop<T : P>(_ x: __owned T) { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} for _ in 0..<1024 { if case let k as SubP1 = x { // expected-note {{use here}} print(k) } else { print("no") } } } public enum EnumWithKlass { case none case klass(P) } public func castTestIfLet2(_ x : __owned EnumWithKlass) { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} if case let .klass(k as SubP1) = x { // expected-note {{use here}} print(k) } else { print("no") } } ///////////////////////// // Partial Apply Tests // ///////////////////////// // Emit a better error here. At least we properly error. public func partialApplyTest<T>(_ x: __owned T) { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} let f = { // expected-note {{use here}} nonConsumingUse(x) } f() } ///////////////// // Defer Tests // ///////////////// // TODO: Emit an error in the defer. public func deferTest<T>(_ x: __owned T) { // expected-error {{'x' used after being moved}} let _ = _move(x) // expected-note {{move here}} defer { // expected-note {{use here}} nonConsumingUse(x) } print("do Something") }
apache-2.0
74a8f2d43540b80011eb960cf824de06
29.962871
125
0.579902
3.45648
false
false
false
false
mz2/Carpaccio
Sources/Carpaccio/ImageLoadingOptions.swift
1
1633
// // ImageLoadingOptions.swift // Carpaccio // // Created by Markus on 27.6.2020. // Copyright © 2020 Matias Piipari & Co. All rights reserved. // import Foundation import CoreGraphics public struct ImageLoadingOptions { public let maximumPixelDimensions: CGSize? public let allowDraftMode: Bool public let baselineExposure: Double? public let noiseReductionAmount: Double public let colorNoiseReductionAmount: Double public let noiseReductionSharpnessAmount: Double public let noiseReductionContrastAmount: Double public let boostShadowAmount: Double public let enableVendorLensCorrection: Bool public init( maximumPixelDimensions: CGSize? = nil, allowDraftMode: Bool = true, baselineExposure: Double? = nil, noiseReductionAmount: Double = 0.5, colorNoiseReductionAmount: Double = 1.0, noiseReductionSharpnessAmount: Double = 0.5, noiseReductionContrastAmount: Double = 0.5, boostShadowAmount: Double = 2.0, enableVendorLensCorrection: Bool = true ) { self.maximumPixelDimensions = maximumPixelDimensions self.allowDraftMode = allowDraftMode self.baselineExposure = baselineExposure self.noiseReductionAmount = noiseReductionAmount self.colorNoiseReductionAmount = colorNoiseReductionAmount self.noiseReductionSharpnessAmount = noiseReductionSharpnessAmount self.noiseReductionContrastAmount = noiseReductionContrastAmount self.boostShadowAmount = boostShadowAmount self.enableVendorLensCorrection = enableVendorLensCorrection } }
mit
34b1dd4cfbb68501a24bebbbf1707bb5
36.090909
74
0.738971
4.8
false
false
false
false
darwin/textyourmom
TextYourMom/ServiceAvailabilityMonitor.swift
1
5532
// bits taken from https://github.com/jhibberd/pophello-ios/blob/0723de26f0acb11a803ce4af7f630d10357398e9/PopCard/ServiceAvailabilityMonitor.swift import CoreLocation import UIKit protocol ServiceAvailabilityMonitorDelegate { func serviceDidBecomeAvailable() func serviceDidBecomeUnavailable() } class ServiceAvailabilityMonitor { var isBackgroundAppRefreshAvailable: Bool var isLocationServicesAuthorized: Bool var isLocationServicesEnabled: Bool var hasRequiredNotificationSettings: Bool var isAvailable: Bool var delegate: ServiceAvailabilityMonitorDelegate? init() { // checked initially isBackgroundAppRefreshAvailable = false isLocationServicesAuthorized = false isLocationServicesEnabled = false hasRequiredNotificationSettings = false isAvailable = false // subscribe to settings changes NSNotificationCenter.defaultCenter().addObserver( self, selector: "backgroundRefreshStatusDidChange:", name: UIApplicationBackgroundRefreshStatusDidChangeNotification, object: nil) } // Perform initial service availability checks when the app is launched. // func checkAvailability() { checkIsBackgroundAppRefreshAvailable() checkIsLocationServicesAuthorized() checkIsLocationServicesEnabled() checkIfHasRequiredNotificationSettings() updateAvailabilityAndNotifyDelegateIfChanged(false) } // Background App Refresh must be available in order for the app to be launched by the OS in response to a significant // location update. // https://developer.apple.com/library/ios/documentation/userexperience/conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html // // This is a setting that can be changed by the user unless the setting is restricted (eg. by parental controls). // Monitoring of changes to this setting are handled by `backgroundRefreshStatusDidChange:`. // func checkIsBackgroundAppRefreshAvailable() { let status = UIApplication.sharedApplication().backgroundRefreshStatus log("*** UIApplication.sharedApplication().backgroundRefreshStatus is \(status.rawValue)") isBackgroundAppRefreshAvailable = status == .Available } // Location Services must be authorized for this app by the user. // // If the user hasn't yet determined whether they want to authorize location services for the app assume that they // will. The first time location services are requested by the app the user will be prompted. If they reject the // request the authorization status will be changed and the UI will be updated accordingly. // // This is a setting that can be changed by the user unless the setting is restricted (eg. by parental controls). // Changes to this user setting are monitored by the app. // func checkIsLocationServicesAuthorized(_ status : CLAuthorizationStatus = CLLocationManager.authorizationStatus()) { CLLocationManager.authorizationStatus() log("*** CLLocationManager.authorizationStatus() is \(status.rawValue)") isLocationServicesAuthorized = status.rawValue == 3 // Swift problem: .AuthorizedAlways is missing } // Location service must be enabled on the device. // // This is a setting that can be changed by the user. Monitoring of changes to this setting is also handled by // `locationAuthorizationStatusDidChange:`. // func checkIsLocationServicesEnabled() { let status = CLLocationManager.locationServicesEnabled() log("*** CLLocationManager.locationServicesEnabled() is \(status)") isLocationServicesEnabled = status } func checkIfHasRequiredNotificationSettings() { if SINCE_IOS8 { let settings = UIApplication.sharedApplication().currentUserNotificationSettings() let hasAlert = (settings.types.rawValue & UIUserNotificationType.Alert.rawValue) != 0 let hasSound = (settings.types.rawValue & UIUserNotificationType.Sound.rawValue) != 0 hasRequiredNotificationSettings = hasAlert } else { hasRequiredNotificationSettings = true } } func updateAvailabilityAndNotifyDelegateIfChanged(notify: Bool) { let isAvailableUpdated = isBackgroundAppRefreshAvailable && isLocationServicesAuthorized && isLocationServicesEnabled && hasRequiredNotificationSettings let changed = isAvailableUpdated == isAvailable isAvailable = isAvailableUpdated if changed && notify { if isAvailable { delegate?.serviceDidBecomeAvailable() } else { delegate?.serviceDidBecomeAvailable() } } } func locationAuthorizationStatusDidChange(status: CLAuthorizationStatus) { log("*** Location authorization status changed: \(status.rawValue)") checkIsLocationServicesAuthorized(status) updateAvailabilityAndNotifyDelegateIfChanged(true) } func backgroundRefreshStatusDidChange(notification: NSNotification) { isBackgroundAppRefreshAvailable = UIApplication.sharedApplication().backgroundRefreshStatus == .Available log("*** Background App Refresh setting changed: \(isBackgroundAppRefreshAvailable)") updateAvailabilityAndNotifyDelegateIfChanged(true) } }
mit
0a6a586ec055cc196b97f3c33a0f4272
42.912698
146
0.710774
5.885106
false
false
false
false
Henryforce/KRActivityIndicatorView
KRActivityIndicatorView/KRActivityIndicatorAnimationBallClipRotateMultiple.swift
1
4245
// // KRActivityIndicatorAnimationBallClipRotateMultiple.swift // KRActivityIndicatorViewDemo // // The MIT License (MIT) // Originally written to work in iOS by Vinh Nguyen in 2016 // Adapted to OSX by Henry Serrano in 2017 // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Cocoa class KRActivityIndicatorAnimationBallClipRotateMultiple: KRActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: NSColor) { let bigCircleSize: CGFloat = size.width let smallCircleSize: CGFloat = size.width / 2 let longDuration: CFTimeInterval = 1 let timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) circleOf(shape: .ringTwoHalfHorizontal, duration: longDuration, timingFunction: timingFunction, layer: layer, size: bigCircleSize, color: color, reverse: false) circleOf(shape: .ringTwoHalfVertical, duration: longDuration, timingFunction: timingFunction, layer: layer, size: smallCircleSize, color: color, reverse: true) } func createAnimationIn(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, reverse: Bool) -> CAAnimation { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.6, 1] scaleAnimation.duration = duration // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.timingFunctions = [timingFunction, timingFunction] if (!reverse) { rotateAnimation.values = [0, Float.pi, 2 * Float.pi] } else { rotateAnimation.values = [0, -Float.pi, -2 * Float.pi] } rotateAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false return animation } func circleOf(shape: KRActivityIndicatorShape, duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGFloat, color: NSColor, reverse: Bool) { let circle = shape.layerWith(size: CGSize(width: size, height: size), color: color) let frame = CGRect(x: (layer.bounds.size.width - size) / 2, y: (layer.bounds.size.height - size) / 2, width: size, height: size) let animation = createAnimationIn(duration: duration, timingFunction: timingFunction, reverse: reverse) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
mit
f93cde40b30c24f97b92dccab734d767
42.762887
179
0.66808
5.221402
false
false
false
false
rosslebeau/AdventOfCode
Day2/AoCD2.playground/Contents.swift
1
1457
//: Playground - noun: a place where people can play import Foundation enum AdventError: Error { case InputPathFailed } func wrappingPaperNeeded(length: Int, width: Int, height: Int) -> Int { return areaOfBox(length: length, width: width, height: height) + areaOfSmallestSide(length: length, width: width, height: height) } func areaOfBox(length: Int, width: Int, height: Int) -> Int { return (2 * length * width) + (2 * width * height) + (2 * height * length) } func areaOfSmallestSide(length: Int, width: Int, height: Int) -> Int { return length * width * height / max(max(length, width), height) } func boxDimensions(fromString: String) -> (Int, Int, Int)? { let dimensions = fromString.characters.split(separator: "x").flatMap { Int(String($0)) } if let length = dimensions.first, let width = dimensions.dropFirst().first, let height = dimensions.dropFirst().dropFirst().first { return (length, width, height) } else { return nil } } // Start guard let filePath = Bundle.main.path(forResource: "input", ofType: nil) else { throw AdventError.InputPathFailed } let fileString: String = try NSString(contentsOfFile: filePath, encoding: String.Encoding.utf8.rawValue) as String let lines = fileString.characters.split(separator: "\n").map(String.init) let answer = lines.flatMap(boxDimensions).map { wrappingPaperNeeded(length: $0.0, width: $0.1, height: $0.2) }.reduce(0, +) print(answer)
mit
aa3f35b6a26335a3c005c1fcae11b45c
33.690476
135
0.695264
3.536408
false
false
false
false
yoha/Thoughtless
Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQKeyboardManager.swift
5
113377
// // IQKeyboardManager.swift // https://github.com/hackiftekhar/IQKeyboardManager // Copyright (c) 2013-16 Iftekhar Qurashi. // // 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 CoreGraphics import UIKit import QuartzCore ///--------------------- /// MARK: IQToolbar tags ///--------------------- /** Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html */ open class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate { /** Default tag for toolbar with Done button -1002. */ fileprivate static let kIQDoneButtonToolbarTag = -1002 /** Default tag for toolbar with Previous/Next buttons -1005. */ fileprivate static let kIQPreviousNextButtonToolbarTag = -1005 ///--------------------------- /// MARK: UIKeyboard handling ///--------------------------- /** Registered classes list with library. */ fileprivate var registeredClasses = [UIView.Type]() /** Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method). */ open var enable = false { didSet { //If not enable, enable it. if enable == true && oldValue == false { //If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard. if _kbShowNotification != nil { keyboardWillShow(_kbShowNotification) } showLog("enabled") } else if enable == false && oldValue == true { //If not disable, desable it. keyboardWillHide(nil) showLog("disabled") } } } fileprivate func privateIsEnabled()-> Bool { var isEnabled = enable if let textFieldViewController = _textFieldView?.viewController() { if isEnabled == false { //If viewController is kind of enable viewController class, then assuming it's enabled. for enabledClass in enabledDistanceHandlingClasses { if textFieldViewController.isKind(of: enabledClass) { isEnabled = true break } } } if isEnabled == true { //If viewController is kind of disabled viewController class, then assuming it's disabled. for disabledClass in disabledDistanceHandlingClasses { if textFieldViewController.isKind(of: disabledClass) { isEnabled = false break } } //Special Controllers if isEnabled == true { let classNameString = NSStringFromClass(type(of:textFieldViewController.self)) //_UIAlertControllerTextFieldViewController if (classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController")) { isEnabled = false } } } } return isEnabled } /** To set keyboard distance from textField. can't be less than zero. Default is 10.0. */ open var keyboardDistanceFromTextField: CGFloat { set { _privateKeyboardDistanceFromTextField = max(0, newValue) showLog("keyboardDistanceFromTextField: \(_privateKeyboardDistanceFromTextField)") } get { return _privateKeyboardDistanceFromTextField } } /** Boolean to know if keyboard is showing. */ open var keyboardShowing: Bool { get { return _privateIsKeyboardShowing } } /** moved distance to the top used to maintain distance between keyboard and textField. Most of the time this will be a positive value. */ open var movedDistance: CGFloat { get { return _privateMovedDistance } } /** Prevent keyboard manager to slide up the rootView to more than keyboard height. Default is YES. */ open var preventShowingBottomBlankSpace = true /** Returns the default singleton instance. */ open class func sharedManager() -> IQKeyboardManager { struct Static { //Singleton instance. Initializing keyboard manger. static let kbManager = IQKeyboardManager() } /** @return Returns the default singleton instance. */ return Static.kbManager } ///------------------------- /// MARK: IQToolbar handling ///------------------------- /** Automatic add the IQToolbar functionality. Default is YES. */ open var enableAutoToolbar = true { didSet { privateIsEnableAutoToolbar() ?addToolbarIfRequired():removeToolbarIfRequired() let enableToolbar = enableAutoToolbar ? "Yes" : "NO" showLog("enableAutoToolbar: \(enableToolbar)") } } fileprivate func privateIsEnableAutoToolbar() -> Bool { var enableToolbar = enableAutoToolbar if let textFieldViewController = _textFieldView?.viewController() { if enableToolbar == false { //If found any toolbar enabled classes then return. for enabledClass in enabledToolbarClasses { if textFieldViewController.isKind(of: enabledClass) { enableToolbar = true break } } } if enableToolbar == true { //If found any toolbar disabled classes then return. for disabledClass in disabledToolbarClasses { if textFieldViewController.isKind(of: disabledClass) { enableToolbar = false break } } //Special Controllers if enableToolbar == true { let classNameString = NSStringFromClass(type(of:textFieldViewController.self)) //_UIAlertControllerTextFieldViewController if (classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController")) { enableToolbar = false } } } } return enableToolbar } /** /** IQAutoToolbarBySubviews: Creates Toolbar according to subview's hirarchy of Textfield's in view. IQAutoToolbarByTag: Creates Toolbar according to tag property of TextField's. IQAutoToolbarByPosition: Creates Toolbar according to the y,x position of textField in it's superview coordinate. Default is IQAutoToolbarBySubviews. */ AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews. */ open var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.bySubviews /** If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO. */ open var shouldToolbarUsesTextFieldTintColor = false /** This is used for toolbar.tintColor when textfield.keyboardAppearance is UIKeyboardAppearanceDefault. If shouldToolbarUsesTextFieldTintColor is YES then this property is ignored. Default is nil and uses black color. */ open var toolbarTintColor : UIColor? /** IQPreviousNextDisplayModeDefault: Show NextPrevious when there are more than 1 textField otherwise hide. IQPreviousNextDisplayModeAlwaysHide: Do not show NextPrevious buttons in any case. IQPreviousNextDisplayModeAlwaysShow: Always show nextPrevious buttons, if there are more than 1 textField then both buttons will be visible but will be shown as disabled. */ open var previousNextDisplayMode = IQPreviousNextDisplayMode.Default /** Toolbar done button icon, If nothing is provided then check toolbarDoneBarButtonItemText to draw done button. */ open var toolbarDoneBarButtonItemImage : UIImage? /** Toolbar done button text, If nothing is provided then system default 'UIBarButtonSystemItemDone' will be used. */ open var toolbarDoneBarButtonItemText : String? /** If YES, then it add the textField's placeholder text on IQToolbar. Default is YES. */ open var shouldShowTextFieldPlaceholder = true /** Placeholder Font. Default is nil. */ open var placeholderFont: UIFont? ///-------------------------- /// MARK: UITextView handling ///-------------------------- /** used to adjust contentInset of UITextView. */ fileprivate var startingTextViewContentInsets = UIEdgeInsets.zero /** used to adjust scrollIndicatorInsets of UITextView. */ fileprivate var startingTextViewScrollIndicatorInsets = UIEdgeInsets.zero /** used with textView to detect a textFieldView contentInset is changed or not. (Bug ID: #92)*/ fileprivate var isTextViewContentInsetChanged = false ///--------------------------------------- /// MARK: UIKeyboard appearance overriding ///--------------------------------------- /** Override the keyboardAppearance for all textField/textView. Default is NO. */ open var overrideKeyboardAppearance = false /** If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property. */ open var keyboardAppearance = UIKeyboardAppearance.default ///----------------------------------------------------------- /// MARK: UITextField/UITextView Next/Previous/Resign handling ///----------------------------------------------------------- /** Resigns Keyboard on touching outside of UITextField/View. Default is NO. */ open var shouldResignOnTouchOutside = false { didSet { _tapGesture.isEnabled = privateShouldResignOnTouchOutside() let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO" showLog("shouldResignOnTouchOutside: \(shouldResign)") } } fileprivate func privateShouldResignOnTouchOutside() -> Bool { var shouldResign = shouldResignOnTouchOutside if let textFieldViewController = _textFieldView?.viewController() { if shouldResign == false { //If viewController is kind of enable viewController class, then assuming shouldResignOnTouchOutside is enabled. for enabledClass in enabledTouchResignedClasses { if textFieldViewController.isKind(of: enabledClass) { shouldResign = true break } } } if shouldResign == true { //If viewController is kind of disable viewController class, then assuming shouldResignOnTouchOutside is disable. for disabledClass in disabledTouchResignedClasses { if textFieldViewController.isKind(of: disabledClass) { shouldResign = false break } } //Special Controllers if shouldResign == true { let classNameString = NSStringFromClass(type(of:textFieldViewController.self)) //_UIAlertControllerTextFieldViewController if (classNameString.contains("UIAlertController") && classNameString.hasSuffix("TextFieldViewController")) { shouldResign = false } } } } return shouldResign } /** Resigns currently first responder field. */ @discardableResult open func resignFirstResponder()-> Bool { if let textFieldRetain = _textFieldView { //Resigning first responder let isResignFirstResponder = textFieldRetain.resignFirstResponder() // If it refuses then becoming it as first responder again. (Bug ID: #96) if isResignFirstResponder == false { //If it refuses to resign then becoming it first responder again for getting notifications callback. textFieldRetain.becomeFirstResponder() showLog("Refuses to resign first responder: \(String(describing: _textFieldView?._IQDescription()))") } return isResignFirstResponder } return false } /** Returns YES if can navigate to previous responder textField/textView, otherwise NO. */ open var canGoPrevious: Bool { //Getting all responder view's. if let textFields = responderViews() { if let textFieldRetain = _textFieldView { //Getting index of current textField. if let index = textFields.index(of: textFieldRetain) { //If it is not first textField. then it's previous object canBecomeFirstResponder. if index > 0 { return true } } } } return false } /** Returns YES if can navigate to next responder textField/textView, otherwise NO. */ open var canGoNext: Bool { //Getting all responder view's. if let textFields = responderViews() { if let textFieldRetain = _textFieldView { //Getting index of current textField. if let index = textFields.index(of: textFieldRetain) { //If it is not first textField. then it's previous object canBecomeFirstResponder. if index < textFields.count-1 { return true } } } } return false } /** Navigate to previous responder textField/textView. */ @discardableResult open func goPrevious()-> Bool { //Getting all responder view's. if let textFieldRetain = _textFieldView { if let textFields = responderViews() { //Getting index of current textField. if let index = textFields.index(of: textFieldRetain) { //If it is not first textField. then it's previous object becomeFirstResponder. if index > 0 { let nextTextField = textFields[index-1] let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder() // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96) if isAcceptAsFirstResponder == false { //If next field refuses to become first responder then restoring old textField as first responder. textFieldRetain.becomeFirstResponder() showLog("Refuses to become first responder: \(nextTextField._IQDescription())") } return isAcceptAsFirstResponder } } } } return false } /** Navigate to next responder textField/textView. */ @discardableResult open func goNext()-> Bool { //Getting all responder view's. if let textFieldRetain = _textFieldView { if let textFields = responderViews() { //Getting index of current textField. if let index = textFields.index(of: textFieldRetain) { //If it is not last textField. then it's next object becomeFirstResponder. if index < textFields.count-1 { let nextTextField = textFields[index+1] let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder() // If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96) if isAcceptAsFirstResponder == false { //If next field refuses to become first responder then restoring old textField as first responder. textFieldRetain.becomeFirstResponder() showLog("Refuses to become first responder: \(nextTextField._IQDescription())") } return isAcceptAsFirstResponder } } } } return false } /** previousAction. */ internal func previousAction (_ barButton : UIBarButtonItem?) { //If user wants to play input Click sound. if shouldPlayInputClicks == true { //Play Input Click Sound. UIDevice.current.playInputClick() } if canGoPrevious == true { if let textFieldRetain = _textFieldView { let isAcceptAsFirstResponder = goPrevious() if isAcceptAsFirstResponder && textFieldRetain.previousInvocation.target != nil && textFieldRetain.previousInvocation.action != nil { UIApplication.shared.sendAction(textFieldRetain.previousInvocation.action!, to: textFieldRetain.previousInvocation.target, from: textFieldRetain, for: UIEvent()) } } } } /** nextAction. */ internal func nextAction (_ barButton : UIBarButtonItem?) { //If user wants to play input Click sound. if shouldPlayInputClicks == true { //Play Input Click Sound. UIDevice.current.playInputClick() } if canGoNext == true { if let textFieldRetain = _textFieldView { let isAcceptAsFirstResponder = goNext() if isAcceptAsFirstResponder && textFieldRetain.nextInvocation.target != nil && textFieldRetain.nextInvocation.action != nil { UIApplication.shared.sendAction(textFieldRetain.nextInvocation.action!, to: textFieldRetain.nextInvocation.target, from: textFieldRetain, for: UIEvent()) } } } } /** doneAction. Resigning current textField. */ internal func doneAction (_ barButton : IQBarButtonItem?) { //If user wants to play input Click sound. if shouldPlayInputClicks == true { //Play Input Click Sound. UIDevice.current.playInputClick() } if let textFieldRetain = _textFieldView { //Resign textFieldView. let isResignedFirstResponder = resignFirstResponder() if isResignedFirstResponder && textFieldRetain.doneInvocation.target != nil && textFieldRetain.doneInvocation.action != nil{ UIApplication.shared.sendAction(textFieldRetain.doneInvocation.action!, to: textFieldRetain.doneInvocation.target, from: textFieldRetain, for: UIEvent()) } } } /** Resigning on tap gesture. (Enhancement ID: #14)*/ internal func tapRecognized(_ gesture: UITapGestureRecognizer) { if gesture.state == UIGestureRecognizerState.ended { //Resigning currently responder textField. _ = resignFirstResponder() } } /** Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */ open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return false } /** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */ open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { // Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145) for ignoreClass in touchResignedGestureIgnoreClasses { if touch.view?.isKind(of: ignoreClass) == true { return false } } return true } ///----------------------- /// MARK: UISound handling ///----------------------- /** If YES, then it plays inputClick sound on next/previous/done click. */ open var shouldPlayInputClicks = true ///--------------------------- /// MARK: UIAnimation handling ///--------------------------- /** If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view. */ open var layoutIfNeededOnUpdate = false ///----------------------------------------------- /// @name InteractivePopGestureRecognizer handling ///----------------------------------------------- /** If YES, then always consider UINavigationController.view begin point as {0,0}, this is a workaround to fix a bug #464 because there are no notification mechanism exist when UINavigationController.view.frame gets changed internally. */ open var shouldFixInteractivePopGestureRecognizer = true ///------------------------------------ /// MARK: Class Level disabling methods ///------------------------------------ /** Disable distance handling within the scope of disabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController. */ open var disabledDistanceHandlingClasses = [UIViewController.Type]() /** Enable distance handling within the scope of enabled distance handling viewControllers classes. Within this scope, 'enabled' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledDistanceHandlingClasses list, then enabledDistanceHandlingClasses will be ignored. */ open var enabledDistanceHandlingClasses = [UIViewController.Type]() /** Disable automatic toolbar creation within the scope of disabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController. */ open var disabledToolbarClasses = [UIViewController.Type]() /** Enable automatic toolbar creation within the scope of enabled toolbar viewControllers classes. Within this scope, 'enableAutoToolbar' property is ignored. Class should be kind of UIViewController. If same Class is added in disabledToolbarClasses list, then enabledToolbarClasses will be ignore. */ open var enabledToolbarClasses = [UIViewController.Type]() /** Allowed subclasses of UIView to add all inner textField, this will allow to navigate between textField contains in different superview. Class should be kind of UIView. */ open var toolbarPreviousNextAllowedClasses = [UIView.Type]() /** Disabled classes to ignore 'shouldResignOnTouchOutside' property, Class should be kind of UIViewController. */ open var disabledTouchResignedClasses = [UIViewController.Type]() /** Enabled classes to forcefully enable 'shouldResignOnTouchOutsite' property. Class should be kind of UIViewController. If same Class is added in disabledTouchResignedClasses list, then enabledTouchResignedClasses will be ignored. */ open var enabledTouchResignedClasses = [UIViewController.Type]() /** if shouldResignOnTouchOutside is enabled then you can customise the behaviour to not recognise gesture touches on some specific view subclasses. Class should be kind of UIView. Default is [UIControl, UINavigationBar] */ open var touchResignedGestureIgnoreClasses = [UIView.Type]() ///------------------------------------------- /// MARK: Third Party Library support /// Add TextField/TextView Notifications customised NSNotifications. For example while using YYTextView https://github.com/ibireme/YYText ///------------------------------------------- /** Add/Remove customised Notification for third party customised TextField/TextView. Please be aware that the NSNotification object must be idential to UITextField/UITextView NSNotification objects and customised TextField/TextView support must be idential to UITextField/UITextView. @param didBeginEditingNotificationName This should be identical to UITextViewTextDidBeginEditingNotification @param didEndEditingNotificationName This should be identical to UITextViewTextDidEndEditingNotification */ open func registerTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName : String, didEndEditingNotificationName : String) { registeredClasses.append(aClass) NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidBeginEditing(_:)), name: NSNotification.Name(rawValue: didBeginEditingNotificationName), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.textFieldViewDidEndEditing(_:)), name: NSNotification.Name(rawValue: didEndEditingNotificationName), object: nil) } open func unregisterTextFieldViewClass(_ aClass: UIView.Type, didBeginEditingNotificationName : String, didEndEditingNotificationName : String) { if let index = registeredClasses.index(where: { element in return element == aClass.self }) { registeredClasses.remove(at: index) } NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: didBeginEditingNotificationName), object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: didEndEditingNotificationName), object: nil) } /**************************************************************************************/ ///------------------------ /// MARK: Private variables ///------------------------ /*******************************************/ /** To save UITextField/UITextView object voa textField/textView notifications. */ fileprivate weak var _textFieldView: UIView? /** To save rootViewController.view.frame. */ fileprivate var _topViewBeginRect = CGRect.zero /** To save rootViewController */ fileprivate weak var _rootViewController: UIViewController? /** To save topBottomLayoutConstraint original constant */ fileprivate var _layoutGuideConstraintInitialConstant: CGFloat = 0 /** To save topBottomLayoutConstraint original constraint reference */ fileprivate weak var _layoutGuideConstraint: NSLayoutConstraint? /*******************************************/ /** Variable to save lastScrollView that was scrolled. */ fileprivate weak var _lastScrollView: UIScrollView? /** LastScrollView's initial contentOffset. */ fileprivate var _startingContentOffset = CGPoint.zero /** LastScrollView's initial scrollIndicatorInsets. */ fileprivate var _startingScrollIndicatorInsets = UIEdgeInsets.zero /** LastScrollView's initial contentInsets. */ fileprivate var _startingContentInsets = UIEdgeInsets.zero /*******************************************/ /** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */ fileprivate var _kbShowNotification: Notification? /** To save keyboard size. */ fileprivate var _kbSize = CGSize.zero /** To save Status Bar size. */ fileprivate var _statusBarFrame = CGRect.zero /** To save keyboard animation duration. */ fileprivate var _animationDuration = 0.25 /** To mimic the keyboard animation */ fileprivate var _animationCurve = UIViewAnimationOptions.curveEaseOut /*******************************************/ /** TapGesture to resign keyboard on view's touch. */ fileprivate var _tapGesture: UITapGestureRecognizer! /*******************************************/ /** Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */ fileprivate var _privateIsKeyboardShowing = false fileprivate var _privateMovedDistance : CGFloat = 0.0 /** To use with keyboardDistanceFromTextField. */ fileprivate var _privateKeyboardDistanceFromTextField: CGFloat = 10.0 /**************************************************************************************/ ///-------------------------------------- /// MARK: Initialization/Deinitialization ///-------------------------------------- /* Singleton Object Initialization. */ override init() { super.init() self.registerAllNotifications() //Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14) _tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapRecognized(_:))) _tapGesture.cancelsTouchesInView = false _tapGesture.delegate = self _tapGesture.isEnabled = shouldResignOnTouchOutside //Loading IQToolbar, IQTitleBarButtonItem, IQBarButtonItem to fix first time keyboard appearance delay (Bug ID: #550) let textField = UITextField() textField.addDoneOnKeyboardWithTarget(nil, action: #selector(self.doneAction(_:))) textField.addPreviousNextDoneOnKeyboardWithTarget(nil, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:))) disabledDistanceHandlingClasses.append(UITableViewController.self) disabledDistanceHandlingClasses.append(UIAlertController.self) disabledToolbarClasses.append(UIAlertController.self) disabledTouchResignedClasses.append(UIAlertController.self) toolbarPreviousNextAllowedClasses.append(UITableView.self) toolbarPreviousNextAllowedClasses.append(UICollectionView.self) toolbarPreviousNextAllowedClasses.append(IQPreviousNextView.self) touchResignedGestureIgnoreClasses.append(UIControl.self) touchResignedGestureIgnoreClasses.append(UINavigationBar.self) } /** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */ /** It doesn't work from Swift 1.2 */ // override public class func load() { // super.load() // // //Enabling IQKeyboardManager. // IQKeyboardManager.sharedManager().enable = true // } deinit { // Disable the keyboard manager. enable = false //Removing notification observers on dealloc. NotificationCenter.default.removeObserver(self) } /** Getting keyWindow. */ fileprivate func keyWindow() -> UIWindow? { if let keyWindow = _textFieldView?.window { return keyWindow } else { struct Static { /** @abstract Save keyWindow object for reuse. @discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */ static var keyWindow : UIWindow? } /* (Bug ID: #23, #25, #73) */ let originalKeyWindow = UIApplication.shared.keyWindow //If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow. if originalKeyWindow != nil && (Static.keyWindow == nil || Static.keyWindow != originalKeyWindow) { Static.keyWindow = originalKeyWindow } //Return KeyWindow return Static.keyWindow } } ///----------------------- /// MARK: Helper Functions ///----------------------- /* Helper function to manipulate RootViewController's frame with animation. */ fileprivate func setRootViewFrame(_ frame: CGRect) { // Getting topMost ViewController. var controller = _textFieldView?.topMostController() if controller == nil { controller = keyWindow()?.topMostController() } if let unwrappedController = controller { var newFrame = frame //frame size needs to be adjusted on iOS8 due to orientation structure changes. newFrame.size = unwrappedController.view.frame.size //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations. UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in // Setting it's new frame unwrappedController.view.frame = newFrame self.showLog("Set \(String(describing: controller?._IQDescription())) frame to : \(newFrame)") //Animating content if needed (Bug ID: #204) if self.layoutIfNeededOnUpdate == true { //Animating content (Bug ID: #160) unwrappedController.view.setNeedsLayout() unwrappedController.view.layoutIfNeeded() } }) { (animated:Bool) -> Void in} } else { // If can't get rootViewController then printing warning to user. showLog("You must set UIWindow.rootViewController in your AppDelegate to work with IQKeyboardManager") } } /* Adjusting RootViewController's frame according to interface orientation. */ fileprivate func adjustFrame() { // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11) if _textFieldView == nil { return } let textFieldView = _textFieldView! let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") // Getting KeyWindow object. let optionalWindow = keyWindow() // Getting RootViewController. (Bug ID: #1, #4) var optionalRootController = _textFieldView?.topMostController() if optionalRootController == nil { optionalRootController = keyWindow()?.topMostController() } // Converting Rectangle according to window bounds. let optionalTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: optionalWindow) if optionalRootController == nil || optionalWindow == nil || optionalTextFieldViewRect == nil { return } let rootController = optionalRootController! let window = optionalWindow! let textFieldViewRect = optionalTextFieldViewRect! // Getting RootViewRect. var rootViewRect = rootController.view.frame //Getting statusBarFrame //Maintain keyboardDistanceFromTextField var specialKeyboardDistanceFromTextField = textFieldView.keyboardDistanceFromTextField if textFieldView.isSearchBarTextField() { if let searchBar = textFieldView.superviewOfClassType(UISearchBar.self) { specialKeyboardDistanceFromTextField = searchBar.keyboardDistanceFromTextField } } let newKeyboardDistanceFromTextField = (specialKeyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance) ? keyboardDistanceFromTextField : specialKeyboardDistanceFromTextField var kbSize = _kbSize kbSize.height += newKeyboardDistanceFromTextField let statusBarFrame = UIApplication.shared.statusBarFrame // (Bug ID: #250) var layoutGuidePosition = IQLayoutGuidePosition.none if let viewController = textFieldView.viewController() { if let constraint = _layoutGuideConstraint { var layoutGuide : UILayoutSupport? if let itemLayoutGuide = constraint.firstItem as? UILayoutSupport { layoutGuide = itemLayoutGuide } else if let itemLayoutGuide = constraint.secondItem as? UILayoutSupport { layoutGuide = itemLayoutGuide } if let itemLayoutGuide : UILayoutSupport = layoutGuide { if (itemLayoutGuide === viewController.topLayoutGuide) //If topLayoutGuide constraint { layoutGuidePosition = .top } else if (itemLayoutGuide === viewController.bottomLayoutGuide) //If bottomLayoutGuice constraint { layoutGuidePosition = .bottom } } } } let topLayoutGuide : CGFloat = statusBarFrame.height var move : CGFloat = 0.0 // Move positive = textField is hidden. // Move negative = textField is showing. // Checking if there is bottomLayoutGuide attached (Bug ID: #250) if layoutGuidePosition == .bottom { // Calculating move position. move = textFieldViewRect.maxY-(window.frame.height-kbSize.height) } else { // Calculating move position. Common for both normal and special cases. move = min(textFieldViewRect.minY-(topLayoutGuide+5), textFieldViewRect.maxY-(window.frame.height-kbSize.height)) } showLog("Need to move: \(move)") var superScrollView : UIScrollView? = nil var superView = textFieldView.superviewOfClassType(UIScrollView.self) as? UIScrollView //Getting UIScrollView whose scrolling is enabled. // (Bug ID: #285) while let view = superView { if (view.isScrollEnabled) { superScrollView = view break } else { // Getting it's superScrollView. // (Enhancement ID: #21, #24) superView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView } } //If there was a lastScrollView. // (Bug ID: #34) if let lastScrollView = _lastScrollView { //If we can't find current superScrollView, then setting lastScrollView to it's original form. if superScrollView == nil { showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)") UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = self._startingContentInsets lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets }) { (animated:Bool) -> Void in } if lastScrollView.shouldRestoreScrollViewContentOffset == true { lastScrollView.setContentOffset(_startingContentOffset, animated: true) } _startingContentInsets = UIEdgeInsets.zero _startingScrollIndicatorInsets = UIEdgeInsets.zero _startingContentOffset = CGPoint.zero _lastScrollView = nil } else if superScrollView != lastScrollView { //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView. showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)") UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = self._startingContentInsets lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets }) { (animated:Bool) -> Void in } if lastScrollView.shouldRestoreScrollViewContentOffset == true { lastScrollView.setContentOffset(_startingContentOffset, animated: true) } _lastScrollView = superScrollView _startingContentInsets = superScrollView!.contentInset _startingScrollIndicatorInsets = superScrollView!.scrollIndicatorInsets _startingContentOffset = superScrollView!.contentOffset showLog("Saving New \(lastScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)") } //Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead } else if let unwrappedSuperScrollView = superScrollView { //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView. _lastScrollView = unwrappedSuperScrollView _startingContentInsets = unwrappedSuperScrollView.contentInset _startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets _startingContentOffset = unwrappedSuperScrollView.contentOffset showLog("Saving \(unwrappedSuperScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)") } // Special case for ScrollView. // If we found lastScrollView then setting it's contentOffset to show textField. if let lastScrollView = _lastScrollView { //Saving var lastView = textFieldView var superScrollView = _lastScrollView while let scrollView = superScrollView { //Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object. if move > 0 ? (move > (-scrollView.contentOffset.y - scrollView.contentInset.top)) : scrollView.contentOffset.y>0 { var tempScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView var nextScrollView : UIScrollView? = nil while let view = tempScrollView { if (view.isScrollEnabled) { nextScrollView = view break } else { tempScrollView = view.superviewOfClassType(UIScrollView.self) as? UIScrollView } } //Getting lastViewRect. if let lastViewRect = lastView.superview?.convert(lastView.frame, to: scrollView) { //Calculating the expected Y offset from move and scrollView's contentOffset. var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y,-move) //Rearranging the expected Y offset according to the view. shouldOffsetY = min(shouldOffsetY, lastViewRect.origin.y /*-5*/) //-5 is for good UI.//Commenting -5 (Bug ID: #69) //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type //nextScrollView == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierrchy.) //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type //shouldOffsetY >= 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92) if textFieldView is UITextView == true && nextScrollView == nil && shouldOffsetY >= 0 { var maintainTopLayout : CGFloat = 0 if let navigationBarFrame = textFieldView.viewController()?.navigationController?.navigationBar.frame { maintainTopLayout = navigationBarFrame.maxY } maintainTopLayout += 10.0 //For good UI // Converting Rectangle according to window bounds. if let currentTextFieldViewRect = textFieldView.superview?.convert(textFieldView.frame, to: window) { //Calculating expected fix distance which needs to be managed from navigation bar let expectedFixDistance = currentTextFieldViewRect.minY - maintainTopLayout //Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) shouldOffsetY = min(shouldOffsetY, scrollView.contentOffset.y + expectedFixDistance) //Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic. move = 0 } else { //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY. move -= (shouldOffsetY-scrollView.contentOffset.y) } } else { //Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY. move -= (shouldOffsetY-scrollView.contentOffset.y) } //Getting problem while using `setContentOffset:animated:`, So I used animation API. UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in self.showLog("Adjusting \(scrollView.contentOffset.y-shouldOffsetY) to \(scrollView._IQDescription()) ContentOffset") self.showLog("Remaining Move: \(move)") scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: shouldOffsetY) }) { (animated:Bool) -> Void in } } // Getting next lastView & superScrollView. lastView = scrollView superScrollView = nextScrollView } else { break } } //Updating contentInset if let lastScrollViewRect = lastScrollView.superview?.convert(lastScrollView.frame, to: window) { let bottom : CGFloat = kbSize.height-newKeyboardDistanceFromTextField-(window.frame.height-lastScrollViewRect.maxY) // Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view. var movedInsets = lastScrollView.contentInset movedInsets.bottom = max(_startingContentInsets.bottom, bottom) showLog("\(lastScrollView._IQDescription()) old ContentInset : \(lastScrollView.contentInset)") //Getting problem while using `setContentOffset:animated:`, So I used animation API. UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = movedInsets var newInset = lastScrollView.scrollIndicatorInsets newInset.bottom = movedInsets.bottom lastScrollView.scrollIndicatorInsets = newInset }) { (animated:Bool) -> Void in } showLog("\(lastScrollView._IQDescription()) new ContentInset : \(lastScrollView.contentInset)") } } //Going ahead. No else if. if layoutGuidePosition == .top { if let constraint = _layoutGuideConstraint { let constant = min(_layoutGuideConstraintInitialConstant, constraint.constant-move) UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in constraint.constant = constant self._rootViewController?.view.setNeedsLayout() self._rootViewController?.view.layoutIfNeeded() }, completion: { (finished) -> Void in }) } } else if layoutGuidePosition == .bottom { if let constraint = _layoutGuideConstraint { let constant = max(_layoutGuideConstraintInitialConstant, constraint.constant+move) UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in constraint.constant = constant self._rootViewController?.view.setNeedsLayout() self._rootViewController?.view.layoutIfNeeded() }, completion: { (finished) -> Void in }) } } else { //Special case for UITextView(Readjusting textView.contentInset when textView hight is too big to fit on screen) //_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView. //[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type if let textView = textFieldView as? UITextView { let textViewHeight = min(textView.frame.height, (window.frame.height-kbSize.height-(topLayoutGuide))) if (textView.frame.size.height-textView.contentInset.bottom>textViewHeight) { UIView.animate(withDuration: _animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.beginFromCurrentState)), animations: { () -> Void in self.showLog("\(textFieldView._IQDescription()) Old UITextView.contentInset : \(textView.contentInset)") //_isTextViewContentInsetChanged, If frame is not change by library in past, then saving user textView properties (Bug ID: #92) if (self.isTextViewContentInsetChanged == false) { self.startingTextViewContentInsets = textView.contentInset self.startingTextViewScrollIndicatorInsets = textView.scrollIndicatorInsets } var newContentInset = textView.contentInset newContentInset.bottom = textView.frame.size.height-textViewHeight textView.contentInset = newContentInset textView.scrollIndicatorInsets = newContentInset self.isTextViewContentInsetChanged = true self.showLog("\(textFieldView._IQDescription()) Old UITextView.contentInset : \(textView.contentInset)") }, completion: { (finished) -> Void in }) } } // Special case for iPad modalPresentationStyle. if rootController.modalPresentationStyle == UIModalPresentationStyle.formSheet || rootController.modalPresentationStyle == UIModalPresentationStyle.pageSheet { showLog("Found Special case for Model Presentation Style: \(rootController.modalPresentationStyle)") // +Positive or zero. if move >= 0 { // We should only manipulate y. rootViewRect.origin.y -= move // From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93) if preventShowingBottomBlankSpace == true { let minimumY: CGFloat = (window.frame.height-rootViewRect.size.height-topLayoutGuide)/2-(kbSize.height-newKeyboardDistanceFromTextField) rootViewRect.origin.y = max(rootViewRect.minY, minimumY) } showLog("Moving Upward") // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) _privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y) } else { // -Negative // Calculating disturbed distance. Pull Request #3 let disturbDistance = rootViewRect.minY-_topViewBeginRect.minY // disturbDistance Negative = frame disturbed. // disturbDistance positive = frame not disturbed. if disturbDistance < 0 { // We should only manipulate y. rootViewRect.origin.y -= max(move, disturbDistance) showLog("Moving Downward") // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) _privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y) } } } else { //If presentation style is neither UIModalPresentationFormSheet nor UIModalPresentationPageSheet then going ahead.(General case) // +Positive or zero. if move >= 0 { rootViewRect.origin.y -= move // From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93) if preventShowingBottomBlankSpace == true { rootViewRect.origin.y = max(rootViewRect.origin.y, min(0, -kbSize.height+newKeyboardDistanceFromTextField)) } showLog("Moving Upward") // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) _privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y) } else { // -Negative let disturbDistance : CGFloat = rootViewRect.minY-_topViewBeginRect.minY // disturbDistance Negative = frame disturbed. // disturbDistance positive = frame not disturbed. if disturbDistance < 0 { rootViewRect.origin.y -= max(move, disturbDistance) showLog("Moving Downward") // Setting adjusted rootViewRect // Setting adjusted rootViewRect setRootViewFrame(rootViewRect) _privateMovedDistance = (_topViewBeginRect.origin.y-rootViewRect.origin.y) } } } } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } ///--------------------- /// MARK: Public Methods ///--------------------- /* Refreshes textField/textView position if any external changes is explicitly made by user. */ open func reloadLayoutIfNeeded() -> Void { if privateIsEnabled() == true { if _textFieldView != nil && _privateIsKeyboardShowing == true && _topViewBeginRect.equalTo(CGRect.zero) == false && _textFieldView?.isAlertViewTextField() == false { adjustFrame() } } } ///------------------------------- /// MARK: UIKeyboard Notifications ///------------------------------- /* UIKeyboardWillShowNotification. */ internal func keyboardWillShow(_ notification : Notification?) -> Void { _kbShowNotification = notification // Boolean to know keyboard is showing/hiding _privateIsKeyboardShowing = true let oldKBSize = _kbSize if let info = (notification as NSNotification?)?.userInfo { // Getting keyboard animation. if let curve = (info[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.uintValue { _animationCurve = UIViewAnimationOptions(rawValue: curve) } else { _animationCurve = UIViewAnimationOptions.curveEaseOut } // Getting keyboard animation duration if let duration = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue { //Saving animation duration if duration != 0.0 { _animationDuration = duration } } else { _animationDuration = 0.25 } // Getting UIKeyboardSize. if let kbFrame = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { let screenSize = UIScreen.main.bounds //Calculating actual keyboard displayed size, keyboard frame may be different when hardware keyboard is attached (Bug ID: #469) (Bug ID: #381) let intersectRect = kbFrame.intersection(screenSize) if intersectRect.isNull { _kbSize = CGSize(width: screenSize.size.width, height: 0) } else { _kbSize = intersectRect.size } showLog("UIKeyboard Size : \(_kbSize)") } } if privateIsEnabled() == false { return } let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") // (Bug ID: #5) if _textFieldView != nil && _topViewBeginRect.equalTo(CGRect.zero) == true { // keyboard is not showing(At the beginning only). We should save rootViewRect. if let constraint = _textFieldView?.viewController()?.IQLayoutGuideConstraint { _layoutGuideConstraint = constraint _layoutGuideConstraintInitialConstant = constraint.constant } // keyboard is not showing(At the beginning only). We should save rootViewRect. _rootViewController = _textFieldView?.topMostController() if _rootViewController == nil { _rootViewController = keyWindow()?.topMostController() } if let unwrappedRootController = _rootViewController { _topViewBeginRect = unwrappedRootController.view.frame if shouldFixInteractivePopGestureRecognizer == true && unwrappedRootController is UINavigationController && unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.formSheet && unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.pageSheet { if let window = keyWindow() { _topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-unwrappedRootController.view.frame.size.height) } else { _topViewBeginRect.origin = CGPoint.zero } } showLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)") } else { _topViewBeginRect = CGRect.zero } } // Getting topMost ViewController. var topMostController = _textFieldView?.topMostController() if topMostController == nil { topMostController = keyWindow()?.topMostController() } //If last restored keyboard size is different(any orientation accure), then refresh. otherwise not. if _kbSize.equalTo(oldKBSize) == false { //If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70). if _privateIsKeyboardShowing == true && _textFieldView != nil && _textFieldView?.isAlertViewTextField() == false { // keyboard is already showing. adjust frame. adjustFrame() } } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } /* UIKeyboardDidShowNotification. */ internal func keyboardDidShow(_ notification : Notification?) -> Void { if privateIsEnabled() == false { return } let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") // Getting topMost ViewController. var topMostController = _textFieldView?.topMostController() if topMostController == nil { topMostController = keyWindow()?.topMostController() } if _textFieldView != nil && (topMostController?.modalPresentationStyle == UIModalPresentationStyle.formSheet || topMostController?.modalPresentationStyle == UIModalPresentationStyle.pageSheet) && _textFieldView?.isAlertViewTextField() == false { //In case of form sheet or page sheet, we'll add adjustFrame call in main queue to perform it when UI thread will do all framing updation so adjustFrame will be executed after all internal operations. OperationQueue.main.addOperation { self.adjustFrame() } } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } /* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */ internal func keyboardWillHide(_ notification : Notification?) -> Void { //If it's not a fake notification generated by [self setEnable:NO]. if notification != nil { _kbShowNotification = nil } // Boolean to know keyboard is showing/hiding _privateIsKeyboardShowing = false let info : [AnyHashable: Any]? = (notification as NSNotification?)?.userInfo // Getting keyboard animation duration if let duration = (info?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue { if duration != 0 { // Setitng keyboard animation duration _animationDuration = duration } } //If not enabled then do nothing. if privateIsEnabled() == false { return } let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") //Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56) // We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11) // if (_textFieldView == nil) return //Restoring the contentOffset of the lastScrollView if let lastScrollView = _lastScrollView { UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in lastScrollView.contentInset = self._startingContentInsets lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets if lastScrollView.shouldRestoreScrollViewContentOffset == true { lastScrollView.contentOffset = self._startingContentOffset } self.showLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(self._startingContentInsets) and contentOffset to : \(self._startingContentOffset)") // TODO: restore scrollView state // This is temporary solution. Have to implement the save and restore scrollView state var superScrollView : UIScrollView? = lastScrollView while let scrollView = superScrollView { let contentSize = CGSize(width: max(scrollView.contentSize.width, scrollView.frame.width), height: max(scrollView.contentSize.height, scrollView.frame.height)) let minimumY = contentSize.height - scrollView.frame.height if minimumY < scrollView.contentOffset.y { scrollView.contentOffset = CGPoint(x: scrollView.contentOffset.x, y: minimumY) self.showLog("Restoring \(scrollView._IQDescription()) contentOffset to : \(self._startingContentOffset)") } superScrollView = scrollView.superviewOfClassType(UIScrollView.self) as? UIScrollView } }) { (finished) -> Void in } } // Setting rootViewController frame to it's original position. // (Bug ID: #18) if _topViewBeginRect.equalTo(CGRect.zero) == false { if let rootViewController = _rootViewController { //frame size needs to be adjusted on iOS8 due to orientation API changes. _topViewBeginRect.size = rootViewController.view.frame.size //Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations. UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in if let constraint = self._layoutGuideConstraint { constraint.constant = self._layoutGuideConstraintInitialConstant rootViewController.view.setNeedsLayout() rootViewController.view.layoutIfNeeded() } else { self.showLog("Restoring \(rootViewController._IQDescription()) frame to : \(self._topViewBeginRect)") // Setting it's new frame rootViewController.view.frame = self._topViewBeginRect self._privateMovedDistance = 0 //Animating content if needed (Bug ID: #204) if self.layoutIfNeededOnUpdate == true { //Animating content (Bug ID: #160) rootViewController.view.setNeedsLayout() rootViewController.view.layoutIfNeeded() } } }) { (finished) -> Void in } _rootViewController = nil } } else if let constraint = self._layoutGuideConstraint { if let rootViewController = _rootViewController { UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in constraint.constant = self._layoutGuideConstraintInitialConstant rootViewController.view.setNeedsLayout() rootViewController.view.layoutIfNeeded() }) { (finished) -> Void in } } } //Reset all values _lastScrollView = nil _kbSize = CGSize.zero _layoutGuideConstraint = nil _layoutGuideConstraintInitialConstant = 0 _startingContentInsets = UIEdgeInsets.zero _startingScrollIndicatorInsets = UIEdgeInsets.zero _startingContentOffset = CGPoint.zero // topViewBeginRect = CGRectZero //Commented due to #82 let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } internal func keyboardDidHide(_ notification:Notification) { let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") _topViewBeginRect = CGRect.zero let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } ///------------------------------------------- /// MARK: UITextField/UITextView Notifications ///------------------------------------------- /** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */ internal func textFieldViewDidBeginEditing(_ notification:Notification) { let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") // Getting object _textFieldView = notification.object as? UIView if overrideKeyboardAppearance == true { if let textFieldView = _textFieldView as? UITextField { //If keyboard appearance is not like the provided appearance if textFieldView.keyboardAppearance != keyboardAppearance { //Setting textField keyboard appearance and reloading inputViews. textFieldView.keyboardAppearance = keyboardAppearance textFieldView.reloadInputViews() } } else if let textFieldView = _textFieldView as? UITextView { //If keyboard appearance is not like the provided appearance if textFieldView.keyboardAppearance != keyboardAppearance { //Setting textField keyboard appearance and reloading inputViews. textFieldView.keyboardAppearance = keyboardAppearance textFieldView.reloadInputViews() } } } //If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required. if privateIsEnableAutoToolbar() == true { //UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it. if _textFieldView is UITextView == true && _textFieldView?.inputAccessoryView == nil { UIView.animate(withDuration: 0.00001, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in self.addToolbarIfRequired() }, completion: { (finished) -> Void in //On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews. self._textFieldView?.reloadInputViews() }) } else { //Adding toolbar addToolbarIfRequired() } } else { removeToolbarIfRequired() } _tapGesture.isEnabled = privateShouldResignOnTouchOutside() _textFieldView?.window?.addGestureRecognizer(_tapGesture) // (Enhancement ID: #14) if privateIsEnabled() == true { if _topViewBeginRect.equalTo(CGRect.zero) == true { // (Bug ID: #5) // keyboard is not showing(At the beginning only). We should save rootViewRect. if let constraint = _textFieldView?.viewController()?.IQLayoutGuideConstraint { _layoutGuideConstraint = constraint _layoutGuideConstraintInitialConstant = constraint.constant } _rootViewController = _textFieldView?.topMostController() if _rootViewController == nil { _rootViewController = keyWindow()?.topMostController() } if let rootViewController = _rootViewController { _topViewBeginRect = rootViewController.view.frame if shouldFixInteractivePopGestureRecognizer == true && rootViewController is UINavigationController && rootViewController.modalPresentationStyle != UIModalPresentationStyle.formSheet && rootViewController.modalPresentationStyle != UIModalPresentationStyle.pageSheet { if let window = keyWindow() { _topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-rootViewController.view.frame.size.height) } else { _topViewBeginRect.origin = CGPoint.zero } } showLog("Saving \(rootViewController._IQDescription()) beginning frame : \(_topViewBeginRect)") } } //If _textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76) //See notes:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70). if _privateIsKeyboardShowing == true && _textFieldView != nil && _textFieldView?.isAlertViewTextField() == false { // keyboard is already showing. adjust frame. adjustFrame() } } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } /** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */ internal func textFieldViewDidEndEditing(_ notification:Notification) { let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") //Removing gesture recognizer (Enhancement ID: #14) _textFieldView?.window?.removeGestureRecognizer(_tapGesture) // We check if there's a change in original frame or not. if let textView = _textFieldView as? UITextView { if isTextViewContentInsetChanged == true { UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in self.isTextViewContentInsetChanged = false self.showLog("Restoring \(textView._IQDescription()) textView.contentInset to : \(self.startingTextViewContentInsets)") //Setting textField to it's initial contentInset textView.contentInset = self.startingTextViewContentInsets textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets }, completion: { (finished) -> Void in }) } } //Setting object to nil _textFieldView = nil let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } ///------------------------------------------ /// MARK: UIStatusBar Notification methods ///------------------------------------------ /** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/ internal func willChangeStatusBarOrientation(_ notification:Notification) { let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") //If textViewContentInsetChanged is saved then restore it. if let textView = _textFieldView as? UITextView { if isTextViewContentInsetChanged == true { UIView.animate(withDuration: _animationDuration, delay: 0, options: UIViewAnimationOptions.beginFromCurrentState.union(_animationCurve), animations: { () -> Void in self.isTextViewContentInsetChanged = false self.showLog("Restoring \(textView._IQDescription()) textView.contentInset to : \(self.startingTextViewContentInsets)") //Setting textField to it's initial contentInset textView.contentInset = self.startingTextViewContentInsets textView.scrollIndicatorInsets = self.startingTextViewScrollIndicatorInsets }, completion: { (finished) -> Void in }) } } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } /** UIApplicationDidChangeStatusBarFrameNotification. Need to refresh view position and update _topViewBeginRect. (Bug ID: #446)*/ internal func didChangeStatusBarFrame(_ notification : Notification?) -> Void { let oldStatusBarFrame = _statusBarFrame; // Getting keyboard animation duration if let newFrame = ((notification as NSNotification?)?.userInfo?[UIApplicationStatusBarFrameUserInfoKey] as? NSNumber)?.cgRectValue { _statusBarFrame = newFrame } if privateIsEnabled() == false { return } let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") if _rootViewController != nil && !_topViewBeginRect.equalTo(_rootViewController!.view.frame) == true { if let unwrappedRootController = _rootViewController { _topViewBeginRect = unwrappedRootController.view.frame if shouldFixInteractivePopGestureRecognizer == true && unwrappedRootController is UINavigationController && unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.formSheet && unwrappedRootController.modalPresentationStyle != UIModalPresentationStyle.pageSheet { if let window = keyWindow() { _topViewBeginRect.origin = CGPoint(x: 0,y: window.frame.size.height-unwrappedRootController.view.frame.size.height) } else { _topViewBeginRect.origin = CGPoint.zero } } showLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)") } else { _topViewBeginRect = CGRect.zero } } //If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html If it is UIAlertView textField then do not affect anything (Bug ID: #70). if _privateIsKeyboardShowing == true && _textFieldView != nil && _statusBarFrame.size.equalTo(oldStatusBarFrame.size) == false && _textFieldView?.isAlertViewTextField() == false { // keyboard is already showing. adjust frame. adjustFrame() } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } ///------------------ /// MARK: AutoToolbar ///------------------ /** Get all UITextField/UITextView siblings of textFieldView. */ fileprivate func responderViews()-> [UIView]? { var superConsideredView : UIView? //If find any consider responderView in it's upper hierarchy then will get deepResponderView. for disabledClass in toolbarPreviousNextAllowedClasses { superConsideredView = _textFieldView?.superviewOfClassType(disabledClass) if superConsideredView != nil { break } } //If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position. (Enhancement ID: #22) if superConsideredView != nil { return superConsideredView?.deepResponderViews() } else { //Otherwise fetching all the siblings if let textFields = _textFieldView?.responderSiblings() { //Sorting textFields according to behaviour switch toolbarManageBehaviour { //If autoToolbar behaviour is bySubviews, then returning it. case IQAutoToolbarManageBehaviour.bySubviews: return textFields //If autoToolbar behaviour is by tag, then sorting it according to tag property. case IQAutoToolbarManageBehaviour.byTag: return textFields.sortedArrayByTag() //If autoToolbar behaviour is by tag, then sorting it according to tag property. case IQAutoToolbarManageBehaviour.byPosition: return textFields.sortedArrayByPosition() } } else { return nil } } } /** Add toolbar if it is required to add on textFields and it's siblings. */ fileprivate func addToolbarIfRequired() { let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") // Getting all the sibling textFields. if let siblings = responderViews() { showLog("Found \(siblings.count) responder sibling(s)") // If only one object is found, then adding only Done button. if (siblings.count == 1 && previousNextDisplayMode == .Default) || previousNextDisplayMode == .alwaysHide { if let textField = _textFieldView { var needReload = false; //Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar). //setInputAccessoryView: check (Bug ID: #307) if textField.responds(to: #selector(setter: UITextField.inputAccessoryView)) { if textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag { //Supporting Custom Done button image (Enhancement ID: #366) if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag { needReload = true } if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage { textField.addRightButtonOnKeyboardWithImage(doneBarButtonItemImage, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder) } //Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376) else if let doneBarButtonItemText = toolbarDoneBarButtonItemText { textField.addRightButtonOnKeyboardWithText(doneBarButtonItemText, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder) } else { //Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27) textField.addDoneOnKeyboardWithTarget(self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder) } textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78) } else if let toolbar = textField.inputAccessoryView as? IQToolbar { if toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag { if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag { if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage { if toolbar.doneImage?.isEqual(doneBarButtonItemImage) == false { textField.addRightButtonOnKeyboardWithImage(doneBarButtonItemImage, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder) needReload = true } } //Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376) else if let doneBarButtonItemText = toolbarDoneBarButtonItemText { if toolbar.doneTitle != doneBarButtonItemText { textField.addRightButtonOnKeyboardWithText(doneBarButtonItemText, target: self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder) needReload = true } } else if (toolbarDoneBarButtonItemText == nil && toolbar.doneTitle != nil) || (toolbarDoneBarButtonItemImage == nil && toolbar.doneImage != nil) { //Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27) textField.addDoneOnKeyboardWithTarget(self, action: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder) needReload = true } textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78) } } } } if textField.inputAccessoryView is IQToolbar && textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag { let toolbar = textField.inputAccessoryView as! IQToolbar // Setting toolbar to keyboard. if let _textField = textField as? UITextField { //Bar style according to keyboard appearance switch _textField.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black toolbar.tintColor = UIColor.white default: toolbar.barStyle = UIBarStyle.default //Setting toolbar tintColor // (Enhancement ID: #30) if shouldToolbarUsesTextFieldTintColor { toolbar.tintColor = _textField.tintColor } else if let tintColor = toolbarTintColor { toolbar.tintColor = tintColor } else { toolbar.tintColor = UIColor.black } } } else if let _textView = textField as? UITextView { //Bar style according to keyboard appearance switch _textView.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black toolbar.tintColor = UIColor.white default: toolbar.barStyle = UIBarStyle.default if shouldToolbarUsesTextFieldTintColor { toolbar.tintColor = _textView.tintColor } else if let tintColor = toolbarTintColor { toolbar.tintColor = tintColor } else { toolbar.tintColor = UIColor.black } } } //Setting toolbar title font. // (Enhancement ID: #30) if shouldShowTextFieldPlaceholder == true && textField.shouldHidePlaceholderText == false { //Updating placeholder font to toolbar. //(Bug ID: #148, #272) if toolbar.title == nil || toolbar.title != textField.drawingPlaceholderText { toolbar.title = textField.drawingPlaceholderText } //Setting toolbar title font. // (Enhancement ID: #30) if placeholderFont != nil { toolbar.titleFont = placeholderFont } } else { toolbar.title = nil } } if needReload { textField.reloadInputViews() } } } else if (siblings.count > 1 && previousNextDisplayMode == .Default) || previousNextDisplayMode == .alwaysShow { // If more than 1 textField is found. then adding previous/next/done buttons on it. for textField in siblings { var needReload = false; //Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Done toolbar). //setInputAccessoryView: check (Bug ID: #307) if textField.responds(to: #selector(setter: UITextField.inputAccessoryView)) && (textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag) { if textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag { if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag { needReload = true } //Supporting Custom Done button image (Enhancement ID: #366) if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage { textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonImage: doneBarButtonItemImage, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder) } //Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376) else if let doneBarButtonItemText = toolbarDoneBarButtonItemText { textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonTitle: doneBarButtonItemText, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder) } else { //Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27) textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder) } } else if let toolbar = textField.inputAccessoryView as? IQToolbar { if textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag { if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage { if toolbar.doneImage?.isEqual(doneBarButtonItemImage) == false { textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonImage: toolbarDoneBarButtonItemImage!, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder) needReload = true } } //Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376) else if let doneBarButtonItemText = toolbarDoneBarButtonItemText { if toolbar.doneTitle != doneBarButtonItemText { textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonTitle: toolbarDoneBarButtonItemText!, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), rightButtonAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder) needReload = true } } else if (toolbarDoneBarButtonItemText == nil && toolbar.doneTitle != nil) || (toolbarDoneBarButtonItemImage == nil && toolbar.doneImage != nil) { //Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27) textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: #selector(self.previousAction(_:)), nextAction: #selector(self.nextAction(_:)), doneAction: #selector(self.doneAction(_:)), shouldShowPlaceholder: shouldShowTextFieldPlaceholder) needReload = true } } } textField.inputAccessoryView?.tag = IQKeyboardManager.kIQPreviousNextButtonToolbarTag // (Bug ID: #78) } if textField.inputAccessoryView is IQToolbar && textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag { let toolbar = textField.inputAccessoryView as! IQToolbar // Setting toolbar to keyboard. if let _textField = textField as? UITextField { //Bar style according to keyboard appearance switch _textField.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black toolbar.tintColor = UIColor.white default: toolbar.barStyle = UIBarStyle.default if shouldToolbarUsesTextFieldTintColor { toolbar.tintColor = _textField.tintColor } else if let tintColor = toolbarTintColor { toolbar.tintColor = tintColor } else { toolbar.tintColor = UIColor.black } } } else if let _textView = textField as? UITextView { //Bar style according to keyboard appearance switch _textView.keyboardAppearance { case UIKeyboardAppearance.dark: toolbar.barStyle = UIBarStyle.black toolbar.tintColor = UIColor.white default: toolbar.barStyle = UIBarStyle.default if shouldToolbarUsesTextFieldTintColor { toolbar.tintColor = _textView.tintColor } else if let tintColor = toolbarTintColor { toolbar.tintColor = tintColor } else { toolbar.tintColor = UIColor.black } } } //Setting toolbar title font. // (Enhancement ID: #30) if shouldShowTextFieldPlaceholder == true && textField.shouldHidePlaceholderText == false { //Updating placeholder font to toolbar. //(Bug ID: #148, #272) if toolbar.title == nil || toolbar.title != textField.drawingPlaceholderText { toolbar.title = textField.drawingPlaceholderText } //Setting toolbar title font. // (Enhancement ID: #30) if placeholderFont != nil { toolbar.titleFont = placeholderFont } } else { toolbar.title = nil } //In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56) // If firstTextField, then previous should not be enabled. if siblings[0] == textField { if (siblings.count == 1) { textField.setEnablePrevious(false, isNextEnabled: false) } else { textField.setEnablePrevious(false, isNextEnabled: true) } } else if siblings.last == textField { // If lastTextField then next should not be enaled. textField.setEnablePrevious(true, isNextEnabled: false) } else { textField.setEnablePrevious(true, isNextEnabled: true) } } if needReload { textField.reloadInputViews() } } } } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } /** Remove any toolbar if it is IQToolbar. */ fileprivate func removeToolbarIfRequired() { // (Bug ID: #18) let startTime = CACurrentMediaTime() showLog("****** \(#function) started ******") // Getting all the sibling textFields. if let siblings = responderViews() { showLog("Found \(siblings.count) responder sibling(s)") for view in siblings { if let toolbar = view.inputAccessoryView as? IQToolbar { //setInputAccessoryView: check (Bug ID: #307) if view.responds(to: #selector(setter: UITextField.inputAccessoryView)) && (toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag || toolbar.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) { if let textField = view as? UITextField { textField.inputAccessoryView = nil } else if let textView = view as? UITextView { textView.inputAccessoryView = nil } } } } } let elapsedTime = CACurrentMediaTime() - startTime showLog("****** \(#function) ended: \(elapsedTime) seconds ******") } /** reloadInputViews to reload toolbar buttons enable/disable state on the fly Enhancement ID #434. */ open func reloadInputViews() { //If enabled then adding toolbar. if privateIsEnableAutoToolbar() == true { self.addToolbarIfRequired() } else { self.removeToolbarIfRequired() } } ///------------------ /// MARK: Debugging & Developer options ///------------------ open var enableDebugging = false /** @warning Use below methods to completely enable/disable notifications registered by library internally. Please keep in mind that library is totally dependent on NSNotification of UITextField, UITextField, Keyboard etc. If you do unregisterAllNotifications then library will not work at all. You should only use below methods if you want to completedly disable all library functions. You should use below methods at your own risk. */ open func registerAllNotifications() { // Registering for keyboard notification. NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidShow(_:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardDidHide(_:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil) // Registering for UITextField notification. registerTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: NSNotification.Name.UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextFieldTextDidEndEditing.rawValue) // Registering for UITextView notification. registerTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: NSNotification.Name.UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextViewTextDidEndEditing.rawValue) // Registering for orientation changes notification NotificationCenter.default.addObserver(self, selector: #selector(self.willChangeStatusBarOrientation(_:)), name: NSNotification.Name.UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared) // Registering for status bar frame change notification NotificationCenter.default.addObserver(self, selector: #selector(self.didChangeStatusBarFrame(_:)), name: NSNotification.Name.UIApplicationDidChangeStatusBarFrame, object: UIApplication.shared) } open func unregisterAllNotifications() { // Unregistering for keyboard notification. NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil) NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidHide, object: nil) // Unregistering for UITextField notification. unregisterTextFieldViewClass(UITextField.self, didBeginEditingNotificationName: NSNotification.Name.UITextFieldTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextFieldTextDidEndEditing.rawValue) // Unregistering for UITextView notification. unregisterTextFieldViewClass(UITextView.self, didBeginEditingNotificationName: NSNotification.Name.UITextViewTextDidBeginEditing.rawValue, didEndEditingNotificationName: NSNotification.Name.UITextViewTextDidEndEditing.rawValue) // Unregistering for orientation changes notification NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillChangeStatusBarOrientation, object: UIApplication.shared) // Unregistering for status bar frame change notification NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidChangeStatusBarFrame, object: UIApplication.shared) } fileprivate func showLog(_ logString: String) { if enableDebugging { print("IQKeyboardManager: " + logString) } } }
mit
e151c69ea04d2a836aaa25a89a76939d
47.974946
434
0.565009
7.183944
false
false
false
false
mentrena/SyncKit
Example/RealmSwift/SyncKitRealmSwiftExample/SyncKitRealmSwiftExample/Model/Realm/IntPrimaryKeyObjects.swift
1
1006
// // QSIntKeyObject.swift // SyncKitRealmSwiftExampleTests // // Created by Manuel Entrena on 02/05/2021. // Copyright © 2021 Manuel Entrena. All rights reserved. // import RealmSwift import SyncKit class QSCompany_Int: Object, PrimaryKey { @objc dynamic var name: String? = "" @objc dynamic var identifier: Int = 0 let sortIndex = RealmOptional<Int>() let employees = LinkingObjects(fromType: QSEmployee_Int.self, property: "company") override class func primaryKey() -> String { return "identifier" } } class QSEmployee_Int: Object, PrimaryKey, ParentKey { @objc dynamic var name: String? = "" let sortIndex = RealmOptional<Int>() @objc dynamic var identifier: Int = 0 @objc dynamic var photo: Data? = nil @objc dynamic var company: QSCompany_Int? override class func primaryKey() -> String { return "identifier" } static func parentKey() -> String { return "company" } }
mit
3cd088560cb99df0c74faf95f0801df0
23.512195
86
0.645771
4.170124
false
false
false
false
mapsme/omim
iphone/Maps/Core/ABTests/Promo/PromoDiscoveryCampaign.swift
4
645
@objc class PromoDiscoveryCampaign: NSObject, IABTest { enum Group: Int { case discoverCatalog = 0 case downloadSamples case buySubscription } private var adapter: PromoDiscoveryCampaignAdapter let group: Group let url: URL? @objc private(set) var hasBeenActivated: Bool = false var enabled: Bool { return adapter.canShowTipButton() && Alohalytics.isFirstSession() && !hasBeenActivated; } required override init() { adapter = PromoDiscoveryCampaignAdapter() group = Group(rawValue: adapter.type) ?? .discoverCatalog url = adapter.url } func onActivate() { hasBeenActivated = true } }
apache-2.0
56d40f048ed9f401d7e8667645c5ff39
22.888889
91
0.708527
4.188312
false
false
false
false
blackspotbear/MMDViewer
MMDViewer/PMXDrawer.swift
1
6455
import Foundation import Metal private func CreateOpaquePipelinesState(_ device: MTLDevice, _ vertexDescriptor: MTLVertexDescriptor, _ vertexFunc: MTLFunction, _ fragmentFunc: MTLFunction) -> MTLRenderPipelineState { let pipelineStateDescriptor = MTLRenderPipelineDescriptor() pipelineStateDescriptor.vertexDescriptor = vertexDescriptor pipelineStateDescriptor.vertexFunction = vertexFunc pipelineStateDescriptor.fragmentFunction = fragmentFunc pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm pipelineStateDescriptor.depthAttachmentPixelFormat = .depth32Float do { return try device.makeRenderPipelineState(descriptor: pipelineStateDescriptor) } catch { fatalError("failed to make render pipeline state") } } private func CreateAlphaPipelinesState(_ device: MTLDevice, _ vertexDescriptor: MTLVertexDescriptor, _ vertexFunc: MTLFunction, _ fragmentFunc: MTLFunction) -> MTLRenderPipelineState { let pipelineStateDescriptor = MTLRenderPipelineDescriptor() pipelineStateDescriptor.vertexDescriptor = vertexDescriptor pipelineStateDescriptor.vertexFunction = vertexFunc pipelineStateDescriptor.fragmentFunction = fragmentFunc pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm pipelineStateDescriptor.depthAttachmentPixelFormat = .depth32Float if let ca = pipelineStateDescriptor.colorAttachments[0] { ca.isBlendingEnabled = true ca.rgbBlendOperation = .add ca.alphaBlendOperation = .add ca.sourceRGBBlendFactor = .one // expect image is PremultipliedLast ca.sourceAlphaBlendFactor = .one ca.destinationRGBBlendFactor = .oneMinusSourceAlpha ca.destinationAlphaBlendFactor = .oneMinusSourceAlpha } do { return try device.makeRenderPipelineState(descriptor: pipelineStateDescriptor) } catch { fatalError("failed to make render pipeline state") } } private func MakePipelineStates(_ device: MTLDevice) -> (MTLRenderPipelineState, MTLRenderPipelineState) { guard let defaultLibrary = device.makeDefaultLibrary() else { fatalError("failed to create default library") } guard let newVertexFunction = defaultLibrary.makeFunction(name: "basic_vertex") else { fatalError("failed to make vertex function") } guard let newFragmentFunction = defaultLibrary.makeFunction(name: "basic_fragment") else { fatalError("failed to make fragment function") } // Define vertex layout let vertexDescriptor = MTLVertexDescriptor() // position vertexDescriptor.attributes[0].offset = 0 vertexDescriptor.attributes[0].format = .float3 vertexDescriptor.attributes[0].bufferIndex = 0 // normal vertexDescriptor.attributes[1].offset = MemoryLayout<Float32>.size * 3 vertexDescriptor.attributes[1].format = .float3 vertexDescriptor.attributes[1].bufferIndex = 0 // uv vertexDescriptor.attributes[2].offset = MemoryLayout<Float32>.size * 6 vertexDescriptor.attributes[2].format = .float2 vertexDescriptor.attributes[2].bufferIndex = 0 // weight vertexDescriptor.attributes[3].offset = MemoryLayout<Float32>.size * 8 vertexDescriptor.attributes[3].format = .float4 vertexDescriptor.attributes[3].bufferIndex = 0 // indices vertexDescriptor.attributes[4].offset = MemoryLayout<Float32>.size * 12 vertexDescriptor.attributes[4].format = .short4 vertexDescriptor.attributes[4].bufferIndex = 0 // layout vertexDescriptor.layouts[0].stepFunction = .perVertex // an error occurred: // Expression was too complex to be solved in reasonable time; // consider breaking up the expression into distinct sub-expressions // //vertexDescriptor.layouts[0].stride = (MemoryLayout<Float32>.size) * (3 + 3 + 2 + 4 + 4/2) let sizeOfFloat32 = MemoryLayout<Float32>.size vertexDescriptor.layouts[0].stride = sizeOfFloat32 * (3 + 3 + 2 + 4 + 4/2) let opaquePipelineState = CreateOpaquePipelinesState(device, vertexDescriptor, newVertexFunction, newFragmentFunction) let alphaPipelineState = CreateAlphaPipelinesState(device, vertexDescriptor, newVertexFunction, newFragmentFunction) return (opaquePipelineState, alphaPipelineState) } class PMXDrawer: Drawer { let pmxObj: PMXObject var opaquePipelineState: MTLRenderPipelineState var alphaPipelineState: MTLRenderPipelineState init(pmxObj: PMXObject, device: MTLDevice) { self.pmxObj = pmxObj (opaquePipelineState, alphaPipelineState) = MakePipelineStates(device) } func draw(_ renderer: Renderer) { guard let renderEncoder = renderer.renderCommandEncoder else { return } guard let currentVertexBuffer = pmxObj.currentVertexBuffer else { return } renderEncoder.setCullMode(.front) renderEncoder.setDepthStencilState(pmxObj.depthStencilState) renderEncoder.setVertexBuffer(currentVertexBuffer, offset: 0, index: 0) renderEncoder.setVertexBuffer(pmxObj.uniformBuffer, offset: 0, index: 1) renderEncoder.setVertexBuffer(pmxObj.matrixPalette, offset: 0, index: 2) renderEncoder.setFragmentBuffer(pmxObj.uniformBuffer, offset: 0, index:0) renderEncoder.setFragmentSamplerState(pmxObj.samplerState, index: 0) // draw primitives for each material var indexByteOffset = 0 var materialByteOffset = 0 for material in pmxObj.pmx.materials { let textureIndex = material.textureIndex != 255 ? material.textureIndex : 0 let texture = pmxObj.textures[textureIndex] let renderPipelineState = texture.hasAlpha ? alphaPipelineState : opaquePipelineState renderEncoder.setRenderPipelineState(renderPipelineState) renderEncoder.setFragmentTexture(texture.texture, index: 0) renderEncoder.setFragmentBuffer(pmxObj.materialBuffer, offset: materialByteOffset, index: 1) renderEncoder.drawIndexedPrimitives( type: .triangle, indexCount: Int(material.vertexCount), indexType: .uint16, indexBuffer: pmxObj.indexBuffer, indexBufferOffset: indexByteOffset) indexByteOffset += Int(material.vertexCount) * 2 // 2 bytes per index materialByteOffset += MemoryLayout<ShaderMaterial>.stride } } }
mit
0fb58aa84c4885bc7ae8917584870d10
42.614865
185
0.728118
5.273693
false
false
false
false
ScreamShot/ScreamShot
ScreamShot/LaunchServicesHelper.swift
1
2955
/* This file is part of mac2imgur. * * mac2imgur is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * mac2imgur is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with mac2imgur. If not, see <http://www.gnu.org/licenses/>. */ import Foundation // Refined version of http://stackoverflow.com/a/27442962 class LaunchServicesHelper { static private let applicationURL = NSURL(fileURLWithPath: NSBundle.mainBundle().bundlePath) static var applicationIsInStartUpItems: Bool { return itemReferencesInLoginItems.existingReference != nil } static var itemReferencesInLoginItems: (existingReference: LSSharedFileListItemRef?, lastReference: LSSharedFileListItemRef?) { let itemURL = UnsafeMutablePointer<Unmanaged<CFURL>?>.alloc(1) if let loginItemsRef = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue() as LSSharedFileListRef? { let loginItems = LSSharedFileListCopySnapshot(loginItemsRef, nil).takeRetainedValue() as NSArray let lastItemRef = loginItems.lastObject as! LSSharedFileListItemRef? for loginItem in loginItems { let currentItemRef = loginItem as! LSSharedFileListItemRef if LSSharedFileListItemResolve(currentItemRef, 0, itemURL, nil) == noErr { if let URLRef = itemURL.memory?.takeRetainedValue() as? NSURL { if URLRef.isEqual(applicationURL) { return (currentItemRef, lastItemRef) } } } } // The application was not found in the startup list return (nil, lastItemRef ?? kLSSharedFileListItemBeforeFirst.takeRetainedValue()) } return (nil, nil) } static func toggleLaunchAtStartup() { let itemReferences = itemReferencesInLoginItems if let loginItemsRef = LSSharedFileListCreate(nil, kLSSharedFileListSessionLoginItems.takeRetainedValue(), nil).takeRetainedValue() as LSSharedFileListRef? { if let existingRef = itemReferences.existingReference { // Remove application from login items LSSharedFileListItemRemove(loginItemsRef, existingRef) } else { // Add application to login items LSSharedFileListInsertItemURL(loginItemsRef, itemReferences.lastReference, nil, nil, applicationURL, nil, nil) } } } }
gpl-3.0
008fe2d9016d875df38ac1db08dd1f72
47.459016
165
0.685279
5.26738
false
false
false
false
touchopia/HackingWithSwift
project24.playground/Contents.swift
1
505
//: Playground - noun: a place where people can play import UIKit extension Int { mutating func plusOne() { self += 1 } } var myInt = 0 myInt.plusOne() myInt // THIS EXTENDS ONLY INT //extension Int { // func squared() -> Int { // return self * self // } //} // THIS EXTENDS ALL INTEGER TYPES extension Integer { func squared() -> Self { return self * self } } let i: Int = 8 print(i.squared()) var str = " Hello " str = str.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
unlicense
bd249ce795056d322099e61e2eca13fb
13.428571
69
0.657426
3.196203
false
false
false
false
mitochrome/complex-gestures-demo
apps/GestureInput/Carthage/Checkouts/RxDataSources/Sources/DataSources/Differentiator.swift
22
29582
// // Differentiator.swift // RxDataSources // // Created by Krunoslav Zaher on 6/27/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation public enum DifferentiatorError : Error , CustomDebugStringConvertible { case duplicateItem(item: Any) case duplicateSection(section: Any) case invalidInitializerImplementation(section: Any, expectedItems: Any, expectedIdentifier: Any) } extension DifferentiatorError { public var debugDescription: String { switch self { case let .duplicateItem(item): return "Duplicate item \(item)" case let .duplicateSection(section): return "Duplicate section \(section)" case let .invalidInitializerImplementation(section, expectedItems, expectedIdentifier): return "Wrong initializer implementation for: \(section)\n" + "Expected it should return items: \(expectedItems)\n" + "Expected it should have id: \(expectedIdentifier)" } } } fileprivate enum EditEvent : CustomDebugStringConvertible { case inserted // can't be found in old sections case insertedAutomatically // Item inside section being inserted case deleted // Was in old, not in new, in it's place is something "not new" :(, otherwise it's Updated case deletedAutomatically // Item inside section that is being deleted case moved // same item, but was on different index, and needs explicit move case movedAutomatically // don't need to specify any changes for those rows case untouched } extension EditEvent { fileprivate var debugDescription: String { get { switch self { case .inserted: return "Inserted" case .insertedAutomatically: return "InsertedAutomatically" case .deleted: return "Deleted" case .deletedAutomatically: return "DeletedAutomatically" case .moved: return "Moved" case .movedAutomatically: return "MovedAutomatically" case .untouched: return "Untouched" } } } } fileprivate struct SectionAssociatedData { var event: EditEvent var indexAfterDelete: Int? var moveIndex: Int? var itemCount: Int } extension SectionAssociatedData : CustomDebugStringConvertible { fileprivate var debugDescription: String { get { return "\(event), \(String(describing: indexAfterDelete))" } } } extension SectionAssociatedData { fileprivate static var initial: SectionAssociatedData { return SectionAssociatedData(event: .untouched, indexAfterDelete: nil, moveIndex: nil, itemCount: 0) } } fileprivate struct ItemAssociatedData { var event: EditEvent var indexAfterDelete: Int? var moveIndex: ItemPath? } extension ItemAssociatedData : CustomDebugStringConvertible { fileprivate var debugDescription: String { get { return "\(event) \(String(describing: indexAfterDelete))" } } } extension ItemAssociatedData { static var initial : ItemAssociatedData { return ItemAssociatedData(event: .untouched, indexAfterDelete: nil, moveIndex: nil) } } fileprivate func indexSections<S: AnimatableSectionModelType>(_ sections: [S]) throws -> [S.Identity : Int] { var indexedSections: [S.Identity : Int] = [:] for (i, section) in sections.enumerated() { guard indexedSections[section.identity] == nil else { #if DEBUG if indexedSections[section.identity] != nil { print("Section \(section) has already been indexed at \(indexedSections[section.identity]!)") } #endif throw DifferentiatorError.duplicateSection(section: section) } indexedSections[section.identity] = i } return indexedSections } //================================================================================ // Optimizations because Swift dictionaries are extremely slow (ARC, bridging ...) //================================================================================ // swift dictionary optimizations { fileprivate struct OptimizedIdentity<E: Hashable> { let hashValue: Int let identity: UnsafePointer<E> init(_ identity: UnsafePointer<E>) { self.identity = identity self.hashValue = identity.pointee.hashValue } } extension OptimizedIdentity: Hashable { } fileprivate func == <E: Hashable>(lhs: OptimizedIdentity<E>, rhs: OptimizedIdentity<E>) -> Bool { if lhs.hashValue != rhs.hashValue { return false } if lhs.identity.distance(to: rhs.identity) == 0 { return true } return lhs.identity.pointee == rhs.identity.pointee } fileprivate func calculateAssociatedData<Item: IdentifiableType>( initialItemCache: ContiguousArray<ContiguousArray<Item>>, finalItemCache: ContiguousArray<ContiguousArray<Item>> ) throws -> (ContiguousArray<ContiguousArray<ItemAssociatedData>>, ContiguousArray<ContiguousArray<ItemAssociatedData>>) { typealias Identity = Item.Identity let totalInitialItems = initialItemCache.map { $0.count }.reduce(0, +) var initialIdentities: ContiguousArray<Identity> = ContiguousArray() var initialItemPaths: ContiguousArray<ItemPath> = ContiguousArray() initialIdentities.reserveCapacity(totalInitialItems) initialItemPaths.reserveCapacity(totalInitialItems) for (i, items) in initialItemCache.enumerated() { for j in 0 ..< items.count { let item = items[j] initialIdentities.append(item.identity) initialItemPaths.append(ItemPath(sectionIndex: i, itemIndex: j)) } } var initialItemData = ContiguousArray(initialItemCache.map { items in return ContiguousArray<ItemAssociatedData>(repeating: ItemAssociatedData.initial, count: items.count) }) var finalItemData = ContiguousArray(finalItemCache.map { items in return ContiguousArray<ItemAssociatedData>(repeating: ItemAssociatedData.initial, count: items.count) }) try initialIdentities.withUnsafeBufferPointer { (identitiesBuffer: UnsafeBufferPointer<Identity>) -> () in var dictionary: [OptimizedIdentity<Identity>: Int] = Dictionary(minimumCapacity: totalInitialItems * 2) for i in 0 ..< initialIdentities.count { let identityPointer = identitiesBuffer.baseAddress!.advanced(by: i) let key = OptimizedIdentity(identityPointer) if let existingValueItemPathIndex = dictionary[key] { let itemPath = initialItemPaths[existingValueItemPathIndex] let item = initialItemCache[itemPath.sectionIndex][itemPath.itemIndex] #if DEBUG print("Item \(item) has already been indexed at \(itemPath)" ) #endif throw DifferentiatorError.duplicateItem(item: item) } dictionary[key] = i } for (i, items) in finalItemCache.enumerated() { for j in 0 ..< items.count { let item = items[j] var identity = item.identity let key = OptimizedIdentity(&identity) guard let initialItemPathIndex = dictionary[key] else { continue } let itemPath = initialItemPaths[initialItemPathIndex] if initialItemData[itemPath.sectionIndex][itemPath.itemIndex].moveIndex != nil { throw DifferentiatorError.duplicateItem(item: item) } initialItemData[itemPath.sectionIndex][itemPath.itemIndex].moveIndex = ItemPath(sectionIndex: i, itemIndex: j) finalItemData[i][j].moveIndex = itemPath } } return () } return (initialItemData, finalItemData) } // } swift dictionary optimizations /* I've uncovered this case during random stress testing of logic. This is the hardest generic update case that causes two passes, first delete, and then move/insert [ NumberSection(model: "1", items: [1111]), NumberSection(model: "2", items: [2222]), ] [ NumberSection(model: "2", items: [0]), NumberSection(model: "1", items: []), ] If update is in the form * Move section from 2 to 1 * Delete Items at paths 0 - 0, 1 - 0 * Insert Items at paths 0 - 0 or * Move section from 2 to 1 * Delete Items at paths 0 - 0 * Reload Items at paths 1 - 0 or * Move section from 2 to 1 * Delete Items at paths 0 - 0 * Reload Items at paths 0 - 0 it crashes table view. No matter what change is performed, it fails for me. If anyone knows how to make this work for one Changeset, PR is welcome. */ // If you are considering working out your own algorithm, these are tricky // transition cases that you can use. // case 1 /* from = [ NumberSection(model: "section 4", items: [10, 11, 12]), NumberSection(model: "section 9", items: [25, 26, 27]), ] to = [ HashableSectionModel(model: "section 9", items: [11, 26, 27]), HashableSectionModel(model: "section 4", items: [10, 12]) ] */ // case 2 /* from = [ HashableSectionModel(model: "section 10", items: [26]), HashableSectionModel(model: "section 7", items: [5, 29]), HashableSectionModel(model: "section 1", items: [14]), HashableSectionModel(model: "section 5", items: [16]), HashableSectionModel(model: "section 4", items: []), HashableSectionModel(model: "section 8", items: [3, 15, 19, 23]), HashableSectionModel(model: "section 3", items: [20]) ] to = [ HashableSectionModel(model: "section 10", items: [26]), HashableSectionModel(model: "section 1", items: [14]), HashableSectionModel(model: "section 9", items: [3]), HashableSectionModel(model: "section 5", items: [16, 8]), HashableSectionModel(model: "section 8", items: [15, 19, 23]), HashableSectionModel(model: "section 3", items: [20]), HashableSectionModel(model: "Section 2", items: [7]) ] */ // case 3 /* from = [ HashableSectionModel(model: "section 4", items: [5]), HashableSectionModel(model: "section 6", items: [20, 14]), HashableSectionModel(model: "section 9", items: []), HashableSectionModel(model: "section 2", items: [2, 26]), HashableSectionModel(model: "section 8", items: [23]), HashableSectionModel(model: "section 10", items: [8, 18, 13]), HashableSectionModel(model: "section 1", items: [28, 25, 6, 11, 10, 29, 24, 7, 19]) ] to = [ HashableSectionModel(model: "section 4", items: [5]), HashableSectionModel(model: "section 6", items: [20, 14]), HashableSectionModel(model: "section 9", items: [16]), HashableSectionModel(model: "section 7", items: [17, 15, 4]), HashableSectionModel(model: "section 2", items: [2, 26, 23]), HashableSectionModel(model: "section 8", items: []), HashableSectionModel(model: "section 10", items: [8, 18, 13]), HashableSectionModel(model: "section 1", items: [28, 25, 6, 11, 10, 29, 24, 7, 19]) ] */ // Generates differential changes suitable for sectioned view consumption. // It will not only detect changes between two states, but it will also try to compress those changes into // almost minimal set of changes. // // I know, I know, it's ugly :( Totally agree, but this is the only general way I could find that works 100%, and // avoids UITableView quirks. // // Please take into consideration that I was also convinced about 20 times that I've found a simple general // solution, but then UITableView falls apart under stress testing :( // // Sincerely, if somebody else would present me this 250 lines of code, I would call him a mad man. I would think // that there has to be a simpler solution. Well, after 3 days, I'm not convinced any more :) // // Maybe it can be made somewhat simpler, but don't think it can be made much simpler. // // The algorithm could take anywhere from 1 to 3 table view transactions to finish the updates. // // * stage 1 - remove deleted sections and items // * stage 2 - move sections into place // * stage 3 - fix moved and new items // // There maybe exists a better division, but time will tell. // public func differencesForSectionedView<S: AnimatableSectionModelType>( initialSections: [S], finalSections: [S]) throws -> [Changeset<S>] { typealias I = S.Item var result: [Changeset<S>] = [] var sectionCommands = try CommandGenerator<S>.generatorForInitialSections(initialSections, finalSections: finalSections) result.append(contentsOf: try sectionCommands.generateDeleteSectionsDeletedItemsAndUpdatedItems()) result.append(contentsOf: try sectionCommands.generateInsertAndMoveSections()) result.append(contentsOf: try sectionCommands.generateInsertAndMovedItems()) return result } @available(*, deprecated, renamed: "differencesForSectionedView(initialSections:finalSections:)") public func differencesForSectionedView<S: AnimatableSectionModelType>( _ initialSections: [S], finalSections: [S]) throws -> [Changeset<S>] { return try differencesForSectionedView(initialSections: initialSections, finalSections: finalSections) } private extension AnimatableSectionModelType { init(safeOriginal: Self, safeItems: [Item]) throws { self.init(original: safeOriginal, items: safeItems) if self.items != safeItems || self.identity != safeOriginal.identity { throw DifferentiatorError.invalidInitializerImplementation(section: self, expectedItems: safeItems, expectedIdentifier: safeOriginal.identity) } } } fileprivate struct CommandGenerator<S: AnimatableSectionModelType> { typealias Item = S.Item let initialSections: [S] let finalSections: [S] let initialSectionData: ContiguousArray<SectionAssociatedData> let finalSectionData: ContiguousArray<SectionAssociatedData> let initialItemData: ContiguousArray<ContiguousArray<ItemAssociatedData>> let finalItemData: ContiguousArray<ContiguousArray<ItemAssociatedData>> let initialItemCache: ContiguousArray<ContiguousArray<Item>> let finalItemCache: ContiguousArray<ContiguousArray<Item>> static func generatorForInitialSections( _ initialSections: [S], finalSections: [S] ) throws -> CommandGenerator<S> { let (initialSectionData, finalSectionData) = try calculateSectionMovements(initialSections: initialSections, finalSections: finalSections) let initialItemCache = ContiguousArray(initialSections.map { ContiguousArray($0.items) }) let finalItemCache = ContiguousArray(finalSections.map { ContiguousArray($0.items) }) let (initialItemData, finalItemData) = try calculateItemMovements( initialItemCache: initialItemCache, finalItemCache: finalItemCache, initialSectionData: initialSectionData, finalSectionData: finalSectionData ) return CommandGenerator<S>( initialSections: initialSections, finalSections: finalSections, initialSectionData: initialSectionData, finalSectionData: finalSectionData, initialItemData: initialItemData, finalItemData: finalItemData, initialItemCache: initialItemCache, finalItemCache: finalItemCache ) } static func calculateItemMovements( initialItemCache: ContiguousArray<ContiguousArray<Item>>, finalItemCache: ContiguousArray<ContiguousArray<Item>>, initialSectionData: ContiguousArray<SectionAssociatedData>, finalSectionData: ContiguousArray<SectionAssociatedData>) throws -> (ContiguousArray<ContiguousArray<ItemAssociatedData>>, ContiguousArray<ContiguousArray<ItemAssociatedData>>) { var (initialItemData, finalItemData) = try calculateAssociatedData( initialItemCache: initialItemCache, finalItemCache: finalItemCache ) let findNextUntouchedOldIndex = { (initialSectionIndex: Int, initialSearchIndex: Int?) -> Int? in guard var i2 = initialSearchIndex else { return nil } while i2 < initialSectionData[initialSectionIndex].itemCount { if initialItemData[initialSectionIndex][i2].event == .untouched { return i2 } i2 = i2 + 1 } return nil } // first mark deleted items for i in 0 ..< initialItemCache.count { guard let _ = initialSectionData[i].moveIndex else { continue } var indexAfterDelete = 0 for j in 0 ..< initialItemCache[i].count { guard let finalIndexPath = initialItemData[i][j].moveIndex else { initialItemData[i][j].event = .deleted continue } // from this point below, section has to be move type because it's initial and not deleted // because there is no move to inserted section if finalSectionData[finalIndexPath.sectionIndex].event == .inserted { initialItemData[i][j].event = .deleted continue } initialItemData[i][j].indexAfterDelete = indexAfterDelete indexAfterDelete += 1 } } // mark moved or moved automatically for i in 0 ..< finalItemCache.count { guard let originalSectionIndex = finalSectionData[i].moveIndex else { continue } var untouchedIndex: Int? = 0 for j in 0 ..< finalItemCache[i].count { untouchedIndex = findNextUntouchedOldIndex(originalSectionIndex, untouchedIndex) guard let originalIndex = finalItemData[i][j].moveIndex else { finalItemData[i][j].event = .inserted continue } // In case trying to move from deleted section, abort, otherwise it will crash table view if initialSectionData[originalIndex.sectionIndex].event == .deleted { finalItemData[i][j].event = .inserted continue } // original section can't be inserted else if initialSectionData[originalIndex.sectionIndex].event == .inserted { try rxPrecondition(false, "New section in initial sections, that is wrong") } let initialSectionEvent = initialSectionData[originalIndex.sectionIndex].event try rxPrecondition(initialSectionEvent == .moved || initialSectionEvent == .movedAutomatically, "Section not moved") let eventType = originalIndex == ItemPath(sectionIndex: originalSectionIndex, itemIndex: untouchedIndex ?? -1) ? EditEvent.movedAutomatically : EditEvent.moved initialItemData[originalIndex.sectionIndex][originalIndex.itemIndex].event = eventType finalItemData[i][j].event = eventType } } return (initialItemData, finalItemData) } static func calculateSectionMovements(initialSections: [S], finalSections: [S]) throws -> (ContiguousArray<SectionAssociatedData>, ContiguousArray<SectionAssociatedData>) { let initialSectionIndexes = try indexSections(initialSections) var initialSectionData = ContiguousArray<SectionAssociatedData>(repeating: SectionAssociatedData.initial, count: initialSections.count) var finalSectionData = ContiguousArray<SectionAssociatedData>(repeating: SectionAssociatedData.initial, count: finalSections.count) for (i, section) in finalSections.enumerated() { finalSectionData[i].itemCount = finalSections[i].items.count guard let initialSectionIndex = initialSectionIndexes[section.identity] else { continue } if initialSectionData[initialSectionIndex].moveIndex != nil { throw DifferentiatorError.duplicateSection(section: section) } initialSectionData[initialSectionIndex].moveIndex = i finalSectionData[i].moveIndex = initialSectionIndex } var sectionIndexAfterDelete = 0 // deleted sections for i in 0 ..< initialSectionData.count { initialSectionData[i].itemCount = initialSections[i].items.count if initialSectionData[i].moveIndex == nil { initialSectionData[i].event = .deleted continue } initialSectionData[i].indexAfterDelete = sectionIndexAfterDelete sectionIndexAfterDelete += 1 } // moved sections var untouchedOldIndex: Int? = 0 let findNextUntouchedOldIndex = { (initialSearchIndex: Int?) -> Int? in guard var i = initialSearchIndex else { return nil } while i < initialSections.count { if initialSectionData[i].event == .untouched { return i } i = i + 1 } return nil } // inserted and moved sections { // this should fix all sections and move them into correct places // 2nd stage for i in 0 ..< finalSections.count { untouchedOldIndex = findNextUntouchedOldIndex(untouchedOldIndex) // oh, it did exist if let oldSectionIndex = finalSectionData[i].moveIndex { let moveType = oldSectionIndex != untouchedOldIndex ? EditEvent.moved : EditEvent.movedAutomatically finalSectionData[i].event = moveType initialSectionData[oldSectionIndex].event = moveType } else { finalSectionData[i].event = .inserted } } // inserted sections for (i, section) in finalSectionData.enumerated() { if section.moveIndex == nil { _ = finalSectionData[i].event == .inserted } } return (initialSectionData, finalSectionData) } mutating func generateDeleteSectionsDeletedItemsAndUpdatedItems() throws -> [Changeset<S>] { var deletedSections = [Int]() var deletedItems = [ItemPath]() var updatedItems = [ItemPath]() var afterDeleteState = [S]() // mark deleted items { // 1rst stage again (I know, I know ...) for (i, initialItems) in initialItemCache.enumerated() { let event = initialSectionData[i].event // Deleted section will take care of deleting child items. // In case of moving an item from deleted section, tableview will // crash anyway, so this is not limiting anything. if event == .deleted { deletedSections.append(i) continue } var afterDeleteItems: [S.Item] = [] for j in 0 ..< initialItems.count { let event = initialItemData[i][j].event switch event { case .deleted: deletedItems.append(ItemPath(sectionIndex: i, itemIndex: j)) case .moved, .movedAutomatically: let finalItemIndex = try initialItemData[i][j].moveIndex.unwrap() let finalItem = finalItemCache[finalItemIndex.sectionIndex][finalItemIndex.itemIndex] if finalItem != initialSections[i].items[j] { updatedItems.append(ItemPath(sectionIndex: i, itemIndex: j)) } afterDeleteItems.append(finalItem) default: try rxPrecondition(false, "Unhandled case") } } afterDeleteState.append(try S(safeOriginal: initialSections[i], safeItems: afterDeleteItems)) } // } if deletedItems.count == 0 && deletedSections.count == 0 && updatedItems.count == 0 { return [] } return [Changeset( finalSections: afterDeleteState, deletedSections: deletedSections, deletedItems: deletedItems, updatedItems: updatedItems )] } func generateInsertAndMoveSections() throws -> [Changeset<S>] { var movedSections = [(from: Int, to: Int)]() var insertedSections = [Int]() for i in 0 ..< initialSections.count { switch initialSectionData[i].event { case .deleted: break case .moved: movedSections.append((from: try initialSectionData[i].indexAfterDelete.unwrap(), to: try initialSectionData[i].moveIndex.unwrap())) case .movedAutomatically: break default: try rxPrecondition(false, "Unhandled case in initial sections") } } for i in 0 ..< finalSections.count { switch finalSectionData[i].event { case .inserted: insertedSections.append(i) default: break } } if insertedSections.count == 0 && movedSections.count == 0 { return [] } // sections should be in place, but items should be original without deleted ones let sectionsAfterChange: [S] = try self.finalSections.enumerated().map { i, s -> S in let event = self.finalSectionData[i].event if event == .inserted { // it's already set up return s } else if event == .moved || event == .movedAutomatically { let originalSectionIndex = try finalSectionData[i].moveIndex.unwrap() let originalSection = initialSections[originalSectionIndex] var items: [S.Item] = [] items.reserveCapacity(originalSection.items.count) let itemAssociatedData = self.initialItemData[originalSectionIndex] for j in 0 ..< originalSection.items.count { let initialData = itemAssociatedData[j] guard initialData.event != .deleted else { continue } guard let finalIndex = initialData.moveIndex else { try rxPrecondition(false, "Item was moved, but no final location.") continue } items.append(finalItemCache[finalIndex.sectionIndex][finalIndex.itemIndex]) } let modifiedSection = try S(safeOriginal: s, safeItems: items) return modifiedSection } else { try rxPrecondition(false, "This is weird, this shouldn't happen") return s } } return [Changeset( finalSections: sectionsAfterChange, insertedSections: insertedSections, movedSections: movedSections )] } mutating func generateInsertAndMovedItems() throws -> [Changeset<S>] { var insertedItems = [ItemPath]() var movedItems = [(from: ItemPath, to: ItemPath)]() // mark new and moved items { // 3rd stage for i in 0 ..< finalSections.count { let finalSection = finalSections[i] let sectionEvent = finalSectionData[i].event // new and deleted sections cause reload automatically if sectionEvent != .moved && sectionEvent != .movedAutomatically { continue } for j in 0 ..< finalSection.items.count { let currentItemEvent = finalItemData[i][j].event try rxPrecondition(currentItemEvent != .untouched, "Current event is not untouched") let event = finalItemData[i][j].event switch event { case .inserted: insertedItems.append(ItemPath(sectionIndex: i, itemIndex: j)) case .moved: let originalIndex = try finalItemData[i][j].moveIndex.unwrap() let finalSectionIndex = try initialSectionData[originalIndex.sectionIndex].moveIndex.unwrap() let moveFromItemWithIndex = try initialItemData[originalIndex.sectionIndex][originalIndex.itemIndex].indexAfterDelete.unwrap() let moveCommand = ( from: ItemPath(sectionIndex: finalSectionIndex, itemIndex: moveFromItemWithIndex), to: ItemPath(sectionIndex: i, itemIndex: j) ) movedItems.append(moveCommand) default: break } } } // } if insertedItems.count == 0 && movedItems.count == 0 { return [] } return [Changeset( finalSections: finalSections, insertedItems: insertedItems, movedItems: movedItems )] } }
mit
9ac752b94fc4952896f782f9c4822a9c
35.746584
154
0.618607
5.389142
false
false
false
false
qualaroo/QualarooSDKiOS
QualarooTests/UserResponseAdapterSpec.swift
1
6774
// // UserResponseAdapterSpec.swift // QualarooTests // // Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved. // // Please refer to the LICENSE.md file for the terms and conditions // under which redistribution and use of this file is permitted. // import Foundation import Quick import Nimble @testable import Qualaroo class UserResponseAdapterSpec: QuickSpec { override func spec() { super.spec() describe("UserResponseAdapter") { let adapter = UserResponseAdapter() let answerOneModel = AnswerResponse(id: 111, alias: "answer_111_alias", text: "Answer111") let answerTwoModel = AnswerResponse(id: 222, alias: "answer_222_alias", text: "Answer222") let answerThreeModel = AnswerResponse(id: 333, alias: "answer_333_alias", text: "Answer333") let questionOneModel = QuestionResponse(id: 11, alias: "question_11_alias", answerList: [answerOneModel]) let questionTwoModel = QuestionResponse(id: 11, alias: "question_22_alias", answerList: [answerTwoModel, answerThreeModel]) let questionThreeModel = QuestionResponse(id: 33, alias: nil, answerList: [answerOneModel]) context("LeadGenResponse") { it("creates UserResponse from leadGen response with one question") { let leadGenModel = LeadGenResponse(id: 1, alias: "leadGen_1_alias", questionList: [questionOneModel]) let responseModel = NodeResponse.leadGen(leadGenModel) let userResponse = adapter.toUserResponse(responseModel)! expect(userResponse.getQuestionAlias()).to(equal("leadGen_1_alias")) expect(userResponse.getFilledElements()).to(equal(["question_11_alias"])) expect(userResponse.getElementText("question_11_alias")).to(equal("Answer111")) } it("creates UserResponse from leadGen response with two questions") { let leadGenModel = LeadGenResponse(id: 1, alias: "leadGen_1_alias", questionList: [questionOneModel, questionTwoModel]) let responseModel = NodeResponse.leadGen(leadGenModel) let userResponse = adapter.toUserResponse(responseModel)! expect(userResponse.getQuestionAlias()).to(equal("leadGen_1_alias")) expect(userResponse.getFilledElements()).to(equal(["question_11_alias", "question_22_alias"])) expect(userResponse.getElementText("question_11_alias")).to(equal("Answer111")) expect(userResponse.getElementText("question_22_alias")).to(equal("Answer222")) } it("skips questions with no alias") { let leadGenModel = LeadGenResponse(id: 1, alias: "leadGen_1_alias", questionList: [questionOneModel, questionTwoModel, questionThreeModel]) let responseModel = NodeResponse.leadGen(leadGenModel) let userResponse = adapter.toUserResponse(responseModel)! expect(userResponse.getQuestionAlias()).to(equal("leadGen_1_alias")) expect(userResponse.getFilledElements()).to(equal(["question_11_alias", "question_22_alias"])) expect(userResponse.getElementText("question_11_alias")).to(equal("Answer111")) expect(userResponse.getElementText("question_22_alias")).to(equal("Answer222")) } it("doesn't create UserResponse if there is empty alias") { let leadGenModel = LeadGenResponse(id: 1, alias: nil, questionList: [questionOneModel]) let responseModel = NodeResponse.leadGen(leadGenModel) let userResponse = adapter.toUserResponse(responseModel) expect(userResponse).to(beNil()) } } context("QuestionResponse") { it("creates UserResponse from question response with one answer") { let responseModel = NodeResponse.question(questionOneModel) let userResponse = adapter.toUserResponse(responseModel)! expect(userResponse.getQuestionAlias()).to(equal("question_11_alias")) expect(userResponse.getFilledElements()).to(equal(["answer_111_alias"])) expect(userResponse.getElementText("answer_111_alias")).to(equal("Answer111")) } it("creates UserResponse from question response with two answers") { let responseModel = NodeResponse.question(questionTwoModel) let userResponse = adapter.toUserResponse(responseModel)! expect(userResponse.getQuestionAlias()).to(equal("question_22_alias")) expect(userResponse.getFilledElements()).to(equal(["answer_222_alias", "answer_333_alias"])) expect(userResponse.getElementText("answer_222_alias")).to(equal("Answer222")) expect(userResponse.getElementText("answer_333_alias")).to(equal("Answer333")) } it("skips answers with no alias") { let answerModel = AnswerResponse(id: 444, alias: nil, text: "Answer444") let questionModel = QuestionResponse(id: 44, alias: "question_44_alias", answerList: [answerTwoModel, answerThreeModel, answerModel]) let responseModel = NodeResponse.question(questionModel) let userResponse = adapter.toUserResponse(responseModel)! expect(userResponse.getQuestionAlias()).to(equal("question_44_alias")) expect(userResponse.getFilledElements()).to(equal(["answer_222_alias", "answer_333_alias"])) expect(userResponse.getElementText("answer_222_alias")).to(equal("Answer222")) expect(userResponse.getElementText("answer_333_alias")).to(equal("Answer333")) } it("doesn't create UserResponse if there is empty alias") { let responseModel = NodeResponse.question(questionThreeModel) let userResponse = adapter.toUserResponse(responseModel) expect(userResponse).to(beNil()) } } } } }
mit
e2f75b9fb19a3884183a6594c0a9d8f9
54.983471
116
0.581636
4.887446
false
false
false
false
Finb/V2ex-Swift
Common/V2Client.swift
1
1171
// // V2Client.swift // V2ex-Swift // // Created by huangfeng on 1/15/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit import DrawerController class V2Client: NSObject { static let sharedInstance = V2Client() var window : UIWindow? = nil var drawerController :DrawerController? = nil var centerViewController : HomeViewController? = nil var centerNavigation : V2EXNavigationController? = nil // 当前程序中,最上层的 NavigationController var topNavigationController : UINavigationController { get{ return V2Client.getTopNavigationController(V2Client.sharedInstance.centerNavigation!) } } fileprivate class func getTopNavigationController(_ currentNavigationController:UINavigationController) -> UINavigationController { if let topNav = currentNavigationController.visibleViewController?.navigationController{ if topNav != currentNavigationController && topNav.isKind(of: UINavigationController.self){ return getTopNavigationController(topNav) } } return currentNavigationController } }
mit
6d2069efa8abf307eec177b3cc1cb41e
30.944444
135
0.706957
5.251142
false
false
false
false
kingcos/Swift-X-Algorithms
Sort/13-HeapSort/13-HeapSort/Heap.swift
2
2083
// // Heap.swift // 01-Heap // // Created by 买明 on 21/03/2017. // Copyright © 2017 买明. All rights reserved. // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms import Foundation public struct Heap<T>: CustomStringConvertible { var isOrdered: (T, T) -> Bool var capacity: Int var elements: Array<T> var count: Int { return elements.count } var isEmpty: Bool { return elements.isEmpty } public var description: String { return elements.description } init(_ capacity: Int, _ isOrdered: @escaping (T, T) -> Bool) { self.capacity = capacity self.isOrdered = isOrdered self.elements = Array<T>() } private mutating func shiftUp(_ index: Int) { var index = index while index > 0 && isOrdered(elements[index], elements[(index - 1) / 2]) { swap(&elements[index], &elements[(index - 1) / 2]) index = (index - 1) / 2 } } private mutating func shiftDown(_ index: Int) { var index = index while 2 * (index + 1) <= count { var j = 2 * index + 1 if j + 1 < count && isOrdered(elements[j + 1], elements[j]) { j += 1 } if isOrdered(elements[j], elements[index]) { swap(&elements[j], &elements[index]) } index = j } } mutating func insert(_ element: T) { assert(count + 1 <= capacity, "Heap out of capacity.") elements.append(element) shiftUp(count - 1) } mutating func extractExtremum() -> T { assert(!isEmpty, "Heap is Empty") let returnElement = elements[0] if count > 1 { swap(&elements[0], &elements[count - 1]) } elements.removeLast() shiftDown(0) return returnElement } public func getExtremum() -> T { assert(!isEmpty, "Heap is Empty") return elements[0] } }
mit
84ad049a0be94eecc85e4abb381d3264
24.925
86
0.525554
4.148
false
false
false
false
liuxuan30/ios-charts
Source/Charts/Renderers/XAxisRendererRadarChart.swift
7
2902
// // XAxisRendererRadarChart.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics open class XAxisRendererRadarChart: XAxisRenderer { @objc open weak var chart: RadarChartView? @objc public init(viewPortHandler: ViewPortHandler, xAxis: XAxis?, chart: RadarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: nil) self.chart = chart } open override func renderAxisLabels(context: CGContext) { guard let xAxis = axis as? XAxis, let chart = chart else { return } if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled { return } let labelFont = xAxis.labelFont let labelTextColor = xAxis.labelTextColor let labelRotationAngleRadians = xAxis.labelRotationAngle.RAD2DEG let drawLabelAnchor = CGPoint(x: 0.5, y: 0.25) let sliceangle = chart.sliceAngle // calculate the factor that is needed for transforming the value to pixels let factor = chart.factor let center = chart.centerOffsets for i in stride(from: 0, to: chart.data?.maxEntryCountSet?.entryCount ?? 0, by: 1) { let label = xAxis.valueFormatter?.stringForValue(Double(i), axis: xAxis) ?? "" let angle = (sliceangle * CGFloat(i) + chart.rotationAngle).truncatingRemainder(dividingBy: 360.0) let p = center.moving(distance: CGFloat(chart.yRange) * factor + xAxis.labelRotatedWidth / 2.0, atAngle: angle) drawLabel(context: context, formattedLabel: label, x: p.x, y: p.y - xAxis.labelRotatedHeight / 2.0, attributes: [NSAttributedString.Key.font: labelFont, NSAttributedString.Key.foregroundColor: labelTextColor], anchor: drawLabelAnchor, angleRadians: labelRotationAngleRadians) } } @objc open func drawLabel( context: CGContext, formattedLabel: String, x: CGFloat, y: CGFloat, attributes: [NSAttributedString.Key : Any], anchor: CGPoint, angleRadians: CGFloat) { ChartUtils.drawText( context: context, text: formattedLabel, point: CGPoint(x: x, y: y), attributes: attributes, anchor: anchor, angleRadians: angleRadians) } open override func renderLimitLines(context: CGContext) { /// XAxis LimitLines on RadarChart not yet supported. } }
apache-2.0
2af7c43e02ef65d44b31e8b7a119f9f3
30.89011
131
0.58787
5.228829
false
false
false
false
mactive/rw-courses-note
advanced-swift-types-and-operations/TypesAndOps.playground/Pages/Equality.xcplaygroundpage/Contents.swift
1
900
//: [Previous](@previous) import Foundation struct Email: Equatable { // add some validation init?(_ raw: String) { guard raw.contains("@") else { return nil } address = raw } private(set) var address: String } class User: Equatable { var id: Int? var name: String var email: Email init(id: Int?, name: String, email: Email) { self.id = id self.name = name self.email = email } static func ==(lhs: User, rhs: User) -> Bool { return lhs.id == rhs.id && lhs.email == rhs.email && lhs.name == rhs.name } } guard let email = Email("mac@meng.com") else { fatalError("Not valid email") } email.address let user1 = User(id: nil, name: "Ray", email: email) let user2 = User(id: nil, name: "Ray", email: email) user1 == user2 user1 === user2 //: [Next](@next)
mit
15d58938ab102916622df8ed18134deb
19
52
0.554444
3.501946
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Player/LyricLoader.swift
1
2443
// // LyricLoader.swift // MusicApp // // Created by Hưng Đỗ on 6/25/17. // Copyright © 2017 HungDo. All rights reserved. // import RxSwift import RxAlamofire protocol LyricLoader { func load(_ url: String) -> Observable<[Lyric]> } class MALyricLoader: LyricLoader { func load(_ url: String) -> Observable<[Lyric]> { return RxAlamofire.string(.get, url) .flatMap { [weak self] content -> Observable<[Lyric]> in guard let this = self else { return .just([]) } return this.load(encryptedContent: content) .retry(1) .catchErrorJustReturn([]) } } private func load(encryptedContent: String) -> Observable<[Lyric]> { let lyricBaseURL = "http://innoxious-cork.000webhostapp.com/crypto.php" return RxAlamofire.json(.post, lyricBaseURL, parameters: ["text": encryptedContent]) .map { data -> [(content: String, times: [String])] in guard let lyrics = data as? [[String:Any]] else { return [] } return lyrics.map { lyric in guard let content = lyric["lyric"] as? String else { fatalError("Can not get the field 'lyric'") } guard let times = lyric["times"] as? [String] else { fatalError("Can not get the field 'times'") } return (content: content, times: times) } } .map { rawLyrics in rawLyrics.flatMap { content, times in times.map { time in Lyric(time:time.timeToSeconds, content: content) } } } .map { lyrics in lyrics.sorted() } } } fileprivate extension String { var timeToSeconds: Int { let minuteString = substring(to: index(startIndex, offsetBy: 2)) let minute = Int(minuteString) ?? 0 let secondString = substring(with: index(startIndex, offsetBy: 3) ..< index(startIndex, offsetBy: 5)) let second = Int(secondString) ?? 0 let miliSecondString = substring(with: index(endIndex, offsetBy: -2) ..< endIndex) let miliSecond = Int(miliSecondString)! return minute * 60 + second + ((miliSecond > 50) ? 1 : 0) } }
mit
4b9ab99a7895e591dc790cb7c15270ba
32.39726
109
0.529532
4.514815
false
false
false
false
skylib/SnapImagePicker
SnapImagePicker/AlbumSelector/View/AlbumCell.swift
1
1320
import UIKit class AlbumCell: UITableViewCell { @IBOutlet weak var albumPreviewImageView: UIImageView? { didSet { albumPreviewImageView?.contentMode = .scaleAspectFill } } @IBOutlet weak var albumNameLabel: UILabel? @IBOutlet weak var albumSizeLabel: UILabel? var displayFont: UIFont? { didSet { albumNameLabel?.font = displayFont albumSizeLabel?.font = displayFont } } var album: Album? { didSet { if let album = album { albumPreviewImageView?.image = album.image.square() albumSizeLabel?.text = formatSizeLabelText(album.size) if album.albumName == AlbumType.allPhotos.getAlbumName() { albumNameLabel?.text = L10n.allPhotosAlbumName.string } else if album.albumName == AlbumType.favorites.getAlbumName() { albumNameLabel?.text = L10n.favoritesAlbumName.string } else { albumNameLabel?.text = album.albumName } } } } fileprivate func formatSizeLabelText(_ size: Int) -> String { return String(size) + " " + ((size == 1) ? L10n.imageLabelText.string : L10n.severalImagesLabelText.string) } }
bsd-3-clause
6f59243af915367dbf3d9332c1748245
34.675676
116
0.580303
4.852941
false
false
false
false
DashiDashCam/iOS-App
Dashi/Dashi/Controllers/SignupViewController.swift
1
4568
// // SignupViewController.swift // Dashi // // Created by Arslan Memon on 11/5/17. // Copyright © 2017 Senior Design. All rights reserved. // import UIKit import PromiseKit import SwiftyJSON class SignupViewController: UIViewController { @IBOutlet weak var name: UITextField! @IBOutlet weak var email: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var confirm: UITextField! @IBOutlet weak var signUpButton: UIButton! @IBOutlet weak var errorMessage: UILabel! @IBAction func exitPushed(_: Any) { dismiss(animated: true, completion: nil) // performSegue(withIdentifier: "signupSegue", sender: self) } override func viewDidLoad() { super.viewDidLoad() updateConstraints() // Do any additional setup after loading the view. // done button above keyboard let toolBar = UIToolbar() toolBar.sizeToFit() let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.done, target: self, action: #selector(self.doneClicked)) toolBar.setItems([doneButton], animated: true) name.inputAccessoryView = toolBar email.inputAccessoryView = toolBar password.inputAccessoryView = toolBar confirm.inputAccessoryView = toolBar // set orientation let value = UIInterfaceOrientation.portrait.rawValue UIDevice.current.setValue(value, forKey: "orientation") // lock orientation AppUtility.lockOrientation(.portrait) } @objc func doneClicked() { view.endEditing(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func signUpPushed(_: Any) { errorMessage.text = "" if password.text! == confirm.text! { DashiAPI.createAccount(email: email.text!, password: password.text!, fullName: name.text!).then { _ -> Void in DashiAPI.loginWithPassword(username: self.email.text!, password: self.password.text!).then { _ -> Void in self.performSegue(withIdentifier: "unwindFromSignUp", sender: self) } }.catch { error in if let e = error as? DashiServiceError { let json = JSON(e.body) if json["errors"].array != nil { self.errorMessage.text = json["errors"].arrayValue[0]["message"].string } else { self.errorMessage.text = json["errors"]["message"].string } } } } else { errorMessage.text = "Password and Confirm Password do not match" } } override func willTransition(to _: UITraitCollection, with _: UIViewControllerTransitionCoordinator) { updateConstraints() } // updates the hardcoded contraints associated with this view func updateConstraints() { // loop through view constraints for constraint in view.constraints { // the device is in landscape if UIDevice.current.orientation == .landscapeLeft || UIDevice.current.orientation == .landscapeRight { // margin above sign up button if constraint.identifier == "signUpMarginTop" { constraint.constant = 0 signUpButton.titleLabel?.font = UIFont.systemFont(ofSize: 20) } } else { // margin above sign up button if constraint.identifier == "signUpMarginTop" { constraint.constant = 20 } } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension SignupViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { switch textField { case name: email.becomeFirstResponder() case email: password.becomeFirstResponder() case password: confirm.becomeFirstResponder() default: confirm.resignFirstResponder() } return true } }
mit
9ace601bcfd9cb544905e333672bc5f8
32.335766
140
0.609591
5.411137
false
false
false
false
february29/Learning
swift/ReactiveCocoaDemo/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift
132
2164
// // DefaultIfEmpty.swift // RxSwift // // Created by sergdort on 23/12/2016. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Emits elements from the source observable sequence, or a default element if the source observable sequence is empty. - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) - parameter default: Default element to be sent if the source does not emit any elements - returns: An observable sequence which emits default element end completes in case the original sequence is empty */ public func ifEmpty(default: E) -> Observable<E> { return DefaultIfEmpty(source: self.asObservable(), default: `default`) } } final fileprivate class DefaultIfEmptySink<O: ObserverType>: Sink<O>, ObserverType { typealias E = O.E private let _default: E private var _isEmpty = true init(default: E, observer: O, cancel: Cancelable) { _default = `default` super.init(observer: observer, cancel: cancel) } func on(_ event: Event<E>) { switch event { case .next(_): _isEmpty = false forwardOn(event) case .error(_): forwardOn(event) dispose() case .completed: if _isEmpty { forwardOn(.next(_default)) } forwardOn(.completed) dispose() } } } final fileprivate class DefaultIfEmpty<SourceType>: Producer<SourceType> { private let _source: Observable<SourceType> private let _default: SourceType init(source: Observable<SourceType>, `default`: SourceType) { _source = source _default = `default` } override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == SourceType { let sink = DefaultIfEmptySink(default: _default, observer: observer, cancel: cancel) let subscription = _source.subscribe(sink) return (sink: sink, subscription: subscription) } }
mit
0a4d12af9d55b907f6d9809906cdc96e
31.772727
147
0.63939
4.582627
false
false
false
false
at-internet/atinternet-ios-swift-sdk
Tracker/Tracker/RichMedia.swift
1
6818
/* This SDK is licensed under the MIT license (MIT) Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France) 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. */ // // RichMedia.swift // Tracker // import UIKit public class RichMedia : BusinessObject { /// Rich media broadcast type public enum BroadcastMode: String { case Clip = "clip" case Live = "live" } /// Rich media hit status public enum Action: String { case Play = "play" case Pause = "pause" case Stop = "stop" case Move = "move" case Refresh = "refresh" } /// Player instance var player: MediaPlayer /// Refresh timer var timer: Timer? /// Media is buffering public var isBuffering: Bool? /// Media is embedded in app public var isEmbedded: Bool? /// Media is live or clip var broadcastMode: BroadcastMode = BroadcastMode.Clip /// Media name public var name: String = "" /// First chapter public var chapter1: String? /// Second chapter public var chapter2: String? /// Third chapter public var chapter3: String? /// Level 2 public var level2: Int? /// Refresh Duration var refreshDuration: Int = 5 /// Action public var action: Action = Action.Play /// Web domain public var webdomain: String? init(player: MediaPlayer) { self.player = player super.init(tracker: player.tracker) } /// Set parameters in buffer override func setEvent() { let encodingOption = ParamOption() encodingOption.encode = true self.tracker = self.tracker.setParam("p", value: buildMediaName(), options: encodingOption) .setParam("plyr", value: player.playerId) .setParam("m6", value: broadcastMode.rawValue) .setParam("a", value: action.rawValue) if let optIsEmbedded = self.isEmbedded { _ = self.tracker.setParam("m5", value: optIsEmbedded ? "ext" : "int") } if let optLevel2 = self.level2 { _ = self.tracker.setParam("s2", value: optLevel2) } if(action == Action.Play) { if let optIsBuffering = self.isBuffering { _ = self.tracker.setParam("buf", value: optIsBuffering ? 1 : 0) } if let optIsEmbedded = self.isEmbedded { if (optIsEmbedded) { if let optWebDomain = self.webdomain { _ = self.tracker.setParam("m9", value: optWebDomain) } } else { if TechnicalContext.screenName != "" { _ = self.tracker.setParam("prich", value: TechnicalContext.screenName, options: encodingOption) } if TechnicalContext.level2 > 0 { _ = self.tracker.setParam("s2rich", value: TechnicalContext.level2) } } } } } /// Media name building func buildMediaName() -> String { var mediaName = chapter1 == nil ? "" : chapter1! + "::" mediaName = chapter2 == nil ? mediaName : mediaName + chapter2! + "::" mediaName = chapter3 == nil ? mediaName : mediaName + chapter3! + "::" mediaName += name return mediaName } /** Send hit when media is played Refresh is enabled with default duration */ public func sendPlay() { self.action = Action.Play self.tracker.dispatcher.dispatch([self]) self.initRefresh() } /** Send hit when media is played Refresh is enabled if resfreshDuration is not equal to 0 - parameter resfreshDuration: duration between refresh hits */ public func sendPlay(_ refreshDuration: Int) { self.action = Action.Play self.tracker.dispatcher.dispatch([self]) if (refreshDuration != 0) { if (refreshDuration > 5) { self.refreshDuration = refreshDuration } self.initRefresh() } } /** Send hit when media is paused */ public func sendPause(){ if let timer = self.timer { if timer.isValid { timer.invalidate() self.timer = nil } } self.action = Action.Pause self.tracker.dispatcher.dispatch([self]) } /** Send hit when media is stopped */ public func sendStop() { if let timer = self.timer { if timer.isValid { timer.invalidate() self.timer = nil } } self.action = Action.Stop self.tracker.dispatcher.dispatch([self]) } /** Send hit when media cursor position is moved */ public func sendMove() { self.action = Action.Move self.tracker.dispatcher.dispatch([self]) } /// Start the refresh timer func initRefresh() { if self.timer == nil { self.timer = Timer.scheduledTimer( timeInterval: TimeInterval(self.refreshDuration), target: self, selector: #selector(RichMedia.sendRefresh), userInfo: nil, repeats: true) } } /// Medthod called on the timer tick @objc func sendRefresh() { self.action = Action.Refresh self.tracker.dispatcher.dispatch([self]) } }
mit
be8bdf171b865f14227bd5a56990f6a9
27.4
153
0.571596
4.766434
false
false
false
false
rafaelcpalmeida/UFP-iOS
UFP/UFP/Carthage/Checkouts/Alamofire/Tests/ResponseSerializationTests.swift
12
39115
// // ResponseSerializationTests.swift // // Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Alamofire import Foundation import XCTest private func httpURLResponse(forStatusCode statusCode: Int, headers: HTTPHeaders = [:]) -> HTTPURLResponse { let url = URL(string: "https://httpbin.org/get")! return HTTPURLResponse(url: url, statusCode: statusCode, httpVersion: "HTTP/1.1", headerFields: headers)! } // MARK: - class DataResponseSerializationTestCase: BaseTestCase { // MARK: Properties private let error = AFError.responseSerializationFailed(reason: .inputDataNil) // MARK: Tests - Data Response Serializer func testThatDataResponseSerializerSucceedsWhenDataIsNotNil() { // Given let serializer = DataRequest.dataResponseSerializer() let data = "data".data(using: .utf8)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatDataResponseSerializerFailsWhenDataIsNil() { // Given let serializer = DataRequest.dataResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNil) } else { XCTFail("error should not be nil") } } func testThatDataResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = DataRequest.dataResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, error) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNil) } else { XCTFail("error should not be nil") } } func testThatDataResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { // Given let serializer = DataRequest.dataResponseSerializer() let response = httpURLResponse(forStatusCode: 200) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isFailure, "result is failure should be true") XCTAssertNil(result.value, "result value should be nil") XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNil) } else { XCTFail("error should not be nil") } } func testThatDataResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseStatusCode() { // Given let serializer = DataRequest.dataResponseSerializer() let response = httpURLResponse(forStatusCode: 204) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) if let data = result.value { XCTAssertEqual(data.count, 0) } } // MARK: Tests - String Response Serializer func testThatStringResponseSerializerFailsWhenDataIsNil() { // Given let serializer = DataRequest.stringResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNil) } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerSucceedsWhenDataIsEmpty() { // Given let serializer = DataRequest.stringResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, Data(), nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatStringResponseSerializerSucceedsWithUTF8DataAndNoProvidedEncoding() { let serializer = DataRequest.stringResponseSerializer() let data = "data".data(using: .utf8)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatStringResponseSerializerSucceedsWithUTF8DataAndUTF8ProvidedEncoding() { let serializer = DataRequest.stringResponseSerializer(encoding: .utf8) let data = "data".data(using: .utf8)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatStringResponseSerializerSucceedsWithUTF8DataUsingResponseTextEncodingName() { let serializer = DataRequest.stringResponseSerializer() let data = "data".data(using: .utf8)! let response = httpURLResponse(forStatusCode: 200, headers: ["Content-Type": "image/jpeg; charset=utf-8"]) // When let result = serializer.serializeResponse(nil, response, data, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ProvidedEncoding() { // Given let serializer = DataRequest.stringResponseSerializer(encoding: .utf8) let data = "random data".data(using: .utf32)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError, let failedEncoding = error.failedStringEncoding { XCTAssertTrue(error.isStringSerializationFailed) XCTAssertEqual(failedEncoding, .utf8) } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ResponseEncoding() { // Given let serializer = DataRequest.stringResponseSerializer() let data = "random data".data(using: .utf32)! let response = httpURLResponse(forStatusCode: 200, headers: ["Content-Type": "image/jpeg; charset=utf-8"]) // When let result = serializer.serializeResponse(nil, response, data, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError, let failedEncoding = error.failedStringEncoding { XCTAssertTrue(error.isStringSerializationFailed) XCTAssertEqual(failedEncoding, .utf8) } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = DataRequest.stringResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, error) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNil) } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { // Given let serializer = DataRequest.stringResponseSerializer() let response = httpURLResponse(forStatusCode: 200) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNil) } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseStatusCode() { // Given let serializer = DataRequest.stringResponseSerializer() let response = httpURLResponse(forStatusCode: 205) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) if let string = result.value { XCTAssertEqual(string, "") } } // MARK: Tests - JSON Response Serializer func testThatJSONResponseSerializerFailsWhenDataIsNil() { // Given let serializer = DataRequest.jsonResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNilOrZeroLength) } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerFailsWhenDataIsEmpty() { // Given let serializer = DataRequest.jsonResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, Data(), nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNilOrZeroLength) } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerSucceedsWhenDataIsValidJSON() { // Given let serializer = DataRequest.jsonResponseSerializer() let data = "{\"json\": true}".data(using: .utf8)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatJSONResponseSerializerFailsWhenDataIsInvalidJSON() { // Given let serializer = DataRequest.jsonResponseSerializer() let data = "definitely not valid json".data(using: .utf8)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError, let underlyingError = error.underlyingError as? CocoaError { XCTAssertTrue(error.isJSONSerializationFailed) XCTAssertEqual(underlyingError.errorCode, 3840) } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = DataRequest.jsonResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, error) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNil) } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { // Given let serializer = DataRequest.jsonResponseSerializer() let response = httpURLResponse(forStatusCode: 200) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNilOrZeroLength) } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseStatusCode() { // Given let serializer = DataRequest.jsonResponseSerializer() let response = httpURLResponse(forStatusCode: 204) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) if let json = result.value as? NSNull { XCTAssertEqual(json, NSNull()) } } // MARK: Tests - Property List Response Serializer func testThatPropertyListResponseSerializerFailsWhenDataIsNil() { // Given let serializer = DataRequest.propertyListResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNilOrZeroLength) } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerFailsWhenDataIsEmpty() { // Given let serializer = DataRequest.propertyListResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, Data(), nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNilOrZeroLength) } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerSucceedsWhenDataIsValidPropertyListData() { // Given let serializer = DataRequest.propertyListResponseSerializer() let data = NSKeyedArchiver.archivedData(withRootObject: ["foo": "bar"]) // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatPropertyListResponseSerializerFailsWhenDataIsInvalidPropertyListData() { // Given let serializer = DataRequest.propertyListResponseSerializer() let data = "definitely not valid plist data".data(using: .utf8)! // When let result = serializer.serializeResponse(nil, nil, data, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError, let underlyingError = error.underlyingError as? CocoaError { XCTAssertTrue(error.isPropertyListSerializationFailed) XCTAssertEqual(underlyingError.errorCode, 3840) } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = DataRequest.propertyListResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, error) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNil) } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { // Given let serializer = DataRequest.propertyListResponseSerializer() let response = httpURLResponse(forStatusCode: 200) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNilOrZeroLength) } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseStatusCode() { // Given let serializer = DataRequest.propertyListResponseSerializer() let response = httpURLResponse(forStatusCode: 205) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) if let plist = result.value as? NSNull { XCTAssertEqual(plist, NSNull()) } } } // MARK: - class DownloadResponseSerializationTestCase: BaseTestCase { // MARK: Properties private let error = AFError.responseSerializationFailed(reason: .inputFileNil) private var jsonEmptyDataFileURL: URL { return url(forResource: "empty_data", withExtension: "json") } private var jsonValidDataFileURL: URL { return url(forResource: "valid_data", withExtension: "json") } private var jsonInvalidDataFileURL: URL { return url(forResource: "invalid_data", withExtension: "json") } private var plistEmptyDataFileURL: URL { return url(forResource: "empty", withExtension: "data") } private var plistValidDataFileURL: URL { return url(forResource: "valid", withExtension: "data") } private var plistInvalidDataFileURL: URL { return url(forResource: "invalid", withExtension: "data") } private var stringEmptyDataFileURL: URL { return url(forResource: "empty_string", withExtension: "txt") } private var stringUTF8DataFileURL: URL { return url(forResource: "utf8_string", withExtension: "txt") } private var stringUTF32DataFileURL: URL { return url(forResource: "utf32_string", withExtension: "txt") } private var invalidFileURL: URL { return URL(fileURLWithPath: "/this/file/does/not/exist.txt") } // MARK: Tests - Data Response Serializer func testThatDataResponseSerializerSucceedsWhenFileDataIsNotNil() { // Given let serializer = DownloadRequest.dataResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, jsonValidDataFileURL, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatDataResponseSerializerSucceedsWhenFileDataIsNil() { // Given let serializer = DownloadRequest.dataResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, jsonEmptyDataFileURL, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatDataResponseSerializerFailsWhenFileURLIsNil() { // Given let serializer = DownloadRequest.dataResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputFileNil) } else { XCTFail("error should not be nil") } } func testThatDataResponseSerializerFailsWhenFileURLIsInvalid() { // Given let serializer = DownloadRequest.dataResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, invalidFileURL, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputFileReadFailed) } else { XCTFail("error should not be nil") } } func testThatDataResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = DownloadRequest.dataResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, error) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputFileNil) } else { XCTFail("error should not be nil") } } func testThatDataResponseSerializerFailsWhenFileURLIsNilWithNonEmptyResponseStatusCode() { // Given let serializer = DownloadRequest.dataResponseSerializer() let response = httpURLResponse(forStatusCode: 200) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputFileNil) } else { XCTFail("error should not be nil") } } func testThatDataResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseStatusCode() { // Given let serializer = DataRequest.dataResponseSerializer() let response = httpURLResponse(forStatusCode: 205) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) if let data = result.value { XCTAssertEqual(data.count, 0) } } // MARK: Tests - String Response Serializer func testThatStringResponseSerializerFailsWhenFileURLIsNil() { // Given let serializer = DownloadRequest.stringResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputFileNil) } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerFailsWhenFileURLIsInvalid() { // Given let serializer = DownloadRequest.stringResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, invalidFileURL, nil) // Then XCTAssertEqual(result.isSuccess, false) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputFileReadFailed) } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerSucceedsWhenFileDataIsEmpty() { // Given let serializer = DownloadRequest.stringResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, stringEmptyDataFileURL, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatStringResponseSerializerSucceedsWithUTF8DataAndNoProvidedEncoding() { let serializer = DownloadRequest.stringResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, stringUTF8DataFileURL, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatStringResponseSerializerSucceedsWithUTF8DataAndUTF8ProvidedEncoding() { let serializer = DownloadRequest.stringResponseSerializer(encoding: .utf8) // When let result = serializer.serializeResponse(nil, nil, stringUTF8DataFileURL, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatStringResponseSerializerSucceedsWithUTF8DataUsingResponseTextEncodingName() { let serializer = DownloadRequest.stringResponseSerializer() let response = httpURLResponse(forStatusCode: 200, headers: ["Content-Type": "image/jpeg; charset=utf-8"]) // When let result = serializer.serializeResponse(nil, response, stringUTF8DataFileURL, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ProvidedEncoding() { // Given let serializer = DownloadRequest.stringResponseSerializer(encoding: .utf8) // When let result = serializer.serializeResponse(nil, nil, stringUTF32DataFileURL, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError, let failedEncoding = error.failedStringEncoding { XCTAssertTrue(error.isStringSerializationFailed) XCTAssertEqual(failedEncoding, .utf8) } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerFailsWithUTF32DataAndUTF8ResponseEncoding() { // Given let serializer = DownloadRequest.stringResponseSerializer() let response = httpURLResponse(forStatusCode: 200, headers: ["Content-Type": "image/jpeg; charset=utf-8"]) // When let result = serializer.serializeResponse(nil, response, stringUTF32DataFileURL, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError, let failedEncoding = error.failedStringEncoding { XCTAssertTrue(error.isStringSerializationFailed) XCTAssertEqual(failedEncoding, .utf8) } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = DownloadRequest.stringResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, error) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputFileNil) } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { // Given let serializer = DataRequest.stringResponseSerializer() let response = httpURLResponse(forStatusCode: 200) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNil) } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseStatusCode() { // Given let serializer = DataRequest.stringResponseSerializer() let response = httpURLResponse(forStatusCode: 204) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) if let string = result.value { XCTAssertEqual(string, "") } } // MARK: Tests - JSON Response Serializer func testThatJSONResponseSerializerFailsWhenFileURLIsNil() { // Given let serializer = DownloadRequest.jsonResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputFileNil) } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerFailsWhenFileURLIsInvalid() { // Given let serializer = DownloadRequest.jsonResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, invalidFileURL, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputFileReadFailed) } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerFailsWhenFileDataIsEmpty() { // Given let serializer = DownloadRequest.jsonResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, jsonEmptyDataFileURL, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNilOrZeroLength) } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerSucceedsWhenDataIsValidJSON() { // Given let serializer = DownloadRequest.jsonResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, jsonValidDataFileURL, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatJSONResponseSerializerFailsWhenDataIsInvalidJSON() { // Given let serializer = DownloadRequest.jsonResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, jsonInvalidDataFileURL, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError, let underlyingError = error.underlyingError as? CocoaError { XCTAssertTrue(error.isJSONSerializationFailed) XCTAssertEqual(underlyingError.errorCode, 3840) } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = DownloadRequest.jsonResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, error) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputFileNil) } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { // Given let serializer = DataRequest.jsonResponseSerializer() let response = httpURLResponse(forStatusCode: 200) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNilOrZeroLength) } else { XCTFail("error should not be nil") } } func testThatJSONResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseStatusCode() { // Given let serializer = DataRequest.jsonResponseSerializer() let response = httpURLResponse(forStatusCode: 205) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) if let json = result.value as? NSNull { XCTAssertEqual(json, NSNull()) } } // MARK: Tests - Property List Response Serializer func testThatPropertyListResponseSerializerFailsWhenFileURLIsNil() { // Given let serializer = DownloadRequest.propertyListResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputFileNil) } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerFailsWhenFileURLIsInvalid() { // Given let serializer = DownloadRequest.propertyListResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, invalidFileURL, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputFileReadFailed) } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerFailsWhenFileDataIsEmpty() { // Given let serializer = DownloadRequest.propertyListResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, plistEmptyDataFileURL, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNilOrZeroLength) } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerSucceedsWhenFileDataIsValidPropertyListData() { // Given let serializer = DownloadRequest.propertyListResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, plistValidDataFileURL, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) } func testThatPropertyListResponseSerializerFailsWhenDataIsInvalidPropertyListData() { // Given let serializer = DownloadRequest.propertyListResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, plistInvalidDataFileURL, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError, let underlyingError = error.underlyingError as? CocoaError { XCTAssertTrue(error.isPropertyListSerializationFailed) XCTAssertEqual(underlyingError.errorCode, 3840) } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerFailsWhenErrorIsNotNil() { // Given let serializer = DownloadRequest.propertyListResponseSerializer() // When let result = serializer.serializeResponse(nil, nil, nil, error) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputFileNil) } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { // Given let serializer = DataRequest.propertyListResponseSerializer() let response = httpURLResponse(forStatusCode: 200) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error as? AFError { XCTAssertTrue(error.isInputDataNilOrZeroLength) } else { XCTFail("error should not be nil") } } func testThatPropertyListResponseSerializerSucceedsWhenDataIsNilWith204ResponseStatusCode() { // Given let serializer = DataRequest.propertyListResponseSerializer() let response = httpURLResponse(forStatusCode: 204) // When let result = serializer.serializeResponse(nil, response, nil, nil) // Then XCTAssertTrue(result.isSuccess) XCTAssertNotNil(result.value) XCTAssertNil(result.error) if let plist = result.value as? NSNull { XCTAssertEqual(plist, NSNull(), "plist should be equal to NSNull") } } }
mit
b97a7a1e81e893f9f6271a2cc570ab9f
31.487542
114
0.655273
5.607081
false
true
false
false
jwalapr/Routing
Source/iOS.swift
1
7634
import UIKit import QuartzCore public enum ControllerSource { case storyboard(storyboard: String, identifier: String, bundle: Bundle?) case nib(controller: UIViewController.Type, name: String?, bundle: Bundle?) case provided(() -> UIViewController) } public indirect enum PresentationStyle { case show case showDetail case present(animated: Bool) case push(animated: Bool) case custom(custom: (_ presenting: UIViewController, _ presented: UIViewController, _ completed: Completed) -> Void) case inNavigationController(PresentationStyle) } public typealias PresentationSetup = (UIViewController, Parameters, Any?) -> Void public protocol RoutingPresentationSetup { func setup(_ route: String, with parameters: Parameters, passing any: Any?) } public extension UINavigationController { func pushViewController(_ vc: UIViewController, animated: Bool, completion: @escaping Completed) { self.commit(completion) { self.pushViewController(vc, animated: animated) } } @discardableResult func popViewControllerAnimated(_ animated: Bool, completion: @escaping Completed) -> UIViewController? { var vc: UIViewController? self.commit(completion) { vc = self.popViewController(animated: animated) } return vc } @discardableResult func popToViewControllerAnimated(_ viewController: UIViewController, animated: Bool, completion: @escaping Completed) -> [UIViewController]? { var vc: [UIViewController]? self.commit(completion) { vc = self.popToViewController(viewController, animated: animated) } return vc } @discardableResult func popToRootViewControllerAnimated(_ animated: Bool, completion: @escaping Completed) -> [UIViewController]? { var vc: [UIViewController]? self.commit(completion) { vc = self.popToRootViewController(animated: animated) } return vc } } public extension UIViewController { func showViewController(_ vc: UIViewController, sender: AnyObject?, completion: @escaping Completed) { self.commit(completion) { self.show(vc, sender: sender) } } func showDetailViewController(_ vc: UIViewController, sender: AnyObject?, completion: @escaping Completed) { self.commit(completion) { self.showDetailViewController(vc, sender: sender) } } fileprivate func commit(_ completed: @escaping Completed, transition: () -> Void) { CATransaction.begin() CATransaction.setCompletionBlock(completed) transition() CATransaction.commit() } } @objc internal protocol ControllerIterator { @objc func nextViewController() -> UIViewController? } extension UITabBarController { @objc internal override func nextViewController() -> UIViewController? { return selectedViewController } } extension UINavigationController { @objc internal override func nextViewController() -> UIViewController? { return visibleViewController } } extension UIViewController : ControllerIterator { internal func nextViewController() -> UIViewController? { return presentedViewController } } public extension Routing { /** Associates a view controller presentation to a string pattern. A Routing instance present the view controller in the event of a matching URL using #open. Routing will only execute the first matching mapped route. This will be the last route added with #map. ```code let router = Routing() router.map("routingexample://route", instance: .Storyboard(storyboard: "Main", identifier: "ViewController", bundle: nil), style: .Present(animated: true)) { vc, parameters in ... // Useful callback for setup such as embedding in navigation controller return vc } ``` - Parameter pattern: A String pattern - Parameter tag: A tag to reference when subscripting a Routing object - Parameter owner: The routes owner. If deallocated the route will be removed. - Parameter source: The source of the view controller instance - Parameter style: The presentation style in presenting the view controller - Parameter setup: A closure provided for additional setup - Returns: The RouteUUID */ @discardableResult func map(_ pattern: String, tags: [String] = ["Views"], owner: RouteOwner? = nil, source: ControllerSource, style: PresentationStyle = .show, setup: PresentationSetup? = nil) -> RouteUUID { let routeHandler: RouteHandler = { [unowned self] (route, parameters, any, completed) in guard let root = UIApplication.shared.keyWindow?.rootViewController else { completed() return } let strongSelf = self let vc = strongSelf.controller(from: source) (vc as? RoutingPresentationSetup)?.setup(route, with: parameters, passing: any) setup?(vc, parameters, any) var presenter = root while let nextVC = presenter.nextViewController() { presenter = nextVC } strongSelf.showController(vc, from: presenter, with: style, completion: completed) } return map(pattern, tags: tags, queue: DispatchQueue.main, owner: owner, handler: routeHandler) } private func controller(from source: ControllerSource) -> UIViewController { switch source { case let .storyboard(storyboard, identifier, bundle): let storyboard = UIStoryboard(name: storyboard, bundle: bundle) return storyboard.instantiateViewController(withIdentifier: identifier) case let .nib(controller, name, bundle): return controller.init(nibName: name, bundle: bundle) case let .provided(provider): return provider() } } private func showController(_ presented: UIViewController, from presenting: UIViewController, with style: PresentationStyle, completion: @escaping Completed) { switch style { case .show: presenting.showViewController(presented, sender: self, completion: completion) break case .showDetail: presenting.showDetailViewController(presented, sender: self, completion: completion) break case let .present(animated): presenting.present(presented, animated: animated, completion: completion) break case let .push(animated): if let presenting = presenting as? UINavigationController { presenting.pushViewController(presented, animated: animated, completion: completion) } else { presenting.navigationController?.pushViewController(presented, animated: animated, completion: completion) } case let .custom(custom): custom(presenting, presented, completion) break case let .inNavigationController(style): showController(UINavigationController(rootViewController: presented), from: presenting, with: style, completion: completion) break } } }
mit
426a4d7dd817ba685398848d3306ff1c
36.239024
146
0.640162
5.572263
false
false
false
false
SwiftGen/SwiftGen
Package.swift
1
2686
// swift-tools-version:5.6 import PackageDescription let package = Package( name: "SwiftGen", platforms: [ .macOS(.v10_11), ], products: [ .executable(name: "swiftgen", targets: ["SwiftGen"]), .library(name: "SwiftGenCLI", targets: ["SwiftGenCLI"]), .library(name: "SwiftGenKit", targets: ["SwiftGenKit"]), ], dependencies: [ .package(url: "https://github.com/apple/swift-argument-parser.git", from: "1.1.3"), .package(url: "https://github.com/jpsim/Yams.git", from: "5.0.1"), .package(url: "https://github.com/kylef/PathKit.git", from: "1.0.1"), .package(url: "https://github.com/krzysztofzablocki/Difference.git", branch: "master"), .package(url: "https://github.com/stencilproject/Stencil.git", from: "0.15.1"), .package(url: "https://github.com/shibapm/Komondor.git", exact: "1.1.3"), .package(url: "https://github.com/SwiftGen/StencilSwiftKit.git", from: "2.10.1"), .package(url: "https://github.com/tid-kijyun/Kanna.git", from: "5.2.7") ], targets: [ .executableTarget(name: "SwiftGen", dependencies: [ "SwiftGenCLI" ]), .target(name: "SwiftGenCLI", dependencies: [ .product(name: "ArgumentParser", package: "swift-argument-parser"), "Kanna", "PathKit", "Stencil", "StencilSwiftKit", "SwiftGenKit", "Yams" ], resources: [ .copy("templates") ]), .target(name: "SwiftGenKit", dependencies: [ "Kanna", "PathKit", "Stencil", "Yams" ]), .testTarget(name: "SwiftGenKitTests", dependencies: [ "SwiftGenKit", "TestUtils" ]), .testTarget(name: "SwiftGenTests", dependencies: [ "SwiftGenCLI", "TestUtils" ]), .testTarget(name: "TemplatesTests", dependencies: [ "StencilSwiftKit", "SwiftGenKit", "TestUtils" ]), .target(name: "TestUtils", dependencies: [ "Difference", "PathKit", "SwiftGenKit", "SwiftGenCLI" ], exclude: [ "Fixtures/CompilationEnvironment" ], resources: [ .copy("Fixtures/Configs"), .copy("Fixtures/Generated"), .copy("Fixtures/Resources"), .copy("Fixtures/StencilContexts") ]) ], swiftLanguageVersions: [.v5] ) #if canImport(PackageConfig) import PackageConfig let config = PackageConfiguration([ "komondor": [ "pre-commit": [ "PATH=\"~/.rbenv/shims:$PATH\" bundler exec rake lint:code", "PATH=\"~/.rbenv/shims:$PATH\" bundler exec rake lint:tests", "PATH=\"~/.rbenv/shims:$PATH\" bundler exec rake lint:output" ], "pre-push": [ "PATH=\"~/.rbenv/shims:$PATH\" bundle exec rake spm:test" ] ], ]).write() #endif
mit
79300b539059c5a2bfe27f1c6058f4c0
28.844444
91
0.601638
3.439181
false
true
false
false
paoloiulita/AbstractNumericStepper
Example/Tests/Tests.swift
1
1189
// https://github.com/Quick/Quick import Quick import Nimble import AbstractNumericStepper class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
69414864915469195fac1d9945731d98
22.66
63
0.370245
5.502326
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/BuySellUIKit/Card/CardDetails/CardDetailsScreenInteractor.swift
1
1614
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import DIKit import FeatureCardPaymentDomain import PlatformKit import RIBs import RxSwift final class CardDetailsScreenInteractor: Interactor { // MARK: - Properties var supportedCardTypes: Single<Set<CardType>> { paymentMethodsService.supportedCardTypes } private let paymentMethodsService: PaymentMethodsServiceAPI private let cardListService: CardListServiceAPI private let routingInteractor: CardRouterInteractor private let cardService: CardServiceAPI // MARK: - Setup init( routingInteractor: CardRouterInteractor, paymentMethodsService: PaymentMethodsServiceAPI = resolve(), cardListService: CardListServiceAPI = resolve(), cardService: CardServiceAPI = resolve() ) { self.routingInteractor = routingInteractor self.paymentMethodsService = paymentMethodsService self.cardListService = cardListService self.cardService = cardService self.cardService.isEnteringDetails = true } func doesCardExist(number: String, expiryMonth: String, expiryYear: String) -> Single<Bool> { cardListService .doesCardExist(number: number, expiryMonth: expiryMonth, expiryYear: expiryYear) .asSingle() } func addBillingAddress(to cardData: CardData) { routingInteractor.addBillingAddress(to: cardData) cardService.isEnteringDetails = false } func cancel() { routingInteractor.previousRelay.accept(()) cardService.isEnteringDetails = false } }
lgpl-3.0
a91ce748cb2e320f897ded4e0787ebb7
30.019231
97
0.717917
5.136943
false
false
false
false
blockchain/My-Wallet-V3-iOS
Blockchain/Wallet/SecondPassword/SecondPasswordHelper.swift
1
2414
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import FeatureAppUI import UIComponentsKit /// Provides a prompt mechanism for second password protocol SecondPasswordHelperAPI: AnyObject { /// - type: The type of the screen /// - confirmHandler: Confirmation handler, receives the password /// - dismissHandler: Dismiss handler (optional - defaults to `nil`) func showPasswordScreen( type: PasswordScreenType, confirmHandler: @escaping (String) -> Void, dismissHandler: (() -> Void)? ) } protocol SecondPasswordPresenterHelper { /// Boolean to determine whether the second password screen is displayed or not var isShowingSecondPasswordScreen: Bool { get set } } /// A temporary helper class that acts as a coordinator/router for displaying the `SecondPasswordController` when needed final class SecondPasswordHelper: SecondPasswordHelperAPI, SecondPasswordPresenterHelper { // MARK: - Private Properties var isShowingSecondPasswordScreen: Bool = false // MARK: - SecondPasswordPrompterAPI func showPasswordScreen( type: PasswordScreenType, confirmHandler: @escaping (String) -> Void, dismissHandler: (() -> Void)? = nil ) { guard !isShowingSecondPasswordScreen else { return } guard let parent = UIApplication.shared.topMostViewController else { return } isShowingSecondPasswordScreen = true let navigationController = UINavigationController() let confirm: (String) -> Void = { [weak navigationController] password in navigationController?.dismiss(animated: true) { confirmHandler(password) } } let dismiss: (() -> Void) = { [weak navigationController] in navigationController?.dismiss(animated: true) { dismissHandler?() } } // loadingViewPresenter.hide() let interactor = PasswordScreenInteractor(type: type) let presenter = PasswordScreenPresenter( interactor: interactor, confirmHandler: confirm, dismissHandler: dismiss ) let viewController = PasswordViewController(presenter: presenter) navigationController.viewControllers = [viewController] parent.present(navigationController, animated: true, completion: nil) } }
lgpl-3.0
f6f3fd81a18d2500b7b31731c44596b4
34.485294
120
0.671778
5.446953
false
false
false
false
cfilipov/MuscleBook
MuscleBook/CalendarWeekCell.swift
1
4187
/* Muscle Book Copyright (C) 2016 Cristian Filipov This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ import Foundation import Eureka import CVCalendar class CalendarWeekCell : Cell<NSDate>, CellType, CVCalendarViewDelegate , CVCalendar.MenuViewDelegate, CVCalendarViewAppearanceDelegate { let cal = NSCalendar.currentCalendar() var numberOfDotsForDate: NSDate -> Int @IBOutlet var menuView: CVCalendarMenuView! @IBOutlet var calendarView: CVCalendarView! required init?(coder aDecoder: NSCoder) { numberOfDotsForDate = { _ in return 0 } super.init(coder: aDecoder) } required init(style: UITableViewCellStyle, reuseIdentifier: String?) { numberOfDotsForDate = { _ in return 0 } super.init(style: style, reuseIdentifier: reuseIdentifier) } override func setup() { super.setup() row.title = nil selectionStyle = .None menuView.menuViewDelegate = self calendarView.calendarDelegate = self calendarView.calendarAppearanceDelegate = self } override func layoutSubviews() { super.layoutSubviews() self.setNeedsUpdateConstraints() menuView.commitMenuViewUpdate() calendarView.commitCalendarViewUpdate() } override func update() { row.title = nil super.update() if let date = row.value { calendarView.presentedDate = CVDate(date: date) calendarView.contentController.refreshPresentedMonth() // calendarView.toggleCurrentDayView() } } func presentationMode() -> CVCalendar.CalendarMode { return .WeekView } func firstWeekday() -> CVCalendar.Weekday { return .Sunday } func shouldShowWeekdaysOut() -> Bool { return true } func shouldScrollOnOutDayViewSelection() -> Bool { return false } func dotMarker(shouldShowOnDayView dayView: CVCalendarDayView) -> Bool { guard let date = dayView.date.convertedDate() else { return false } return numberOfDotsForDate(cal.startOfDayForDate(date)) > 0 } func dotMarker(colorOnDayView dayView: CVCalendarDayView) -> [UIColor] { guard let date = dayView.date.convertedDate() else { return [] } switch numberOfDotsForDate(cal.startOfDayForDate(date)) { case 0: return [] case 1: return [UIColor.redColor()] case 2: return [UIColor.redColor(), UIColor.redColor()] default: return [UIColor.redColor(), UIColor.redColor(), UIColor.redColor()] } } func dotMarker(shouldMoveOnHighlightingOnDayView dayView: CVCalendarDayView) -> Bool { return false } func dotMarker(sizeOnDayView dayView: DayView) -> CGFloat { return 14 } func dotMarker(moveOffsetOnDayView dayView: DayView) -> CGFloat { return 10 } func dayLabelWeekdaySelectedBackgroundColor() -> UIColor { return UIColor.redColor() } func presentedDateUpdated(date: CVDate) { row.value = cal.startOfDayForDate(date.convertedDate()!) } } final class CalendarWeekRow: Row<NSDate, CalendarWeekCell>, RowType { var numberOfDotsForDate: NSDate -> Int { get { return cell.numberOfDotsForDate } set(newVal) { cell.numberOfDotsForDate = newVal } } required init(tag: String?) { super.init(tag: tag) displayValueFor = nil cellProvider = CellProvider<CalendarWeekCell>(nibName: "CalendarWeekCell") } }
gpl-3.0
5b00ac01d44c3496ce2209be978c1416
28.27972
137
0.664438
4.868605
false
false
false
false
YQqiang/Nunchakus
Nunchakus/Nunchakus/Selfie/ViewController/VideoViewController.swift
1
5665
// // VideoViewController.swift // Nunchakus // // Created by sungrow on 2017/4/6. // Copyright © 2017年 sungrow. All rights reserved. // import UIKit class VideoViewController: BaseViewController { fileprivate var headerView: HeaderView! fileprivate var contentCollectionView: ContentCollectionView! fileprivate var currentIndex = 0 lazy var categories: [String] = { return ["棍友自拍", "舞台表演", "棍法教学", "媒体关注", "影视动画", "国外聚焦", "极限跑酷"] }() lazy var videoTypes: [VideoType] = { return [VideoType.zipai, VideoType.biaoyan, VideoType.jiaoxue, VideoType.media, VideoType.movie, VideoType.guowai, VideoType.paoku] }() var videoControllers: [SelfieViewController]! override func viewDidLoad() { super.viewDidLoad() emptyDataView.isHidden = true view.backgroundColor = UIColor.white setupView() videoControllers = [] for index in 0..<videoTypes.count { let videoC = SelfieViewController() addChildViewController(videoC) videoC.videoType = videoTypes[index] videoControllers.append(videoC) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let _ = contentCollectionView.dataSource { } else { contentCollectionView.dataSource = self } if let _ = contentCollectionView.delegate { } else { contentCollectionView.delegate = self } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if currentIndex == videoControllers.count - 1 { headerView.delegate?.categoryHeaderView(headerView: headerView, selectedIndex: currentIndex) headerView.selectTitle(of: currentIndex) } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() var willShowFull = false for (_, videoVC) in videoControllers.enumerated() { if videoVC.willShowFullScreen { willShowFull = true videoVC.willShowFullScreen = false break } } if willShowFull { contentCollectionView.dataSource = nil contentCollectionView.delegate = nil } } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return UIInterfaceOrientationMask.portrait } private func setupView() { self.automaticallyAdjustsScrollViewInsets = false do { headerView = HeaderView() headerView.delegate = self view.addSubview(headerView) headerView.categories = categories headerView.snp.makeConstraints({ (make) in make.left.right.equalToSuperview() make.height.equalTo(40) make.top.equalTo(self.topLayoutGuide.snp.bottom) }) } do { contentCollectionView = ContentCollectionView() contentCollectionView.register(cellClass: NewsContentCell.self, forCellWithReuseIdentifier: "cell") view.addSubview(contentCollectionView) contentCollectionView.snp.makeConstraints({ (make) in make.top.equalTo(headerView.snp.bottom) make.left.right.bottom.equalToSuperview() }) } } } extension VideoViewController: HeaderViewDelegate { func categoryHeaderView(headerView: HeaderView, selectedIndex: Int) { let indexPath = IndexPath(item: selectedIndex, section: 0) contentCollectionView.scrollAffectToNoOnce() contentCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false) for (i, videoVC) in videoControllers.enumerated() { if i != selectedIndex { if videoVC.isViewLoaded { videoVC.player.prepareToDealloc() videoVC.player.removeFromSuperview() } } } currentIndex = selectedIndex // contentCollectionView.reloadData() } } extension VideoViewController: ContentCollectionViewDelegate { func contentCollectionView(_ contentView: ContentCollectionView, didShowViewWith index: Int) { headerView.selectTitle(of: index) for (i, videoVC) in videoControllers.enumerated() { if i != index { if videoVC.isViewLoaded { videoVC.player.prepareToDealloc() videoVC.player.removeFromSuperview() } } } currentIndex = index // contentCollectionView.reloadData() } func contentCollectionView(_ contentView: ContentCollectionView, didScrollFrom fromIndex: Int, to toIndex: Int, scale: Float) { headerView.adjustTitle(from: fromIndex, to: toIndex, scale: scale) } } extension VideoViewController: ContentCollectionViewDataSource { func numberOfItems(in collectionView: UICollectionView) -> Int { return categories.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? NewsContentCell cell!.videoVC = videoControllers[indexPath.item] return cell! } }
mit
230cdb6742801c677973eb81c3d4ee55
33.819876
139
0.630574
5.354346
false
false
false
false
mattermost/mattermost-mobile
ios/MattermostShare/Models/ServerModel.swift
1
1405
// // ServerModel.swift // MattermostShare // // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. // import Foundation struct ServerModel: Identifiable, Codable, Hashable { var id: String var displayName: String var url: String var hasChannels: Bool = false var maxMessageLength: Int64 = 4000 var maxFileSize: Int64 = 50 * 1024 * 1024 // 50MB var maxImageResolution: Int64 = 7680 * 4320 // 8K, ~33MPX var uploadsDisabled: Bool = false enum ServerKeys: String, CodingKey { case id, url case displayName = "display_name" } init(id: String, displayName: String, url: String) { self.id = id self.displayName = displayName self.url = url } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: ServerKeys.self) id = try container.decode(String.self, forKey: .id) displayName = try container.decode(String.self, forKey: .displayName) url = try container.decode(String.self, forKey: .url) } mutating func updateSettings(_ hasChannels: Bool, _ postSize: Int64?, _ fileSize: Int64?, _ uploadsEnabled: Bool) { self.hasChannels = hasChannels self.uploadsDisabled = !uploadsEnabled if let length = postSize { self.maxMessageLength = length } if let size = fileSize { self.maxFileSize = size } } }
apache-2.0
86a7754d1324b7c7af55791e65387665
26.54902
117
0.680427
3.828338
false
false
false
false
yunzhu-li/nextbus-tracker
nextbus-tracker/nextbus-tracker/src/viewcontrollers/bookmarks/NTVCBookmarks.swift
1
6596
// // This file is part of Nextbus Tracker. // // Created by Yunzhu Li on 04/23/15. // Copyright (c) 2015 Yunzhu Li. // // Nextbus Tracker is free software: you can redistribute // it and/or modify it under the terms of the GNU General // Public License version 3 as published by the Free // Software Foundation. // // Nextbus Tracker is distributed in the hope that it will // be useful, but WITHOUT ANY WARRANTY; without even the // implied warranty of MERCHANTABILITY or FITNESS FOR A // PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public // License along with Nextbus Tracker. // If not, see http://www.gnu.org/licenses/. // import UIKit import CoreLocation class NTVCBookmarks: UIViewController, UITableViewDelegate, UITableViewDataSource { // UI @IBOutlet weak var tblBookmarks: UITableView! var tblRefreshControl: UIRefreshControl! // Location manager var locationManager: CLLocationManager = CLLocationManager() // Data var preditions: [Dictionary<String, String>] = [] var initialReload = true var tmAutoRefresh: Timer = Timer() override func viewDidLoad() { super.viewDidLoad() // Request location permission locationManager.requestWhenInUseAuthorization() // Configure navigation bar appearance self.navigationController?.navigationBar.barTintColor = UIColor(red: 0, green: 0.57, blue: 1, alpha: 1) self.navigationController?.navigationBar.tintColor = UIColor.white self.navigationController?.navigationBar.titleTextAttributes = [ NSAttributedStringKey.foregroundColor : UIColor.white ] // Configure Refresh Control self.tblRefreshControl = UIRefreshControl() self.tblRefreshControl.addTarget(self, action: #selector(NTVCBookmarks.refreshData), for: UIControlEvents.valueChanged) self.tblRefreshControl.tintColor = UIColor.white self.tblBookmarks.addSubview(tblRefreshControl) //NTMNextbus.writeDebugData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) initialReload = true refreshData() self.enableRefreshTimer(enabled: true) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.enableRefreshTimer(enabled: false) } @IBAction func btnAddAct(_ sender: UIBarButtonItem) { self.performSegue(withIdentifier: "PushToRouteSelector", sender: self) } func enableRefreshTimer(enabled: Bool) { tmAutoRefresh.invalidate() if (enabled) { tmAutoRefresh.invalidate() tmAutoRefresh = Timer.scheduledTimer(timeInterval: 7, target: self, selector: #selector(NTVCBookmarks.refreshData), userInfo: nil, repeats: true) } } @objc func refreshData() { self.preditions = [] if let array = FLLocalStorageUtils.readObjectFromUserDefaults(key: NTMNextbus.NTMBookmarksLocalStorageKey) as? [Dictionary<String, String>] { var routes: [String] = [], directions: [String] = [], stops: [String] = [] for i in 0 ..< array.count { var prediction = array[i] prediction[NTMNextbus.NTMKeyMinutes] = "Refreshing..." self.preditions.append(prediction) // Parameters for request routes.append(array[i][NTMNextbus.NTMKeyRoute] as String!) directions.append(array[i][NTMNextbus.NTMKeyDirection] as String!) stops.append(array[i][NTMNextbus.NTMKeyStop] as String!) } // Show "Refreshing..." in cells self.tblBookmarks.reloadData() // Get predictions NTMNextbus.getPredictionsOfBookmarkedStops(mode: NTMNextbus.NTMPredictionFetchMode.Full) { (data, error) -> Void in if let _data = data as? [Dictionary<String, String>] { self.preditions = _data } self.tblBookmarks.reloadData() self.tblRefreshControl.endRefreshing() } } else { self.tblRefreshControl.endRefreshing() } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return preditions.count + 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if (indexPath.row == preditions.count) { return tblBookmarks.dequeueReusableCell(withIdentifier: "tblCellBookmarksNew")! } let cell: NTTblCellBookmarks = tblBookmarks.dequeueReusableCell(withIdentifier: "tblCellBookmarks") as! NTTblCellBookmarks cell.lblStop.text = preditions[indexPath.row][NTMNextbus.NTMKeyStopTitle] cell.lblRoute.text = preditions[indexPath.row][NTMNextbus.NTMKeyRouteTitle] cell.lblPredictions.text = "No predictions available." if (preditions[indexPath.row].index(forKey: NTMNextbus.NTMKeyMinutes) != nil) { let _p_str: String = preditions[indexPath.row][NTMNextbus.NTMKeyMinutes]! if (_p_str.lengthOfBytes(using: String.Encoding.utf8) != 0) { cell.lblPredictions.text = _p_str } } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if (indexPath.row == preditions.count) { self.btnAddAct(UIBarButtonItem()) } } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if (indexPath.row < preditions.count) { return true } return false } func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) { self.enableRefreshTimer(enabled: false) } func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) { self.enableRefreshTimer(enabled: true) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { preditions.remove(at: indexPath.row) _ = NTMNextbus.removeStopFromLocalStorage(index: indexPath.row) tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.automatic) } }
gpl-3.0
81bb256b3c485b429613378e5ed3e2e3
38.261905
157
0.646604
4.731707
false
false
false
false
Nikita2k/Himotoki
Himotoki/Extractor.swift
1
3294
// // Extractor.swift // Himotoki // // Created by Syo Ikeda on 5/2/15. // Copyright (c) 2015 Syo Ikeda. All rights reserved. // import Foundation public struct Extractor { public let rawValue: AnyObject private let isDictionary: Bool internal init(_ rawValue: AnyObject) { self.rawValue = rawValue self.isDictionary = rawValue is NSDictionary } private func rawValue(keyPath: KeyPath) throws -> AnyObject? { if !isDictionary { throw DecodeError.TypeMismatch( expected: "Dictionary", actual: "\(rawValue)", keyPath: keyPath ) } let components = ArraySlice(keyPath.components) return valueFor(components, rawValue) } /// - Throws: DecodeError public func value<T: Decodable where T.DecodedType == T>(keyPath: KeyPath) throws -> T { guard let value: T = try valueOptional(keyPath) else { throw DecodeError.MissingKeyPath(keyPath) } return value } /// - Throws: DecodeError public func valueOptional<T: Decodable where T.DecodedType == T>(keyPath: KeyPath) throws -> T? { do { return try rawValue(keyPath).map(decode) } catch let DecodeError.TypeMismatch(expected, actual, _) { throw DecodeError.TypeMismatch(expected: expected, actual: actual, keyPath: keyPath) } } /// - Throws: DecodeError public func array<T: Decodable where T.DecodedType == T>(keyPath: KeyPath) throws -> [T] { guard let array: [T] = try arrayOptional(keyPath) else { throw DecodeError.MissingKeyPath(keyPath) } return array } /// - Throws: DecodeError public func arrayOptional<T: Decodable where T.DecodedType == T>(keyPath: KeyPath) throws -> [T]? { return try rawValue(keyPath).map(decodeArray) } /// - Throws: DecodeError public func dictionary<T: Decodable where T.DecodedType == T>(keyPath: KeyPath) throws -> [String: T] { guard let dictionary: [String: T] = try dictionaryOptional(keyPath) else { throw DecodeError.MissingKeyPath(keyPath) } return dictionary } /// - Throws: DecodeError public func dictionaryOptional<T: Decodable where T.DecodedType == T>(keyPath: KeyPath) throws -> [String: T]? { return try rawValue(keyPath).map(decodeDictionary) } } extension Extractor: Decodable { public static func decode(e: Extractor) throws -> Extractor { return e } } // Implement it as a tail recursive function. // // `ArraySlice` is used for performance optimization. // See https://gist.github.com/norio-nomura/d9ec7212f2cfde3fb662. private func valueFor(keyPathComponents: ArraySlice<String>, _ object: AnyObject) -> AnyObject? { guard let first = keyPathComponents.first else { return nil } // This type annotation is necessary to select intended `subscript` method. guard let nested: AnyObject? = object[first] else { return nil } if nested is NSNull { return nil } else if keyPathComponents.count > 1 { let tail = keyPathComponents.dropFirst() return valueFor(tail, nested!) } else { return nested } }
mit
990cf91800764ace7310918760d976ee
29.5
116
0.633576
4.518519
false
false
false
false
cwaffles/Soulcast
Soulcast/SoulQueue.swift
1
267
import Foundation let singleSoulQueue = SoulQueue() //a data type to temporarily store souls class SoulQueue { var elementCount:Int = 0 func enqueue(_ incomingSoul:Soul){ // assert(incomingSoul.type == .Broadcast) elementCount += 1 } }
mit
336bc788a04e6d28d8ee064fb2ec264c
13.833333
45
0.670412
3.814286
false
false
false
false
Vadimkomis/Myclok
Pods/Auth0/Auth0/Auth0.swift
2
6032
// Auth0.swift // // Copyright (c) 2016 Auth0 (http://auth0.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 /** Auth0 Authentication API to authenticate your user using a Database, Social, Enterprise or Passwordless connections ``` Auth0.authentication(clientId: clientId, domain: "samples.auth0.com") ``` - parameter clientId: clientId of your Auth0 client/application - parameter domain: domain of your Auth0 account. e.g.: 'samples.auth0.com' - parameter session: instance of NSURLSession used for networking. By default it will use the shared NSURLSession - returns: Auth0 Authentication API */ public func authentication(clientId: String, domain: String, session: URLSession = .shared) -> Authentication { return Auth0Authentication(clientId: clientId, url: .a0_url(domain), session: session) } /** Auth0 Authentication API to authenticate your user using a Database, Social, Enterprise or Passwordless connections. ``` Auth0.authentication() ``` Auth0 clientId & domain are loaded from the file `Auth0.plist` in your main bundle with the following content: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>ClientId</key> <string>{YOUR_CLIENT_ID}</string> <key>Domain</key> <string>{YOUR_DOMAIN}</string> </dict> </plist> ``` - parameter session: instance of NSURLSession used for networking. By default it will use the shared NSURLSession - parameter bundle: bundle used to locate the `Auth0.plist` file. By default is the main bundle - returns: Auth0 Authentication API - important: Calling this method without a valid `Auth0.plist` will crash your application */ public func authentication(session: URLSession = .shared, bundle: Bundle = .main) -> Authentication { let values = plistValues(bundle: bundle)! return authentication(clientId: values.clientId, domain: values.domain, session: session) } /** Auth0 Management Users API v2 that allows CRUD operations with the users endpoint. ``` Auth0.users(token: token) ``` Currently you can only perform the following operations: * Get an user by id * Update an user, e.g. by adding `user_metadata` * Link users * Unlink users Auth0 domain is loaded from the file `Auth0.plist` in your main bundle with the following content: ``` <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>ClientId</key> <string>{YOUR_CLIENT_ID}</string> <key>Domain</key> <string>{YOUR_DOMAIN}</string> </dict> </plist> ``` - parameter token: token of Management API v2 with the correct allowed scopes to perform the desired action - parameter session: instance of NSURLSession used for networking. By default it will use the shared NSURLSession - parameter bundle: bundle used to locate the `Auth0.plist` file. By default is the main bundle - returns: Auth0 Management API v2 - important: Calling this method without a valid `Auth0.plist` will crash your application */ public func users(token: String, session: URLSession = .shared, bundle: Bundle = .main) -> Users { let values = plistValues(bundle: bundle)! return users(token: token, domain: values.domain, session: session) } /** Auth0 Management Users API v2 that allows CRUD operations with the users endpoint. ``` Auth0.users(token: token, domain: "samples.auth0.com") ``` Currently you can only perform the following operations: * Get an user by id * Update an user, e.g. by adding `user_metadata` * Link users * Unlink users - parameter token: token of Management API v2 with the correct allowed scopes to perform the desired action - parameter domain: domain of your Auth0 account. e.g.: 'samples.auth0.com' - parameter session: instance of NSURLSession used for networking. By default it will use the shared NSURLSession - returns: Auth0 Management API v2 */ public func users(token: String, domain: String, session: URLSession = .shared) -> Users { return Management(token: token, url: .a0_url(domain), session: session) } func plistValues(bundle: Bundle) -> (clientId: String, domain: String)? { guard let path = bundle.path(forResource: "Auth0", ofType: "plist"), let values = NSDictionary(contentsOfFile: path) as? [String: Any] else { print("Missing Auth0.plist file with 'ClientId' and 'Domain' entries in main bundle!") return nil } guard let clientId = values["ClientId"] as? String, let domain = values["Domain"] as? String else { print("Auth0.plist file at \(path) is missing 'ClientId' and/or 'Domain' entries!") print("File currently has the following entries: \(values)") return nil } return (clientId: clientId, domain: domain) }
mit
b681b15ee28ce171c3b448b766688f78
37.177215
117
0.717507
4.034783
false
false
false
false
wjk/MacBond
MacBond/Bond+Foundation.swift
1
2473
// // Bond+Foundation.swift // BondDemo // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation private var XXContext = 0 @objc private class DynamicKVOHelper: NSObject { let listener: AnyObject -> Void weak var object: NSObject? let keyPath: String init(keyPath: String, object: NSObject, listener: AnyObject -> Void) { self.keyPath = keyPath self.object = object self.listener = listener super.init() self.object?.addObserver(self, forKeyPath: keyPath, options: .New, context: &XXContext) } deinit { object?.removeObserver(self, forKeyPath: keyPath) } override dynamic func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if context == &XXContext { if let newValue: AnyObject = change[NSKeyValueChangeNewKey] { listener(newValue) } } } } public extension Dynamic { public class func asObservableFor(object: NSObject, keyPath: String) -> Dynamic<T> { let dynamic = DynamicExtended(object.valueForKeyPath(keyPath) as! T) let helper = DynamicKVOHelper(keyPath: keyPath, object: object as NSObject) { [unowned dynamic] (v: AnyObject) -> Void in dynamic.value = v as! T } dynamic.retain(helper) return dynamic } }
mit
3f31a43e33f0c98ad36d6ae7f9065dc7
33.347222
162
0.714517
4.293403
false
false
false
false
kraffslol/react-native-braintree-xplat
ios/RCTBraintree/Braintree/UnitTests/BTAppSwitch_Tests.swift
3
3338
import XCTest class BTAppSwitch_Tests: XCTestCase { var appSwitch = BTAppSwitch.sharedInstance() override func setUp() { super.setUp() appSwitch = BTAppSwitch.sharedInstance() } override func tearDown() { MockAppSwitchHandler.cannedCanHandle = false MockAppSwitchHandler.lastCanHandleURL = nil MockAppSwitchHandler.lastCanHandleSourceApplication = nil MockAppSwitchHandler.lastHandleAppSwitchReturnURL = nil super.tearDown() } func testHandleOpenURL_whenHandlerIsRegistered_invokesCanHandleAppSwitchReturnURL() { appSwitch.register(MockAppSwitchHandler.self) let expectedURL = URL(string: "fake://url")! let expectedSourceApplication = "fakeSourceApplication" BTAppSwitch.handleOpen(expectedURL, sourceApplication: expectedSourceApplication) XCTAssertEqual(MockAppSwitchHandler.lastCanHandleURL!, expectedURL) XCTAssertEqual(MockAppSwitchHandler.lastCanHandleSourceApplication!, expectedSourceApplication) } func testHandleOpenURL_whenHandlerCanHandleOpenURL_invokesHandleAppSwitchReturnURL() { appSwitch.register(MockAppSwitchHandler.self) MockAppSwitchHandler.cannedCanHandle = true let expectedURL = URL(string: "fake://url")! let handled = BTAppSwitch.handleOpen(expectedURL, sourceApplication: "not important") XCTAssert(handled) XCTAssertEqual(MockAppSwitchHandler.lastHandleAppSwitchReturnURL!, expectedURL) } func testHandleOpenURL_whenHandlerCantHandleOpenURL_doesNotInvokeHandleAppSwitchReturnURL() { appSwitch.register(MockAppSwitchHandler.self) MockAppSwitchHandler.cannedCanHandle = false BTAppSwitch.handleOpen(URL(string: "fake://url")!, sourceApplication: "not important") XCTAssertNil(MockAppSwitchHandler.lastHandleAppSwitchReturnURL) } func testHandleOpenURL_whenHandlerCantHandleOpenURL_returnsFalse() { appSwitch.register(MockAppSwitchHandler.self) MockAppSwitchHandler.cannedCanHandle = false XCTAssertFalse(BTAppSwitch.handleOpen(URL(string: "fake://url")!, sourceApplication: "not important")) } func testHandleOpenURL_acceptsOptionalSourceApplication() { // This doesn't assert any behavior about nil source application. It only checks that the code will compile! let sourceApplication : String? = nil BTAppSwitch.handleOpen(URL(string: "fake://url")!, sourceApplication: sourceApplication) } func testHandleOpenURL_withNoAppSwitching() { let handled = BTAppSwitch.handleOpen(URL(string: "scheme://")!, sourceApplication: "com.yourcompany.hi") XCTAssertFalse(handled) } } class MockAppSwitchHandler: BTAppSwitchHandler { static var cannedCanHandle = false static var lastCanHandleURL : URL? = nil static var lastCanHandleSourceApplication : String? = nil static var lastHandleAppSwitchReturnURL : URL? = nil @objc static func canHandleAppSwitchReturn(_ url: URL, sourceApplication: String) -> Bool { lastCanHandleURL = url lastCanHandleSourceApplication = sourceApplication return cannedCanHandle } @objc static func handleAppSwitchReturn(_ url: URL) { lastHandleAppSwitchReturnURL = url } }
mit
b51b19f0a9e65db14c6f448f505a4765
37.813953
116
0.732475
4.997006
false
true
false
false
debugsquad/metalic
metalic/View/Home/VHomeMenu.swift
1
5570
import UIKit class VHomeMenu:UIView, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { weak var controller:CHome! weak var collectionView:UICollectionView! weak var selectedItem:MFiltersItem? let model:MFilters private let kCellWidth:CGFloat = 90 private let kMarginHorizontal:CGFloat = 10 private let kAfterSelect:TimeInterval = 0.1 init(controller:CHome) { model = MFilters() super.init(frame:CGRect.zero) self.controller = controller clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false let flow:UICollectionViewFlowLayout = UICollectionViewFlowLayout() flow.headerReferenceSize = CGSize.zero flow.footerReferenceSize = CGSize.zero flow.minimumInteritemSpacing = 0 flow.minimumLineSpacing = 0 flow.sectionInset = UIEdgeInsets( top:0, left:kMarginHorizontal, bottom:0, right:kMarginHorizontal) flow.scrollDirection = UICollectionViewScrollDirection.horizontal let collectionView:UICollectionView = UICollectionView(frame:CGRect.zero, collectionViewLayout:flow) collectionView.clipsToBounds = true collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = UIColor.clear collectionView.showsHorizontalScrollIndicator = false collectionView.showsVerticalScrollIndicator = false collectionView.alwaysBounceHorizontal = true collectionView.delegate = self collectionView.dataSource = self collectionView.register( VHomeMenuCell.self, forCellWithReuseIdentifier: VHomeMenuCell.reusableIdentifier) self.collectionView = collectionView addSubview(collectionView) let views:[String:UIView] = [ "collectionView":collectionView] let metrics:[String:CGFloat] = [:] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-0-[collectionView]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[collectionView]-0-|", options:[], metrics:metrics, views:views)) NotificationCenter.default.addObserver( self, selector:#selector(notifiedFiltersLoaded(sender:)), name:Notification.filtersLoaded, object:nil) } required init?(coder:NSCoder) { fatalError() } deinit { NotificationCenter.default.removeObserver(self) } //MARK: notified func notifiedFiltersLoaded(sender notification:Notification) { DispatchQueue.main.async { [weak self] in self?.filtersLoaded() } } //MARK: private private func filtersLoaded() { collectionView.reloadData() if model.items.count > 0 { DispatchQueue.main.asyncAfter(deadline:DispatchTime.now() + kAfterSelect) { [weak self] in let index:IndexPath = IndexPath(item:0, section:0) self?.collectionView.selectItem( at:index, animated:false, scrollPosition:UICollectionViewScrollPosition()) self?.selectItemAtIndex(index:index) } } } private func modelAtIndex(index:IndexPath) -> MFiltersItem { let item:MFiltersItem = model.items[index.item] return item } private func selectItemAtIndex(index:IndexPath) { let item:MFiltersItem = modelAtIndex(index:index) if selectedItem !== item { selectedItem = item controller.updateFilter() } } //MARK: collection delegate func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize { let height:CGFloat = collectionView.bounds.maxY let size:CGSize = CGSize(width:kCellWidth, height:height) return size } func numberOfSections(in collectionView:UICollectionView) -> Int { return 1 } func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int { let count:Int = model.items.count return count } func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell { let item:MFiltersItem = modelAtIndex(index:indexPath) let cell:VHomeMenuCell = collectionView.dequeueReusableCell( withReuseIdentifier: VHomeMenuCell.reusableIdentifier, for:indexPath) as! VHomeMenuCell cell.config(model:item) return cell } func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath) { collectionView.scrollToItem( at:indexPath, at:UICollectionViewScrollPosition.centeredHorizontally, animated:true) selectItemAtIndex(index:indexPath) } }
mit
cef42deaa1fadadba3cfd636041bb6c1
30.292135
156
0.623519
6.127613
false
false
false
false
CatchChat/Yep
OpenGraph/Service.swift
1
12267
// // Service.swift // Yep // // Created by NIX on 16/5/20. // Copyright © 2016年 Catch Inc. All rights reserved. // import Foundation import YepNetworking import Alamofire import Kanna public func titleOfURL(URL: NSURL, failureHandler: FailureHandler?, completion: (title: String) -> Void) { Alamofire.request(.GET, URL.absoluteString, parameters: nil, encoding: .URL).responseString(encoding: NSUTF8StringEncoding, completionHandler: { response in let error = response.result.error guard error == nil else { if let failureHandler = failureHandler { failureHandler(reason: .Other(error), errorMessage: NSLocalizedString("Get title of URL failed!", comment: "")) } else { defaultFailureHandler(reason: .Other(error), errorMessage: NSLocalizedString("Get title of URL failed!", comment: "")) } return } guard let HTMLString = response.result.value, data = response.data else { if let failureHandler = failureHandler { failureHandler(reason: .CouldNotParseJSON, errorMessage: "No HTMLString or data!") } else { defaultFailureHandler(reason: .CouldNotParseJSON, errorMessage: "No HTMLString or data!") } return } //println("\ntitleOfURL: \(URL)\n\(HTMLString)") // 编码转换 let newHTMLString = getUTF8HTMLStringFromHTMLString(HTMLString, withData: data) guard let doc = Kanna.HTML(html: newHTMLString, encoding: NSUTF8StringEncoding), title = doc.head?.css("title").first?.text where !title.isEmpty else { if let failureHandler = failureHandler { failureHandler(reason: .CouldNotParseJSON, errorMessage: NSLocalizedString("No title for URL!", comment: "")) } else { defaultFailureHandler(reason: .CouldNotParseJSON, errorMessage: NSLocalizedString("No title for URL!", comment: "")) } return } completion(title: title) }) } public func openGraphWithURL(URL: NSURL, failureHandler: FailureHandler?, completion: OpenGraph -> Void) { Alamofire.request(.GET, URL.absoluteString, parameters: nil, encoding: .URL).responseString(encoding: NSUTF8StringEncoding, completionHandler: { response in let error = response.result.error guard error == nil else { if let failureHandler = failureHandler { failureHandler(reason: .Other(error), errorMessage: nil) } else { defaultFailureHandler(reason: .Other(error), errorMessage: nil) } return } if let HTMLString = response.result.value, data = response.data { //println("\n openGraphWithURLString: \(URL)\n\(HTMLString)") // 尽量使用长链接 var finalURL = URL if let _finalURL = response.response?.URL { finalURL = _finalURL } // 编码转换 let newHTMLString = getUTF8HTMLStringFromHTMLString(HTMLString, withData: data) //println("newHTMLString: \(newHTMLString)") if let openGraph = OpenGraph.fromHTMLString(newHTMLString, forURL: finalURL) { completion(openGraph) /* var openGraph = openGraph guard let URL = response.response?.URL, host = URL.host, _ = NSURL.AppleOnlineStoreHost(rawValue: host) else { completion(openGraph) return } if let lookupID = URL.yep_iTunesArtworkID { iTunesLookupWithID(lookupID, failureHandler: nil, completion: { artworkInfo in //println("iTunesLookupWithID: \(lookupID), \(artworkInfo)") if let kind = artworkInfo["kind"] as? String { switch kind.lowercaseString { case "song": openGraph.kind = .AppleMusic openGraph.previewAudioURLString = artworkInfo["previewUrl"] as? String var appleMusic = OpenGraph.AppleMusic() appleMusic.artistName = artworkInfo["artistName"] as? String appleMusic.artworkURLString30 = artworkInfo["artworkUrl30"] as? String appleMusic.artworkURLString60 = artworkInfo["artworkUrl60"] as? String appleMusic.artworkURLString100 = artworkInfo["artworkUrl100"] as? String appleMusic.collectionName = artworkInfo["collectionName"] as? String appleMusic.collectionViewURLString = artworkInfo["collectionViewUrl"] as? String appleMusic.trackTimeMillis = artworkInfo["trackTimeMillis"] as? Int appleMusic.trackViewURLString = artworkInfo["trackViewUrl"] as? String openGraph.appleMusic = appleMusic case "feature-movie": openGraph.kind = .AppleMovie openGraph.previewVideoURLString = artworkInfo["previewUrl"] as? String var appleMovie = OpenGraph.AppleMovie() appleMovie.artistName = artworkInfo["artistName"] as? String appleMovie.artworkURLString30 = artworkInfo["artworkUrl30"] as? String appleMovie.artworkURLString60 = artworkInfo["artworkUrl60"] as? String appleMovie.artworkURLString100 = artworkInfo["artworkUrl100"] as? String appleMovie.shortDescription = artworkInfo["shortDescription"] as? String appleMovie.longDescription = artworkInfo["longDescription"] as? String appleMovie.trackTimeMillis = artworkInfo["trackTimeMillis"] as? Int appleMovie.trackViewURLString = artworkInfo["trackViewUrl"] as? String openGraph.appleMovie = appleMovie case "ebook": openGraph.kind = .AppleEBook var appleEBook = OpenGraph.AppleEBook() appleEBook.artistName = artworkInfo["artistName"] as? String appleEBook.artworkURLString60 = artworkInfo["artworkUrl60"] as? String appleEBook.artworkURLString100 = artworkInfo["artworkUrl100"] as? String appleEBook.description = artworkInfo["description"] as? String appleEBook.trackName = artworkInfo["trackName"] as? String appleEBook.trackViewURLString = artworkInfo["trackViewUrl"] as? String openGraph.appleEBook = appleEBook default: break } } if let collectionType = artworkInfo["collectionType"] as? String { switch collectionType.lowercaseString { case "album": var appleMusic = OpenGraph.AppleMusic() appleMusic.artistName = artworkInfo["artistName"] as? String appleMusic.artworkURLString100 = artworkInfo["artworkUrl100"] as? String appleMusic.artworkURLString160 = artworkInfo["artworkUrl160"] as? String appleMusic.collectionType = collectionType appleMusic.collectionName = artworkInfo["collectionName"] as? String appleMusic.collectionViewURLString = artworkInfo["collectionViewUrl"] as? String openGraph.appleMusic = appleMusic default: break } } completion(openGraph) }) } */ return } } if let failureHandler = failureHandler { failureHandler(reason: .CouldNotParseJSON, errorMessage: nil) } else { defaultFailureHandler(reason: .CouldNotParseJSON, errorMessage: nil) } }) } // ref http://a4esl.org/c/charset.html private enum WeirdCharset: String { // China case GB2312 = "GB2312" case GBK = "GBK" case GB18030 = "GB18030" // Taiwan, HongKong ... case BIG5 = "BIG5" case BIG5HKSCS = "BIG5-HKSCS" // Korean case EUCKR = "EUC-KR" } private func getUTF8HTMLStringFromHTMLString(HTMLString: String, withData data: NSData) -> String { let pattern = "charset=([A-Za-z0-9\\-]+)" guard let charsetRegex = try? NSRegularExpression(pattern: pattern, options: [.CaseInsensitive]), result = charsetRegex.firstMatchInString(HTMLString, options: [.ReportCompletion], range: NSMakeRange(0, (HTMLString as NSString).length)) else { return HTMLString } let charsetStringRange = result.rangeAtIndex(1) let charsetString = (HTMLString as NSString).substringWithRange(charsetStringRange).uppercaseString guard let weirdCharset = WeirdCharset(rawValue: charsetString) else { return HTMLString } let encoding: NSStringEncoding switch weirdCharset { case .GB2312, .GBK, .GB18030: let china = CFStringEncodings.GB_18030_2000 encoding = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(china.rawValue)) case .BIG5, .BIG5HKSCS: let taiwan = CFStringEncodings.Big5_HKSCS_1999 encoding = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(taiwan.rawValue)) case .EUCKR: let korean = CFStringEncodings.EUC_KR encoding = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(korean.rawValue)) } guard let newHTMLString = String(data: data, encoding: encoding) else { return HTMLString } return newHTMLString } private enum iTunesCountry: String { case China = "cn" case USA = "us" } private func iTunesLookupWithID(lookupID: String, inCountry country: iTunesCountry, failureHandler: ((Reason, String?) -> Void)?, completion: JSONDictionary? -> Void) { let lookUpURLString = "https://itunes.apple.com/lookup?id=\(lookupID)&country=\(country.rawValue)" Alamofire.request(.GET, lookUpURLString).responseJSON { response in print("iTunesLookupWithID \(lookupID): \(response)") guard let info = response.result.value as? JSONDictionary, let resultCount = info["resultCount"] as? Int where resultCount > 0, let result = (info["results"] as? [JSONDictionary])?.first else { completion(nil) return } completion(result) } } private func iTunesLookupWithID(lookupID: String, failureHandler: ((Reason, String?) -> Void)?, completion: JSONDictionary -> Void) { iTunesLookupWithID(lookupID, inCountry: .China, failureHandler: failureHandler, completion: { result in if let result = result { completion(result) } else { iTunesLookupWithID(lookupID, inCountry: .USA, failureHandler: failureHandler, completion: { result in if let result = result { completion(result) } else { if let failureHandler = failureHandler { failureHandler(.NoData, nil) } else { defaultFailureHandler(reason: .NoData, errorMessage: nil) } } }) } }) }
mit
9945a9df653cb76c777b1dafd64492c8
36.759259
168
0.566618
5.471377
false
false
false
false
buscarini/vitemo
vitemo/Carthage/Checkouts/GRMustache.swift/Mustache/Rendering/RenderingEngine.swift
4
15754
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation final class RenderingEngine { init(templateAST: TemplateAST, context: Context) { self.templateAST = templateAST self.baseContext = context buffer = "" } func render(# error: NSErrorPointer) -> Rendering? { buffer = "" switch renderTemplateAST(templateAST, inContext: baseContext) { case .Error(let renderError): if error != nil { error.memory = renderError } return nil default: return Rendering(buffer, templateAST.contentType) } } // MARK: - Rendering private let templateAST: TemplateAST private let baseContext: Context private var buffer: String private enum RenderResult { case Success case Error(NSError) } private func renderTemplateAST(templateAST: TemplateAST, inContext context: Context) -> RenderResult { // We must take care of eventual content-type mismatch between the // currently rendered AST (defined by init), and the argument. // // For example, the partial loaded by the HTML template `{{>partial}}` // may be a text one. In this case, we must render the partial as text, // and then HTML-encode its rendering. See the "Partial containing // CONTENT_TYPE:TEXT pragma is HTML-escaped when embedded." test in // the text_rendering.json test suite. // // So let's check for a content-type mismatch: let targetContentType = self.templateAST.contentType! if templateAST.contentType == targetContentType { // Content-type match for node in templateAST.nodes { let result = renderNode(node, inContext: context) switch result { case .Error: return result default: break } } return .Success } else { // Content-type mismatch // // Render separately, so that we can HTML-escape the rendering of // the templateAST before appending to our buffer. let renderingEngine = RenderingEngine(templateAST: templateAST, context: context) var error: NSError? if let rendering = renderingEngine.render(error: &error) { switch (targetContentType, rendering.contentType) { case (.HTML, .Text): buffer.extend(escapeHTML(rendering.string)) default: buffer.extend(rendering.string) } return .Success } else { return .Error(error!) } } } private func renderNode(node: TemplateASTNode, inContext context: Context) -> RenderResult { switch node { case .InheritableSectionNode(let inheritableSection): // {{$ name }}...{{/ name }} // // Render the inner content of the resolved inheritable section. let resolvedSection = resolveInheritableSection(inheritableSection, inContext: context) return renderTemplateAST(resolvedSection.innerTemplateAST, inContext: context) case .InheritedPartialNode(let inheritedPartial): // {{< name }}...{{/ name }} // // Extend the inheritance stack, and render the content of the parent partial let context = context.extendedContext(inheritedPartial: inheritedPartial) return renderTemplateAST(inheritedPartial.parentPartial.templateAST, inContext: context) case .PartialNode(let partial): // {{> name }} // // Render the content of the partial return renderTemplateAST(partial.templateAST, inContext: context) case .SectionNode(let section): // {{# name }}...{{/ name }} // {{^ name }}...{{/ name }} // // We have common rendering for sections and variable tags, yet with // a few specific flags: return renderTag(section.tag, escapesHTML: true, inverted: section.inverted, expression: section.expression, inContext: context) case .TextNode(let text): // text is the trivial case: buffer.extend(text) return .Success case .VariableNode(let variable): // {{ name }} // {{{ name }}} // {{& name }} // // We have common rendering for sections and variable tags, yet with // a few specific flags: return renderTag(variable.tag, escapesHTML: variable.escapesHTML, inverted: false, expression: variable.expression, inContext: context) } } private func renderTag(tag: Tag, escapesHTML: Bool, inverted: Bool, expression: Expression, inContext context: Context) -> RenderResult { // 1. Evaluate expression switch ExpressionInvocation(expression: expression).invokeWithContext(context) { case .Error(let error): var userInfo = error.userInfo ?? [:] if let originalLocalizedDescription: AnyObject = userInfo[NSLocalizedDescriptionKey] { userInfo[NSLocalizedDescriptionKey] = "Error evaluating \(tag.description): \(originalLocalizedDescription)" } else { userInfo[NSLocalizedDescriptionKey] = "Error evaluating \(tag.description)" } return .Error(NSError(domain: error.domain, code: error.code, userInfo: userInfo)) case .Success(var box): // 2. Let willRender functions alter the box for willRender in context.willRenderStack { box = willRender(tag: tag, box: box) } // 3. Render the box var error: NSError? let rendering: Rendering? switch tag.type { case .Variable: let info = RenderingInfo(tag: tag, context: context, enumerationItem: false) rendering = box.render(info: info, error: &error) case .Section: switch (inverted, box.boolValue) { case (false, true): // {{# true }}...{{/ true }} // Only case where we trigger the RenderFunction of the Box let info = RenderingInfo(tag: tag, context: context, enumerationItem: false) rendering = box.render(info: info, error: &error) case (true, false): // {{^ false }}...{{/ false }} rendering = tag.render(context, error: &error) default: // {{^ true }}...{{/ true }} // {{# false }}...{{/ false }} rendering = Rendering("") } } if let rendering = rendering { // 4. Extend buffer with the rendering, HTML-escaped if needed. let string: String switch (templateAST.contentType!, rendering.contentType, escapesHTML) { case (.HTML, .Text, true): string = escapeHTML(rendering.string) default: string = rendering.string } buffer.extend(string) // 5. Let didRender functions do their job for didRender in context.didRenderStack { didRender(tag: tag, box: box, string: string) } return .Success } else { for didRender in context.didRenderStack { didRender(tag: tag, box: box, string: nil) } return .Error(error!) } } } // MARK: - Template inheritance private func resolveInheritableSection(section: TemplateASTNode.InheritableSection, inContext context: Context) -> TemplateASTNode.InheritableSection { // As we iterate inherited partials, section becomes the deepest overriden section. // context.overridingTemplateASTStack has been built in renderNode(node:inContext:). // // We also update an array of used parent template AST in order to support // nested inherited partials. var usedParentTemplateASTs: [TemplateAST] = [] return reduce(context.inheritedPartialStack, section) { (section, inheritedPartial) in // Don't apply already used partial // // Relevant test: // { // "name": "com.github.mustachejava.ExtensionTest.testNested", // "template": "{{<box}}{{$box_content}}{{<main}}{{$main_content}}{{<box}}{{$box_content}}{{<tweetbox}}{{$tweetbox_classes}}tweetbox-largetweetbox-user-styled{{/tweetbox_classes}}{{$tweetbox_attrs}}data-rich-text{{/tweetbox_attrs}}{{/tweetbox}}{{/box_content}}{{/box}}{{/main_content}}{{/main}}{{/box_content}}{{/box}}", // "partials": { // "box": "<box>{{$box_content}}{{/box_content}}</box>", // "main": "<main>{{$main_content}}{{/main_content}}</main>", // "tweetbox": "<tweetbox classes=\"{{$tweetbox_classes}}{{/tweetbox_classes}}\" attrs=\"{{$tweetbox_attrs}}{{/tweetbox_attrs}}\"></tweetbox>" // }, // "expected": "<box><main><box><tweetbox classes=\"tweetbox-largetweetbox-user-styled\" attrs=\"data-rich-text\"></tweetbox></box></main></box>" // } let parentTemplateAST = inheritedPartial.parentPartial.templateAST if (contains(usedParentTemplateASTs) { $0 === parentTemplateAST }) { return section } else { let (resolvedSection, modified) = resolveInheritableSection(section, inOverridingTemplateAST: inheritedPartial.overridingTemplateAST) if modified { usedParentTemplateASTs.append(parentTemplateAST) } return resolvedSection } } } // Looks for an override for the section argument in a TemplateAST. // Returns the resolvedSection, and a boolean that tells whether the section // was actually overriden. private func resolveInheritableSection(section: TemplateASTNode.InheritableSection, inOverridingTemplateAST overridingTemplateAST: TemplateAST) -> (TemplateASTNode.InheritableSection, Bool) { // As we iterate template AST nodes, section becomes the last inherited // section in the template AST. // // The boolean turns to true once the section has been actually overriden. return reduce(overridingTemplateAST.nodes, (section, false)) { (step, node) in let (section, modified) = step switch node { case .InheritableSectionNode(let resolvedSection) where resolvedSection.name == section.name: // {{$ name }}...{{/ name }} // // An inheritable section is overriden by another inheritable section with the same name. return (resolvedSection, true) case .InheritedPartialNode(let inheritedPartial): // {{< partial }}...{{/ partial }} // // Inherited partials can provide an override in two ways: in // the parent partial, and inside the overriding section. // // Relevant tests: // // { // "name": "Two levels of inheritance: inherited partial with overriding content containing another inherited partial", // "data": { }, // "template": "{{<partial}}{{<partial2}}{{/partial2}}{{/partial}}", // "partials": { // "partial": "{{$inheritable}}ignored{{/inheritable}}", // "partial2": "{{$inheritable}}inherited{{/inheritable}}" }, // "expected": "inherited" // }, // { // "name": "Two levels of inheritance: inherited partial with overriding content containing another inherited partial with overriding content containing an inheritable section", // "data": { }, // "template": "{{<partial}}{{<partial2}}{{$inheritable}}inherited{{/inheritable}}{{/partial2}}{{/partial}}", // "partials": { // "partial": "{{$inheritable}}ignored{{/inheritable}}", // "partial2": "{{$inheritable}}ignored{{/inheritable}}" }, // "expected": "inherited" // } let (resolvedSection1, modified1) = resolveInheritableSection(section, inOverridingTemplateAST: inheritedPartial.parentPartial.templateAST) let (resolvedSection2, modified2) = resolveInheritableSection(resolvedSection1, inOverridingTemplateAST: inheritedPartial.overridingTemplateAST) return (resolvedSection2, modified || modified1 || modified2) case .PartialNode(let partial): // {{> partial }} // // Relevant test: // // { // "name": "Partials in inherited partials can override inheritable sections", // "data": { }, // "template": "{{<partial2}}{{>partial1}}{{/partial2}}", // "partials": { // "partial1": "{{$inheritable}}partial1{{/inheritable}}", // "partial2": "{{$inheritable}}ignored{{/inheritable}}" }, // "expected": "partial1" // }, let (resolvedSection1, modified1) = resolveInheritableSection(section, inOverridingTemplateAST: partial.templateAST) return (resolvedSection1, modified || modified1) default: // Other nodes can't override the section. return (section, modified) } } } }
mit
ee5a4e199bbef297b6a9123e1d7d7ff6
44.66087
334
0.555005
5.394863
false
false
false
false
SwifterSwift/SwifterSwift
Tests/UIKitTests/UITextViewExtensionsTests.swift
1
3040
// UITextViewExtensionsTests.swift - Copyright 2020 SwifterSwift @testable import SwifterSwift import XCTest #if canImport(UIKit) && !os(watchOS) import UIKit final class UITextViewExtensionsTests: XCTestCase { var textView = UITextView(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) override func setUp() { super.setUp() } func testClear() { textView.text = "Hello" textView.clear() XCTAssertEqual(textView.text, "") XCTAssertEqual(textView.attributedText?.string, "") } func testScroll() { let text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation." textView.text = text textView.scrollToBottom() XCTAssertGreaterThan(textView.contentOffset.y, 0.0) textView.scrollToTop() XCTAssertNotEqual(textView.contentOffset.y, 0.0) } func testWrapToContent() { let text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." // initial setting textView.frame = CGRect(origin: .zero, size: CGSize(width: 100, height: 20)) textView.font = UIFont.systemFont(ofSize: 20.0) textView.text = text // determining the text size let constraintRect = CGSize(width: 100, height: CGFloat.greatestFiniteMagnitude) let boundingBox = text.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [.font: textView.font!], context: nil) let textHeight = ceil(boundingBox.height) let textSize = CGSize(width: 100, height: textHeight) // before setting wrap, content won't be equal to bounds XCTAssertNotEqual(textView.bounds.size, textView.contentSize) // calling the wrap extension method textView.wrapToContent() // Setting the frame: // This is important to set the frame after calling the wrapToContent, otherwise // boundingRect can give you fractional value, and method call `sizeToFit` inside the // wrapToContent would change to the fractional value instead of the ceil value. textView.bounds = CGRect(origin: .zero, size: textSize) #if !targetEnvironment(macCatalyst) // after setting wrap, content size will be equal to bounds XCTAssertEqual(textView.bounds.size, textView.contentSize) #endif } } #endif
mit
6d9f52344f2339c739d6122896c5532e
41.816901
459
0.667434
5.214408
false
true
false
false
schrockblock/eson
Example/Eson/MyPlayground.playground/Contents.swift
1
1725
//: Playground - noun: a place where people can play import UIKit //let neo = Human() //neo.name = "Neo" //neo.title = "The Chosen One" //neo.shipName = "Nebuchadnezzar" let number: Int = 3 let intString = "Human" let intIns = NSClassFromString(intString) public class ServerObject: NSObject { public var objectId: Int! } ServerObject().respondsToSelector(Selector("objectId")) class NSStringSerializer: NSObject { var stringExample: String? func objectForValue(value: AnyObject?) -> AnyObject? { return value } func exampleValue() -> AnyObject { stringExample = String(NSDate().timeIntervalSince1970) return String() } } class Eph: NSObject { static var currentUser: Eph? var objectId = 0 var name: String? var major: String? var extracurriculars: String? var currentActivity: String? var imageUrl: String? let deviceType = "ios" var pushToken: String? static func generateDummyUser() -> Eph { let user = Eph() user.name = "Ephraim Williams"; user.major = "Defeating-the-French major"; user.extracurriculars = "Being a Colonel, Establishing schools"; user.currentActivity = "Namesake of the best college evar"; user.imageUrl = "https://s-media-cache-ak0.pinimg.com/736x/9e/a7/90/9ea790fc99d386ff0126e1ee1ac8265a.jpg"; return user } } let eph = Eph.generateDummyUser() let serializer = NSStringSerializer() serializer.exampleValue().dynamicType eph.name!.dynamicType eph.name!.dynamicType == serializer.exampleValue().dynamicType serializer.exampleValue() is String let y = serializer.exampleValue().dynamicType let x = "".dynamicType y == String.self
mit
63d78d72b87c702241a3c6794b1bbaa5
25.538462
114
0.686377
3.701717
false
false
false
false
jairoeli/Habit
Zero/Sources/Views/MarkdownBar.swift
1
2073
// // MarkdownBar.swift // Zero // // Created by Jairo Eli de Leon on 6/27/17. // Copyright © 2017 Jairo Eli de León. All rights reserved. // import UIKit import RxCocoa import RxSwift final class MarkdownBar: UIView { struct Metric { static let buttonWidth = 58.f static let buttonHeight = 35.f } // MARK: UI fileprivate lazy var toolbar = UIView() <== { $0.backgroundColor = .snow } fileprivate lazy var saveButton = UIButton(type: .system) <== { $0.setTitle("Save", for: .normal) $0.titleLabel?.font = .black(size: 16) $0.setTitleColor(.snow, for: .normal) $0.backgroundColor = .azure $0.layer.cornerRadius = 4 } var isEnabled: Bool = false { didSet { self.saveButton.isEnabled = isEnabled } } fileprivate let separatorView = UIView() <== { $0.backgroundColor = .platinumBorder } // MARK: Initializing override init(frame: CGRect) { super.init(frame: frame) self.translatesAutoresizingMaskIntoConstraints = false let subviews: [UIView] = [toolbar, separatorView, saveButton] self.add(subviews) setupLayout() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Size override var intrinsicContentSize: CGSize { return CGSize(width: self.width, height: 45) } // MARK: - Layout fileprivate func setupLayout() { self.separatorView.snp.makeConstraints { make in make.top.left.right.equalToSuperview() make.height.equalTo(1 / UIScreen.main.scale) } self.toolbar.snp.makeConstraints { make in make.edges.equalToSuperview() } self.saveButton.snp.makeConstraints { make in make.centerY.equalToSuperview() make.height.equalTo(Metric.buttonHeight) make.width.equalTo(Metric.buttonWidth) make.trailing.equalTo(-12) } } } // MARK: - Reactive extension Reactive where Base: MarkdownBar { var saveButtonTap: ControlEvent<Void> { let source = base.saveButton.rx.tap return ControlEvent(events: source) } }
mit
78347e0345764808adfc8c996273369e
21.268817
65
0.669242
3.990366
false
false
false
false
regexident/Gestalt
GestaltDemo/Views/StageDesignView.swift
1
1109
// // StageDesignView.swift // GestaltDemo // // Created by Vincent Esche on 5/15/18. // Copyright © 2018 Vincent Esche. All rights reserved. // import UIKit import Gestalt @IBDesignable class StageDesignView: UIView { @IBOutlet private var lightView: UIImageView? @IBOutlet private var fixtureView: UIImageView? @IBOutlet private var shadowView: UIImageView? override func awakeFromNib() { super.awakeFromNib() self.observe(theme: \ApplicationTheme.custom.stageDesign) } } extension StageDesignView: Themeable { typealias Theme = StageDesignViewTheme func apply(theme: Theme) { UIView.performWithoutAnimation { self.backgroundColor = theme.backgroundColor self.shadowView?.layer.opacity = theme.shadowOpacity } UIView.animate(withDuration: 5.0, animations: { self.lightView?.layer.opacity = theme.lightOpacity }) self.lightView?.image = theme.lightImage self.fixtureView?.image = theme.fixtureImage self.shadowView?.image = theme.shadowImage } }
mpl-2.0
59fe3bf0ba49c696f1d423bb156a2182
24.767442
65
0.6787
4.48583
false
false
false
false
enstulen/ARKitAnimation
Pods/SwiftCharts/SwiftCharts/Layers/ChartPointsViewsLayer.swift
2
6701
// // ChartPointsViewsLayer.swift // SwiftCharts // // Created by ischuetz on 27/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public enum ChartPointsViewsLayerMode { case scaleAndTranslate, translate, custom } open class ChartPointsViewsLayer<T: ChartPoint, U: UIView>: ChartPointsLayer<T> { public typealias ChartPointViewGenerator = (_ chartPointModel: ChartPointLayerModel<T>, _ layer: ChartPointsViewsLayer<T, U>, _ chart: Chart) -> U? public typealias ViewWithChartPoint = (view: U, chartPointModel: ChartPointLayerModel<T>) open internal(set) var viewsWithChartPoints: [ViewWithChartPoint] = [] fileprivate let delayBetweenItems: Float = 0 let viewGenerator: ChartPointViewGenerator fileprivate var conflictSolver: ChartViewsConflictSolver<T, U>? fileprivate let mode: ChartPointsViewsLayerMode // For cases when layers behind re-add subviews on pan/zoom, ensure views of this layer stays on front // TODO z ordering fileprivate let keepOnFront: Bool public let delayInit: Bool public var customTransformer: ((ChartPointLayerModel<T>, UIView, ChartPointsViewsLayer<T, U>) -> Void)? fileprivate let clipViews: Bool public init(xAxis: ChartAxis, yAxis: ChartAxis, chartPoints:[T], viewGenerator: @escaping ChartPointViewGenerator, conflictSolver: ChartViewsConflictSolver<T, U>? = nil, displayDelay: Float = 0, delayBetweenItems: Float = 0, mode: ChartPointsViewsLayerMode = .scaleAndTranslate, keepOnFront: Bool = true, delayInit: Bool = false, clipViews: Bool = true) { self.viewGenerator = viewGenerator self.conflictSolver = conflictSolver self.mode = mode self.keepOnFront = keepOnFront self.delayInit = delayInit self.clipViews = clipViews super.init(xAxis: xAxis, yAxis: yAxis, chartPoints: chartPoints, displayDelay: displayDelay) } override open func display(chart: Chart) { super.display(chart: chart) if !delayInit { initViews(chart) } } open func initViews(_ chart: Chart) { viewsWithChartPoints = generateChartPointViews(chartPointModels: chartPointsModels, chart: chart) if delayBetweenItems =~ 0 { for v in viewsWithChartPoints {addSubview(chart, view: v.view)} } else { for viewWithChartPoint in viewsWithChartPoints { let view = viewWithChartPoint.view addSubview(chart, view: view) } } } func addSubview(_ chart: Chart, view: UIView) { switch mode { case .scaleAndTranslate: chart.addSubview(view) case .translate: fallthrough case .custom: if !clipViews { chart.addSubviewNoTransformUnclipped(view) } else { chart.addSubviewNoTransform(view) } } } func reloadViews() { guard let chart = chart else {return} for v in viewsWithChartPoints { v.view.removeFromSuperview() } display(chart: chart) } fileprivate func generateChartPointViews(chartPointModels: [ChartPointLayerModel<T>], chart: Chart) -> [ViewWithChartPoint] { let viewsWithChartPoints: [ViewWithChartPoint] = chartPointsModels.flatMap {model in if let view = viewGenerator(model, self, chart) { return (view: view, chartPointModel: model) } else { return nil } } conflictSolver?.solveConflicts(views: viewsWithChartPoints) return viewsWithChartPoints } override open func chartPointsForScreenLoc(_ screenLoc: CGPoint) -> [T] { return filterChartPoints{inXBounds(screenLoc.x, view: $0.view) && inYBounds(screenLoc.y, view: $0.view)} } override open func chartPointsForScreenLocX(_ x: CGFloat) -> [T] { return filterChartPoints{inXBounds(x, view: $0.view)} } override open func chartPointsForScreenLocY(_ y: CGFloat) -> [T] { return filterChartPoints{inYBounds(y, view: $0.view)} } fileprivate func filterChartPoints(_ filter: (ViewWithChartPoint) -> Bool) -> [T] { return viewsWithChartPoints.reduce([]) {arr, viewWithChartPoint in if filter(viewWithChartPoint) { return arr + [viewWithChartPoint.chartPointModel.chartPoint] } else { return arr } } } fileprivate func inXBounds(_ x: CGFloat, view: UIView) -> Bool { return (x > view.frame.origin.x) && (x < (view.frame.origin.x + view.frame.width)) } fileprivate func inYBounds(_ y: CGFloat, view: UIView) -> Bool { return (y > view.frame.origin.y) && (y < (view.frame.origin.y + view.frame.height)) } open override func zoom(_ x: CGFloat, y: CGFloat, centerX: CGFloat, centerY: CGFloat) { super.zoom(x, y: y, centerX: centerX, centerY: centerY) updateForTransform() } open override func pan(_ deltaX: CGFloat, deltaY: CGFloat) { super.pan(deltaX, deltaY: deltaY) updateForTransform() } func updateForTransform() { switch mode { case .scaleAndTranslate: updateChartPointsScreenLocations() case .translate: for i in 0..<viewsWithChartPoints.count { viewsWithChartPoints[i].chartPointModel.screenLoc = modelLocToScreenLoc(x: viewsWithChartPoints[i].chartPointModel.chartPoint.x.scalar, y: viewsWithChartPoints[i].chartPointModel.chartPoint.y.scalar) viewsWithChartPoints[i].view.center = viewsWithChartPoints[i].chartPointModel.screenLoc } case .custom: for i in 0..<viewsWithChartPoints.count { customTransformer?(viewsWithChartPoints[i].chartPointModel, viewsWithChartPoints[i].view, self) } } if keepOnFront { bringToFront() } } open override func modelLocToScreenLoc(x: Double, y: Double) -> CGPoint { switch mode { case .scaleAndTranslate: return super.modelLocToScreenLoc(x: x, y: y) case .translate: fallthrough case .custom: return super.modelLocToContainerScreenLoc(x: x, y: y) } } open func bringToFront() { for (view, _) in viewsWithChartPoints { view.superview?.bringSubview(toFront: view) } } }
mit
f554f283e71d331ef5532b1c30713ec4
34.643617
359
0.622594
4.729005
false
false
false
false
benjaminhorner/BHModalPushBackTransition
BHModalPushBack/BHModalPushBackTransition.swift
1
2830
// // BHModalPushBackTransition.swift // BHModalPushBack // // Created by Benjamin Horner on 10/12/2015. // Copyright © 2015 Qanda. All rights reserved. // import UIKit class BHModalPushBackTransition: NSObject, UIViewControllerAnimatedTransitioning { let duration = 0.35 let startSize: CGFloat = 1 let endSize: CGFloat = 0.95 let startOpacity: CGFloat = 1 let endOpacity: CGFloat = 0.65 let startPosition: CGFloat = UIScreen.mainScreen().bounds.height let endPosition: CGFloat = 30 var presenting: Bool = true func transitionDuration(transitionContext: UIViewControllerContextTransitioning?)-> NSTimeInterval { return duration } func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView()! let fromVC = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) let showingView = presenting ? fromVC!.view : toVC!.view let modalView = presenting ? toVC!.view : fromVC!.view let toView = modalView let origin = presenting ? startPosition : endPosition let end = presenting ? endPosition : startPosition let xScaleFactorOrigin = presenting ? startSize : endSize let yScaleFactorOrigin = presenting ? startSize : endSize let xScaleFactorEnd = presenting ? endSize : startSize let yScaleFactorEnd = presenting ? endSize : startSize let scaleTransformOrigin = CGAffineTransformMakeScale(CGFloat(xScaleFactorOrigin), CGFloat(yScaleFactorOrigin)) let scaleTransformEnd = CGAffineTransformMakeScale(CGFloat(xScaleFactorEnd), CGFloat(yScaleFactorEnd)) let opacityOrigin = presenting ? startOpacity : endOpacity let opacityEnd = presenting ? endOpacity : startOpacity showingView.transform = scaleTransformOrigin showingView.alpha = opacityOrigin modalView.frame.origin.y = origin containerView.addSubview(toView) toVC?.beginAppearanceTransition(true, animated: true) UIView.animateWithDuration(duration, animations: { () -> Void in modalView.frame.origin.y = end showingView.transform = scaleTransformEnd showingView.alpha = opacityEnd }) { (completed) -> Void in toVC?.endAppearanceTransition() transitionContext.completeTransition(true) } } }
mit
d9a28e5c73d0a700c6e058238b4aa222
31.517241
119
0.64369
6.083871
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/AviasalesSource/PriceCalendar/PriceCalendarChart/PriceCalendarPriceView.swift
1
3237
// // PriceCalendarPriceView.swift // Aviasales iOS Apps // // Created by Dmitry Ryumin on 15/06/15. // Copyright (c) 2015 aviasales. All rights reserved. // import UIKit private let arrowWidth: CGFloat = 12.0 private let arrowHeight: CGFloat = 6.0 private let cornerRadius: CGFloat = 6.0 private let noPriceText = "–" class PriceCalendarPriceView: UIView { fileprivate let textLabel = UILabel() fileprivate let bubbleLayer = CAShapeLayer() fileprivate var widthConstraint: NSLayoutConstraint! override init(frame: CGRect) { super.init(frame: frame) textLabel.textAlignment = NSTextAlignment.center textLabel.font = UIFont.systemFont(ofSize: 13, weight: UIFont.Weight.medium) textLabel.textColor = JRColorScheme.mainColor() addSubview(textLabel) textLabel.translatesAutoresizingMaskIntoConstraints = false addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-19-[textLabel]-19-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["textLabel": textLabel])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-6-[textLabel]-12-|", options: NSLayoutConstraint.FormatOptions(), metrics: nil, views: ["textLabel": textLabel])) textLabel.text = noPriceText layer.addSublayer(bubbleLayer) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() bubbleLayer.path = makePath(bounds) bubbleLayer.fillColor = UIColor.clear.cgColor bubbleLayer.strokeColor = JRColorScheme.mainColor().cgColor } private func makePath(_ rect: CGRect) -> CGPath? { let path = CGMutablePath() path.move(to: CGPoint(x: 0, y: rect.height/2)) path.addArc(tangent1End: .zero, tangent2End: CGPoint(x: rect.width, y: 0), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: rect.width, y: 0), tangent2End: CGPoint(x: rect.width, y: rect.height), radius: cornerRadius) path.addArc(tangent1End: CGPoint(x: rect.width, y: rect.height - arrowHeight), tangent2End: CGPoint(x: 0, y: rect.height - arrowHeight), radius: cornerRadius) path.addLine(to: CGPoint(x: rect.width/2 + arrowWidth/2, y: rect.height - arrowHeight)) path.addLine(to: CGPoint(x: rect.width/2, y: rect.height)) path.addLine(to: CGPoint(x: rect.width/2 - arrowWidth/2, y: rect.height - arrowHeight)) path.addArc(tangent1End: CGPoint(x: 0, y: rect.height - arrowHeight), tangent2End: .zero, radius: cornerRadius) path.addLine(to: CGPoint(x: 0, y: rect.height/2)) return path.copy() } } extension PriceCalendarPriceView { func setPriceCalendarDeparture(_ departure: JRSDKPriceCalendarDeparture) { if let value = departure.minPrice() { let format = NSLS("PRICE_CALENDAR_PRICE_VIEW_TEXT") let price = JRSDKPrice.price(currency: RUB_CURRENCY, value: value.floatValue)?.formattedPriceinUserCurrency() ?? noPriceText textLabel.text = String(format: format, price) } else { textLabel.text = noPriceText } } }
mit
99797a031f0849386e59f1722dcec38f
37.511905
191
0.686862
4.121019
false
false
false
false
OscarSwanros/swift
test/IDE/coloring.swift
7
23776
// RUN: %target-swift-ide-test -syntax-coloring -source-filename %s | %FileCheck %s // RUN: %target-swift-ide-test -syntax-coloring -typecheck -source-filename %s | %FileCheck %s // XFAIL: broken_std_regex #line 17 "abc.swift" // CHECK: <kw>#line</kw> <int>17</int> <str>"abc.swift"</str> @available(iOS 8.0, OSX 10.10, *) // CHECK: <attr-builtin>@available</attr-builtin>(<kw>iOS</kw> <float>8.0</float>, <kw>OSX</kw> <float>10.10</float>, *) func foo() { // CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> <float>10.10</float>, <kw>iOS</kw> <float>8.01</float>, *) {<kw>let</kw> <kw>_</kw> = <str>"iOS"</str>} if #available (OSX 10.10, iOS 8.01, *) {let _ = "iOS"} } enum List<T> { case Nil // rdar://21927124 // CHECK: <attr-builtin>indirect</attr-builtin> <kw>case</kw> Cons(T, List) indirect case Cons(T, List) } // CHECK: <kw>struct</kw> S { struct S { // CHECK: <kw>var</kw> x : <type>Int</type> var x : Int // CHECK: <kw>var</kw> y : <type>Int</type>.<type>Int</type> var y : Int.Int // CHECK: <kw>var</kw> a, b : <type>Int</type> var a, b : Int } enum EnumWithDerivedEquatableConformance : Int { // CHECK-LABEL: <kw>enum</kw> EnumWithDerivedEquatableConformance : {{(<type>)}}Int{{(</type>)?}} { case CaseA // CHECK-NEXT: <kw>case</kw> CaseA case CaseB, CaseC // CHECK-NEXT: <kw>case</kw> CaseB, CaseC case CaseD = 30, CaseE // CHECK-NEXT: <kw>case</kw> CaseD = <int>30</int>, CaseE } // CHECK-NEXT: } // CHECK: <kw>class</kw> MyCls { class MyCls { // CHECK: <kw>var</kw> www : <type>Int</type> var www : Int // CHECK: <kw>func</kw> foo(x: <type>Int</type>) {} func foo(x: Int) {} // CHECK: <kw>var</kw> aaa : <type>Int</type> { var aaa : Int { // CHECK: <kw>get</kw> {} get {} // CHECK: <kw>set</kw> {} set {} } // CHECK: <kw>var</kw> bbb : <type>Int</type> { var bbb : Int { // CHECK: <kw>set</kw> { set { // CHECK: <kw>var</kw> tmp : <type>Int</type> var tmp : Int } // CHECK: <kw>get</kw> { get { // CHECK: <kw>var</kw> tmp : <type>Int</type> var tmp : Int } } // CHECK: <kw>subscript</kw> (i : <type>Int</type>, j : <type>Int</type>) -> <type>Int</type> { subscript (i : Int, j : Int) -> Int { // CHECK: <kw>get</kw> { get { // CHECK: <kw>return</kw> i + j return i + j } // CHECK: <kw>set</kw>(v) { set(v) { // CHECK: v + i - j v + i - j } } // CHECK: <kw>func</kw> multi(<kw>_</kw> name: <type>Int</type>, otherpart x: <type>Int</type>) {} func multi(_ name: Int, otherpart x: Int) {} } // CHECK-LABEL: <kw>class</kw> Attributes { class Attributes { // CHECK: <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> v0: <type>Int</type> @IBOutlet var v0: Int // CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-id>@IBOutlet</attr-id> <kw>var</kw> {{(<attr-builtin>)?}}v1{{(</attr-builtin>)?}}: <type>String</type> @IBOutlet @IBOutlet var v1: String // CHECK: <attr-builtin>@objc</attr-builtin> <attr-builtin>@IBOutlet</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v2{{(</attr-builtin>)?}}: <type>String</type> @objc @IBOutlet var v2: String // CHECK: <attr-builtin>@IBOutlet</attr-builtin> <attr-builtin>@objc</attr-builtin> <kw>var</kw> {{(<attr-builtin>)?}}v3{{(</attr-builtin>)?}}: <type>String</type> @IBOutlet @objc var v3: String // CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f1() {} @available(*, unavailable) func f1() {} // CHECK: <attr-builtin>@available</attr-builtin>(*, unavailable) <attr-builtin>@IBAction</attr-builtin> <kw>func</kw> f2() {} @available(*, unavailable) @IBAction func f2() {} // CHECK: <attr-builtin>@IBAction</attr-builtin> <attr-builtin>@available</attr-builtin>(*, unavailable) <kw>func</kw> f3() {} @IBAction @available(*, unavailable) func f3() {} // CHECK: <attr-builtin>mutating</attr-builtin> <kw>func</kw> func_mutating_1() {} mutating func func_mutating_1() {} // CHECK: <attr-builtin>nonmutating</attr-builtin> <kw>func</kw> func_mutating_2() {} nonmutating func func_mutating_2() {} } func stringLikeLiterals() { // CHECK: <kw>var</kw> us1: <type>UnicodeScalar</type> = <str>"a"</str> var us1: UnicodeScalar = "a" // CHECK: <kw>var</kw> us2: <type>UnicodeScalar</type> = <str>"ы"</str> var us2: UnicodeScalar = "ы" // CHECK: <kw>var</kw> ch1: <type>Character</type> = <str>"a"</str> var ch1: Character = "a" // CHECK: <kw>var</kw> ch2: <type>Character</type> = <str>"あ"</str> var ch2: Character = "あ" // CHECK: <kw>var</kw> s1 = <str>"abc абвгд あいうえお"</str> var s1 = "abc абвгд あいうえお" } // CHECK: <kw>var</kw> globComp : <type>Int</type> var globComp : Int { // CHECK: <kw>get</kw> { get { // CHECK: <kw>return</kw> <int>0</int> return 0 } } // CHECK: <comment-block>/* foo is the best */</comment-block> /* foo is the best */ // CHECK: <kw>func</kw> foo(n: <type>Float</type>) -> <type>Int</type> { func foo(n: Float) -> Int { // CHECK: <kw>var</kw> fnComp : <type>Int</type> var fnComp : Int { // CHECK: <kw>get</kw> { get { // CHECK: <kw>var</kw> a: <type>Int</type> // CHECK: <kw>return</kw> <int>0</int> var a: Int return 0 } } // CHECK: <kw>var</kw> q = {{(<type>)?}}MyCls{{(</type>)?}}() var q = MyCls() // CHECK: <kw>var</kw> ee = <str>"yoo"</str>; var ee = "yoo"; // CHECK: <kw>return</kw> <int>100009</int> return 100009 } ///- returns: single-line, no space // CHECK: ///- <doc-comment-field>returns</doc-comment-field>: single-line, no space /// - returns: single-line, 1 space // CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 1 space /// - returns: single-line, 2 spaces // CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, 2 spaces /// - returns: single-line, more spaces // CHECK: /// - <doc-comment-field>returns</doc-comment-field>: single-line, more spaces // CHECK: <kw>protocol</kw> Prot { protocol Prot { // CHECK: <kw>typealias</kw> Blarg typealias Blarg // CHECK: <kw>func</kw> protMeth(x: <type>Int</type>) func protMeth(x: Int) // CHECK: <kw>var</kw> protocolProperty1: <type>Int</type> { <kw>get</kw> } var protocolProperty1: Int { get } // CHECK: <kw>var</kw> protocolProperty2: <type>Int</type> { <kw>get</kw> <kw>set</kw> } var protocolProperty2: Int { get set } } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-* : FunnyPrecedence{{$}} infix operator *-* : FunnyPrecedence // CHECK: <kw>precedencegroup</kw> FunnyPrecedence // CHECK-NEXT: <kw>associativity</kw>: left{{$}} // CHECK-NEXT: <kw>higherThan</kw>: MultiplicationPrecedence precedencegroup FunnyPrecedence { associativity: left higherThan: MultiplicationPrecedence } // CHECK: <kw>func</kw> *-*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}} func *-*(l: Int, r: Int) -> Int { return l } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *-+* : FunnyPrecedence infix operator *-+* : FunnyPrecedence // CHECK: <kw>func</kw> *-+*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}} func *-+*(l: Int, r: Int) -> Int { return l } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> *--*{{$}} infix operator *--* // CHECK: <kw>func</kw> *--*(l: <type>Int</type>, r: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> l }{{$}} func *--*(l: Int, r: Int) -> Int { return l } // CHECK: <kw>protocol</kw> Prot2 : <type>Prot</type> {} protocol Prot2 : Prot {} // CHECK: <kw>class</kw> SubCls : <type>MyCls</type>, <type>Prot</type> {} class SubCls : MyCls, Prot {} // CHECK: <kw>func</kw> genFn<T : <type>Prot</type> <kw>where</kw> <type>T</type>.<type>Blarg</type> : <type>Prot2</type>>(<kw>_</kw>: <type>T</type>) -> <type>Int</type> {}{{$}} func genFn<T : Prot where T.Blarg : Prot2>(_: T) -> Int {} func f(x: Int) -> Int { // CHECK: <comment-line>// string interpolation is the best</comment-line> // string interpolation is the best // CHECK: <str>"This is string </str>\<anchor>(</anchor>genFn({(a:<type>Int</type> -> <type>Int</type>) <kw>in</kw> a})<anchor>)</anchor><str> interpolation"</str> "This is string \(genFn({(a:Int -> Int) in a})) interpolation" // CHECK: <str>"This is unterminated</str> "This is unterminated // CHECK: <str>"This is unterminated with ignored \(interpolation) in it</str> "This is unterminated with ignored \(interpolation) in it // CHECK: <str>"This is terminated with invalid \(interpolation" + "in it"</str> "This is terminated with invalid \(interpolation" + "in it" // CHECK: <str>""" // CHECK-NEXT: This is a multiline string. // CHECK-NEXT: """</str> """ This is a multiline string. """ // CHECK: <str>""" // CHECK-NEXT: This is a multiline</str>\<anchor>(</anchor> <str>"interpolated"</str> <anchor>)</anchor><str>string // CHECK-NEXT: </str>\<anchor>(</anchor> // CHECK-NEXT: <str>""" // CHECK-NEXT: inner // CHECK-NEXT: """</str> // CHECK-NEXT: <anchor>)</anchor><str> // CHECK-NEXT: """</str> """ This is a multiline\( "interpolated" )string \( """ inner """ ) """ // CHECK: <str>"</str>\<anchor>(</anchor><int>1</int><anchor>)</anchor>\<anchor>(</anchor><int>1</int><anchor>)</anchor><str>"</str> "\(1)\(1)" } // CHECK: <kw>func</kw> bar(x: <type>Int</type>) -> (<type>Int</type>, <type>Float</type>) { func bar(x: Int) -> (Int, Float) { // CHECK: foo({{(<type>)?}}Float{{(</type>)?}}()) foo(Float()) } class GenC<T1,T2> {} func test() { // CHECK: {{(<type>)?}}GenC{{(</type>)?}}<<type>Int</type>, <type>Float</type>>() var x = GenC<Int, Float>() } // CHECK: <kw>typealias</kw> MyInt = <type>Int</type> typealias MyInt = Int func test2(x: Int) { // CHECK: <str>"</str>\<anchor>(</anchor>x<anchor>)</anchor><str>"</str> "\(x)" } // CHECK: <kw>class</kw> Observers { class Observers { // CHECK: <kw>var</kw> p1 : <type>Int</type> { var p1 : Int { // CHECK: <kw>willSet</kw>(newValue) {} willSet(newValue) {} // CHECK: <kw>didSet</kw> {} didSet {} } // CHECK: <kw>var</kw> p2 : <type>Int</type> { var p2 : Int { // CHECK: <kw>didSet</kw> {} didSet {} // CHECK: <kw>willSet</kw> {} willSet {} } } // CHECK: <kw>func</kw> test3(o: <type>AnyObject</type>) { func test3(o: AnyObject) { // CHECK: <kw>let</kw> x = o <kw>as</kw>! <type>MyCls</type> let x = o as! MyCls } // CHECK: <kw>func</kw> test4(<kw>inout</kw> a: <type>Int</type>) {{{$}} func test4(inout a: Int) { // CHECK: <kw>if</kw> <kw>#available</kw> (<kw>OSX</kw> >= <float>10.10</float>, <kw>iOS</kw> >= <float>8.01</float>) {<kw>let</kw> OSX = <str>"iOS"</str>}}{{$}} if #available (OSX >= 10.10, iOS >= 8.01) {let OSX = "iOS"}} // CHECK: <kw>func</kw> test4b(a: <kw>inout</kw> <type>Int</type>) {{{$}} func test4b(a: inout Int) { } // CHECK: <kw>class</kw> MySubClass : <type>MyCls</type> { class MySubClass : MyCls { // CHECK: <attr-builtin>override</attr-builtin> <kw>func</kw> foo(x: <type>Int</type>) {} override func foo(x: Int) {} // CHECK: <attr-builtin>convenience</attr-builtin> <kw>init</kw>(a: <type>Int</type>) {} convenience init(a: Int) {} } // CHECK: <kw>var</kw> g1 = { (x: <type>Int</type>) -> <type>Int</type> <kw>in</kw> <kw>return</kw> <int>0</int> } var g1 = { (x: Int) -> Int in return 0 } // CHECK: <attr-builtin>infix</attr-builtin> <kw>operator</kw> ~~ { infix operator ~~ {} // CHECK: <attr-builtin>prefix</attr-builtin> <kw>operator</kw> *~~ { prefix operator *~~ {} // CHECK: <attr-builtin>postfix</attr-builtin> <kw>operator</kw> ~~* { postfix operator ~~* {} func test_defer() { defer { // CHECK: <kw>let</kw> x : <type>Int</type> = <int>0</int> let x : Int = 0 } } // FIXME: blah. // FIXME: blah blah // Something something, FIXME: blah // CHECK: <comment-line>// <comment-marker>FIXME: blah.</comment-marker></comment-line> // CHECK: <comment-line>// <comment-marker>FIXME: blah blah</comment-marker></comment-line> // CHECK: <comment-line>// Something something, <comment-marker>FIXME: blah</comment-marker></comment-line> /* FIXME: blah*/ // CHECK: <comment-block>/* <comment-marker>FIXME: blah*/</comment-marker></comment-block> /* * FIXME: blah * Blah, blah. */ // CHECK: <comment-block>/* // CHECK: * <comment-marker>FIXME: blah</comment-marker> // CHECK: * Blah, blah. // CHECK: */</comment-block> // TODO: blah. // TTODO: blah. // MARK: blah. // CHECK: <comment-line>// <comment-marker>TODO: blah.</comment-marker></comment-line> // CHECK: <comment-line>// T<comment-marker>TODO: blah.</comment-marker></comment-line> // CHECK: <comment-line>// <comment-marker>MARK: blah.</comment-marker></comment-line> // CHECK: <kw>func</kw> test5() -> <type>Int</type> { func test5() -> Int { // CHECK: <comment-line>// <comment-marker>TODO: something, something.</comment-marker></comment-line> // TODO: something, something. // CHECK: <kw>return</kw> <int>0</int> return 0 } func test6<T : Prot>(x: T) {} // CHECK: <kw>func</kw> test6<T : <type>Prot</type>>(x: <type>T</type>) {}{{$}} // http://whatever.com?ee=2&yy=1 and radar://123456 /* http://whatever.com FIXME: see in http://whatever.com/fixme http://whatever.com */ // CHECK: <comment-line>// <comment-url>http://whatever.com?ee=2&yy=1</comment-url> and <comment-url>radar://123456</comment-url></comment-line> // CHECK: <comment-block>/* <comment-url>http://whatever.com</comment-url> <comment-marker>FIXME: see in <comment-url>http://whatever.com/fixme</comment-url></comment-marker> // CHECK: <comment-url>http://whatever.com</comment-url> */</comment-block> // CHECK: <comment-line>// <comment-url>http://whatever.com/what-ever</comment-url></comment-line> // http://whatever.com/what-ever // CHECK: <kw>func</kw> <placeholder><#test1#></placeholder> () {} func <#test1#> () {} /// Brief. /// /// Simple case. /// /// - parameter x: A number /// - parameter y: Another number /// - PaRamEteR z-hyphen-q: Another number /// - parameter : A strange number... /// - parameternope1: Another number /// - parameter nope2 /// - parameter: nope3 /// -parameter nope4: Another number /// * parameter nope5: Another number /// - parameter nope6: Another number /// - Parameters: nope7 /// - seealso: yes /// - seealso: yes /// - seealso: /// -seealso: nope /// - seealso : nope /// - seealso nope /// - returns: `x + y` func foo(x: Int, y: Int) -> Int { return x + y } // CHECK: <doc-comment-line>/// Brief. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// Simple case. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> x: A number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> y: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>PaRamEteR</doc-comment-field> z-hyphen-q: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>parameter</doc-comment-field> : A strange number... // CHECK: </doc-comment-line><doc-comment-line>/// - parameternope1: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope2 // CHECK: </doc-comment-line><doc-comment-line>/// - parameter: nope3 // CHECK: </doc-comment-line><doc-comment-line>/// -parameter nope4: Another number // CHECK: </doc-comment-line><doc-comment-line>/// * parameter nope5: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - parameter nope6: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - Parameters: nope7 // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: yes // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>seealso</doc-comment-field>: // CHECK: </doc-comment-line><doc-comment-line>/// -seealso: nope // CHECK: </doc-comment-line><doc-comment-line>/// - seealso : nope // CHECK: </doc-comment-line><doc-comment-line>/// - seealso nope // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y` // CHECK: </doc-comment-line><kw>func</kw> foo(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y } /// Brief. /// /// Simple case. /// /// - Parameters: /// - x: A number /// - y: Another number /// ///- note: NOTE1 /// /// - NOTE: NOTE2 /// - note: Not a Note field (not at top level) /// - returns: `x + y` func bar(x: Int, y: Int) -> Int { return x + y } // CHECK: <doc-comment-line>/// Brief. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// Simple case. // CHECK: </doc-comment-line><doc-comment-line>/// // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>Parameters</doc-comment-field>: // CHECK: </doc-comment-line><doc-comment-line>/// - x: A number // CHECK: </doc-comment-line><doc-comment-line>/// - y: Another number // CHECK: </doc-comment-line><doc-comment-line>/// - <doc-comment-field>returns</doc-comment-field>: `x + y` // CHECK: </doc-comment-line><kw>func</kw> bar(x: <type>Int</type>, y: <type>Int</type>) -> <type>Int</type> { <kw>return</kw> x + y } /** Does pretty much nothing. Not a parameter list: improper indentation. - Parameters: sdfadsf - WARNING: - WARNING: Should only have one field - $$$: Not a field. Empty field, OK: */ func baz() {} // CHECK: <doc-comment-block>/** // CHECK: Does pretty much nothing. // CHECK: Not a parameter list: improper indentation. // CHECK: - Parameters: sdfadsf // CHECK: - <doc-comment-field>WARNING</doc-comment-field>: - WARNING: Should only have one field // CHECK: - $$$: Not a field. // CHECK: Empty field, OK: // CHECK: */</doc-comment-block> // CHECK: <kw>func</kw> baz() {} /***/ func emptyDocBlockComment() {} // CHECK: <doc-comment-block>/***/</doc-comment-block> // CHECK: <kw>func</kw> emptyDocBlockComment() {} /** */ func emptyDocBlockComment2() {} // CHECK: <doc-comment-block>/** // CHECK: */ // CHECK: <kw>func</kw> emptyDocBlockComment2() {} /** */ func emptyDocBlockComment3() {} // CHECK: <doc-comment-block>/** */ // CHECK: <kw>func</kw> emptyDocBlockComment3() {} /**/ func malformedBlockComment(f : () throws -> ()) rethrows {} // CHECK: <doc-comment-block>/**/</doc-comment-block> // CHECK: <kw>func</kw> malformedBlockComment(f : () <kw>throws</kw> -> ()) <attr-builtin>rethrows</attr-builtin> {} //: playground doc comment line func playgroundCommentLine(f : () throws -> ()) rethrows {} // CHECK: <comment-line>//: playground doc comment line</comment-line> /*: playground doc comment multi-line */ func playgroundCommentMultiLine(f : () throws -> ()) rethrows {} // CHECK: <comment-block>/*: // CHECK: playground doc comment multi-line // CHECK: */</comment-block> /// [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings) // CHECK: <doc-comment-line>/// [strict weak ordering](<comment-url>http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings</comment-url> func funcTakingFor(for internalName: Int) {} // CHECK: <kw>func</kw> funcTakingFor(for internalName: <type>Int</type>) {} func funcTakingIn(in internalName: Int) {} // CHECK: <kw>func</kw> funcTakingIn(in internalName: <type>Int</type>) {} _ = 123 // CHECK: <int>123</int> _ = -123 // CHECK: <int>-123</int> _ = -1 // CHECK: <int>-1</int> _ = -0x123 // CHECK: <int>-0x123</int> _ = -3.1e-5 // CHECK: <float>-3.1e-5</float> /** aaa - returns: something */ // CHECK: - <doc-comment-field>returns</doc-comment-field>: something let filename = #file // CHECK: <kw>let</kw> filename = <kw>#file</kw> let line = #line // CHECK: <kw>let</kw> line = <kw>#line</kw> let column = #column // CHECK: <kw>let</kw> column = <kw>#column</kw> let function = #function // CHECK: <kw>let</kw> function = <kw>#function</kw> let image = #imageLiteral(resourceName: "cloud.png") // CHECK: <kw>let</kw> image = <object-literal>#imageLiteral(resourceName: "cloud.png")</object-literal> let file = #fileLiteral(resourceName: "cloud.png") // CHECK: <kw>let</kw> file = <object-literal>#fileLiteral(resourceName: "cloud.png")</object-literal> let black = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) // CHECK: <kw>let</kw> black = <object-literal>#colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)</object-literal> let rgb = [#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1), #colorLiteral(red: 0, green: 1, blue: 0, alpha: 1), #colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)] // CHECK: <kw>let</kw> rgb = [<object-literal>#colorLiteral(red: 1, green: 0, blue: 0, alpha: 1)</object-literal>, // CHECK: <object-literal>#colorLiteral(red: 0, green: 1, blue: 0, alpha: 1)</object-literal>, // CHECK: <object-literal>#colorLiteral(red: 0, green: 0, blue: 1, alpha: 1)</object-literal>] "--\"\(x) --" // CHECK: <str>"--\"</str>\<anchor>(</anchor>x<anchor>)</anchor><str> --"</str> func keywordAsLabel1(in: Int) {} // CHECK: <kw>func</kw> keywordAsLabel1(in: <type>Int</type>) {} func keywordAsLabel2(for: Int) {} // CHECK: <kw>func</kw> keywordAsLabel2(for: <type>Int</type>) {} func keywordAsLabel3(if: Int, for: Int) {} // CHECK: <kw>func</kw> keywordAsLabel3(if: <type>Int</type>, for: <type>Int</type>) {} func keywordAsLabel4(_: Int) {} // CHECK: <kw>func</kw> keywordAsLabel4(<kw>_</kw>: <type>Int</type>) {} func keywordAsLabel5(_: Int, for: Int) {} // CHECK: <kw>func</kw> keywordAsLabel5(<kw>_</kw>: <type>Int</type>, for: <type>Int</type>) {} func keywordAsLabel6(if let: Int) {} // CHECK: <kw>func</kw> keywordAsLabel6(if <kw>let</kw>: <type>Int</type>) {} func foo1() { // CHECK: <kw>func</kw> foo1() { keywordAsLabel1(in: 1) // CHECK: keywordAsLabel1(in: <int>1</int>) keywordAsLabel2(for: 1) // CHECK: keywordAsLabel2(for: <int>1</int>) keywordAsLabel3(if: 1, for: 2) // CHECK: keywordAsLabel3(if: <int>1</int>, for: <int>2</int>) keywordAsLabel5(1, for: 2) // CHECK: keywordAsLabel5(<int>1</int>, for: <int>2</int>) _ = (if: 0, for: 2) // CHECK: <kw>_</kw> = (if: <int>0</int>, for: <int>2</int>) _ = (_: 0, _: 2) // CHECK: <kw>_</kw> = (<kw>_</kw>: <int>0</int>, <kw>_</kw>: <int>2</int>) } func foo2(O1 : Int?, O2: Int?, O3: Int?) { guard let _ = O1, var _ = O2, let _ = O3 else { } // CHECK: <kw>guard</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 <kw>else</kw> { } if let _ = O1, var _ = O2, let _ = O3 {} // CHECK: <kw>if</kw> <kw>let</kw> <kw>_</kw> = O1, <kw>var</kw> <kw>_</kw> = O2, <kw>let</kw> <kw>_</kw> = O3 {} } func keywordInCaseAndLocalArgLabel(_ for: Int, for in: Int, class _: Int) { // CHECK: <kw>func</kw> keywordInCaseAndLocalArgLabel(<kw>_</kw> for: <type>Int</type>, for in: <type>Int</type>, class <kw>_</kw>: <type>Int</type>) { switch(`for`, `in`) { case (let x, let y): // CHECK: <kw>case</kw> (<kw>let</kw> x, <kw>let</kw> y): print(x, y) } } #if os(macOS) #endif // CHECK: <#kw>#if</#kw> <#id>os</#id>(<#id>macOS</#id>) // Keep this as the last test /** Trailing off ... func unterminatedBlockComment() {} // CHECK: <comment-line>// Keep this as the last test</comment-line> // CHECK: <doc-comment-block>/** // CHECK: Trailing off ... // CHECK: func unterminatedBlockComment() {} // CHECK: </doc-comment-block>
apache-2.0
3bce7361b72662cfbec376d191444856
35.978193
178
0.604718
2.90291
false
false
false
false
IamAlchemist/DemoAnimations
Animations/UINTViewController.swift
2
2563
// // UINTViewController.swift // DemoAnimations // // Created by Wizard Li on 5/30/16. // Copyright © 2016 Alchemist. All rights reserved. // import UIKit import SnapKit class UINTViewController : UIViewController { var panState : PaneState = .Closed var draggableView : DraggableView! var springAnimation : UINTSpringAnimation? var targetPoint : CGPoint { let size = view.bounds.size return panState == .Closed ? CGPoint(x: size.width/2, y: size.height * 1.25) : CGPoint(x: size.width/2, y: size.height/2 + 200) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.whiteColor() draggableView = DraggableView(frame: CGRectZero) draggableView.layer.cornerRadius = 6 view.addSubview(draggableView) draggableView.snp_makeConstraints { (make) in make.left.equalTo(view) make.right.equalTo(view) make.width.equalTo(view) make.height.equalTo(view) make.top.equalTo(view).offset(view.bounds.height * 0.75) } draggableView.backgroundColor = UIColor.cyanColor() draggableView.delegate = self let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(didPan(_:))) view.addGestureRecognizer(tapRecognizer) } func didPan(gesture : UITapGestureRecognizer){ panState = panState == .Open ? .Closed : .Open guard let springAnimation = springAnimation else { return } startAnimatingView(draggableView, initialVelocity: springAnimation.velocity) } func startAnimatingView(view: DraggableView, initialVelocity: CGPoint) { cancelSpringAnimation() springAnimation = UINTSpringAnimation.animationWithView(view, target: targetPoint, velocity: initialVelocity) view.animator()?.addAnimation(springAnimation!) } private func cancelSpringAnimation() { if let springAnimation = springAnimation{ view.animator()?.removeAnimation(springAnimation) self.springAnimation = nil } } } extension UINTViewController : DraggableViewDelegate { func draggableViewBeganDraggin(view: DraggableView) { cancelSpringAnimation() } func draggableView(view: DraggableView, draggingEndedWithVelocity velocity: CGPoint) { panState = velocity.y >= 0 ? .Closed : .Open startAnimatingView(view, initialVelocity: velocity) } }
mit
24897e17a45de014f5951359101dd035
32.272727
135
0.657689
4.936416
false
false
false
false
zendobk/RealmS
Sources/Mapping.swift
1
2130
// // RealmMapper.swift // RealmS // // Created by DaoNV on 1/12/16. // Copyright © 2016 Apple Inc. All rights reserved. // import RealmSwift import ObjectMapper // MARK: - Main extension RealmS { // MARK: Map /** Import JSON as BaseMappable Object. - parammeter T: BaseMappable Object. - parameter type: mapped type. - parameter json: JSON type is `[String: Any]`. - returns: mapped object. */ @discardableResult public func map<T: Object>(_ type: T.Type, json: [String: Any]) -> T? where T: BaseMappable { guard let obj = Mapper<T>().map(JSON: json) else { return nil } if obj.realm == nil { add(obj) } return obj } /** Import JSON as array of BaseMappable Object. - parammeter T: BaseMappable Object. - parameter type: mapped type. - parameter json: JSON type is `[[String: Any]]`. - returns: mapped objects. */ @discardableResult public func map<T: Object>(_ type: T.Type, json: [[String: Any]]) -> [T] where T: BaseMappable { var objs = [T]() for js in json { if let obj = map(type, json: js) { objs.append(obj) } } return objs } } // MARK: - StaticMappable pre-implement extension RealmS { /** Find cached BaseMappable Object. - parammeter T: BaseMappable Object. - parameter type: object type. - parameter map: Map object contains JSON. - parameter jsPk: primary key of JSON, default is equal to `primaryKey`. - returns: cached object. */ public func object<T: Object>(ofType type: T.Type, forMapping map: Map, jsonPrimaryKey jsPk: String? = T.primaryKey()) -> T? where T: BaseMappable { guard let pk = T.primaryKey(), let jsPk = jsPk else { return T() } guard let id: Any = map[jsPk].value() else { return nil } if let exist = object(ofType: T.self, forPrimaryKey: id) { return exist } let new = T() new.setValue(id, forKey: pk) return new } }
mit
3c42ebca19f6daf8400c6a62e17b9808
27.013158
152
0.572569
4.00188
false
false
false
false
whiteath/ReadFoundationSource
Foundation/NSDictionary.swift
2
26795
// 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 CoreFoundation import Dispatch open class NSDictionary : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding { private let _cfinfo = _CFInfo(typeID: CFDictionaryGetTypeID()) internal var _storage: [NSObject: AnyObject] open var count: Int { guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else { NSRequiresConcreteImplementation() } return _storage.count } open func object(forKey aKey: Any) -> Any? { guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else { NSRequiresConcreteImplementation() } if let val = _storage[_SwiftValue.store(aKey)] { return _SwiftValue.fetch(nonOptional: val) } return nil } open func keyEnumerator() -> NSEnumerator { guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else { NSRequiresConcreteImplementation() } return NSGeneratorEnumerator(_storage.keys.map { _SwiftValue.fetch(nonOptional: $0) }.makeIterator()) } public override convenience init() { self.init(objects: [], forKeys: [], count: 0) } public required init(objects: UnsafePointer<AnyObject>!, forKeys keys: UnsafePointer<NSObject>!, count cnt: Int) { _storage = [NSObject : AnyObject](minimumCapacity: cnt) for idx in 0..<cnt { let key = keys[idx].copy() let value = objects[idx] _storage[key as! NSObject] = value } } public required convenience init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.objects") { let keys = aDecoder._decodeArrayOfObjectsForKey("NS.keys").map() { return $0 as! NSObject } let objects = aDecoder._decodeArrayOfObjectsForKey("NS.objects") self.init(objects: objects as! [NSObject], forKeys: keys) } else { var objects = [AnyObject]() var keys = [NSObject]() var count = 0 while let key = aDecoder.decodeObject(forKey: "NS.key.\(count)"), let object = aDecoder.decodeObject(forKey: "NS.object.\(count)") { keys.append(key as! NSObject) objects.append(object as! NSObject) count += 1 } self.init(objects: objects, forKeys: keys) } } open func encode(with aCoder: NSCoder) { if let keyedArchiver = aCoder as? NSKeyedArchiver { keyedArchiver._encodeArrayOfObjects(self.allKeys._nsObject, forKey:"NS.keys") keyedArchiver._encodeArrayOfObjects(self.allValues._nsObject, forKey:"NS.objects") } else { NSUnimplemented() } } public static var supportsSecureCoding: Bool { return true } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { if type(of: self) === NSDictionary.self { // return self for immutable type return self } else if type(of: self) === NSMutableDictionary.self { let dictionary = NSDictionary() dictionary._storage = self._storage return dictionary } return NSDictionary(objects: self.allValues, forKeys: self.allKeys.map({ $0 as! NSObject})) } open override func mutableCopy() -> Any { return mutableCopy(with: nil) } open func mutableCopy(with zone: NSZone? = nil) -> Any { if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self { // always create and return an NSMutableDictionary let mutableDictionary = NSMutableDictionary() mutableDictionary._storage = self._storage return mutableDictionary } return NSMutableDictionary(objects: self.allValues, forKeys: self.allKeys.map { _SwiftValue.store($0) } ) } public convenience init(object: Any, forKey key: NSCopying) { self.init(objects: [object], forKeys: [key as! NSObject]) } public convenience init(objects: [Any], forKeys keys: [NSObject]) { let keyBuffer = UnsafeMutablePointer<NSObject>.allocate(capacity: keys.count) keyBuffer.initialize(from: keys, count: keys.count) let valueBuffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: objects.count) valueBuffer.initialize(from: objects.map { _SwiftValue.store($0) }, count: objects.count) self.init(objects: valueBuffer, forKeys:keyBuffer, count: keys.count) keyBuffer.deinitialize(count: keys.count) valueBuffer.deinitialize(count: objects.count) keyBuffer.deallocate(capacity: keys.count) valueBuffer.deallocate(capacity: objects.count) } public convenience init(dictionary otherDictionary: [AnyHashable : Any]) { self.init(objects: Array(otherDictionary.values), forKeys: otherDictionary.keys.map { _SwiftValue.store($0) }) } open override func isEqual(_ value: Any?) -> Bool { switch value { case let other as Dictionary<AnyHashable, Any>: return isEqual(to: other) case let other as NSDictionary: return isEqual(to: Dictionary._unconditionallyBridgeFromObjectiveC(other)) default: return false } } open override var hash: Int { return self.count } open var allKeys: [Any] { if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self { return Array(_storage.keys) } else { var keys = [Any]() let enumerator = keyEnumerator() while let key = enumerator.nextObject() { keys.append(key) } return keys } } open var allValues: [Any] { if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self { return Array(_storage.values) } else { var values = [Any]() let enumerator = keyEnumerator() while let key = enumerator.nextObject() { values.append(object(forKey: key)!) } return values } } /// Alternative pseudo funnel method for fastpath fetches from dictionaries /// - Experiment: This is a draft API currently under consideration for official import into Foundation /// - Note: Since this API is under consideration it may be either removed or revised in the near future open func getObjects(_ objects: inout [Any], andKeys keys: inout [Any], count: Int) { if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self { for (key, value) in _storage { keys.append(_SwiftValue.fetch(nonOptional: key)) objects.append(_SwiftValue.fetch(nonOptional: value)) } } else { let enumerator = keyEnumerator() while let key = enumerator.nextObject() { let value = object(forKey: key)! keys.append(key) objects.append(value) } } } open subscript (key: Any) -> Any? { return object(forKey: key) } open func allKeys(for anObject: Any) -> [Any] { var matching = Array<Any>() enumerateKeysAndObjects(options: []) { key, value, _ in if let val = value as? AnyHashable, let obj = anObject as? AnyHashable { if val == obj { matching.append(key) } } } return matching } /// A string that represents the contents of the dictionary, formatted as /// a property list (read-only) /// /// If each key in the dictionary is an NSString object, the entries are /// listed in ascending order by key, otherwise the order in which the entries /// are listed is undefined. This property is intended to produce readable /// output for debugging purposes, not for serializing data. If you want to /// store dictionary data for later retrieval, see /// [Property List Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/PropertyLists/Introduction/Introduction.html#//apple_ref/doc/uid/10000048i) /// and [Archives and Serializations Programming Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Archiving/Archiving.html#//apple_ref/doc/uid/10000047i). open override var description: String { return description(withLocale: nil) } private func getDescription(of object: Any) -> String? { switch object { case is NSArray.Type: return (object as! NSArray).description(withLocale: nil, indent: 1) case is NSDecimalNumber.Type: return (object as! NSDecimalNumber).description(withLocale: nil) case is NSDate.Type: return (object as! NSDate).description(with: nil) case is NSOrderedSet.Type: return (object as! NSOrderedSet).description(withLocale: nil) case is NSSet.Type: return (object as! NSSet).description(withLocale: nil) case is NSDictionary.Type: return (object as! NSDictionary).description(withLocale: nil) default: if let hashableObject = object as? Dictionary<AnyHashable, Any> { return hashableObject._nsObject.description(withLocale: nil, indent: 1) } else { return nil } } } open var descriptionInStringsFileFormat: String { var lines = [String]() for key in self.allKeys { let line = NSMutableString(capacity: 0) line.append("\"") if let descriptionByType = getDescription(of: key) { line.append(descriptionByType) } else { line.append("\(key)") } line.append("\"") line.append(" = ") line.append("\"") let value = self.object(forKey: key)! if let descriptionByTypeValue = getDescription(of: value) { line.append(descriptionByTypeValue) } else { line.append("\(value)") } line.append("\"") line.append(";") lines.append(line._bridgeToSwift()) } return lines.joined(separator: "\n") } /// Returns a string object that represents the contents of the dictionary, /// formatted as a property list. /// /// - parameter locale: An object that specifies options used for formatting /// each of the dictionary’s keys and values; pass `nil` if you don’t /// want them formatted. open func description(withLocale locale: Locale?) -> String { return description(withLocale: locale, indent: 0) } /// Returns a string object that represents the contents of the dictionary, /// formatted as a property list. /// /// - parameter locale: An object that specifies options used for formatting /// each of the dictionary’s keys and values; pass `nil` if you don’t /// want them formatted. /// /// - parameter level: Specifies a level of indentation, to make the output /// more readable: the indentation is (4 spaces) * level. /// /// - returns: A string object that represents the contents of the dictionary, /// formatted as a property list. open func description(withLocale locale: Locale?, indent level: Int) -> String { if level > 100 { return "..." } var lines = [String]() let indentation = String(repeating: " ", count: level * 4) lines.append(indentation + "{") for key in self.allKeys { var line = String(repeating: " ", count: (level + 1) * 4) if key is NSArray { line += (key as! NSArray).description(withLocale: locale, indent: level + 1) } else if key is Date { line += (key as! NSDate).description(with: locale) } else if key is NSDecimalNumber { line += (key as! NSDecimalNumber).description(withLocale: locale) } else if key is NSDictionary { line += (key as! NSDictionary).description(withLocale: locale, indent: level + 1) } else if key is NSOrderedSet { line += (key as! NSOrderedSet).description(withLocale: locale, indent: level + 1) } else if key is NSSet { line += (key as! NSSet).description(withLocale: locale) } else { line += "\(key)" } line += " = " let object = self.object(forKey: key)! if object is NSArray { line += (object as! NSArray).description(withLocale: locale, indent: level + 1) } else if object is Date { line += (object as! NSDate).description(with: locale) } else if object is NSDecimalNumber { line += (object as! NSDecimalNumber).description(withLocale: locale) } else if object is NSDictionary { line += (object as! NSDictionary).description(withLocale: locale, indent: level + 1) } else if object is NSOrderedSet { line += (object as! NSOrderedSet).description(withLocale: locale, indent: level + 1) } else if object is NSSet { line += (object as! NSSet).description(withLocale: locale) } else { if let hashableObject = object as? Dictionary<AnyHashable, Any> { line += hashableObject._nsObject.description(withLocale: nil, indent: level+1) } else { line += "\(object)" } } line += ";" lines.append(line) } lines.append(indentation + "}") return lines.joined(separator: "\n") } open func isEqual(to otherDictionary: [AnyHashable : Any]) -> Bool { if count != otherDictionary.count { return false } for key in keyEnumerator() { if let otherValue = otherDictionary[key as! AnyHashable] as? AnyHashable, let value = object(forKey: key)! as? AnyHashable { if otherValue != value { return false } } else if let otherBridgeable = otherDictionary[key as! AnyHashable] as? _ObjectBridgeable, let bridgeable = object(forKey: key)! as? _ObjectBridgeable { if !(otherBridgeable._bridgeToAnyObject() as! NSObject).isEqual(bridgeable._bridgeToAnyObject()) { return false } } else { return false } } return true } public struct Iterator : IteratorProtocol { let dictionary : NSDictionary var keyGenerator : Array<Any>.Iterator public mutating func next() -> (key: Any, value: Any)? { if let key = keyGenerator.next() { return (key, dictionary.object(forKey: key)!) } else { return nil } } init(_ dict : NSDictionary) { self.dictionary = dict self.keyGenerator = dict.allKeys.makeIterator() } } internal struct ObjectGenerator: IteratorProtocol { let dictionary : NSDictionary var keyGenerator : Array<Any>.Iterator mutating func next() -> Any? { if let key = keyGenerator.next() { return dictionary.object(forKey: key)! } else { return nil } } init(_ dict : NSDictionary) { self.dictionary = dict self.keyGenerator = dict.allKeys.makeIterator() } } open func objectEnumerator() -> NSEnumerator { return NSGeneratorEnumerator(ObjectGenerator(self)) } open func objects(forKeys keys: [Any], notFoundMarker marker: Any) -> [Any] { var objects = [Any]() for key in keys { if let object = object(forKey: key) { objects.append(object) } else { objects.append(marker) } } return objects } open func write(toFile path: String, atomically useAuxiliaryFile: Bool) -> Bool { return write(to: URL(fileURLWithPath: path), atomically: useAuxiliaryFile) } // the atomically flag is ignored if url of a type that cannot be written atomically. open func write(to url: URL, atomically: Bool) -> Bool { do { let pListData = try PropertyListSerialization.data(fromPropertyList: self, format: PropertyListSerialization.PropertyListFormat.xml, options: 0) try pListData.write(to: url, options: atomically ? .atomic : []) return true } catch { return false } } open func enumerateKeysAndObjects(_ block: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) { enumerateKeysAndObjects(options: [], using: block) } open func enumerateKeysAndObjects(options opts: NSEnumerationOptions = [], using block: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Void) { let count = self.count var keys = [Any]() var objects = [Any]() var sharedStop = ObjCBool(false) let lock = NSLock() getObjects(&objects, andKeys: &keys, count: count) let iteration: (Int) -> Void = withoutActuallyEscaping(block) { (closure: @escaping (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Void) -> (Int) -> Void in return { (idx) in lock.lock() var stop = sharedStop lock.unlock() if stop { return } closure(keys[idx], objects[idx], &stop) if stop { lock.lock() sharedStop = stop lock.unlock() return } } } if opts.contains(.concurrent) { DispatchQueue.concurrentPerform(iterations: count, execute: iteration) } else { for idx in 0..<count { iteration(idx) } } } open func keysSortedByValue(comparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] { return keysSortedByValue(options: [], usingComparator: cmptr) } open func keysSortedByValue(options opts: NSSortOptions = [], usingComparator cmptr: (Any, Any) -> ComparisonResult) -> [Any] { let sorted = allKeys.sorted { lhs, rhs in return cmptr(lhs, rhs) == .orderedSame } return sorted } open func keysOfEntries(passingTest predicate: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> { return keysOfEntries(options: [], passingTest: predicate) } open func keysOfEntries(options opts: NSEnumerationOptions = [], passingTest predicate: (Any, Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> { var matching = Set<AnyHashable>() enumerateKeysAndObjects(options: opts) { key, value, stop in if predicate(key, value, stop) { matching.insert(key as! AnyHashable) } } return matching } override open var _cfTypeID: CFTypeID { return CFDictionaryGetTypeID() } required public convenience init(dictionaryLiteral elements: (Any, Any)...) { var keys = [NSObject]() var values = [Any]() for (key, value) in elements { keys.append(_SwiftValue.store(key)) values.append(value) } self.init(objects: values, forKeys: keys) } } extension NSDictionary : _CFBridgeable, _SwiftBridgeable { internal var _cfObject: CFDictionary { return unsafeBitCast(self, to: CFDictionary.self) } internal var _swiftObject: Dictionary<AnyHashable, Any> { return Dictionary._unconditionallyBridgeFromObjectiveC(self) } } extension NSMutableDictionary { internal var _cfMutableObject: CFMutableDictionary { return unsafeBitCast(self, to: CFMutableDictionary.self) } } extension CFDictionary : _NSBridgeable, _SwiftBridgeable { internal var _nsObject: NSDictionary { return unsafeBitCast(self, to: NSDictionary.self) } internal var _swiftObject: [AnyHashable: Any] { return _nsObject._swiftObject } } extension Dictionary : _NSBridgeable, _CFBridgeable { internal var _nsObject: NSDictionary { return _bridgeToObjectiveC() } internal var _cfObject: CFDictionary { return _nsObject._cfObject } } open class NSMutableDictionary : NSDictionary { open func removeObject(forKey aKey: Any) { guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else { NSRequiresConcreteImplementation() } _storage.removeValue(forKey: _SwiftValue.store(aKey)) } /// - Note: this diverges from the darwin version that requires NSCopying (this differential preserves allowing strings and such to be used as keys) open func setObject(_ anObject: Any, forKey aKey: AnyHashable) { guard type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self else { NSRequiresConcreteImplementation() } _storage[(aKey as! NSObject)] = _SwiftValue.store(anObject) } public convenience required init() { self.init(capacity: 0) } public convenience init(capacity numItems: Int) { self.init(objects: [], forKeys: [], count: 0) // It is safe to reset the storage here because we know is empty _storage = [NSObject: AnyObject](minimumCapacity: numItems) } public required init(objects: UnsafePointer<AnyObject>!, forKeys keys: UnsafePointer<NSObject>!, count cnt: Int) { super.init(objects: objects, forKeys: keys, count: cnt) } public convenience init?(contentsOfFile path: String) { self.init(contentsOfURL: URL(fileURLWithPath: path)) } public convenience init?(contentsOfURL url: URL) { do { guard let plistDoc = try? Data(contentsOf: url) else { return nil } let plistDict = try PropertyListSerialization.propertyList(from: plistDoc, options: [], format: nil) as? Dictionary<AnyHashable,Any> guard let plistDictionary = plistDict else { return nil } self.init(dictionary: plistDictionary) } catch { return nil } } } extension NSMutableDictionary { open func addEntries(from otherDictionary: [AnyHashable : Any]) { for (key, obj) in otherDictionary { setObject(obj, forKey: key) } } open func removeAllObjects() { if type(of: self) === NSDictionary.self || type(of: self) === NSMutableDictionary.self { _storage.removeAll() } else { for key in allKeys { removeObject(forKey: key) } } } open func removeObjects(forKeys keyArray: [Any]) { for key in keyArray { removeObject(forKey: key) } } open func setDictionary(_ otherDictionary: [AnyHashable : Any]) { removeAllObjects() for (key, obj) in otherDictionary { setObject(obj, forKey: key) } } /// - Note: See setObject(_:,forKey:) for details on the differential here public subscript (key: AnyHashable) -> Any? { get { return object(forKey: key) } set { if let val = newValue { setObject(val, forKey: key) } else { removeObject(forKey: key) } } } } extension NSDictionary : Sequence { public func makeIterator() -> Iterator { return Iterator(self) } } // MARK - Shared Key Sets extension NSDictionary { /* Use this method to create a key set to pass to +dictionaryWithSharedKeySet:. The keys are copied from the array and must be copyable. If the array parameter is nil or not an NSArray, an exception is thrown. If the array of keys is empty, an empty key set is returned. The array of keys may contain duplicates, which are ignored (it is undefined which object of each duplicate pair is used). As for any usage of hashing, is recommended that the keys have a well-distributed implementation of -hash, and the hash codes must satisfy the hash/isEqual: invariant. Keys with duplicate hash codes are allowed, but will cause lower performance and increase memory usage. */ open class func sharedKeySet(forKeys keys: [NSCopying]) -> Any { NSUnimplemented() } } extension NSMutableDictionary { /* Create a mutable dictionary which is optimized for dealing with a known set of keys. Keys that are not in the key set can still be set into the dictionary, but that usage is not optimal. As with any dictionary, the keys must be copyable. If keyset is nil, an exception is thrown. If keyset is not an object returned by +sharedKeySetForKeys:, an exception is thrown. */ public convenience init(sharedKeySet keyset: Any) { NSUnimplemented() } } extension NSDictionary : ExpressibleByDictionaryLiteral { } extension NSDictionary : CustomReflectable { public var customMirror: Mirror { NSUnimplemented() } } extension NSDictionary : _StructTypeBridgeable { public typealias _StructType = Dictionary<AnyHashable,Any> public func _bridgeToSwift() -> _StructType { return _StructType._unconditionallyBridgeFromObjectiveC(self) } }
apache-2.0
4d161e33c62075a040430bc9f31b4279
37.597983
188
0.597603
4.908741
false
false
false
false
gcharita/XMLMapper
XMLMapper/Classes/XMLNSDecimalNumberTransform.swift
1
876
// // XMLNSDecimalNumberTransform.swift // XMLMapper // // Created by Giorgos Charitakis on 14/09/2017. // // import Foundation open class NSDecimalNumberTransform: XMLTransformType { public typealias Object = NSDecimalNumber public typealias XML = String public init() {} open func transformFromXML(_ value: Any?) -> Object? { if let string = value as? String { return NSDecimalNumber(string: string) } else if let number = value as? NSNumber { return NSDecimalNumber(decimal: number.decimalValue) } else if let double = value as? Double { return NSDecimalNumber(floatLiteral: double) } return nil } open func transformToXML(_ value: NSDecimalNumber?) -> XML? { guard let value = value else { return nil } return value.description } }
mit
dddcbff431d9542f36c5ed89b9d4dc51
26.375
65
0.635845
4.709677
false
false
false
false
Ramotion/animated-tab-bar
RAMAnimatedTabBarController/RAMItemAnimationProtocol.swift
1
3747
// RAMItemAnimationProtocol.swift // // Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit public protocol RAMItemAnimationProtocol { func playAnimation(_ icon: UIImageView, textLabel: UILabel) func deselectAnimation(_ icon: UIImageView, textLabel: UILabel, defaultTextColor: UIColor, defaultIconColor: UIColor) func selectedState(_ icon: UIImageView, textLabel: UILabel) } /// Base class for UITabBarItems animation open class RAMItemAnimation: NSObject, RAMItemAnimationProtocol { // MARK: constants struct Constants { struct AnimationKeys { static let scale = "transform.scale" static let rotation = "transform.rotation" static let keyFrame = "contents" static let positionY = "position.y" static let opacity = "opacity" } } // MARK: properties /// The duration of the animation @IBInspectable open var duration: CGFloat = 0.5 /// The text color in selected state. @IBInspectable open var textSelectedColor: UIColor = UIColor(red: 0, green: 0.478431, blue: 1, alpha: 1) /// The icon color in selected state. @IBInspectable open var iconSelectedColor: UIColor! /** Start animation, method call when UITabBarItem is selected - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel */ open func playAnimation(_: UIImageView, textLabel _: UILabel) { fatalError("override method in subclass") } /** Start animation, method call when UITabBarItem is unselected - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel - parameter defaultTextColor: default UITabBarItem text color - parameter defaultIconColor: default UITabBarItem icon color */ open func deselectAnimation(_: UIImageView, textLabel _: UILabel, defaultTextColor _: UIColor, defaultIconColor _: UIColor) { fatalError("override method in subclass") } /** Method call when TabBarController did load - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel */ open func selectedState(_: UIImageView, textLabel _: UILabel) { fatalError("override method in subclass") } /** (Optional) Method call when TabBarController did load - parameter icon: animating UITabBarItem icon - parameter textLabel: animating UITabBarItem textLabel */ open func deselectedState(_: UIImageView, textLabel _: UILabel) {} }
mit
7e34d92ca20f151c3f18a188f8a45934
36.47
129
0.710702
5.247899
false
false
false
false
ikesyo/swift-corelibs-foundation
TestFoundation/TestTimeZone.swift
6
9979
// 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 // #if DEPLOYMENT_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif class TestTimeZone: XCTestCase { static var allTests: [(String, (TestTimeZone) -> () throws -> Void)] { return [ // Disabled see https://bugs.swift.org/browse/SR-300 // ("test_abbreviation", test_abbreviation), // Disabled because `CFTimeZoneSetAbbreviationDictionary()` attempts // to release non-CF objects while removing values from // `__CFTimeZoneCache` // ("test_abbreviationDictionary", test_abbreviationDictionary), ("test_changingDefaultTimeZone", test_changingDefaultTimeZone), ("test_computedPropertiesMatchMethodReturnValues", test_computedPropertiesMatchMethodReturnValues), ("test_initializingTimeZoneWithOffset", test_initializingTimeZoneWithOffset), ("test_initializingTimeZoneWithAbbreviation", test_initializingTimeZoneWithAbbreviation), ("test_localizedName", test_localizedName), // Also disabled due to https://bugs.swift.org/browse/SR-300 // ("test_systemTimeZoneUsesSystemTime", test_systemTimeZoneUsesSystemTime), ("test_customMirror", test_tz_customMirror), ] } func test_abbreviation() { let tz = NSTimeZone.system let abbreviation1 = tz.abbreviation() let abbreviation2 = tz.abbreviation(for: Date()) XCTAssertEqual(abbreviation1, abbreviation2, "\(abbreviation1 as Optional) should be equal to \(abbreviation2 as Optional)") } func test_abbreviationDictionary() { let oldDictionary = TimeZone.abbreviationDictionary let newDictionary = [ "UTC": "UTC", "JST": "Asia/Tokyo", "GMT": "GMT", "ICT": "Asia/Bangkok", "TEST": "Foundation/TestNSTimeZone" ] TimeZone.abbreviationDictionary = newDictionary XCTAssertEqual(TimeZone.abbreviationDictionary, newDictionary) TimeZone.abbreviationDictionary = oldDictionary XCTAssertEqual(TimeZone.abbreviationDictionary, oldDictionary) } func test_changingDefaultTimeZone() { let oldDefault = NSTimeZone.default let oldSystem = NSTimeZone.system let expectedDefault = TimeZone(identifier: "GMT-0400")! NSTimeZone.default = expectedDefault let newDefault = NSTimeZone.default let newSystem = NSTimeZone.system XCTAssertEqual(oldSystem, newSystem) XCTAssertEqual(expectedDefault, newDefault) let expectedDefault2 = TimeZone(identifier: "GMT+0400")! NSTimeZone.default = expectedDefault2 let newDefault2 = NSTimeZone.default XCTAssertEqual(expectedDefault2, newDefault2) XCTAssertNotEqual(newDefault, newDefault2) NSTimeZone.default = oldDefault let revertedDefault = NSTimeZone.default XCTAssertEqual(oldDefault, revertedDefault) } func test_computedPropertiesMatchMethodReturnValues() { let tz = NSTimeZone.default let obj = tz._bridgeToObjectiveC() let secondsFromGMT1 = tz.secondsFromGMT() let secondsFromGMT2 = obj.secondsFromGMT let secondsFromGMT3 = tz.secondsFromGMT() XCTAssert(secondsFromGMT1 == secondsFromGMT2 || secondsFromGMT2 == secondsFromGMT3, "\(secondsFromGMT1) should be equal to \(secondsFromGMT2), or in the rare circumstance where a daylight saving time transition has just occurred, \(secondsFromGMT2) should be equal to \(secondsFromGMT3)") let abbreviation1 = tz.abbreviation() let abbreviation2 = obj.abbreviation XCTAssertEqual(abbreviation1, abbreviation2, "\(abbreviation1 as Optional) should be equal to \(abbreviation2 as Optional)") let isDaylightSavingTime1 = tz.isDaylightSavingTime() let isDaylightSavingTime2 = obj.isDaylightSavingTime let isDaylightSavingTime3 = tz.isDaylightSavingTime() XCTAssert(isDaylightSavingTime1 == isDaylightSavingTime2 || isDaylightSavingTime2 == isDaylightSavingTime3, "\(isDaylightSavingTime1) should be equal to \(isDaylightSavingTime2), or in the rare circumstance where a daylight saving time transition has just occurred, \(isDaylightSavingTime2) should be equal to \(isDaylightSavingTime3)") let daylightSavingTimeOffset1 = tz.daylightSavingTimeOffset() let daylightSavingTimeOffset2 = obj.daylightSavingTimeOffset XCTAssertEqual(daylightSavingTimeOffset1, daylightSavingTimeOffset2, "\(daylightSavingTimeOffset1) should be equal to \(daylightSavingTimeOffset2)") let nextDaylightSavingTimeTransition1 = tz.nextDaylightSavingTimeTransition let nextDaylightSavingTimeTransition2 = obj.nextDaylightSavingTimeTransition let nextDaylightSavingTimeTransition3 = tz.nextDaylightSavingTimeTransition(after: Date()) XCTAssert(nextDaylightSavingTimeTransition1 == nextDaylightSavingTimeTransition2 || nextDaylightSavingTimeTransition2 == nextDaylightSavingTimeTransition3, "\(nextDaylightSavingTimeTransition1 as Optional) should be equal to \(nextDaylightSavingTimeTransition2 as Optional), or in the rare circumstance where a daylight saving time transition has just occurred, \(nextDaylightSavingTimeTransition2 as Optional) should be equal to \(nextDaylightSavingTimeTransition3 as Optional)") } func test_knownTimeZoneNames() { let known = NSTimeZone.knownTimeZoneNames XCTAssertNotEqual([], known, "known time zone names not expected to be empty") } func test_localizedName() { #if os(Android) XCTFail("Named timezones not available on Android") #else let initialTimeZone = NSTimeZone.default NSTimeZone.default = TimeZone(identifier: "America/New_York")! let defaultTimeZone = NSTimeZone.default let locale = Locale(identifier: "en_US") XCTAssertEqual(defaultTimeZone.localizedName(for: .standard, locale: locale), "Eastern Standard Time") XCTAssertEqual(defaultTimeZone.localizedName(for: .shortStandard, locale: locale), "EST") XCTAssertEqual(defaultTimeZone.localizedName(for: .generic, locale: locale), "Eastern Time") XCTAssertEqual(defaultTimeZone.localizedName(for: .daylightSaving, locale: locale), "Eastern Daylight Time") XCTAssertEqual(defaultTimeZone.localizedName(for: .shortDaylightSaving, locale: locale), "EDT") XCTAssertEqual(defaultTimeZone.localizedName(for: .shortGeneric, locale: locale), "ET") NSTimeZone.default = initialTimeZone //reset the TimeZone #endif } func test_initializingTimeZoneWithOffset() { let tz = TimeZone(identifier: "GMT-0400") XCTAssertNotNil(tz) let seconds = tz?.secondsFromGMT(for: Date()) ?? 0 XCTAssertEqual(seconds, -14400, "GMT-0400 should be -14400 seconds but got \(seconds) instead") let tz2 = TimeZone(secondsFromGMT: -14400) XCTAssertNotNil(tz2) let expectedName = "GMT-0400" let actualName = tz2?.identifier XCTAssertEqual(actualName, expectedName, "expected name \"\(expectedName)\" is not equal to \"\(actualName as Optional)\"") let expectedLocalizedName = "GMT-04:00" let actualLocalizedName = tz2?.localizedName(for: .generic, locale: Locale(identifier: "en_US")) XCTAssertEqual(actualLocalizedName, expectedLocalizedName, "expected name \"\(expectedLocalizedName)\" is not equal to \"\(actualLocalizedName as Optional)\"") let seconds2 = tz2?.secondsFromGMT() ?? 0 XCTAssertEqual(seconds2, -14400, "GMT-0400 should be -14400 seconds but got \(seconds2) instead") let tz3 = TimeZone(identifier: "GMT-9999") XCTAssertNil(tz3) XCTAssertNotNil(TimeZone(secondsFromGMT: -18 * 3600)) XCTAssertNotNil(TimeZone(secondsFromGMT: 18 * 3600)) XCTAssertNil(TimeZone(secondsFromGMT: -18 * 3600 - 1)) XCTAssertNil(TimeZone(secondsFromGMT: 18 * 3600 + 1)) } func test_initializingTimeZoneWithAbbreviation() { // Test invalid timezone abbreviation var tz = TimeZone(abbreviation: "XXX") XCTAssertNil(tz) // Test valid timezone abbreviation of "AST" for "America/Halifax" tz = TimeZone(abbreviation: "AST") let expectedIdentifier = "America/Halifax" let actualIdentifier = tz?.identifier XCTAssertEqual(actualIdentifier, expectedIdentifier, "expected identifier \"\(expectedIdentifier)\" is not equal to \"\(actualIdentifier as Optional)\"") } func test_systemTimeZoneUsesSystemTime() { tzset() var t = time(nil) var lt = tm() localtime_r(&t, &lt) let zoneName = NSTimeZone.system.abbreviation() ?? "Invalid Abbreviation" let expectedName = String(cString: lt.tm_zone, encoding: String.Encoding.ascii) ?? "Invalid Zone" XCTAssertEqual(zoneName, expectedName, "expected name \"\(expectedName)\" is not equal to \"\(zoneName)\"") } func test_tz_customMirror() { let tz = TimeZone.current let mirror = Mirror(reflecting: tz as TimeZone) var children = [String : Any](minimumCapacity: Int(mirror.children.count)) mirror.children.forEach { if let label = $0.label { children[label] = $0.value } } XCTAssertNotNil(children["identifier"]) XCTAssertNotNil(children["kind"]) XCTAssertNotNil(children["secondsFromGMT"]) XCTAssertNotNil(children["isDaylightSavingTime"]) } }
apache-2.0
0a18133b33c6a8d4faf9fdffd5cff55d
47.916667
488
0.700471
5.08873
false
true
false
false
clrung/DCMetroWidget
DCMetroWidget/SettingsViewController.swift
1
4029
// // SettingsViewController.swift // DCMetro // // Created by Christopher Rung on 6/30/16. // Copyright © 2016 Christopher Rung. All rights reserved. // import Cocoa import NotificationCenter import CoreLocation import WMATAFetcher var didSelectStation: Bool = false class SettingsViewController: NCWidgetListViewController { @IBOutlet weak var selectStationTextField: NSTextField! @IBOutlet weak var selectStationAndRadioButtonsHeightConstraint: NSLayoutConstraint! @IBOutlet weak var stationRadioButton1: NSButton! @IBOutlet weak var stationRadioButton2: NSButton! @IBOutlet weak var stationRadioButton3: NSButton! @IBOutlet weak var stationRadioButton4: NSButton! @IBOutlet weak var stationRadioButton5: NSButton! var stationRadioButtons: [NSButton] = [] @IBOutlet weak var chooseFromListTextField: NSTextField! @IBOutlet weak var stationPopUpButton: NSPopUpButton! @IBOutlet weak var unitsSegmentedControl: NSSegmentedControl! override var nibName: String? { return "SettingsViewController" } override func viewDidLoad() { super.viewDidLoad() setupPopUpButton() UserDefaults.standard.bool(forKey: "isMetric") ? unitsSegmentedControl.setSelected(true, forSegment: 1) : unitsSegmentedControl.setSelected(true, forSegment: 0) } override func viewWillAppear() { super.viewWillAppear() } override func viewWillLayout() { super.viewWillLayout() stationRadioButtons = [stationRadioButton1, stationRadioButton2, stationRadioButton3, stationRadioButton4, stationRadioButton5] if currentLocation != nil { selectStationAndRadioButtonsHeightConstraint.constant = 23 chooseFromListTextField.stringValue = "or choose from the list" populateStationRadioButtonTitles() } else { selectStationAndRadioButtonsHeightConstraint.constant = 2 chooseFromListTextField.stringValue = "Choose a station from the list" for radioButton in stationRadioButtons { radioButton.isHidden = true } } } func setupPopUpButton() { let sortedStations = Station.allValues.sorted( by: { $0.description < $1.description } ) for station in sortedStations { stationPopUpButton.addItem(withTitle: station.description) var rawValue = station.rawValue switch rawValue { case Station.C01.rawValue: rawValue = Station.A01.rawValue case Station.F01.rawValue: rawValue = Station.B01.rawValue case Station.E06.rawValue: rawValue = Station.B06.rawValue case Station.F03.rawValue: rawValue = Station.D03.rawValue default: break } stationPopUpButton.item(withTitle: station.description)?.representedObject = rawValue } stationPopUpButton.selectItem(withTitle: selectedStation.description) } @IBAction func touchStationRadioButton(_ sender: NSButton) { setSelectedStation(fiveClosestStations[sender.tag].rawValue) sender.state = NSOnState } @IBAction func touchStationPopUpButton(_ sender: NSPopUpButton) { setSelectedStation(sender.selectedItem?.representedObject as! String) } @IBAction func touchUnitsSegmentedControl(_ sender: NSSegmentedControl) { unitsSegmentedControl.isSelected(forSegment: 1) ? UserDefaults.standard.set(true, forKey: "isMetric") : UserDefaults.standard.set(false, forKey: "isMetric") populateStationRadioButtonTitles() } func setSelectedStation(_ selectedStationCode: String) { for radioButton in stationRadioButtons { radioButton.state = NSOffState } selectedStation = Station(rawValue: selectedStationCode)! UserDefaults.standard.set(selectedStation.rawValue, forKey: "selectedStation") didSelectStation = true } func populateStationRadioButtonTitles() { for (index, radioButton) in stationRadioButtons.enumerated() { radioButton.isHidden = false let station = fiveClosestStations[index] let distance = WMATAfetcher.getDistanceFromStation(location: currentLocation!, station: station, isMetric: unitsSegmentedControl.isSelected(forSegment: 1)) stationRadioButtons[index].title = station.description + String(format: " (%@)", distance) } } }
mit
1b0dbf66f3a798852536256c0122c838
33.135593
162
0.779543
4.226653
false
false
false
false
waltflanagan/AdventOfCode
2017/AdventOfCode.playground/Pages/2018 Day 3.xcplaygroundpage/Contents.swift
1
1811
//: [Previous](@previous) import Foundation struct Instruction { let name: String let rect: CGRect init(aocString: String) { let components = aocString.components(separatedBy: " @ ") name = components.first! rect = CGRect(aocString: components.last!) } } let f = #fileLiteral(resourceName: "instructions.txt") f let contents = try! NSString(contentsOf: f, encoding: String.Encoding.utf8.rawValue) let rows = contents.trimmingCharacters(in: .newlines).components(separatedBy: .newlines) let instructions = rows.map { Instruction(aocString: $0) } extension CGPoint { init(aocString: String) { let components = aocString.components(separatedBy: ",") let x = Int(components.first!)! let y = Int(components.last!)! self.init(x: x, y: y) } } extension CGSize { init(aocString: String) { let components = aocString.components(separatedBy: "x") let width = Int(components.first!)! let height = Int(components.last!)! self.init(width: width, height: height) } } extension CGRect { init(aocString: String) { let components = aocString.components(separatedBy: ": ") //"922,417" let coordinateString = components.first! let sizeString = components.last! self.init(origin: CGPoint(aocString: coordinateString), size: CGSize(aocString: sizeString)) } } extension CGPoint: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(Int(x)) hasher.combine(Int(y) * 100_000_000) } } let rects = instructions.map({ $0.rect }) let context = Context() context.addRects(rects) context.overlapping let name = instructions.filter({ !context.rectOverlaps($0.rect) }).first?.name name //: [Next](@next)
mit
5aa0a98be8a846a095304442c439254d
24.507042
100
0.652126
3.765073
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Foundation/UIAlgorithm/UIAlgorithm/ViewController.swift
1
3266
// // ViewController.swift // UIAlgorithm // // Created by 朱双泉 on 2018/5/18. // Copyright © 2018 Castie!. All rights reserved. // import UIKit extension UIColor { var toImage: UIImage { let bounds = CGRect(origin: .zero, size: CGSize(width: 1.0, height: 1.0)) let renderer = UIGraphicsImageRenderer(bounds: bounds) return renderer.image { context in self.setFill() context.fill(CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)) } } } extension Int { var arc4random: Int { if self > 0 { return Int(arc4random_uniform(UInt32(self))) } else if self < 0 { return -Int(arc4random_uniform(UInt32(self))) } else { return 0 } } } extension UIViewController { var contents: UIViewController { if let navcon = self as? UINavigationController { return navcon.visibleViewController ?? navcon } else { return self } } } class ViewController: UIViewController, UIPopoverPresentationControllerDelegate { @IBOutlet var lights: [UIButton]! { didSet { for (index, light) in lights.enumerated() { light.setBackgroundImage(UIColor.yellow.toImage, for: .normal) light.setBackgroundImage(UIColor.darkGray.toImage, for: .selected) light.isSelected = switchs.lights[index] == 1 ? true : false } } } @IBAction func lightUp(_ sender: UIButton) { switchs.lightUp(index: lights.index(of: sender)) for (index, light) in lights.enumerated() { light.isSelected = switchs.lights[index] == 1 ? true : false } if Set(switchs.lights).count == 1 { let alert = UIAlertController(title: "Congratulation", message: "You made all light up successfully", preferredStyle: .alert) alert.addAction(UIAlertAction( title: "again", style: .default, handler: { [weak self] _ in self?.restart() } )) present(alert, animated: true) } } @IBAction func restart(_ sender: UIButton? = nil) { switchs = LightSwitch(matrix: Matrix(rows: 5, columns: 6)) for (index, light) in (self.lights.enumerated()) { light.isSelected = self.switchs.lights[index] == 1 ? true : false } } @IBOutlet weak var hintButton: UIButton! @IBAction func hintUp(_ sender: UIButton) { switchs.hintUp() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "Show Hint", let destination = segue.destination.contents as? HintViewController, let ppc = destination.popoverPresentationController { ppc.delegate = self ppc.sourceRect = hintButton.bounds destination.switchs = switchs } } func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } var switchs: LightSwitch = LightSwitch(matrix: Matrix(rows: 5, columns: 6)) }
mit
ab4dc3e587b6e46ee2cc2a9e40a3a8e4
30.95098
142
0.586683
4.495172
false
false
false
false