repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
richeterre/jumu-nordost-ios
JumuNordost/Application/PerformanceCell.swift
1
3080
// // PerformanceCell.swift // JumuNordost // // Created by Martin Richter on 21/02/16. // Copyright © 2016 Martin Richter. All rights reserved. // import Cartography class PerformanceCell: UITableViewCell { private let timeLabel = Label(fontWeight: .Bold, fontStyle: .Normal, fontSize: .Medium) private let categoryInfoLabel = Label(fontWeight: .Bold, fontStyle: .Normal, fontSize: .Medium) private let mainAppearancesLabel = Label(fontWeight: .Regular, fontStyle: .Normal, fontSize: .Medium) private let accompanistsLabel = Label(fontWeight: .Regular, fontStyle: .Normal, fontSize: .Medium) private let predecessorInfoLabel = Label(fontWeight: .Regular, fontStyle: .Normal, fontSize: .Medium) // MARK: - Lifecycle override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: .Default, reuseIdentifier: reuseIdentifier) mainAppearancesLabel.numberOfLines = 0 accompanistsLabel.numberOfLines = 0 contentView.addSubview(timeLabel) contentView.addSubview(categoryInfoLabel) contentView.addSubview(predecessorInfoLabel) contentView.addSubview(mainAppearancesLabel) contentView.addSubview(accompanistsLabel) makeConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Layout private func makeConstraints() { constrain(contentView, timeLabel) { contentView, timeLabel in timeLabel.top == contentView.topMargin timeLabel.left == contentView.leftMargin timeLabel.width == 43 } constrain(categoryInfoLabel, timeLabel, contentView) { categoryInfoLabel, timeLabel, contentView in align(top: timeLabel, categoryInfoLabel) categoryInfoLabel.left == timeLabel.right + 8 categoryInfoLabel.right == contentView.rightMargin } constrain(categoryInfoLabel, mainAppearancesLabel, accompanistsLabel, predecessorInfoLabel, contentView) { categoryInfoLabel, mainAppearancesLabel, accompanistsLabel, predecessorInfoLabel, contentView in align(left: categoryInfoLabel, mainAppearancesLabel, accompanistsLabel, predecessorInfoLabel) align(right: categoryInfoLabel, mainAppearancesLabel, accompanistsLabel, predecessorInfoLabel) mainAppearancesLabel.top == categoryInfoLabel.bottom + 8 accompanistsLabel.top == mainAppearancesLabel.bottom predecessorInfoLabel.top == accompanistsLabel.bottom + 8 predecessorInfoLabel.bottom == contentView.bottomMargin } } // MARK: - Content func configure(performance: FormattedListPerformance) { timeLabel.text = performance.stageTime categoryInfoLabel.text = "\(performance.category), \(performance.ageGroup)" mainAppearancesLabel.text = performance.mainAppearances accompanistsLabel.text = performance.accompanists predecessorInfoLabel.text = performance.predecessorInfo } }
mit
ca7a0078b48727e1c7d94099cab47205
38.987013
211
0.714518
5.131667
false
false
false
false
openhab/openhab.ios
OpenHABCore/Sources/OpenHABCore/Util/Future.swift
1
3578
// Copyright (c) 2010-2022 Contributors to the openHAB project // // See the NOTICE file(s) distributed with this work for additional // information. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // http://www.eclipse.org/legal/epl-2.0 // // SPDX-License-Identifier: EPL-2.0 import Foundation // swiftlint:disable file_types_order public class Future<Value> { public typealias Result = Swift.Result<Value, Error> fileprivate var result: Result? { // Observe whenever a result is assigned, and report it: didSet { result.map(report) } } private var callbacks = [(Result) -> Void]() public func observe(using callback: @escaping (Result) -> Void) { // If a result has already been set, call the callback directly: if let result = result { return callback(result) } callbacks.append(callback) } private func report(result: Result) { callbacks.forEach { $0(result) } callbacks = [] } } public class Promise<Value>: Future<Value> { public init(value: Value? = nil) { super.init() // If the value was already known at the time the promise // was constructed, we can report it directly: result = value.map(Result.success) } public func resolve(with value: Value) { result = .success(value) } public func reject(with error: Error) { result = .failure(error) } } public enum NetworkingError: Error { case invalidURL } public typealias Networking = (Endpoint) -> Future<Data> extension Future { func chained<T>(using closure: @escaping (Value) throws -> Future<T>) -> Future<T> { // We'll start by constructing a "wrapper" promise that will be // returned from this method: let promise = Promise<T>() // Observe the current future: observe { result in switch result { case let .success(value): do { // Attempt to construct a new future using the value // returned from the first one: let future = try closure(value) // Observe the "nested" future, and once it // completes, resolve/reject the "wrapper" future: future.observe { result in switch result { case let .success(value): promise.resolve(with: value) case let .failure(error): promise.reject(with: error) } } } catch { promise.reject(with: error) } case let .failure(error): promise.reject(with: error) } } return promise } } public extension Future { func transformed<T>(with closure: @escaping (Value) throws -> T) -> Future<T> { chained { value in try Promise(value: closure(value)) } } } // extension Future where Value == Data { // func decoded<T: Decodable>() -> Future<T> { // decoded(as: T.self, using: JSONDecoder()) // } // } public extension Future where Value == Data { func decoded<T: Decodable>(as type: T.Type = T.self, using decoder: JSONDecoder = .init()) -> Future<T> { transformed { data in try decoder.decode(T.self, from: data) } } }
epl-1.0
d68099bdc1a34cb45de523b69594a52f
28.570248
109
0.564841
4.466916
false
false
false
false
MadAppGang/SmartLog
iOS/Pods/CoreStore/Sources/DataStack+Observing.swift
2
12747
// // DataStack+Observing.swift // CoreStore // // Copyright © 2015 John Rommel Estropia // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreData // MARK: - DataStack @available(OSX 10.12, *) public extension DataStack { /** Creates an `ObjectMonitor` for the specified `DynamicObject`. Multiple `ObjectObserver`s may then register themselves to be notified when changes are made to the `DynamicObject`. - parameter object: the `DynamicObject` to observe changes from - returns: a `ObjectMonitor` that monitors changes to `object` */ public func monitorObject<T: DynamicObject>(_ object: T) -> ObjectMonitor<T> { CoreStore.assert( Thread.isMainThread, "Attempted to observe objects from \(cs_typeName(self)) outside the main thread." ) return ObjectMonitor(dataStack: self, object: object) } /** Creates a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ public func monitorList<T: DynamicObject>(_ from: From<T>, _ fetchClauses: FetchClause...) -> ListMonitor<T> { return self.monitorList(from, fetchClauses) } /** Creates a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ public func monitorList<T: DynamicObject>(_ from: From<T>, _ fetchClauses: [FetchClause]) -> ListMonitor<T> { CoreStore.assert( Thread.isMainThread, "Attempted to observe objects from \(cs_typeName(self)) outside the main thread." ) return ListMonitor( dataStack: self, from: from, sectionBy: nil, applyFetchClauses: { fetchRequest in fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) } CoreStore.assert( fetchRequest.sortDescriptors?.isEmpty == false, "An \(cs_typeName(ListMonitor<T>.self)) requires a sort information. Specify from a \(cs_typeName(OrderBy.self)) clause or any custom \(cs_typeName(FetchClause.self)) that provides a sort descriptor." ) } ) } /** Asynchronously creates a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed. - parameter createAsynchronously: the closure that receives the created `ListMonitor` instance - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ public func monitorList<T: DynamicObject>(createAsynchronously: @escaping (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: FetchClause...) { self.monitorList(createAsynchronously: createAsynchronously, from, fetchClauses) } /** Asynchronously creates a `ListMonitor` for a list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed. - parameter createAsynchronously: the closure that receives the created `ListMonitor` instance - parameter from: a `From` clause indicating the entity type - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ public func monitorList<T: DynamicObject>(createAsynchronously: @escaping (ListMonitor<T>) -> Void, _ from: From<T>, _ fetchClauses: [FetchClause]) { CoreStore.assert( Thread.isMainThread, "Attempted to observe objects from \(cs_typeName(self)) outside the main thread." ) _ = ListMonitor( dataStack: self, from: from, sectionBy: nil, applyFetchClauses: { fetchRequest in fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) } CoreStore.assert( fetchRequest.sortDescriptors?.isEmpty == false, "An \(cs_typeName(ListMonitor<T>.self)) requires a sort information. Specify from a \(cs_typeName(OrderBy.self)) clause or any custom \(cs_typeName(FetchClause.self)) that provides a sort descriptor." ) }, createAsynchronously: createAsynchronously ) } /** Creates a `ListMonitor` for a sectioned list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. - parameter from: a `From` clause indicating the entity type - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ public func monitorSectionedList<T: DynamicObject>(_ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) -> ListMonitor<T> { return self.monitorSectionedList(from, sectionBy, fetchClauses) } /** Creates a `ListMonitor` for a sectioned list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. - parameter from: a `From` clause indicating the entity type - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. - returns: a `ListMonitor` instance that monitors changes to the list */ public func monitorSectionedList<T: DynamicObject>(_ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) -> ListMonitor<T> { CoreStore.assert( Thread.isMainThread, "Attempted to observe objects from \(cs_typeName(self)) outside the main thread." ) return ListMonitor( dataStack: self, from: from, sectionBy: sectionBy, applyFetchClauses: { fetchRequest in fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) } CoreStore.assert( fetchRequest.sortDescriptors?.isEmpty == false, "An \(cs_typeName(ListMonitor<T>.self)) requires a sort information. Specify from a \(cs_typeName(OrderBy.self)) clause or any custom \(cs_typeName(FetchClause.self)) that provides a sort descriptor." ) } ) } /** Asynchronously creates a `ListMonitor` for a sectioned list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed. - parameter createAsynchronously: the closure that receives the created `ListMonitor` instance - parameter from: a `From` clause indicating the entity type - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ public func monitorSectionedList<T: DynamicObject>(createAsynchronously: @escaping (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: FetchClause...) { self.monitorSectionedList(createAsynchronously: createAsynchronously, from, sectionBy, fetchClauses) } /** Asynchronously creates a `ListMonitor` for a sectioned list of `DynamicObject`s that satisfy the specified fetch clauses. Multiple `ListObserver`s may then register themselves to be notified when changes are made to the list. Since `NSFetchedResultsController` greedily locks the persistent store on initial fetch, you may prefer this method instead of the synchronous counterpart to avoid deadlocks while background updates/saves are being executed. - parameter createAsynchronously: the closure that receives the created `ListMonitor` instance - parameter from: a `From` clause indicating the entity type - parameter sectionBy: a `SectionBy` clause indicating the keyPath for the attribute to use when sorting the list into sections. - parameter fetchClauses: a series of `FetchClause` instances for fetching the object list. Accepts `Where`, `OrderBy`, and `Tweak` clauses. */ public func monitorSectionedList<T: DynamicObject>(createAsynchronously: @escaping (ListMonitor<T>) -> Void, _ from: From<T>, _ sectionBy: SectionBy, _ fetchClauses: [FetchClause]) { CoreStore.assert( Thread.isMainThread, "Attempted to observe objects from \(cs_typeName(self)) outside the main thread." ) _ = ListMonitor( dataStack: self, from: from, sectionBy: sectionBy, applyFetchClauses: { fetchRequest in fetchClauses.forEach { $0.applyToFetchRequest(fetchRequest) } CoreStore.assert( fetchRequest.sortDescriptors?.isEmpty == false, "An \(cs_typeName(ListMonitor<T>.self)) requires a sort information. Specify from a \(cs_typeName(OrderBy.self)) clause or any custom \(cs_typeName(FetchClause.self)) that provides a sort descriptor." ) }, createAsynchronously: createAsynchronously ) } }
mit
2a67a8ae7193ac43bd2e6c5f2135836c
56.674208
455
0.683744
5.253916
false
false
false
false
dylan/GistSwift
GistSwift/Gist.swift
1
6320
///// ___ _ _ ___ _ __ _ //// / __(_)__| |_/ __|_ __ _(_)/ _| |_ /// | (_ | (_-< _\__ \ V V / | _| _| // \___|_/__/\__|___/\_/\_/|_|_| \__| import Foundation import GistSwiftWrapper public final class Gist { fileprivate let gist: OpaquePointer /// The class for performing all Gist audio analyses. /// /// - parameters: /// - frameSize: The input audio frame size. /// - sampleRate: The input sample rate. public init(frameSize: Int, sampleRate: Int) { gist = initGist(Int32(frameSize), Int32(sampleRate)) } /// Process an audio frame. /// /// - parameters: /// - frame: The audio frame to process. /// - samples: The number of samples in the audio frame. public func processAudio(frame: [Float]) { var frame = frame GistSwiftWrapper.processAudioFrame(gist, &frame, UInt(frame.count)) } /// Gist automatically calculates the magnitude spectrum when processAudioFrame() is called, this function returns it. /// /// - returns: The current magnitude spectrum. public func magnitudeSpectrum() -> [Float] { let value = GistSwiftWrapper.magnitudeSpectrum(gist) let bufferPointer = UnsafeBufferPointer<Float>(start: value.elements, count: Int(value.numElements)) defer { free(value.elements) } return Array(bufferPointer) } // MARK: - Core Time Domain Features /// The average signal energy observed in each audio frame, i.e., an indication of signal energy or loudness. /// /// - returns: The root mean square (RMS) of the currently stored audio frame. public func rootMeanSquare() -> Float { return GistSwiftWrapper.rootMeanSquare(gist) } /// The maximum observed signal value in each audio frame, i.e., an indication of signal energy or loudness. /// /// - returns: The peak energy of the currently stored audio frame. public func peakEnergy() -> Float { return GistSwiftWrapper.peakEnergy(gist) } /// The count of zero crossings in each observed frame, i.e., A feature giving an indication of the brightness of a sound. /// /// - returns: The count of zero crossings in each observed frame. public func zeroCrossingRate() -> Float { return GistSwiftWrapper.zeroCrossingRate(gist) } // MARK: - Core Frequency Domain Features /// The centre of mass of the magnitude spectrum, i.e., a feature correlated with the brightness of a sound. /// /// - returns: The spectral centroid from the magnitude spectrum. public func spectralCentroid() -> Float { return GistSwiftWrapper.spectralCentroid(gist) } /// The ratio of the maximum value in the power spectrum to the mean, i.e., the measure of how tonal the signal is. /// /// - returns: The spectral crest. public func spectralCrest() -> Float { return GistSwiftWrapper.spectralCrest(gist) } /// The geometric mean of the magnitude spectrum divided by the arithmetic mean, i.e., an indication of how "noise-like" the signal is. /// /// - returns: The spectral flatness of the magnitude spectrum. public func spectralFlatness() -> Float { return GistSwiftWrapper.spectralFlatness(gist) } /// - returns: The spectral rolloff of the magnitude spectrum. public func spectralRolloff() -> Float { return GistSwiftWrapper.spectralRolloff(gist) } /// - returns: The spectral kurtosis of the magnitude spectrum. public func spectralKurtosis() -> Float { return GistSwiftWrapper.spectralKurtosis(gist) } // MARK: - Onset Detection /// - returns: Calculates the energy difference onset detection function. public func energyDifference() -> Float { return GistSwiftWrapper.energyDifference(gist) } /// - returns: Calculates the spectral difference onset detection function sample for the magnitude spectrum frame. public func spectralDifference() -> Float { return GistSwiftWrapper.spectralDifference(gist) } /// - returns: Calculates the half wave rectified spectral difference between the current magnitude spectrum and the previous magnitude spectrum. public func spectralDifferenceHWR() -> Float { return GistSwiftWrapper.spectralDifferenceHWR(gist) } /// - returns: Calculates the complex spectral difference from the real and imaginary parts of the FFT. public func complexSpectralDifference() -> Float { return GistSwiftWrapper.complexSpectralDifference(gist) } /// - returns: Calculates the high frequency content onset detection function from the magnitude spectrum. public func highFrequencyContent() -> Float { return GistSwiftWrapper.highFrequencyContent(gist) } // MARK: - Pitch Detection /// An implementation of the Yin pitch detection algorithm by de Cheveigne and Kawahara (2002). Output in Hz. /// /// - returns: An estimation of the pitch in Hz of a sound - for use on monophonic signals only. public func pitch() -> Float { return GistSwiftWrapper.pitch(gist) } // MARK: - Mel Frequency Related /// The magnitude spectrum mapped on to a Mel scale using a bank of triangular filters, i.e., a feature showing you how energy is distributed across the frequency range, on a scale related to human perception. /// /// - returns: The Mel Frequency Spectrum. public func melFrequencySpectrum() -> [Float] { let value = GistSwiftWrapper.melFrequencySpectrum(gist) let bufferPointer = UnsafeBufferPointer<Float>(start: value.elements, count: Int(value.numElements)) defer { free(value.elements) } return Array(bufferPointer) } /// - returns: the Mel Frequency Cepstral Coefficients as an array of ```Float```. public func melFrequencyCepstralCoefficients() -> [Float] { let value = GistSwiftWrapper.melFrequencyCepstralCoefficients(gist) let bufferPointer = UnsafeBufferPointer<Float>(start: value.elements, count: Int(value.numElements)) defer { free(value.elements) } return Array(bufferPointer) } // MARK: - deinit { GistSwiftWrapper.deinitGist(gist) } }
gpl-3.0
12ac75ff81b0d755179c1e7f3afc9f78
37.536585
213
0.660918
4.391939
false
false
false
false
alankarmisra/SwiftSignatureView
Pod/Classes/SwiftSignatureView.swift
1
5124
// // SwiftSignatureView.swift // SwiftSignatureView // // Created by Alankar Misra on 6/23/15. // // SwiftSignatureView is available under the MIT license. See the LICENSE file for more info. import UIKit import PencilKit public protocol ISignatureView: AnyObject { var delegate: SwiftSignatureViewDelegate? { get set } var scale: CGFloat { get set } var maximumStrokeWidth: CGFloat { get set } var minimumStrokeWidth: CGFloat { get set } var strokeColor: UIColor { get set } var strokeAlpha: CGFloat { get set } var signature: UIImage? { get set } var isEmpty: Bool { get } func clear(cache: Bool) func undo() func redo() func getCroppedSignature() -> UIImage? } extension ISignatureView { func clear(cache: Bool = false) { self.clear(cache: cache) } } /// A lightweight, fast and customizable option for capturing fluid, variable-stroke-width signatures within your app. open class SwiftSignatureView: UIView, ISignatureView { private var viewReady: Bool = false private lazy var instance: ISignatureView = { if #available(iOS 13.0, *) { return PencilKitSignatureView(frame: bounds) } return LegacySwiftSignatureView(frame: bounds) }() public weak var delegate: SwiftSignatureViewDelegate? { didSet { instance.delegate = self.delegate } } @IBInspectable public var scale: CGFloat { get { instance.scale } set { instance.scale = newValue } } /** The minimum stroke width. WARNING: This property is ignored in iOS13+. */ @IBInspectable public var minimumStrokeWidth: CGFloat { get { instance.minimumStrokeWidth } set { instance.minimumStrokeWidth = newValue } } /** The maximum stroke width. */ @IBInspectable public var maximumStrokeWidth: CGFloat { get { instance.maximumStrokeWidth } set { instance.maximumStrokeWidth = newValue } } /** The stroke color. */ @IBInspectable public var strokeColor: UIColor { get { instance.strokeColor } set { instance.strokeColor = newValue } } /** The stroke alpha. Prefer higher values to prevent stroke segments from showing through. */ @IBInspectable public var strokeAlpha: CGFloat { get { instance.strokeAlpha } set { instance.strokeAlpha = newValue } } /** The UIImage representation of the signature. Read/write. */ @IBInspectable public var signature: UIImage? { get { instance.signature } set { instance.signature = newValue } } open var isEmpty: Bool { get { instance.isEmpty } } /** Clear the signature. */ public func clear(cache: Bool = false) { instance.clear(cache: cache) } public func undo() { instance.undo() } public func redo() { instance.redo() } /** Get a cropped version of the signature. WARNING: This does not work with iOS13+ */ public func getCroppedSignature() -> UIImage? { instance.getCroppedSignature() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) createSignatureView() setNeedsUpdateConstraints() updateConstraintsIfNeeded() } override public init(frame: CGRect) { super.init(frame: frame) createSignatureView() setNeedsUpdateConstraints() updateConstraintsIfNeeded() } override open func updateConstraintsIfNeeded() { super.updateConstraintsIfNeeded() if viewReady { return } viewReady = true guard let subview: UIView = instance as? UIView else { return } self.addConstraint(NSLayoutConstraint(item: subview, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: subview, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: subview, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0)) self.addConstraint(NSLayoutConstraint(item: subview, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0)) } private func createSignatureView() { guard let subview: UIView = instance as? UIView else { return } subview.translatesAutoresizingMaskIntoConstraints = false subview.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleBottomMargin] self.addSubview(subview) } }
mit
f07a88cfed55faa9af155e44a89703cc
25.276923
166
0.617096
4.86148
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/DataSources/SearchDataSourceTests.swift
1
2384
@testable import Kickstarter_Framework @testable import KsApi @testable import Library import Prelude import XCTest final class SearchDataSourceTests: XCTestCase { let dataSource = SearchDataSource() let tableView = UITableView() func testPopularTitle() { let section = SearchDataSource.Section.popularTitle.rawValue self.dataSource.popularTitle(isVisible: false) XCTAssertEqual(1, self.dataSource.numberOfSections(in: self.tableView)) XCTAssertEqual(0, self.dataSource.tableView(self.tableView, numberOfRowsInSection: section)) self.dataSource.popularTitle(isVisible: true) XCTAssertEqual(1, self.dataSource.numberOfSections(in: self.tableView)) XCTAssertEqual(1, self.dataSource.tableView(self.tableView, numberOfRowsInSection: section)) XCTAssertEqual("MostPopularCell", self.dataSource.reusableId(item: 0, section: section)) } func testProjects() { let section = SearchDataSource.Section.projects.rawValue self.dataSource.load(projects: [ .template |> Project.lens.id .~ 1, .template |> Project.lens.id .~ 2, .template |> Project.lens.id .~ 3 ]) XCTAssertEqual(2, self.dataSource.numberOfSections(in: self.tableView)) XCTAssertEqual(3, self.dataSource.tableView(self.tableView, numberOfRowsInSection: section)) XCTAssertEqual("MostPopularSearchProjectCell", self.dataSource.reusableId(item: 0, section: section)) XCTAssertEqual("SearchProjectCell", self.dataSource.reusableId(item: 1, section: section)) XCTAssertEqual("SearchProjectCell", self.dataSource.reusableId(item: 2, section: section)) } func testProjects_WithNoResults() { let section = SearchDataSource.Section.projects.rawValue self.dataSource.load(projects: []) XCTAssertEqual(2, self.dataSource.numberOfSections(in: self.tableView)) XCTAssertEqual(0, self.dataSource.tableView(self.tableView, numberOfRowsInSection: section)) } func testProjects_WithSingleResult() { let section = SearchDataSource.Section.projects.rawValue self.dataSource.load(projects: [.template |> Project.lens.id .~ 1]) XCTAssertEqual(2, self.dataSource.numberOfSections(in: self.tableView)) XCTAssertEqual(1, self.dataSource.tableView(self.tableView, numberOfRowsInSection: section)) XCTAssertEqual("MostPopularSearchProjectCell", self.dataSource.reusableId(item: 0, section: section)) } }
apache-2.0
4d501c19ac7afbc8b66def6974d8ea71
38.733333
105
0.763003
4.489642
false
true
false
false
jpedrosa/sua
examples/exercise/thread_chat/Sources/main.swift
1
524
import Glibc import CSua import Sua var network: [String?] = [] var networkMutex = Mutex() var tClient = Thread() { while true { let s = readLine() networkMutex.lock() defer { networkMutex.unlock() } network.append(s) } } var tServer = Thread() { while true { IO.sleep(1) networkMutex.lock() defer { networkMutex.unlock() } if !network.isEmpty { if let s = network.removeFirst() { let z = s ?? "" print("server: \(z)") } } } } try tClient.join()
apache-2.0
ba36c4ae61de480ea599f0e319e97fb9
14.878788
40
0.570611
3.316456
false
false
false
false
PedroTrujilloV/TIY-Assignments
32--Save-the-Clock-Tower/GlobalTime/GlobalTime/root_main_GlobalTimeTableViewController.swift
1
6029
// // root_main_GlobalTimeTableViewController.swift // GlobalTime // // Created by Pedro Trujillo on 11/17/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import UIKit let DEFAULT_CLOCK_SIZE:CGFloat = 100.0 protocol SearchTimeZoneProtocol { func timeZoneWasChosen(timeZone:String)//timeZone:timezone) } class root_main_GlobalTimeTableViewController: UITableViewController,SearchTimeZoneProtocol { var timeZonesNamesArray:Array<String>! override func viewDidLoad() { super.viewDidLoad() self.title = "Global Time 🌐" timeZonesNamesArray = [] // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. self.navigationItem.leftBarButtonItem = self.editButtonItem() self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "addButtonActionTapped:") self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier:"UITableViewCell") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return timeZonesNamesArray.count } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return DEFAULT_CLOCK_SIZE+10 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath: indexPath) // Configure the cell... let newClockView = ClockView(frame: CGRect(x: 20.0, y: 10.0, width: DEFAULT_CLOCK_SIZE, height: DEFAULT_CLOCK_SIZE)) newClockView.timezone = NSTimeZone(name: timeZonesNamesArray[indexPath.row]) cell.imageView?.image = UIImage(named: "gravatar.png") cell.addSubview(newClockView) //newClockView cell.textLabel?.text = timeZonesNamesArray[indexPath.row] return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source let cellViews = tableView.cellForRowAtIndexPath(indexPath)?.subviews for UIv in cellViews! { if UIv is ClockView { (UIv as! ClockView).animationTimer?.invalidate()//pedir cell.tag par aexperimentar } } print(cellViews?.count) timeZonesNamesArray.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } // else if editingStyle == .Insert // { // // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view // } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func timeZoneWasChosen(timeZone:String)//timeZone:timezone) { print(timeZone) timeZonesNamesArray.append(timeZone) tableView.reloadData() } //MARK: Action Handlers func addButtonActionTapped(sender:UIButton) { print("Hay que rico me clicaste el addButtonActionTapped") let newGTSearchTVC = SearchGTTableViewController() let searchNavigationController = UINavigationController(rootViewController: newGTSearchTVC) newGTSearchTVC.delegator = self presentViewController(searchNavigationController, animated: true, completion: nil) } } //reference [1] :http://stackoverflow.com/questions/25476139/how-do-i-make-an-uiimage-view-with-rounded-corners-cgrect-swift // let imageView = UIImageView(frame: CGRectMake(0, 0, 100, 100)) // imageView.backgroundColor = UIColor.redColor() // imageView.layer.cornerRadius = 8.0 // imageView.clipsToBounds = true
cc0-1.0
12a6448240832aed094dcc2f97c07d91
32.104396
160
0.664232
5.280456
false
false
false
false
franklinsch/marylou
ios/MarylouiOS/Source/MKButton.swift
3
4060
// // MKButton.swift // MaterialKit // // Created by LeVan Nghia on 11/14/14. // Copyright (c) 2014 Le Van Nghia. All rights reserved. // import UIKit @IBDesignable class MKButton : UIButton { @IBInspectable var maskEnabled: Bool = true { didSet { mkLayer.enableMask(enable: maskEnabled) } } @IBInspectable var rippleLocation: MKRippleLocation = .TapLocation { didSet { mkLayer.rippleLocation = rippleLocation } } @IBInspectable var circleGrowRatioMax: Float = 0.9 { didSet { mkLayer.circleGrowRatioMax = circleGrowRatioMax } } @IBInspectable var backgroundLayerCornerRadius: CGFloat = 0.0 { didSet { mkLayer.setBackgroundLayerCornerRadius(backgroundLayerCornerRadius) } } // animations @IBInspectable var shadowAniEnabled: Bool = true @IBInspectable var backgroundAniEnabled: Bool = true { didSet { if !backgroundAniEnabled { mkLayer.enableOnlyCircleLayer() } } } @IBInspectable var aniDuration: Float = 0.65 @IBInspectable var circleAniTimingFunction: MKTimingFunction = .Linear @IBInspectable var backgroundAniTimingFunction: MKTimingFunction = .Linear @IBInspectable var shadowAniTimingFunction: MKTimingFunction = .EaseOut @IBInspectable var cornerRadius: CGFloat = 2.5 { didSet { layer.cornerRadius = cornerRadius mkLayer.setMaskLayerCornerRadius(cornerRadius) } } // color @IBInspectable var circleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) { didSet { mkLayer.setCircleLayerColor(circleLayerColor) } } @IBInspectable var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) { didSet { mkLayer.setBackgroundLayerColor(backgroundLayerColor) } } override var bounds: CGRect { didSet { mkLayer.superLayerDidResize() } } private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer) // MARK - initilization override init(frame: CGRect) { super.init(frame: frame) setupLayer() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupLayer() } // MARK - setup methods private func setupLayer() { adjustsImageWhenHighlighted = false self.cornerRadius = 2.5 mkLayer.setBackgroundLayerColor(backgroundLayerColor) mkLayer.setCircleLayerColor(circleLayerColor) } // MARK - location tracking methods override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool { if rippleLocation == .TapLocation { mkLayer.didChangeTapLocation(touch.locationInView(self)) } // circleLayer animation mkLayer.animateScaleForCircleLayer(0.45, toScale: 1.0, timingFunction: circleAniTimingFunction, duration: CFTimeInterval(aniDuration)) // backgroundLayer animation if backgroundAniEnabled { mkLayer.animateAlphaForBackgroundLayer(backgroundAniTimingFunction, duration: CFTimeInterval(aniDuration)) } // shadow animation for self if shadowAniEnabled { let shadowRadius = self.layer.shadowRadius let shadowOpacity = self.layer.shadowOpacity //if mkType == .Flat { // mkLayer.animateMaskLayerShadow() //} else { mkLayer.animateSuperLayerShadow(10, toRadius: shadowRadius, fromOpacity: 0, toOpacity: shadowOpacity, timingFunction: shadowAniTimingFunction, duration: CFTimeInterval(aniDuration)) //} } return super.beginTrackingWithTouch(touch, withEvent: event) } } // Copyright belongs to original author // http://code4app.net (en) http://code4app.com (cn) // From the most professional code share website: Code4App.net
apache-2.0
53606426c600de287e6749b8f8fff858
31.741935
197
0.640887
5.218509
false
false
false
false
Hipmunk/HIPWebApp
HIPWebAppDemo/Examples/MessageHandlingExampleWebAppViewController.swift
1
1413
// // MessageHandlingExampleWebAppViewController.swift // WebAppDemo // // Created by Steve Johnson on 4/22/16. // Copyright © 2016 Hipmunk, Inc. All rights reserved. // import Foundation import HIPWebApp class MessageHandlingExampleWebAppViewController: WebAppViewController, MessageHandlingExampleWebAppDelegate { /// Convenience cast to expected web app class fileprivate var _messageHandlingWebApp: MessageHandlingExampleWebApp? { return webApp as? MessageHandlingExampleWebApp } override func createWebApp() -> WebApp { let webApp = MessageHandlingExampleWebApp() webApp.delegate = self return webApp } override func viewDidLoad() { self.loggingDelegate = BASIC_LOGGING super.viewDidLoad() self.loadWebAppInitialURL() } /// Delegate method implementation func buttonWasClicked(data: Any?) { NSLog("FIRE ZE MISSILES!!! Data: \(data)") } } //MARK: Actions extension MessageHandlingExampleWebAppViewController { @IBAction func redAction(sender: Any? = nil) { _messageHandlingWebApp?.setButtonColor(cssColorString: "red") } @IBAction func greenAction(sender: Any? = nil) { _messageHandlingWebApp?.setButtonColor(cssColorString: "green") } @IBAction func blueAction(sender: Any? = nil) { _messageHandlingWebApp?.setButtonColor(cssColorString: "blue") } }
mit
73d585b562d2cec76deaadcb8ce06f3f
26.153846
124
0.705382
4.304878
false
false
false
false
radvansky-tomas/NutriFacts
nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Data/BubbleChartDataSet.swift
3
2330
// // BubbleChartDataSet.swift // Charts // // Bubble chart implementation: // Copyright 2015 Pierre-Marc Airoldi // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics; public class BubbleChartDataSet: BarLineScatterCandleChartDataSet { internal var _xMax = Float(0.0) internal var _xMin = Float(0.0) internal var _maxSize = CGFloat(0.0) public var xMin: Float { return _xMin } public var xMax: Float { return _xMax } public var maxSize: CGFloat { return _maxSize } public func setColor(color: UIColor, alpha: CGFloat) { super.setColor(color.colorWithAlphaComponent(alpha)) } internal override func calcMinMax() { let entries = yVals as! [BubbleChartDataEntry]; // need chart width to guess this properly for entry in entries { let ymin = yMin(entry) let ymax = yMax(entry) if (ymin < _yMin) { _yMin = ymin } if (ymax > _yMax) { _yMax = ymax; } let xmin = xMin(entry) let xmax = xMax(entry) if (xmin < _xMin) { _xMin = xmin; } if (xmax > _xMax) { _xMax = xmax; } let size = largestSize(entry) if (size > _maxSize) { _maxSize = size } } } /// Sets/gets the width of the circle that surrounds the bubble when highlighted public var highlightCircleWidth: CGFloat = 2.5; private func yMin(entry: BubbleChartDataEntry) -> Float { return entry.value } private func yMax(entry: BubbleChartDataEntry) -> Float { return entry.value } private func xMin(entry: BubbleChartDataEntry) -> Float { return Float(entry.xIndex) } private func xMax(entry: BubbleChartDataEntry) -> Float { return Float(entry.xIndex) } private func largestSize(entry: BubbleChartDataEntry) -> CGFloat { return entry.size } }
gpl-2.0
df3e77373c2a32b1e504279d215b7547
22.3
84
0.523176
4.874477
false
false
false
false
TCA-Team/iOS
TUM Campus App/Tuition.swift
1
1890
// // Tuition.swift // TUM Campus App // // This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS // Copyright (c) 2018 TCA // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // import Sweeft import SWXMLHash final class Tuition: DataElement { let frist: Date let semester: String let soll: Double init(frist: Date, semester: String, soll: Double) { self.frist = frist self.semester = semester self.soll = soll } func getCellIdentifier() -> String { return "tuition" } var text: String { return semester } } extension Tuition: XMLDeserializable { convenience init?(from xml: XMLIndexer, api: TUMOnlineAPI, maxCache: CacheTime) { let formatter = NumberFormatter() formatter.locale = Locale(identifier: "de_DE") guard let soll = (xml["soll"].element?.text).flatMap(formatter.number(from:)), let frist = xml["frist"].element?.text.date(using: "yyyy-MM-dd"), let semester = xml["semester_bezeichnung"].element?.text else { return nil } self.init(frist: frist, semester: semester, soll: soll.doubleValue) } } extension Tuition { var isPaid: Bool { return soll <= 0 } }
gpl-3.0
222495e9a404492d5390dcea5c4e5f84
26
88
0.636508
3.9375
false
false
false
false
opencv/opencv
modules/core/misc/objc/test/KeyPointTest.swift
2
1805
// // KeyPointTest.swift // // Created by Giles Payne on 2020/01/31. // import XCTest import OpenCV class KeyPointTest: OpenCVTestCase { let angle:Float = 30 let classId:Int32 = 1 let octave:Int32 = 1 let response:Float = 2.0 let size:Float = 3.0 let x:Float = 1.0 let y:Float = 2.0 func testKeyPoint() { let keyPoint = KeyPoint() assertPoint2fEquals(Point2f(x: 0, y: 0), keyPoint.pt, OpenCVTestCase.FEPS) } func testKeyPointFloatFloatFloat() { let keyPoint = KeyPoint(x: x, y: y, size: size) assertPoint2fEquals(Point2f(x: 1, y: 2), keyPoint.pt, OpenCVTestCase.FEPS) } func testKeyPointFloatFloatFloatFloat() { let keyPoint = KeyPoint(x: x, y: y, size: size, angle: 10.0) XCTAssertEqual(10.0, keyPoint.angle); } func testKeyPointFloatFloatFloatFloatFloat() { let keyPoint = KeyPoint(x: x, y: y, size: size, angle: 1.0, response: 1.0) XCTAssertEqual(1.0, keyPoint.response) } func testKeyPointFloatFloatFloatFloatFloatInt() { let keyPoint = KeyPoint(x: x, y: y, size: size, angle: 1.0, response: 1.0, octave: 1) XCTAssertEqual(1, keyPoint.octave) } func testKeyPointFloatFloatFloatFloatFloatIntInt() { let keyPoint = KeyPoint(x: x, y: y, size: size, angle: 1.0, response: 1.0, octave: 1, classId: 1) XCTAssertEqual(1, keyPoint.classId) } func testToString() { let keyPoint = KeyPoint(x: x, y: y, size: size, angle: angle, response: response, octave: octave, classId: classId) let actual = "\(keyPoint)" let expected = "KeyPoint { pt: Point2f {1.000000,2.000000}, size: 3.000000, angle: 30.000000, response: 2.000000, octave: 1, classId: 1}" XCTAssertEqual(expected, actual) } }
apache-2.0
794f0a05e35bdf184f4f8cac5042c419
29.59322
145
0.636011
3.330258
false
true
false
false
chromatic-seashell/weibo
新浪微博/新浪微博/classes/home/PhotoBrowser/GDWPhotoBroserAnimationManager.swift
1
5611
// // GDWPhotoBroserAnimationManager.swift // 新浪微博 // // Created by apple on 16/3/18. // Copyright © 2016年 apple. All rights reserved. // import UIKit // MARK: - 定义协议 protocol GDWPhotoBroserAnimationManagerDelegate : NSObjectProtocol{ /// 返回和点击的UIImageView一模一样的UIImageView func photoBrowserImageView(path: NSIndexPath) -> UIImageView /// 返回被点击的UIImageView相对于keywindow的frame func photoBrowserFromRect(path: NSIndexPath) -> CGRect /// 返回被点击的UIImageView最终在图片浏览器中显示的尺寸 func photoBrowserToRect(path: NSIndexPath) -> CGRect } class GDWPhotoBroserAnimationManager: UIPresentationController { /// 当前被点击图片的索引 private var path: NSIndexPath? /// 记录当前是否是展现 private var isPresent = false /// 负责展现动画的代理 weak var photoBrowserDelegate : GDWPhotoBroserAnimationManagerDelegate? /// 初始化方法 func setDefaultInfo(path: NSIndexPath) { self.path = path } } extension GDWPhotoBroserAnimationManager : UIViewControllerTransitioningDelegate,UIViewControllerAnimatedTransitioning{ // MARK: - UIViewControllerTransitioningDelegate func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? { return UIPresentationController(presentedViewController: presented, presentingViewController: presenting) } /// 告诉系统谁来负责展现的样式 func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = true return self } /// 告诉系统谁来负责消失的样式 func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = false return self } // MARK: - UIViewControllerAnimatedTransitioning /// 该方法用于告诉系统展现或者消失动画的时长 func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } /// 无论是展现还是消失都会调用这个方法 func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // 1.拿到菜单, 将菜单添加到容器视图上 if isPresent { // 1.1获取图片浏览器 let toView = transitionContext.viewForKey(UITransitionContextToViewKey) transitionContext.containerView()?.addSubview(toView!) toView?.alpha = 0.0 // 1.2获取需要添加到容器视图上的UIImageView // 该方法必须返回一个UIImageView let iv = photoBrowserDelegate!.photoBrowserImageView(path!) // 1.3获取需要添加到容器视图上的UIImageView的frame let fromRect = photoBrowserDelegate!.photoBrowserFromRect(path!) iv.frame = fromRect transitionContext.containerView()?.addSubview(iv) // 1.4获取需要添加到容器仕途上的UIImageView最终的frame let toRect = photoBrowserDelegate!.photoBrowserToRect(path!) // 2.执行动画 UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in iv.frame = toRect }, completion: { (_) -> Void in // 删除iv iv.removeFromSuperview() // 显示图片浏览器 toView?.alpha = 1.0 // 告诉系统动画执行完毕 transitionContext.completeTransition(true) }) }else { // 消失 // 1.1获取图片浏览器 let fromVc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) //将图片浏览器的view从容器view中移除 fromVc?.view.removeFromSuperview() // 1.2获取需要添加到容器视图上的UIImageView // 该方法必须返回一个UIImageView let iv = photoBrowserDelegate!.photoBrowserImageView(path!) // 1.3获取需要添加到容器视图上的UIImageView的frame let fromRect = photoBrowserDelegate!.photoBrowserToRect(path!) // 1.4获取需要添加到容器视图上的UIImageView最终的frame let toRect = photoBrowserDelegate!.photoBrowserFromRect(path!) iv.frame = fromRect transitionContext.containerView()?.addSubview(iv) // 2.执行动画 UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in iv.frame = toRect }, completion: { (_) -> Void in // 删除iv iv.removeFromSuperview() // 告诉系统动画执行完毕 transitionContext.completeTransition(true) }) } } }
apache-2.0
b0982755856e050a47d04c3ab6cf62b3
32.187919
217
0.622371
5.75553
false
false
false
false
karwa/swift
test/Parse/recovery.swift
1
35108
// RUN: %target-typecheck-verify-swift //===--- Helper types used in this file. protocol FooProtocol {} //===--- Tests. func garbage() -> () { var a : Int ) this line is invalid, but we will stop at the keyword below... // expected-error{{expected expression}} return a + "a" // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } func moreGarbage() -> () { ) this line is invalid, but we will stop at the declaration... // expected-error{{expected expression}} func a() -> Int { return 4 } return a() + "a" // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}} } class Container<T> { func exists() -> Bool { return true } } func useContainer() -> () { var a : Container<not a type [skip this greater: >] >, b : Int // expected-error{{expected '>' to complete generic argument list}} expected-note{{to match this opening '<'}} b = 5 // no-warning a.exists() } @xyz class BadAttributes { // expected-error{{unknown attribute 'xyz'}} func exists() -> Bool { return true } } // expected-note @+2 {{did you mean 'test'?}} // expected-note @+1 {{'test' declared here}} func test(a: BadAttributes) -> () { _ = a.exists() // no-warning } // Here is an extra random close-brace! } // expected-error{{extraneous '}' at top level}} {{1-3=}} //===--- Recovery for braced blocks. func braceStmt1() { { braceStmt1(); } // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} } func braceStmt2() { { () in braceStmt2(); } // expected-error {{closure expression is unused}} } func braceStmt3() { { // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} undefinedIdentifier {} // expected-error {{use of unresolved identifier 'undefinedIdentifier'}} } } //===--- Recovery for misplaced 'static'. static func toplevelStaticFunc() {} // expected-error {{static methods may only be declared on a type}} {{1-8=}} static struct StaticStruct {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} static class StaticClass {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} static protocol StaticProtocol {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} static typealias StaticTypealias = Int // expected-error {{declaration cannot be marked 'static'}} {{1-8=}} class ClassWithStaticDecls { class var a = 42 // expected-error {{class stored properties not supported}} } //===--- Recovery for missing controlling expression in statements. func missingControllingExprInIf() { if // expected-error {{expected expression, var, or let in 'if' condition}} if { // expected-error {{missing condition in an 'if' statement}} } if // expected-error {{missing condition in an 'if' statement}} { } if true { } else if { // expected-error {{missing condition in an 'if' statement}} } // It is debatable if we should do recovery here and parse { true } as the // body, but the error message should be sensible. if { true } { // expected-error {{missing condition in an 'if' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{14-14=;}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{15-15=do }} expected-warning {{boolean literal is unused}} } if { true }() { // expected-error {{missing condition in an 'if' statement}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{17-17=do }} expected-warning {{boolean literal is unused}} } // <rdar://problem/18940198> if { { } } // expected-error{{missing condition in an 'if' statement}} expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{8-8=do }} } func missingControllingExprInWhile() { while // expected-error {{expected expression, var, or let in 'while' condition}} while { // expected-error {{missing condition in a 'while' statement}} } while // expected-error {{missing condition in a 'while' statement}} { } // It is debatable if we should do recovery here and parse { true } as the // body, but the error message should be sensible. while { true } { // expected-error {{missing condition in a 'while' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{17-17=;}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{18-18=do }} expected-warning {{boolean literal is unused}} } while { true }() { // expected-error {{missing condition in a 'while' statement}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{20-20=do }} expected-warning {{boolean literal is unused}} } // <rdar://problem/18940198> while { { } } // expected-error{{missing condition in a 'while' statement}} expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{11-11=do }} } func missingControllingExprInRepeatWhile() { repeat { } while // expected-error {{missing condition in a 'while' statement}} { // expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} missingControllingExprInRepeatWhile(); } repeat { } while { true }() // expected-error{{missing condition in a 'while' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{10-10=;}} expected-warning {{result of call to closure returning 'Bool' is unused}} } // SR-165 func missingWhileInRepeat() { repeat { } // expected-error {{expected 'while' after body of 'repeat' statement}} } func acceptsClosure<T>(t: T) -> Bool { return true } func missingControllingExprInFor() { for ; { // expected-error {{C-style for statement has been removed in Swift 3}} } for ; // expected-error {{C-style for statement has been removed in Swift 3}} { } for ; true { // expected-error {{C-style for statement has been removed in Swift 3}} } for var i = 0; true { // expected-error {{C-style for statement has been removed in Swift 3}} i += 1 } } func missingControllingExprInForEach() { // expected-error @+3 {{expected pattern}} // expected-error @+2 {{expected Sequence expression for for-each loop}} // expected-error @+1 {{expected '{' to start the body of for-each loop}} for // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for { } // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for { } // expected-error @+2 {{expected 'in' after for-each pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for i { } // expected-error @+2 {{expected 'in' after for-each pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for var i { } // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for in { } // expected-error @+1 {{expected pattern}} for 0..<12 { } // expected-error @+3 {{expected pattern}} // expected-error @+2 {{expected Sequence expression for for-each loop}} // expected-error @+1 {{expected '{' to start the body of for-each loop}} for for in { } for i in { // expected-error {{expected Sequence expression for for-each loop}} } // The #if block is used to provide a scope for the for stmt to force it to end // where necessary to provoke the crash. #if true // <rdar://problem/21679557> compiler crashes on "for{{" // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for{{ // expected-note 2 {{to match this opening '{'}} #endif // expected-error {{expected '}' at end of closure}} expected-error {{expected '}' at end of brace statement}} #if true // expected-error @+2 {{expected pattern}} // expected-error @+1 {{expected Sequence expression for for-each loop}} for{ var x = 42 } #endif // SR-5943 struct User { let name: String? } let users = [User]() for user in users whe { // expected-error {{expected '{' to start the body of for-each loop}} if let name = user.name { let key = "\(name)" } } for // expected-error {{expected pattern}} expected-error {{Sequence expression for for-each loop}} ; // expected-error {{expected '{' to start the body of for-each loop}} } func missingControllingExprInSwitch() { switch // expected-error {{expected expression in 'switch' statement}} expected-error {{expected '{' after 'switch' subject expression}} switch { // expected-error {{expected expression in 'switch' statement}} expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} } switch // expected-error {{expected expression in 'switch' statement}} expected-error {{'switch' statement body must have at least one 'case' or 'default' block}} { } switch { // expected-error {{expected expression in 'switch' statement}} case _: return } switch { // expected-error {{expected expression in 'switch' statement}} case Int: return // expected-error {{'is' keyword required to pattern match against type name}} {{10-10=is }} case _: return } switch { 42 } { // expected-error {{expected expression in 'switch' statement}} expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} expected-error{{consecutive statements on a line must be separated by ';'}} {{16-16=;}} expected-error{{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{17-17=do }} // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} case _: return // expected-error{{'case' label can only appear inside a 'switch' statement}} } switch { 42 }() { // expected-error {{expected expression in 'switch' statement}} expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error{{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{19-19=do }} // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}} case _: return // expected-error{{'case' label can only appear inside a 'switch' statement}} } } //===--- Recovery for missing braces in nominal type decls. struct NoBracesStruct1() // expected-error {{expected '{' in struct}} enum NoBracesUnion1() // expected-error {{expected '{' in enum}} class NoBracesClass1() // expected-error {{expected '{' in class}} protocol NoBracesProtocol1() // expected-error {{expected '{' in protocol type}} extension NoBracesStruct1() // expected-error {{expected '{' in extension}} struct NoBracesStruct2 // expected-error {{expected '{' in struct}} enum NoBracesUnion2 // expected-error {{expected '{' in enum}} class NoBracesClass2 // expected-error {{expected '{' in class}} protocol NoBracesProtocol2 // expected-error {{expected '{' in protocol type}} extension NoBracesStruct2 // expected-error {{expected '{' in extension}} //===--- Recovery for multiple identifiers in decls protocol Multi ident {} // expected-error @-1 {{found an unexpected second identifier in protocol declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{10-21=Multiident}} // expected-note @-3 {{join the identifiers together with camel-case}} {{10-21=MultiIdent}} class CCC CCC<T> {} // expected-error @-1 {{found an unexpected second identifier in class declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{7-14=CCCCCC}} enum EE EE<T> where T : Multi { // expected-error @-1 {{found an unexpected second identifier in enum declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{6-11=EEEE}} case a a // expected-error @-1 {{found an unexpected second identifier in enum 'case' declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{8-11=aa}} // expected-note @-3 {{join the identifiers together with camel-case}} {{8-11=aA}} case b } struct SS SS : Multi { // expected-error @-1 {{found an unexpected second identifier in struct declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{8-13=SSSS}} private var a b : Int = "" // expected-error @-1 {{found an unexpected second identifier in variable declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{15-18=ab}} // expected-note @-3 {{join the identifiers together with camel-case}} {{15-18=aB}} // expected-error @-4 {{cannot convert value of type 'String' to specified type 'Int'}} func f() { var c d = 5 // expected-error @-1 {{found an unexpected second identifier in variable declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{9-12=cd}} // expected-note @-3 {{join the identifiers together with camel-case}} {{9-12=cD}} // expected-warning @-4 {{initialization of variable 'c' was never used; consider replacing with assignment to '_' or removing it}} let _ = 0 } } let (efg hij, foobar) = (5, 6) // expected-error @-1 {{found an unexpected second identifier in constant declaration; is there an accidental break?}} // expected-note @-2 {{join the identifiers together}} {{6-13=efghij}} // expected-note @-3 {{join the identifiers together with camel-case}} {{6-13=efgHij}} _ = foobar // OK. //===--- Recovery for parse errors in types. struct ErrorTypeInVarDecl1 { var v1 : // expected-error {{expected type}} {{11-11= <#type#>}} } struct ErrorTypeInVarDecl2 { var v1 : Int. // expected-error {{expected member name following '.'}} var v2 : Int } struct ErrorTypeInVarDecl3 { var v1 : Int< // expected-error {{expected type}} var v2 : Int } struct ErrorTypeInVarDecl4 { var v1 : Int<, // expected-error {{expected type}} {{16-16= <#type#>}} var v2 : Int } struct ErrorTypeInVarDecl5 { var v1 : Int<Int // expected-error {{expected '>' to complete generic argument list}} expected-note {{to match this opening '<'}} var v2 : Int } struct ErrorTypeInVarDecl6 { var v1 : Int<Int, // expected-note {{to match this opening '<'}} Int // expected-error {{expected '>' to complete generic argument list}} var v2 : Int } struct ErrorTypeInVarDecl7 { var v1 : Int<Int, // expected-error {{expected type}} var v2 : Int } struct ErrorTypeInVarDecl8 { var v1 : protocol<FooProtocol // expected-error {{expected '>' to complete protocol-constrained type}} expected-note {{to match this opening '<'}} var v2 : Int } struct ErrorTypeInVarDecl9 { var v1 : protocol // expected-error {{expected type}} var v2 : Int } struct ErrorTypeInVarDecl10 { var v1 : protocol<FooProtocol // expected-error {{expected '>' to complete protocol-constrained type}} expected-note {{to match this opening '<'}} var v2 : Int } struct ErrorTypeInVarDecl11 { var v1 : protocol<FooProtocol, // expected-error {{expected identifier for type name}} var v2 : Int } func ErrorTypeInPattern1(_: protocol<) { } // expected-error {{expected identifier for type name}} func ErrorTypeInPattern2(_: protocol<F) { } // expected-error {{expected '>' to complete protocol-constrained type}} // expected-note@-1 {{to match this opening '<'}} // expected-error@-2 {{use of undeclared type 'F'}} func ErrorTypeInPattern3(_: protocol<F,) { } // expected-error {{expected identifier for type name}} // expected-error@-1 {{use of undeclared type 'F'}} struct ErrorTypeInVarDecl12 { var v1 : FooProtocol & // expected-error{{expected identifier for type name}} var v2 : Int } struct ErrorTypeInVarDecl13 { // expected-note {{in declaration of 'ErrorTypeInVarDecl13'}} var v1 : & FooProtocol // expected-error {{expected type}} expected-error {{consecutive declarations on a line must be separated by ';'}} expected-error{{expected declaration}} var v2 : Int } struct ErrorTypeInVarDecl16 { var v1 : FooProtocol & // expected-error {{expected identifier for type name}} var v2 : Int } func ErrorTypeInPattern4(_: FooProtocol & ) { } // expected-error {{expected identifier for type name}} struct ErrorGenericParameterList1< // expected-error {{expected an identifier to name generic parameter}} expected-error {{expected '{' in struct}} struct ErrorGenericParameterList2<T // expected-error {{expected '>' to complete generic parameter list}} expected-note {{to match this opening '<'}} expected-error {{expected '{' in struct}} struct ErrorGenericParameterList3<T, // expected-error {{expected an identifier to name generic parameter}} expected-error {{expected '{' in struct}} // Note: Don't move braces to a different line here. struct ErrorGenericParameterList4< // expected-error {{expected an identifier to name generic parameter}} { } // Note: Don't move braces to a different line here. struct ErrorGenericParameterList5<T // expected-error {{expected '>' to complete generic parameter list}} expected-note {{to match this opening '<'}} { } // Note: Don't move braces to a different line here. struct ErrorGenericParameterList6<T, // expected-error {{expected an identifier to name generic parameter}} { } struct ErrorTypeInVarDeclFunctionType1 { var v1 : () -> // expected-error {{expected type for function result}} var v2 : Int } struct ErrorTypeInVarDeclArrayType1 { var v1 : Int[+] // expected-error {{unexpected ']' in type; did you mean to write an array type?}} // expected-error @-1 {{expected expression after unary operator}} // expected-error @-2 {{expected expression}} var v2 : Int } struct ErrorTypeInVarDeclArrayType2 { var v1 : Int[+ // expected-error {{unary operator cannot be separated from its operand}} var v2 : Int // expected-error {{expected expression}} } struct ErrorTypeInVarDeclArrayType3 { var v1 : Int[ ; // expected-error {{expected expression}} var v2 : Int } struct ErrorTypeInVarDeclArrayType4 { var v1 : Int[1 // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} var v2 : Int] // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{12-12=[}} } struct ErrorTypeInVarDeclArrayType5 { // expected-note {{in declaration of 'ErrorTypeInVarDeclArrayType5'}} let a1: Swift.Int] // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{11-11=[}} let a2: Set<Int]> // expected-error {{expected '>' to complete generic argument list}} // expected-note {{to match this opening '<'}} let a3: Set<Int>] // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{11-11=[}} let a4: Int]? // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{11-11=[}} // expected-error @-1 {{consecutive declarations on a line must be separated by ';'}} // expected-error @-1 {{expected declaration}} let a5: Int?] // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{11-11=[}} let a6: [Int]] // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{11-11=[}} let a7: [String: Int]] // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{11-11=[}} } struct ErrorTypeInVarDeclDictionaryType { let a1: String: // expected-error {{unexpected ':' in type; did you mean to write a dictionary type?}} {{11-11=[}} // expected-error @-1 {{expected dictionary value type}} let a2: String: Int] // expected-error {{unexpected ':' in type; did you mean to write a dictionary type?}} {{11-11=[}} let a3: String: [Int] // expected-error {{unexpected ':' in type; did you mean to write a dictionary type?}} {{11-11=[}} {{24-24=]}} let a4: String: Int // expected-error {{unexpected ':' in type; did you mean to write a dictionary type?}} {{11-11=[}} {{22-22=]}} } struct ErrorInFunctionSignatureResultArrayType1 { func foo() -> Int[ { // expected-error {{expected '{' in body of function declaration}} return [0] } func bar() -> Int] { // expected-error {{unexpected ']' in type; did you mean to write an array type?}} {{17-17=[}} return [0] } } struct ErrorInFunctionSignatureResultArrayType2 { func foo() -> Int[0 { // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} return [0] // expected-error {{cannot convert return expression of type '[Int]' to return type 'Int'}} } } struct ErrorInFunctionSignatureResultArrayType3 { func foo() -> Int[0] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}} return [0] } } struct ErrorInFunctionSignatureResultArrayType4 { func foo() -> Int[0_1] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}} return [0] } } struct ErrorInFunctionSignatureResultArrayType5 { func foo() -> Int[0b1] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}} return [0] } } struct ErrorInFunctionSignatureResultArrayType11 { // expected-note{{in declaration of 'ErrorInFunctionSignatureResultArrayType11'}} func foo() -> Int[(a){a++}] { // expected-error {{consecutive declarations on a line must be separated by ';'}} {{29-29=;}} expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} expected-error {{use of unresolved operator '++'; did you mean '+= 1'?}} expected-error {{use of unresolved identifier 'a'}} expected-error {{expected declaration}} } } //===--- Recovery for missing initial value in var decls. struct MissingInitializer1 { var v1 : Int = // expected-error {{expected initial value after '='}} } //===--- Recovery for expr-postfix. func exprPostfix1(x : Int) { x. // expected-error {{expected member name following '.'}} } func exprPostfix2() { _ = .42 // expected-error {{'.42' is not a valid floating point literal; it must be written '0.42'}} {{7-7=0}} } //===--- Recovery for expr-super. class Base {} class ExprSuper1 { init() { super // expected-error {{expected '.' or '[' after 'super'}} } } class ExprSuper2 { init() { super. // expected-error {{expected member name following '.'}} } } //===--- Recovery for braces inside a nominal decl. struct BracesInsideNominalDecl1 { // expected-note{{in declaration of 'BracesInsideNominalDecl1'}} { // expected-error {{expected declaration}} aaa } typealias A = Int } func use_BracesInsideNominalDecl1() { // Ensure that the typealias decl is not skipped. var _ : BracesInsideNominalDecl1.A // no-error } class SR771 { print("No one else was in the room where it happened") // expected-note {{'print()' previously declared here}} // expected-error @-1 {{expected 'func' keyword in instance method declaration}} // expected-error @-2 {{expected '{' in body of function declaration}} // expected-error @-3 {{expected parameter name followed by ':'}} } extension SR771 { print("The room where it happened, the room where it happened") // expected-error @-1 {{expected 'func' keyword in instance method declaration}} // expected-error @-2 {{expected '{' in body of function declaration}} // expected-error @-3 {{invalid redeclaration of 'print()'}} // expected-error @-4 {{expected parameter name followed by ':'}} } //===--- Recovery for wrong decl introducer keyword. class WrongDeclIntroducerKeyword1 { notAKeyword() {} // expected-error {{expected 'func' keyword in instance method declaration}} func foo() {} class func bar() {} } //===--- Recovery for wrong inheritance clause. class Base2<T> { } class SubModule { class Base1 {} class Base2<T> {} } // expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} {{34-35=}} class WrongInheritanceClause1(Int) {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} {{41-42=}} class WrongInheritanceClause2(Base2<Int>) {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{33-34=: }} {{49-50=}} class WrongInheritanceClause3<T>(SubModule.Base1) where T:AnyObject {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} {{51-52=}} class WrongInheritanceClause4(SubModule.Base2<Int>) {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{33-34=: }} {{54-55=}} class WrongInheritanceClause5<T>(SubModule.Base2<Int>) where T:AnyObject {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{30-31=: }} class WrongInheritanceClause6(Int {} // expected-error@+1 {{expected ':' to begin inheritance clause}} {{33-34=: }} class WrongInheritanceClause7<T>(Int where T:AnyObject {} // <rdar://problem/18502220> [swift-crashes 078] parser crash on invalid cast in sequence expr Base=1 as Base=1 // expected-error {{cannot convert value of type 'Int' to type 'Base' in coercion}} // <rdar://problem/18634543> Parser hangs at swift::Parser::parseType public enum TestA { // expected-error @+1{{expected '{' in body of function declaration}} public static func convertFromExtenndition( // expected-error {{expected parameter name followed by ':'}} // expected-error@+1{{expected parameter name followed by ':'}} s._core.count != 0, "Can't form a Character from an empty String") } public enum TestB { // expected-error@+1{{expected '{' in body of function declaration}} public static func convertFromExtenndition( // expected-error {{expected parameter name followed by ':'}} // expected-error@+1 {{expected parameter name followed by ':'}} s._core.count ?= 0, "Can't form a Character from an empty String") } // <rdar://problem/18634543> Infinite loop and unbounded memory consumption in parser class bar {} var baz: bar // expected-error@+1{{unnamed parameters must be written with the empty name '_'}} func foo1(bar!=baz) {} // expected-note {{did you mean 'foo1'?}} // expected-error@+1{{unnamed parameters must be written with the empty name '_'}} func foo2(bar! = baz) {}// expected-note {{did you mean 'foo2'?}} // rdar://19605567 // expected-error@+1{{use of unresolved identifier 'esp'; did you mean 'test'?}} switch esp { case let (jeb): // expected-error@+5{{top-level statement cannot begin with a closure expression}} // expected-error@+4{{closure expression is unused}} // expected-note@+3{{did you mean to use a 'do' statement?}} // expected-error@+2{{expected an identifier to name generic parameter}} // expected-error@+1{{expected '{' in class}} class Ceac<}> {} // expected-error@+1{{extraneous '}' at top level}} {{1-2=}} } #if true // rdar://19605164 // expected-error@+2{{use of undeclared type 'S'}} struct Foo19605164 { func a(s: S[{{g) -> Int {} // expected-error@+2 {{expected parameter name followed by ':'}} // expected-error@+1 {{expected ',' separator}} }}} #endif // rdar://19605567 // expected-error@+3{{expected '(' for initializer parameters}} // expected-error@+2{{initializers may only be declared within a type}} // expected-error@+1{{expected an identifier to name generic parameter}} func F() { init<( } )} // expected-note 2{{did you mean 'F'?}} struct InitializerWithName { init x() {} // expected-error {{initializers cannot have a name}} {{8-9=}} } struct InitializerWithNameAndParam { init a(b: Int) {} // expected-error {{initializers cannot have a name}} {{8-9=}} init? c(_ d: Int) {} // expected-error {{initializers cannot have a name}} {{9-10=}} init e<T>(f: T) {} // expected-error {{initializers cannot have a name}} {{8-9=}} init? g<T>(_: T) {} // expected-error {{initializers cannot have a name}} {{9-10=}} } struct InitializerWithLabels { init c d: Int {} // expected-error @-1 {{expected '(' for initializer parameters}} } // rdar://20337695 func f1() { // expected-error @+6 {{use of unresolved identifier 'C'}} // expected-note @+5 {{did you mean 'n'?}} // expected-error @+4 {{unary operator cannot be separated from its operand}} {{11-12=}} // expected-error @+3 {{'==' is not a prefix unary operator}} // expected-error @+2 {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // expected-error@+1 {{type annotation missing in pattern}} let n == C { get {} // expected-error {{use of unresolved identifier 'get'}} } } // <rdar://problem/20489838> QoI: Nonsensical error and fixit if "let" is missing between 'if let ... where' clauses func testMultiPatternConditionRecovery(x: Int?) { // expected-error@+1 {{expected ',' joining parts of a multi-clause condition}} {{15-21=,}} if let y = x where y == 0, let z = x { _ = y _ = z } if var y = x, y == 0, var z = x { z = y; y = z } if var y = x, z = x { // expected-error {{expected 'var' in conditional}} {{17-17=var }} z = y; y = z } // <rdar://problem/20883210> QoI: Following a "let" condition with boolean condition spouts nonsensical errors guard let x: Int? = 1, x == 1 else { } // expected-warning @-1 {{explicitly specified type 'Int?' adds an additional level of optional to the initializer, making the optional check always succeed}} {{16-20=Int}} } // rdar://20866942 func testRefutableLet() { var e : Int? let x? = e // expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}} // expected-error @-1 {{expected expression}} // expected-error @-2 {{type annotation missing in pattern}} } // <rdar://problem/19833424> QoI: Bad error message when using Objective-C literals (@"Hello") in Swift files let myString = @"foo" // expected-error {{string literals in Swift are not preceded by an '@' sign}} {{16-17=}} // <rdar://problem/16990885> support curly quotes for string literals // expected-error @+1 {{unicode curly quote found, replace with '"'}} {{35-38="}} let curlyQuotes1 = “hello world!” // expected-error {{unicode curly quote found, replace with '"'}} {{20-23="}} // expected-error @+1 {{unicode curly quote found, replace with '"'}} {{20-23="}} let curlyQuotes2 = “hello world!" // <rdar://problem/21196171> compiler should recover better from "unicode Specials" characters let tryx = 123 // expected-error {{invalid character in source file}} {{5-8= }} // <rdar://problem/21369926> Malformed Swift Enums crash playground service enum Rank: Int { // expected-error {{'Rank' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} case Ace = 1 case Two = 2.1 // expected-error {{cannot convert value of type 'Double' to raw type 'Int'}} } // rdar://22240342 - Crash in diagRecursivePropertyAccess class r22240342 { lazy var xx: Int = { foo { // expected-error {{use of unresolved identifier 'foo'}} let issueView = 42 issueView.delegate = 12 } return 42 }() } // <rdar://problem/22387625> QoI: Common errors: 'let x= 5' and 'let x =5' could use Fix-its func r22387625() { let _= 5 // expected-error{{'=' must have consistent whitespace on both sides}} {{8-8= }} let _ =5 // expected-error{{'=' must have consistent whitespace on both sides}} {{10-10= }} } // <https://bugs.swift.org/browse/SR-3135> func SR3135() { let _: Int= 5 // expected-error{{'=' must have consistent whitespace on both sides}} {{13-13= }} let _: Array<Int>= [] // expected-error{{'=' must have consistent whitespace on both sides}} {{20-20= }} } // <rdar://problem/23086402> Swift compiler crash in CSDiag protocol A23086402 { var b: B23086402 { get } } protocol B23086402 { var c: [String] { get } } func test23086402(a: A23086402) { print(a.b.c + "") // should not crash but: expected-error {{}} } // <rdar://problem/23550816> QoI: Poor diagnostic in argument list of "print" (varargs related) // The situation has changed. String now conforms to the RangeReplaceableCollection protocol // and `ss + s` becomes ambiguous. Diambiguation is provided with the unavailable overload // in order to produce a meaningful diagnostics. (Related: <rdar://problem/31763930>) func test23550816(ss: [String], s: String) { print(ss + s) // expected-error {{'+' is unavailable: Operator '+' cannot be used to append a String to a sequence of strings}} } // <rdar://problem/23719432> [practicalswift] Compiler crashes on &(Int:_) func test23719432() { var x = 42 &(Int:x) // expected-error {{use of extraneous '&'}} } // <rdar://problem/19911096> QoI: terrible recovery when using '·' for an operator infix operator · { // expected-error {{'·' is considered to be an identifier, not an operator}} associativity none precedence 150 } // <rdar://problem/21712891> Swift Compiler bug: String subscripts with range should require closing bracket. func r21712891(s : String) -> String { let a = s.startIndex..<s.startIndex _ = a // The specific errors produced don't actually matter, but we need to reject this. return "\(s[a)" // expected-error {{expected ']' in expression list}} expected-note {{to match this opening '['}} } // <rdar://problem/24029542> "Postfix '.' is reserved" error message" isn't helpful func postfixDot(a : String) { _ = a.utf8 _ = a. utf8 // expected-error {{extraneous whitespace after '.' is not permitted}} {{9-12=}} _ = a. // expected-error {{expected member name following '.'}} a. // expected-error {{expected member name following '.'}} } // <rdar://problem/22290244> QoI: "UIColor." gives two issues, should only give one func f() { // expected-note 2{{did you mean 'f'?}} _ = ClassWithStaticDecls. // expected-error {{expected member name following '.'}} } // <rdar://problem/22478168> | SR-11006 // expected-error@+1 {{expected '=' instead of '==' to assign default value for parameter}} {{21-23==}} func SR11006(a: Int == 0) {} // rdar://38225184 extension Collection where Element == Int && Index == Int {} // expected-error@-1 {{expected ',' to separate the requirements of this 'where' clause}} {{43-45=,}}
apache-2.0
a9123e2e966367bbf0d6da64b84a4e03
40.193662
469
0.67473
3.953701
false
false
false
false
blg-andreasbraun/ProcedureKit
Sources/Cloud/CKFetchSubscriptionsOperation.swift
2
2853
// // ProcedureKit // // Copyright © 2016 ProcedureKit. All rights reserved. // import CloudKit #if !os(watchOS) /// A generic protocol which exposes the properties used by Apple's CKFetchSubscriptionsOperation. public protocol CKFetchSubscriptionsOperationProtocol: CKDatabaseOperationProtocol { /// - returns: the subscription IDs var subscriptionIDs: [String]? { get set } /// - returns: the fetch subscription completion block var fetchSubscriptionCompletionBlock: (([String: Subscription]?, Error?) -> Void)? { get set } } public struct FetchSubscriptionsError<Subscription>: CloudKitError { public let underlyingError: Error public let subscriptionsByID: [String: Subscription]? } extension CKFetchSubscriptionsOperation: CKFetchSubscriptionsOperationProtocol, AssociatedErrorProtocol { // The associated error type public typealias AssociatedError = FetchSubscriptionsError<Subscription> } extension CKProcedure where T: CKFetchSubscriptionsOperationProtocol, T: AssociatedErrorProtocol, T.AssociatedError: CloudKitError { public var subscriptionIDs: [String]? { get { return operation.subscriptionIDs } set { operation.subscriptionIDs = newValue } } func setFetchSubscriptionCompletionBlock(_ block: @escaping CloudKitProcedure<T>.FetchSubscriptionCompletionBlock) { operation.fetchSubscriptionCompletionBlock = { [weak self] subscriptionsByID, error in if let strongSelf = self, let error = error { strongSelf.append(fatalError: FetchSubscriptionsError(underlyingError: error, subscriptionsByID: subscriptionsByID)) } else { block(subscriptionsByID) } } } } extension CloudKitProcedure where T: CKFetchSubscriptionsOperationProtocol, T: AssociatedErrorProtocol, T.AssociatedError: CloudKitError { /// A typealias for the block types used by CloudKitOperation<CKFetchSubscriptionsOperation> public typealias FetchSubscriptionCompletionBlock = ([String: T.Subscription]?) -> Void /// - returns: the subscription IDs public var subscriptionIDs: [String]? { get { return current.subscriptionIDs } set { current.subscriptionIDs = newValue appendConfigureBlock { $0.subscriptionIDs = newValue } } } /** Before adding the CloudKitOperation instance to a queue, set a completion block to collect the results in the successful case. Setting this completion block also ensures that error handling gets triggered. - parameter block: a FetchSubscriptionCompletionBlock block */ public func setFetchSubscriptionCompletionBlock(block: @escaping FetchSubscriptionCompletionBlock) { appendConfigureBlock { $0.setFetchSubscriptionCompletionBlock(block) } } } #endif
mit
71b3843fd5660ff16e5ca4980998a012
35.101266
138
0.731066
5.422053
false
false
false
false
steve-holmes/music-app-2
MusicApp/Modules/Category/Coordinators/CategoryPresentAnimationController.swift
1
2135
// // CategoryPresentAnimationController.swift // MusicApp // // Created by Hưng Đỗ on 6/17/17. // Copyright © 2017 HungDo. All rights reserved. // import UIKit class CategoryPresentAnimationController: NSObject, UIViewControllerAnimatedTransitioning, CategoryAnimationOptions { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let toViewController = transitionContext.viewController(forKey: .to), let toView = transitionContext.view(forKey: .to) else { return } let containerView = transitionContext.containerView let toViewFinalFrame = transitionContext.finalFrame(for: toViewController) let toViewInitialFrame = scaleRect(CGRect( origin: CGPoint(x: 0, y: containerView.frame.size.height / 2), size: toViewFinalFrame.size ), by: 0.1) let snapshot = toViewController.view.snapshotView(afterScreenUpdates: true)! snapshot.frame = toViewInitialFrame containerView.addSubview(toView) containerView.addSubview(snapshot) toView.isHidden = true let duration = transitionDuration(using: transitionContext) UIView.animate( withDuration: duration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: initialVelocity, options: [], animations: { snapshot.frame = toViewFinalFrame }, completion: { _ in let success = !transitionContext.transitionWasCancelled if !success { toView.removeFromSuperview() } toView.isHidden = false snapshot.removeFromSuperview() transitionContext.completeTransition(success) } ) } }
mit
41454d957d4954cbc45822da65c13df8
32.809524
117
0.612207
6.396396
false
false
false
false
evamalloc/Calculator-Test
CalculatorModel.swift
1
2111
// // CalculatorModel.swift // CalculatorTest // // Created by Yang Tian on 11/23/15. // Copyright © 2015 Jiao Chu. All rights reserved. // import Foundation class CalculatorModel { private var operandStack = [String]() //store + - × ÷ private var operatorStack = [Double]() //store digits //store digits on stack func appendOperator(number: Double) { operatorStack.append(number) } //clear everything for new calculation func clearButtonFunc() { operatorStack.removeAll() operandStack.removeAll() } //perform calculator when there are enough numbers in the stack //return tuple: result for dispaly after finish calculate; flag indecate perform one calculate, when flag is false, result is useless so set it to 0.0 func appendOperand(operand: String) -> (result: Double, flag: Bool){ if(!operandStack.isEmpty) { let operation = self.operandStack.popLast()! var result: Double = 0 //print for test print("operand number \(operandStack.count) \(operandStack)") print("operator number \(operatorStack.count) \(operatorStack)") //whent there are at least two numbers on the stack, calculate if(operatorStack.count > 1) { result = performOperation(operation, num2: operatorStack.popLast()!, num1: operatorStack.popLast()!) } if(operand != "=") { operandStack.append(operand)//store for next calculate } return (result, true) } else { operandStack.append(operand) return (0.0, false) } } func performOperation(str: String, num2: Double, num1: Double) -> Double { switch str { case "+": return num1 + num2 case "−": return num1 - num2 case "×": return num1 * num2 case "÷": return num1 / num2 default: break } return 0 } }
bsd-3-clause
8c21786f22ab839448cf88270937f6c2
28.647887
154
0.566065
4.685969
false
false
false
false
rabbitinspace/Tosoka
Tests/TosokaTests/JSON/Jay/Reader.swift
2
5137
// // Reader.swift // Jay // // Created by Honza Dvorsky on 2/17/16. // Copyright © 2016 Honza Dvorsky. All rights reserved. // public protocol Reader: class { // Returns the currently pointed-at char func curr() -> UInt8 // Moves cursor to the next char func next() throws // Returns `true` if all characters have been read func isDone() -> Bool // Finish parsing when valid JSON object has been parsed? // Return true: for streaming parsers that never end, so that we don't // hang on waiting for more data even though a valid JSON // object has been parsed. // Return false: for parsers that already have all data in memory, stricter // mode that ensures that no invalid trailing bytes have been // sent after the valid JSON object. func finishParsingWhenValid() -> Bool } //@discardableResult //func consumeWhitespace<R: Reader>(_ reader: R) throws -> Int { // var counter = 0 // while !reader.isDone() { // let char = reader.curr() // if Const.Whitespace.contains(char) { // //consume // counter += 1 // try reader.next() // } else { // //non-whitespace, return // break // } // } // return counter //} // //func ensureNotDone<R: Reader>(_ reader: R) throws { // if reader.isDone() { // throw JayError.unexpectedEnd(reader) // } //} // //func nextAndCheckNotDone<R: Reader>(_ reader: R) throws { // try reader.next() // try reader.ensureNotDone() //} extension Reader { func readNext(_ next: Int) throws -> [JChar] { try ensureNotDone() var buff = [JChar]() while buff.count < next { buff.append(self.curr()) try nextAndCheckNotDone() } return buff } func ensureNotDone() throws { if isDone() { throw JayError.unexpectedEnd(self) } } func nextAndCheckNotDone() throws { try next() try ensureNotDone() } // Consumes all contiguous whitespace and returns # of consumed chars @discardableResult func consumeWhitespace() throws -> Int { var counter = 0 while !self.isDone() { let char = self.curr() if Const.Whitespace.contains(char) { //consume counter += 1 try self.next() } else { //non-whitespace, return break } } return counter } // Gathers all bytes until `terminator` is found, returns everything except the terminator // the cursor is right after the terminator // If the end of `self` is encountered without finding `terminator`, `foundTerminator` is false func collectUntil(terminator: [JChar]) throws -> (collected: [JChar], foundTerminator: Bool) { var collected: [UInt8] = [] var nextBuffer = CircularBuffer<UInt8>(size: terminator.count, defaultValue: 0) while !isDone() { let char = curr() nextBuffer.append(char) collected.append(char) if nextBuffer == terminator { //remove the terminator from collected try next() return (Array(collected.dropLast(terminator.count)), true) } try next() } return (collected, false) } // Iterates both readers and checks that characters match until // a) expectedReader runs out of characters -> great! all match // b) self runs out of characters -> bad, no match! // c) we encounter a difference -> bad, no match! func stopAtFirstDifference<R: Reader>(_ other: R) throws { while true { if other.isDone() { //a) all matched, return return } if isDone() { //b) no match throw JayError.mismatch(self, other) } let charSelf = curr() let charOther = other.curr() guard charSelf == charOther else { //c) no match throw JayError.mismatch(self, other) } try next() try other.next() } } } struct CircularBuffer<T: Equatable> { let size: Int private var _cursor: Int = 0 private var _storage: [T] init(size: Int, defaultValue: T) { self.size = size self._storage = Array(repeating: defaultValue, count: size) } mutating func append(_ element: T) { _storage[_cursor] = element _cursor = (_cursor + 1) % size } static func ==(lhs: CircularBuffer<T>, rhs: [T]) -> Bool { let size = lhs.size guard lhs.size == rhs.count else { return false } let offset = lhs._cursor for i in 0..<size { guard lhs._storage[(i + offset) % size] == rhs[i] else { return false } } return true } }
mit
a24124f8084d90a2e1716889359501b7
28.181818
99
0.538941
4.446753
false
false
false
false
hrscy/TodayNews
News/News/Classes/Mine/View/OfflineSectionHeader.swift
1
866
// // OfflineSectionHeader.swift // News // // Created by 杨蒙 on 2018/1/15. // Copyright © 2018年 hrscy. All rights reserved. // import UIKit class OfflineSectionHeader: UIView { override init(frame: CGRect) { super.init(frame: frame) theme_backgroundColor = "colors.tableViewBackgroundColor" let label = UILabel(frame: CGRect(x: 20, y: 0, width: screenWidth, height: height)) label.text = "我的频道" label.theme_textColor = "colors.black" let separatorView = UIView(frame: CGRect(x: 0, y: height - 1, width: screenWidth, height: 1)) separatorView.theme_backgroundColor = "colors.separatorViewColor" addSubview(separatorView) addSubview(label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
12e054b3e2fb895b57e4ec36bdda7544
28.344828
101
0.650999
4.014151
false
false
false
false
wordpress-mobile/AztecEditor-iOS
Example/AztecUITests/ImagesTests.swift
2
2805
import XCTest class ImagesTests: XCTestCase { private var richEditorPage: EditorPage! override func setUp() { super.setUp() // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIDevice.shared.orientation = .portrait let app = XCUIApplication() app.launchArguments = ["NoAnimations"] app.activate() let blogsPage = BlogsPage() richEditorPage = blogsPage.gotoEmptyDemo() } override func tearDown() { richEditorPage.gotoRootPage() super.tearDown() } func testAddPhoto() { let regex = "<p><a href=.+><img src=.+></a></p>" let html = richEditorPage .addImageByOrder(id: 0) .switchContentView() .getViewContent() XCTAssert(NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: html)) } func testAddPhotoAndText() { let sampleText = "sample text sample text sample text" let regex = "<p>.+<a href=.+><img src=.+></a></p>" let html = richEditorPage .enterText(text: sampleText) .addImageByOrder(id: 0) .switchContentView() .getViewContent() XCTAssert(NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: html)) } func testAddTwoPhotos() { let regex = "<p>.*<img src=.+>.*<img src=.+></p>" let imgHTML = "<img src=\"https://examplebloge.files.wordpress.com/2017/02/3def4804-d9b5-11e6-88e6-d7d8864392e0.png\">" let html = richEditorPage .switchContentView() .enterText(text: imgHTML) .switchContentView() .addImageByOrder(id: 0) .switchContentView() .getViewContent() XCTAssert(NSPredicate(format: "SELF MATCHES %@", regex).evaluate(with: html)) } // Tests the issue described in // https://github.com/wordpress-mobile/AztecEditor-Android/issues/196 func testParsingOfImagesWithLink() { let imageHtml = "<a href=\"https://github.com/wordpress-mobile/WordPress-Aztec-Android\"><img src=\"https://examplebloge.files.wordpress.com/2017/02/3def4804-d9b5-11e6-88e6-d7d8864392e0.png\" class=\"alignnone\"></a>" let expectedHTML = "<p>" + imageHtml + "</p>" let html = richEditorPage .switchContentView() .enterText(text: imageHtml) .switchContentView() .switchContentView() .getViewContent() XCTAssertEqual(html, expectedHTML) } }
mpl-2.0
82ac20089c13b263e8cd4b1517912af4
33.207317
225
0.588592
4.335394
false
true
false
false
apple/swift-format
Tests/SwiftFormatPrettyPrintTests/AttributeTests.swift
1
8416
import SwiftFormatConfiguration final class AttributeTests: PrettyPrintTestCase { func testAttributeParamSpacing() { let input = """ @available( iOS 9.0,* ) func f() {} @available(*, unavailable ,renamed:"MyRenamedProtocol") func f() {} @available(iOS 10.0, macOS 10.12, *) func f() {} """ let expected = """ @available(iOS 9.0, *) func f() {} @available(*, unavailable, renamed: "MyRenamedProtocol") func f() {} @available(iOS 10.0, macOS 10.12, *) func f() {} """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 60) } func testAttributeBinPackedWrapping() { let input = """ @available(iOS 9.0, *) func f() {} @available(*,unavailable, renamed:"MyRenamedProtocol") func f() {} @available(iOS 10.0, macOS 10.12, *) func f() {} """ let expected = """ @available(iOS 9.0, *) func f() {} @available( *, unavailable, renamed: "MyRenamedProtocol" ) func f() {} @available( iOS 10.0, macOS 10.12, * ) func f() {} """ // Attributes should wrap to avoid overflowing the line length, using the following priorities: // 1. Keep the entire attribute together, on 1 line. // 2. Otherwise, try to keep the entire attribute argument list together on 1 line. // 3. Otherwise, use argument list consistency (default: inconsistent) for the arguments. assertPrettyPrintEqual(input: input, expected: expected, linelength: 32) } func testAttributeArgumentPerLineWrapping() { let input = """ @available(iOS 9.0, *) func f() {} @available(*,unavailable, renamed:"MyRenamedProtocol") func f() {} @available(iOS 10.0, macOS 10.12, *) func f() {} """ let expected = """ @available(iOS 9.0, *) func f() {} @available( *, unavailable, renamed: "MyRenamedProtocol" ) func f() {} @available( iOS 10.0, macOS 10.12, * ) func f() {} """ var configuration = Configuration() configuration.lineBreakBeforeEachArgument = true assertPrettyPrintEqual( input: input, expected: expected, linelength: 32, configuration: configuration) } func testAttributeFormattingRespectsDiscretionaryLineBreaks() { let input = """ @available( iOSApplicationExtension, introduced: 10.0, deprecated: 11.0, message: "Use something else because this is definitely deprecated.") func f2() {} """ let expected = """ @available( iOSApplicationExtension, introduced: 10.0, deprecated: 11.0, message: "Use something else because this is definitely deprecated." ) func f2() {} """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 40) } func testAttributeInterArgumentBinPackedLineBreaking() { let input = """ @available(iOSApplicationExtension, introduced: 10.0, deprecated: 11.0, message: "Use something else because this is definitely deprecated.") func f2() {} """ let expected = """ @available( iOSApplicationExtension, introduced: 10.0, deprecated: 11.0, message: "Use something else because this is definitely deprecated." ) func f2() {} """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 40) } func testAttributArgumentPerLineBreaking() { let input = """ @available(iOSApplicationExtension, introduced: 10.0, deprecated: 11.0, message: "Use something else because this is definitely deprecated.") func f2() {} """ let expected = """ @available( iOSApplicationExtension, introduced: 10.0, deprecated: 11.0, message: "Use something else because this is definitely deprecated." ) func f2() {} """ var configuration = Configuration() configuration.lineBreakBeforeEachArgument = true assertPrettyPrintEqual( input: input, expected: expected, linelength: 40, configuration: configuration) } func testObjCBinPackedAttributes() { let input = """ @objc func f() {} @objc(foo:bar:baz:) func f() {} @objc(thisMethodHasAVeryLongName:foo:bar:) func f() {} @objc(thisMethodHasAVeryLongName:andThisArgumentHasANameToo:soDoesThisOne:bar:) func f() {} """ let expected = """ @objc func f() {} @objc(foo:bar:baz:) func f() {} @objc( thisMethodHasAVeryLongName:foo:bar: ) func f() {} @objc( thisMethodHasAVeryLongName: andThisArgumentHasANameToo: soDoesThisOne:bar: ) func f() {} """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 40) } func testObjCAttributesPerLineBreaking() { let input = """ @objc func f() {} @objc(foo:bar:baz) func f() {} @objc(thisMethodHasAVeryLongName:foo:bar:) func f() {} @objc(thisMethodHasAVeryLongName:andThisArgumentHasANameToo:soDoesThisOne:bar:) func f() {} """ let expected = """ @objc func f() {} @objc(foo:bar:baz) func f() {} @objc( thisMethodHasAVeryLongName: foo: bar: ) func f() {} @objc( thisMethodHasAVeryLongName: andThisArgumentHasANameToo: soDoesThisOne: bar: ) func f() {} """ var configuration = Configuration() configuration.lineBreakBeforeEachArgument = true assertPrettyPrintEqual( input: input, expected: expected, linelength: 40, configuration: configuration) } func testObjCAttributesDiscretionaryLineBreaking() { // The discretionary newlines in the 3rd function declaration are invalid, because new lines // should be after the ":" character in Objective-C selector pieces, so they should be removed. let input = """ @objc func f() {} @objc(foo: bar: baz:) func f() {} @objc(foo :bar :baz:) func f() {} @objc( thisMethodHasAVeryLongName: foo: bar: ) func f() {} """ let expected = """ @objc func f() {} @objc( foo: bar: baz: ) func f() {} @objc(foo:bar:baz:) func f() {} @objc( thisMethodHasAVeryLongName: foo: bar: ) func f() {} """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 80) } func testIgnoresDiscretionaryLineBreakAfterColon() { let input = """ @available( *, unavailable, renamed: "MyRenamedFunction" ) func f() {} """ let expected = """ @available( *, unavailable, renamed: "MyRenamedFunction" ) func f() {} """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 30) } func testPropertyWrappers() { // Property wrappers are `CustomAttributeSyntax` nodes (not `AttributeSyntax`) and their // arguments are `TupleExprElementListSyntax` (like regular function call argument lists), so // make sure that those are formatted properly. let input = """ struct X { @Wrapper var value: String @Wrapper ( ) var value: String @Wrapper (arg1:"value")var value: String @Wrapper (arg1:"value") var value: String @Wrapper (arg1:"value",arg2:otherValue) var value: String } """ let expected = """ struct X { @Wrapper var value: String @Wrapper() var value: String @Wrapper(arg1: "value") var value: String @Wrapper(arg1: "value") var value: String @Wrapper( arg1: "value", arg2: otherValue) var value: String } """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 32) } }
apache-2.0
cb837e8939e061dfe932635addbdf3e9
22.248619
147
0.560361
4.406283
false
false
false
false
WhisperSystems/Signal-iOS
SignalMessaging/ViewControllers/SheetViewController.swift
1
8346
// // Copyright (c) 2018 Open Whisper Systems. All rights reserved. // import Foundation @objc(OWSSheetViewControllerDelegate) public protocol SheetViewControllerDelegate: class { func sheetViewControllerRequestedDismiss(_ sheetViewController: SheetViewController) } @objc(OWSSheetViewController) public class SheetViewController: UIViewController { @objc weak var delegate: SheetViewControllerDelegate? @objc public let contentView: UIView = UIView() private let sheetView: SheetView = SheetView() private let handleView: UIView = UIView() deinit { Logger.verbose("") } @objc public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.transitioningDelegate = self self.modalPresentationStyle = .overCurrentContext } public required init?(coder aDecoder: NSCoder) { notImplemented() } // MARK: View LifeCycle var sheetViewVerticalConstraint: NSLayoutConstraint? override public func loadView() { self.view = UIView() sheetView.preservesSuperviewLayoutMargins = true sheetView.addSubview(contentView) contentView.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .bottom) contentView.autoPinEdge(toSuperviewMargin: .bottom) view.addSubview(sheetView) sheetView.autoPinWidthToSuperview() sheetView.setContentHuggingVerticalHigh() sheetView.setCompressionResistanceHigh() self.sheetViewVerticalConstraint = sheetView.autoPinEdge(.top, to: .bottom, of: self.view) handleView.backgroundColor = Theme.isDarkThemeEnabled ? UIColor.ows_white : UIColor.ows_gray05 let kHandleViewHeight: CGFloat = 5 handleView.autoSetDimensions(to: CGSize(width: 40, height: kHandleViewHeight)) handleView.layer.cornerRadius = kHandleViewHeight / 2 view.addSubview(handleView) handleView.autoAlignAxis(.vertical, toSameAxisOf: sheetView) handleView.autoPinEdge(.bottom, to: .top, of: sheetView, withOffset: -6) // Gestures let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapBackground)) self.view.addGestureRecognizer(tapGesture) let swipeDownGesture = UISwipeGestureRecognizer(target: self, action: #selector(didSwipeDown)) swipeDownGesture.direction = .down self.view.addGestureRecognizer(swipeDownGesture) } // MARK: Present / Dismiss animations fileprivate func animatePresentation(completion: @escaping (Bool) -> Void) { guard let sheetViewVerticalConstraint = self.sheetViewVerticalConstraint else { owsFailDebug("sheetViewVerticalConstraint was unexpectedly nil") return } let backgroundDuration: TimeInterval = 0.1 UIView.animate(withDuration: backgroundDuration) { let alpha: CGFloat = Theme.isDarkThemeEnabled ? 0.7 : 0.6 self.view.backgroundColor = UIColor.black.withAlphaComponent(alpha) } self.sheetView.superview?.layoutIfNeeded() NSLayoutConstraint.deactivate([sheetViewVerticalConstraint]) self.sheetViewVerticalConstraint = self.sheetView.autoPinEdge(toSuperviewEdge: .bottom) UIView.animate(withDuration: 0.2, delay: backgroundDuration, options: .curveEaseOut, animations: { self.sheetView.superview?.layoutIfNeeded() }, completion: completion) } fileprivate func animateDismiss(completion: @escaping (Bool) -> Void) { guard let sheetViewVerticalConstraint = self.sheetViewVerticalConstraint else { owsFailDebug("sheetVerticalConstraint was unexpectedly nil") return } self.sheetView.superview?.layoutIfNeeded() NSLayoutConstraint.deactivate([sheetViewVerticalConstraint]) let dismissDuration: TimeInterval = 0.2 self.sheetViewVerticalConstraint = self.sheetView.autoPinEdge(.top, to: .bottom, of: self.view) UIView.animate(withDuration: dismissDuration, delay: 0, options: .curveEaseOut, animations: { self.view.backgroundColor = UIColor.clear self.sheetView.superview?.layoutIfNeeded() }, completion: completion) } // MARK: Actions @objc func didTapBackground() { // inform delegate to delegate?.sheetViewControllerRequestedDismiss(self) } @objc func didSwipeDown() { // inform delegate to delegate?.sheetViewControllerRequestedDismiss(self) } } extension SheetViewController: UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return SheetViewPresentationController(sheetViewController: self) } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return SheetViewDismissalController(sheetViewController: self) } } private class SheetViewPresentationController: NSObject, UIViewControllerAnimatedTransitioning { let sheetViewController: SheetViewController init(sheetViewController: SheetViewController) { self.sheetViewController = sheetViewController } // This is used for percent driven interactive transitions, as well as for // container controllers that have companion animations that might need to // synchronize with the main animation. public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } // This method can only be a nop if the transition is interactive and not a percentDriven interactive transition. public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { Logger.debug("") transitionContext.containerView.addSubview(sheetViewController.view) sheetViewController.view.autoPinEdgesToSuperviewEdges() sheetViewController.animatePresentation { didComplete in Logger.debug("completed: \(didComplete)") transitionContext.completeTransition(didComplete) } } } private class SheetViewDismissalController: NSObject, UIViewControllerAnimatedTransitioning { let sheetViewController: SheetViewController init(sheetViewController: SheetViewController) { self.sheetViewController = sheetViewController } // This is used for percent driven interactive transitions, as well as for // container controllers that have companion animations that might need to // synchronize with the main animation. public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.3 } // This method can only be a nop if the transition is interactive and not a percentDriven interactive transition. public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { Logger.debug("") sheetViewController.animateDismiss { didComplete in Logger.debug("completed: \(didComplete)") transitionContext.completeTransition(didComplete) } } } private class SheetView: UIView { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = Theme.isDarkThemeEnabled ? UIColor.ows_gray90 : UIColor.ows_gray05 } required init?(coder aDecoder: NSCoder) { notImplemented() } override var bounds: CGRect { didSet { updateMask() } } private func updateMask() { let cornerRadius: CGFloat = 16 let path: UIBezierPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)) let mask = CAShapeLayer() mask.path = path.cgPath self.layer.mask = mask } }
gpl-3.0
30d87a500adfd09d5d2ed9dc5ff26b11
36.426009
177
0.698299
5.61642
false
false
false
false
t1gerr/LeetCode
src/implement_strstr/solution1.swift
3
1048
class Solution { func strStr(_ haystack: String, _ needle: String) -> Int { let haystack_len = haystack.characters.count let needle_len = needle.characters.count let haystack_chars = Array(haystack.characters) let needle_chars = Array(needle.characters) guard haystack_len >= needle_len else { return -1 } guard needle_len != 0 else { return 0 } for i in 0 ... haystack_len - needle_len { // use str.index(str.startIndex, offsetBy: i) may cause time limit issue when string is too long if haystack_chars[i] == needle_chars[0] { for j in 0 ..< needle_len { if haystack_chars[i + j] != needle_chars[j] { break } if j + 1 == needle_len { return i } } } } return -1 } }
mit
bb3ab70d37886eb389c23cbf8b542ebe
30.8125
108
0.442748
4.897196
false
false
false
false
practicalswift/swift
test/DebugInfo/global_resilience.swift
6
998
// RUN: %empty-directory(%t) // // Compile the external swift module. // RUN: %target-swift-frontend -g -emit-module -enable-resilience \ // RUN: -emit-module-path=%t/resilient_struct.swiftmodule \ // RUN: -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // // RUN: %target-swift-frontend -g -I %t -emit-ir -enable-resilience %s -o - \ // RUN: | %FileCheck %s import resilient_struct // Fits in buffer let small = Size(w: 1, h: 2) // Needs out-of-line allocation let large = Rectangle(p: Point(x: 1, y: 2), s: Size(w: 3, h: 4), color: 5) // CHECK: @"$s17global_resilience5small16resilient_struct4SizeVvp" = // CHECK-SAME: !dbg ![[SMALL:[0-9]+]] // CHECK: @"$s17global_resilience5large16resilient_struct9RectangleVvp" = // CHECK-SAME: !dbg ![[LARGE:[0-9]+]] // CHECK: ![[SMALL]] = !DIGlobalVariableExpression( // CHECK-SAME: expr: !DIExpression()) // CHECK: ![[LARGE]] = !DIGlobalVariableExpression( // CHECK-SAME: expr: !DIExpression(DW_OP_deref))
apache-2.0
be9e393f93caf7db6e62cfe2434d2c3f
35.962963
78
0.657315
3.042683
false
false
false
false
keygx/ButtonStyleKit
ButtonStyleKitSample/ButtonStyleKitSample/ButtonStyle/SampleButtonCheckboxStyle.swift
1
1686
// // SampleButtonCheckboxStyle.swift // ButtonStyleKitSample // // Created by keygx on 2016/08/04. // Copyright © 2016年 keygx. All rights reserved. // import UIKit import ButtonStyleKit final class SampleButtonCheckboxStyle: ButtonStyleSelectableBase { private let buttonStyle = ButtonStyleBuilder() private var checkImageView = UIImageView() final override func initializedTrigger() { /*---------- Common Settings ----------*/ buttonStyle .setButton(self) .setState(.all) .setFont(UIFont.systemFont(ofSize: 16)) .setContentHorizontalAlignment(.left) .setContentVerticalAlignment(.center) .setTitleEdgeInsets(top: 0, right: 0, bottom: 0, left: 30) .setExclusiveTouch(true) .build() /*---------- For State Settings ----------*/ buttonStyle .setState(.normal) .setTitle("checkbox") .build() checkImageView = buttonStyle.createImageView(frame: CGRect(x: 0, y: 4, width: 28, height: 28), normal: UIImage(named: "checkbox")!, highlighted: UIImage(named: "checkbox_on")!) addSubview(checkImageView) buttonStyle.apply() } final override var currentState: ButtonStyleKit.ButtonState { didSet { /*---------- ButtonState Settings ----------*/ switch currentState { case .selected: checkImageView.isHighlighted = true default: checkImageView.isHighlighted = false } } } }
mit
da770e97730e9e8d04e878fa69aee471
30.754717
134
0.553773
5.376997
false
false
false
false
yanif/circator
MetabolicCompass/View Controller/TabController/ManageDashboard/ManageDashboardCell.swift
1
1406
// // ManageDashboardCell.swift // MetabolicCompass // // Created by Inaiur on 5/6/16. // Copyright © 2016 Yanif Ahmad, Tom Woolf. All rights reserved. // import UIKit class ManageDashboardCell: UITableViewCell { @IBOutlet weak var leftImageView: UIImageView! @IBOutlet weak var captionLabel: UILabel! @IBOutlet weak var button: UIButton! @IBOutlet weak var reorderImage: UIImageView? override func awakeFromNib() { super.awakeFromNib() // Initialization code self.button.userInteractionEnabled = false } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func updateSelectionStatus (selected: Bool, appearanceProvider: DashboardMetricsAppearanceProvider, itemType: String) { self.button.selected = selected if (selected) { self.reorderImage?.image = UIImage(named: "icon-manage-filters-active") } else { self.reorderImage?.image = UIImage(named: "icon-manage-filters-unactive") } self.leftImageView.image = appearanceProvider.imageForSampleType(itemType, active: selected) self.captionLabel.attributedText = appearanceProvider.titleForSampleType(itemType, active: selected) } }
apache-2.0
0acf3cf33ed418155a6f151d6d64957a
29.543478
121
0.670463
4.762712
false
false
false
false
nRewik/CardScrollView
Example/CardScollView/ViewController.swift
1
1155
// // ViewController.swift // CardScollView // // Created by nRewik on 10/23/2015. // Copyright (c) 2015 nRewik. All rights reserved. // import UIKit import CardScollView class ViewController: UIViewController { @IBOutlet weak var cardScrollView: CardScrollView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } @IBAction func toggleSelectionMode(sender: AnyObject) { UIView.animateWithDuration(0.3){ self.cardScrollView.selectionMode = !self.cardScrollView.selectionMode } } var count = 0 @IBAction func addItemButtonTapped(sender: AnyObject) { let colors = [UIColor.redColor(),UIColor.brownColor(),UIColor.yellowColor()] let newCard = cardScrollView.addCardAtIndex(cardScrollView.selectedIndex, animated: true) newCard.backgroundColor = colors[ (self.count++) % colors.count ] } @IBAction func removeButtonTapped(sender: AnyObject) { self.cardScrollView.removeCardAtIndex(self.cardScrollView.selectedIndex, animated: true) } }
mit
4e0e10266d362f00832be0b1db44bfce
27.875
97
0.687446
4.547244
false
false
false
false
ProVir/WebServiceSwift
WebServiceExample/SiteWebProvider.swift
1
5316
// // SiteWebProvider.swift // WebServiceExample // // Created by Короткий Виталий on 19.04.2018. // Copyright © 2018 ProVir. All rights reserved. // import Foundation import WebServiceSwift //MARK: Provider protocol SiteWebProviderDelegate: class { func webServiceResponse(request: WebServiceBaseRequesting, isStorageRequest: Bool, html: String) func webServiceResponse(request: WebServiceBaseRequesting, isStorageRequest: Bool, error: Error) } class SiteWebProvider: WebServiceProvider { private let webService: WebService required init(webService: WebService) { self.webService = webService } weak var delegate: SiteWebProviderDelegate? //MARK: Request use SiteWebProviderDelegate func requestHtmlDataFromSiteSearch(_ request: SiteWebServiceRequests.SiteSearch, includeResponseStorage: Bool) { if includeResponseStorage { internalReadStorageHtmlData(request, dataFromStorage: nil) } webService.performRequest(request, excludeDuplicate: true, responseDelegate: self) } func requestHtmlDataFromSiteMail(_ request: SiteWebServiceRequests.SiteMail, includeResponseStorage: Bool) { if includeResponseStorage { internalReadStorageHtmlData(request, dataFromStorage: nil) } webService.performRequest(request, key: request.site, excludeDuplicate: true, responseDelegate: self) } func requestHtmlDataFromSiteYouTube(includeResponseStorage: Bool) { let request = SiteWebServiceRequests.SiteYouTube() if includeResponseStorage { internalReadStorageHtmlData(request, dataFromStorage: nil) } webService.performRequest(request, responseDelegate: self) } //MARK: Request use closures func requestHtmlDataFromSiteSearch(_ request: SiteWebServiceRequests.SiteSearch, dataFromStorage: ((_ data:String) -> Void)? = nil, completionHandler: @escaping (_ response: WebServiceResponse<String>) -> Void) { if let dataFromStorage = dataFromStorage { internalReadStorageHtmlData(request, dataFromStorage: dataFromStorage) } webService.performRequest(request, completionHandler: completionHandler) } func requestHtmlDataFromSiteMail(_ request: SiteWebServiceRequests.SiteMail, dataFromStorage: ((_ data:String) -> Void)? = nil, completionHandler: @escaping (_ response: WebServiceResponse<String>) -> Void) { if let dataFromStorage = dataFromStorage { internalReadStorageHtmlData(request, dataFromStorage: dataFromStorage) } webService.performRequest(request, completionHandler: completionHandler) } func requestHtmlDataFromSiteYouTube(dataFromStorage: ((_ data:String) -> Void)? = nil, completionHandler: @escaping (_ response: WebServiceResponse<String>) -> Void) { let request = SiteWebServiceRequests.SiteYouTube() if let dataFromStorage = dataFromStorage { internalReadStorageHtmlData(request, dataFromStorage: dataFromStorage) } webService.performRequest(request, completionHandler: completionHandler) } func cancelAllRequests() { webService.cancelRequests(type: SiteWebServiceRequests.SiteSearch.self) webService.cancelRequests(keyType: SiteWebServiceRequests.SiteMail.Site.self) webService.cancelRequests(SiteWebServiceRequests.SiteYouTube()) } //MARK: - Private private func internalReadStorageHtmlData(_ request: WebServiceBaseRequesting, dataFromStorage: ((_ data: String) -> Void)?) { if let dataFromStorage = dataFromStorage { webService.readStorageAnyData(request, dependencyNextRequest: .dependFull) { _, response in let response = response.convert(String.self) if case .data(let data) = response { dataFromStorage(data) } } } else { webService.readStorage(request, dependencyNextRequest: .dependFull, responseOnlyData: true, responseDelegate: self) } } } extension SiteWebProvider: WebServiceDelegate { func webServiceResponse(request: WebServiceBaseRequesting, key: AnyHashable?, isStorageRequest: Bool, response: WebServiceAnyResponse) { let responseText: WebServiceResponse<String> if let request = request as? SiteWebServiceRequests.SiteSearch { responseText = response.convert(request: request) } else if let request = request as? SiteWebServiceRequests.SiteMail { responseText = response.convert(request: request) } else if let request = request as? SiteWebServiceRequests.SiteYouTube { responseText = response.convert(request: request) } else { return } switch responseText { case .data(let html): delegate?.webServiceResponse(request: request, isStorageRequest: isStorageRequest, html: html) case .error(let error): delegate?.webServiceResponse(request: request, isStorageRequest: isStorageRequest, error: error) case .canceledRequest: break } } }
mit
17717a37a503fb2511399eaa0aab90d8
45.086957
140
0.687358
5.11583
false
false
false
false
cwwise/Keyboard-swift
Sources/Emoticon/EmoticonToolView.swift
3
7338
// // CWEmoticonToolView.swift // CWWeChat // // Created by wei chen on 2017/7/19. // Copyright © 2017年 cwcoder. All rights reserved. // import UIKit private let kItemWidth: CGFloat = 45 private let kDurationTime: TimeInterval = 0.15 protocol EmoticonToolViewDelegate { func didPressSend() // 切换表情数组 func didChangeEmoticonGroup(_ index: Int) } /// 表情标签 class EmoticonToolView: UIView { var delegate: EmoticonToolViewDelegate? /// 数据源 var groupList: [EmoticonGroup] = [EmoticonGroup]() var selectIndex: Int = 0 lazy var collectionView: UICollectionView = { var layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.itemSize = CGSize(width: kItemWidth, height: self.frame.height) let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout) collectionView.register(EmoticonToolItemCell.self, forCellWithReuseIdentifier: "cell") collectionView.backgroundColor = .white collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0) collectionView.delegate = self collectionView.dataSource = self collectionView.scrollsToTop = false collectionView.alwaysBounceHorizontal = true collectionView.showsVerticalScrollIndicator = false collectionView.showsHorizontalScrollIndicator = false return collectionView }() // 发送按钮 let sendButton: UIButton = { let sendButton = UIButton(type: .custom) sendButton.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0) sendButton.titleLabel?.font = UIFont.systemFont(ofSize: 14) sendButton.setTitle("发送", for: .normal) sendButton.setTitleColor(.white, for: .normal) sendButton.setTitleColor(.lightGray, for: .highlighted) sendButton.setTitleColor(.gray, for: .disabled) sendButton.setBackgroundImage(UIImage(named: "EmotionsSendBtnBlue"), for: .normal) sendButton.setBackgroundImage(UIImage(named: "EmotionsSendBtnBlueHL"), for: .highlighted) sendButton.setBackgroundImage(UIImage(named: "EmotionsSendBtnGrey"), for: .disabled) sendButton.isEnabled = true sendButton.addTarget(self, action: #selector(sendButtonClick), for: .touchUpInside) return sendButton }() // 设置 let settingButton: UIButton = { let settingButton = UIButton(type: .custom) settingButton.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0) settingButton.setImage(UIImage(named: "EmotionsSetting"), for: .normal) settingButton.setBackgroundImage(UIImage(named: "EmotionsSendBtnGrey"), for: .normal) settingButton.setBackgroundImage(UIImage(named: "EmotionsSendBtnGrey"), for: .highlighted) return settingButton }() lazy var addButton: UIButton = { let addButton = UIButton(type: .custom) addButton.setImage(UIImage(named: "EmotionsBagAdd"), for: .normal) addButton.frame = CGRect(x: 0, y: 0, width: kItemWidth, height: self.height) // 添加一条线 let line: CALayer = CALayer() line.backgroundColor = UIColor(white: 0.9, alpha: 1.0).cgColor line.frame = CGRect(x: kItemWidth-0.5, y: 8, width: 0.5, height: self.height - 2*8) addButton.layer.addSublayer(line) return addButton }() func loadData(_ groupList: [EmoticonGroup]) { if groupList == self.groupList { return } self.groupList = groupList self.collectionView.reloadData() let firstIndex = IndexPath(row: selectIndex, section: 0) self.collectionView.selectItem(at: firstIndex, animated: false, scrollPosition: .centeredHorizontally) } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.white self.addSubview(addButton) self.addSubview(collectionView) self.addSubview(sendButton) self.addSubview(settingButton) collectionView.frame = CGRect(x: addButton.right, y: 0, width: self.width-kItemWidth, height: self.height) let buttonWidth: CGFloat = 52 sendButton.frame = CGRect(x: self.width-buttonWidth, y: 0, width: buttonWidth, height: self.height) settingButton.frame = CGRect(x: self.width, y: 0, width: buttonWidth, height: self.height) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateEmoticonGroup(_ index: Int) { selectIndex = index changeAnimate(index == 0) let indexPath = IndexPath(row: selectIndex, section: 0) collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally) } @objc func sendButtonClick() { self.delegate?.didPressSend() } } extension EmoticonToolView: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.row == selectIndex { return } selectIndex = indexPath.row changeAnimate(indexPath.row == 0) // 通知代理 self.delegate?.didChangeEmoticonGroup(indexPath.row) } func changeAnimate(_ showSendButton: Bool) { // 切换动画 // 是一个 显示发送按钮 if showSendButton { UIView.animate(withDuration: kDurationTime, delay: 0, options: .curveEaseInOut, animations: { self.settingButton.left = self.width }, completion: { (finshed) in UIView.animate(withDuration: kDurationTime, delay: 0, options: .curveEaseInOut, animations: { self.sendButton.left = self.width-self.sendButton.width }, completion: { (finshed) in }) }) } else { UIView.animate(withDuration: kDurationTime, delay: 0, options: .curveEaseInOut, animations: { self.sendButton.left = self.width }, completion: { (finshed) in UIView.animate(withDuration: kDurationTime, delay: 0, options: .curveEaseInOut, animations: { self.settingButton.left = self.width-self.settingButton.width }, completion: { (finshed) in }) }) } } } extension EmoticonToolView: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return groupList.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! EmoticonToolItemCell cell.imageView.image = UIImage(contentsOfFile: groupList[indexPath.row].iconPath) return cell } }
mit
3e2296e8bc3cc6f959d9aa15d0ca220d
34.886139
123
0.637053
4.968472
false
false
false
false
danielpassos/aerogear-ios-oauth2
AeroGearOAuth2Tests/OAuth2ModuleTest.swift
2
10243
/* * JBoss, Home of Professional Open Source. * Copyright Red Hat, Inc., and individual contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import UIKit import XCTest @testable import AeroGearOAuth2 import AeroGearHttp import OHHTTPStubs public func stub(condition: @escaping OHHTTPStubsTestBlock, response: @escaping OHHTTPStubsResponseBlock) -> OHHTTPStubsDescriptor { return OHHTTPStubs.stubRequests(passingTest: condition, withStubResponse: response) } func setupStubWithNSURLSessionDefaultConfiguration() { // set up http stub _ = stub(condition: {_ in return true}, response: { (request: URLRequest!) -> OHHTTPStubsResponse in let stubJsonResponse = ["name": "John", "family_name": "Smith"] switch request.url!.path { case "/plus/v1/people/me/openIdConnect": let data = try! JSONSerialization.data(withJSONObject: stubJsonResponse, options: JSONSerialization.WritingOptions()) return OHHTTPStubsResponse(data:data, statusCode: 200, headers: ["Content-Type" : "text/json"]) case "/v2.10/me": let string = "{\"id\":\"10204448880356292\",\"first_name\":\"Corinne\",\"gender\":\"female\",\"last_name\":\"Krych\",\"link\":\"https:\\/\\/www.facebook.com\\/app_scoped_user_id\\/10204448880356292\\/\",\"locale\":\"en_GB\",\"name\":\"Corinne Krych\",\"timezone\":1,\"updated_time\":\"2014-09-24T10:51:12+0000\",\"verified\":true}" let data = string.data(using: String.Encoding.utf8) return OHHTTPStubsResponse(data:data!, statusCode: 200, headers: ["Content-Type" : "text/json"]) case "/o/oauth2/token": let string = "{\"access_token\":\"NEWLY_REFRESHED_ACCESS_TOKEN\", \"refresh_token\":\"REFRESH_TOKEN\",\"expires_in\":23}" let data = string.data(using: String.Encoding.utf8) return OHHTTPStubsResponse(data:data!, statusCode: 200, headers: ["Content-Type" : "text/json"]) case "/o/oauth2/revoke": let string = "{}" let data = string.data(using: String.Encoding.utf8) return OHHTTPStubsResponse(data:data!, statusCode: 200, headers: ["Content-Type" : "text/json"]) default: return OHHTTPStubsResponse(data:Data(), statusCode: 200, headers: ["Content-Type" : "text/json"]) } }) } func setupStubWithNSURLSessionDefaultConfigurationWithoutRefreshTokenIssued() { // set up http stub _ = stub(condition: {_ in return true}, response: { (request: URLRequest!) -> OHHTTPStubsResponse in switch request.url!.path { case "/o/oauth2/token": let string = "{\"access_token\":\"ACCESS_TOKEN\"}" let data = string.data(using: String.Encoding.utf8) return OHHTTPStubsResponse(data:data!, statusCode: 200, headers: ["Content-Type" : "text/json"]) default: return OHHTTPStubsResponse(data:Data(), statusCode: 200, headers: ["Content-Type" : "text/json"]) } }) } class OAuth2ModuleTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() OHHTTPStubs.removeAllStubs() } func testRequestAccessWithAccessTokenAlreadyStored() { let expectation = self.expectation(description: "AccessRequestAlreadyAccessTokenPresent") let googleConfig = GoogleConfig( clientId: "xxx.apps.googleusercontent.com", scopes:["https://www.googleapis.com/auth/drive"]) let partialMock = OAuth2Module(config: googleConfig, session: MockOAuth2SessionWithValidAccessTokenStored()) partialMock.requestAccess { (response: AnyObject?, error: NSError?) -> Void in XCTAssertTrue("TOKEN" == response as! String, "If access token present and still valid") expectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testRequestAccessWithRefreshFlow() { let expectation = self.expectation(description: "AccessRequestwithRefreshFlow") let googleConfig = GoogleConfig( clientId: "873670803862-g6pjsgt64gvp7r25edgf4154e8sld5nq.apps.googleusercontent.com", scopes:["https://www.googleapis.com/auth/drive"]) let partialMock = OAuth2ModulePartialMock(config: googleConfig, session: MockOAuth2SessionWithRefreshToken()) partialMock.requestAccess { (response: AnyObject?, error: NSError?) -> Void in XCTAssertTrue("NEW_ACCESS_TOKEN" == response as! String, "If access token not valid but refresh token present and still valid") expectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testRequestAccessWithAuthzCodeFlow() { let expectation = self.expectation(description: "AccessRequestWithAuthzFlow") let googleConfig = GoogleConfig( clientId: "xxx.apps.googleusercontent.com", scopes:["https://www.googleapis.com/auth/drive"]) let partialMock = OAuth2ModulePartialMock(config: googleConfig, session: MockOAuth2SessionWithAuthzCode()) partialMock.requestAccess { (response: AnyObject?, error: NSError?) -> Void in XCTAssertTrue("ACCESS_TOKEN" == response as! String, "If access token not valid and no refresh token present") expectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testRefreshAccess() { setupStubWithNSURLSessionDefaultConfiguration() let expectation = self.expectation(description: "Refresh") let googleConfig = GoogleConfig( clientId: "xxx.apps.googleusercontent.com", scopes:["https://www.googleapis.com/auth/drive"]) let mockedSession = MockOAuth2SessionWithRefreshToken() let oauth2Module = OAuth2Module(config: googleConfig, session: mockedSession) oauth2Module.refreshAccessToken { (response: AnyObject?, error: NSError?) -> Void in XCTAssertTrue("NEWLY_REFRESHED_ACCESS_TOKEN" == response as! String, "If access token not valid but refresh token present and still valid") XCTAssertTrue("REFRESH_TOKEN" == mockedSession.savedRefreshedToken, "Saved newly issued refresh token") expectation.fulfill() } waitForExpectations(timeout: 10, handler: nil) } func testExchangeAuthorizationCodeForAccessToken() { setupStubWithNSURLSessionDefaultConfiguration() let expectation = self.expectation(description: "AccessRequest") let googleConfig = GoogleConfig( clientId: "xxx.apps.googleusercontent.com", scopes:["https://www.googleapis.com/auth/drive"]) let oauth2Module = OAuth2Module(config: googleConfig, session: MockOAuth2SessionWithRefreshToken()) oauth2Module.exchangeAuthorizationCodeForAccessToken (code: "CODE", completionHandler: {(response: AnyObject?, error: NSError?) -> Void in XCTAssertTrue("NEWLY_REFRESHED_ACCESS_TOKEN" == response as! String, "If access token not valid but refresh token present and still valid") expectation.fulfill() }) waitForExpectations(timeout: 10, handler: nil) } func testExchangeAuthorizationCodeForAccessTokenwithoutRefreshTokenIssued() { setupStubWithNSURLSessionDefaultConfigurationWithoutRefreshTokenIssued() let expectation = self.expectation(description: "AccessRequest") let googleConfig = GoogleConfig( clientId: "xxx.apps.googleusercontent.com", scopes:["https://www.googleapis.com/auth/drive"]) let oauth2Module = OAuth2Module(config: googleConfig, session: MockOAuth2SessionWithRefreshToken()) oauth2Module.exchangeAuthorizationCodeForAccessToken (code: "CODE", completionHandler: {(response: AnyObject?, error: NSError?) -> Void in XCTAssertTrue("ACCESS_TOKEN" == response as! String, "If access token not valid but refresh token present and still valid") expectation.fulfill() }) waitForExpectations(timeout: 10, handler: nil) } func testRevokeAccess() { setupStubWithNSURLSessionDefaultConfiguration() let expectation = self.expectation(description: "Revoke") let googleConfig = GoogleConfig( clientId: "xxx.apps.googleusercontent.com", scopes:["https://www.googleapis.com/auth/drive"]) let mockedSession = MockOAuth2SessionWithRefreshToken() let oauth2Module = OAuth2Module(config: googleConfig, session: mockedSession) oauth2Module.revokeAccess(completionHandler: {(response: AnyObject?, error: NSError?) -> Void in XCTAssertTrue(mockedSession.initCalled == 1, "revoke token reset session") expectation.fulfill() }) waitForExpectations(timeout: 10, handler: nil) } func testGoogleURLParams() { let googleConfig = GoogleConfig( clientId: "xxx.apps.googleusercontent.com", scopes:["https://www.googleapis.com/auth/drive"], audienceId: "xxx2.apps.googleusercontent.com" ) googleConfig.webView = Config.WebViewType.embeddedWebView let mockedSession = MockOAuth2SessionWithRefreshToken() let oauth2Module = OAuth2Module(config: googleConfig, session: mockedSession) oauth2Module.requestAuthorizationCode { (response: AnyObject?, error:NSError?) -> Void in // noop } let urlString = oauth2Module.webView!.targetURL.absoluteString XCTAssertNotNil(urlString.range(of: "audience"), "If URL string doesn't contain an audience field") } }
apache-2.0
98dbdc5c17d58539c51504c42c591560
49.458128
347
0.675681
4.662267
false
true
false
false
rporzuc/FindFriends
FindFriends/FindFriends/MyAccount/Edit User Data/ChangePasswordViewController.swift
1
3872
// // ChangePasswordViewController.swift // FindFriends // // Created by MacOSXRAFAL on 3/24/17. // Copyright © 2017 MacOSXRAFAL. All rights reserved. // import UIKit class ChangePasswordViewController: UIViewController, UITextFieldDelegate { static var delegate : DelegateProtocolSendDataToMyAccount! var currentPassword : String! = "rafal" @IBOutlet var textFieldCurrentPassword: UITextField! @IBOutlet var textFieldNewPassword: UITextField! @IBOutlet var textFieldRepeatPassword: UITextField! @IBAction func btnReturnClicked(_ sender: UIButton) { _ = self.navigationController?.popViewController(animated: true) } @IBAction func btnShowPasswordClicked(_ sender: Any) { for txtField in [textFieldCurrentPassword, textFieldNewPassword, textFieldRepeatPassword] { txtField?.isSecureTextEntry = !(txtField?.isSecureTextEntry)! } } @IBAction func btnSaveClicked(_ sender: Any) { if (textFieldCurrentPassword.text == "" || textFieldNewPassword.text == "" || textFieldRepeatPassword.text == "") { self.showInformationAlertView(message: "Please enter your password.") }else if (textFieldCurrentPassword.text! != currentPassword) { self.showInformationAlertView(message: "Current password is incorrect.") }else { let passwordRegEx = "[A-Z0-9a-z._%+-]{7,35}" let passwordTest = NSPredicate(format: "SELF MATCHES %@" , passwordRegEx) if (passwordTest.evaluate(with: textFieldNewPassword.text) == false) { self.showInformationAlertView(message: "Invalid New Password. You must use at least 7 of the following characters: A-Z, a-z, 0-9, + , _ , - , %") }else if (textFieldNewPassword.text != textFieldRepeatPassword.text) { self.showInformationAlertView(message: "The password don't match!") }else { let connectionToServer = ConnectionToServer.shared connectionToServer.changePassword(password: textFieldNewPassword.text!, completion: { boolValue in if boolValue == true { ChangePasswordViewController.delegate.saveValueFromChangePasswordViewController(password: self.textFieldNewPassword.text!) let alertView = UIAlertController(title: "Change Password", message: "Your password has been change.", preferredStyle: UIAlertControllerStyle.alert) alertView.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: { (UIAlertAction) in _ = self.navigationController?.popViewController(animated: true) })) self.present(alertView, animated: true, completion: nil) }else { self.showInformationAlertView(message: "During save password was an error. Please try again later.") } }) } } } override func viewDidLoad() { super.viewDidLoad() for txtField in [textFieldCurrentPassword, textFieldNewPassword, textFieldRepeatPassword] { txtField?.delegate = self txtField?.setBottomBorderWithoutPlaceholder(viewColor: UIColor.white, borderColor: UIColor.lightGray, borderSize: 1) } } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return true } }
gpl-3.0
233c10b61db69ee8f443ae404cf0bbc3
36.582524
172
0.590545
5.626453
false
false
false
false
ncalexan/firefox-ios
Client/Application/AppDelegate.swift
1
42106
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import Storage import AVFoundation import XCGLogger import MessageUI import WebImage import SwiftKeychainWrapper import LocalAuthentication import Telemetry import SwiftRouter import Sync import CoreSpotlight private let log = Logger.browserLogger let LatestAppVersionProfileKey = "latestAppVersion" let AllowThirdPartyKeyboardsKey = "settings.allowThirdPartyKeyboards" private let InitialPingSentKey = "initialPingSent" class AppDelegate: UIResponder, UIApplicationDelegate, UIViewControllerRestoration { public static func viewController(withRestorationIdentifierPath identifierComponents: [Any], coder: NSCoder) -> UIViewController? { return nil } var window: UIWindow? var browserViewController: BrowserViewController! var rootViewController: UIViewController! weak var profile: Profile? var tabManager: TabManager! var adjustIntegration: AdjustIntegration? var foregroundStartTime = 0 var applicationCleanlyBackgrounded = true weak var application: UIApplication? var launchOptions: [AnyHashable: Any]? let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String var openInFirefoxParams: LaunchParams? var systemBrightness: CGFloat = UIScreen.main.brightness var receivedURLs: [URL]? @discardableResult func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // // Determine if the application cleanly exited last time it was used. We default to true in // case we have never done this before. Then check if the "ApplicationCleanlyBackgrounded" user // default exists and whether was properly set to true on app exit. // // Then we always set the user default to false. It will be set to true when we the application // is backgrounded. // self.applicationCleanlyBackgrounded = true let defaults = UserDefaults() if defaults.object(forKey: "ApplicationCleanlyBackgrounded") != nil { self.applicationCleanlyBackgrounded = defaults.bool(forKey: "ApplicationCleanlyBackgrounded") } defaults.set(false, forKey: "ApplicationCleanlyBackgrounded") defaults.synchronize() // Hold references to willFinishLaunching parameters for delayed app launch self.application = application self.launchOptions = launchOptions log.debug("Configuring window…") self.window = UIWindow(frame: UIScreen.main.bounds) self.window!.backgroundColor = UIColor.white // Short circuit the app if we want to email logs from the debug menu if DebugSettingsBundleOptions.launchIntoEmailComposer { self.window?.rootViewController = UIViewController() presentEmailComposerWithLogs() return true } else { return startApplication(application, withLaunchOptions: launchOptions) } } @discardableResult fileprivate func startApplication(_ application: UIApplication, withLaunchOptions launchOptions: [AnyHashable: Any]?) -> Bool { log.debug("Initializing Sentry…") // Need to get "settings.sendUsageData" this way so that Sentry can be initialized // before getting the Profile. let sendUsageData = NSUserDefaultsPrefs(prefix: "profile").boolForKey("settings.sendUsageData") ?? true SentryIntegration.shared.setup(sendUsageData: sendUsageData) log.debug("Setting UA…") // Set the Firefox UA for browsing. setUserAgent() log.debug("Starting keyboard helper…") // Start the keyboard helper to monitor and cache keyboard state. KeyboardHelper.defaultHelper.startObserving() log.debug("Starting dynamic font helper…") DynamicFontHelper.defaultHelper.startObserving() log.debug("Setting custom menu items…") MenuHelper.defaultHelper.setItems() log.debug("Creating Sync log file…") let logDate = Date() // Create a new sync log file on cold app launch. Note that this doesn't roll old logs. Logger.syncLogger.newLogWithDate(logDate) log.debug("Creating Browser log file…") Logger.browserLogger.newLogWithDate(logDate) log.debug("Getting profile…") let profile = getProfile(application) log.debug("Initializing telemetry…") Telemetry.initWithPrefs(profile.prefs) if !DebugSettingsBundleOptions.disableLocalWebServer { log.debug("Starting web server…") // Set up a web server that serves us static content. Do this early so that it is ready when the UI is presented. setUpWebServer(profile) } log.debug("Setting AVAudioSession category…") do { // for aural progress bar: play even with silent switch on, and do not stop audio from other apps (like music) try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers) } catch _ { log.error("Failed to assign AVAudioSession category to allow playing with silent switch on for aural progress bar") } let imageStore = DiskImageStore(files: profile.files, namespace: "TabManagerScreenshots", quality: UIConstants.ScreenshotQuality) // Temporary fix for Bug 1390871 - NSInvalidArgumentException: -[WKContentView menuHelperFindInPage]: unrecognized selector if #available(iOS 11, *) { if let clazz = NSClassFromString("WKCont" + "ent" + "View"), let swizzledMethod = class_getInstanceMethod(TabWebViewMenuHelper.self, #selector(TabWebViewMenuHelper.swizzledMenuHelperFindInPage)) { class_addMethod(clazz, MenuHelper.SelectorFindInPage, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)) } } log.debug("Configuring tabManager…") self.tabManager = TabManager(prefs: profile.prefs, imageStore: imageStore) self.tabManager.stateDelegate = self // Add restoration class, the factory that will return the ViewController we // will restore with. log.debug("Initing BVC…") browserViewController = BrowserViewController(profile: self.profile!, tabManager: self.tabManager) browserViewController.edgesForExtendedLayout = [] browserViewController.restorationIdentifier = NSStringFromClass(BrowserViewController.self) browserViewController.restorationClass = AppDelegate.self let navigationController = UINavigationController(rootViewController: browserViewController) navigationController.delegate = self navigationController.isNavigationBarHidden = true navigationController.edgesForExtendedLayout = UIRectEdge(rawValue: 0) rootViewController = navigationController self.window!.rootViewController = rootViewController log.debug("Adding observers…") NotificationCenter.default.addObserver(forName: NSNotification.Name.FSReadingListAddReadingListItem, object: nil, queue: nil) { (notification) -> Void in if let userInfo = notification.userInfo, let url = userInfo["URL"] as? URL { let title = (userInfo["Title"] as? String) ?? "" profile.readingList?.createRecordWithURL(url.absoluteString, title: title, addedBy: UIDevice.current.name) } } NotificationCenter.default.addObserver(forName: NotificationFirefoxAccountDeviceRegistrationUpdated, object: nil, queue: nil) { _ in profile.flushAccount() } // check to see if we started 'cos someone tapped on a notification. if let localNotification = launchOptions?[UIApplicationLaunchOptionsKey.localNotification] as? UILocalNotification { viewURLInNewTab(localNotification) } adjustIntegration = AdjustIntegration(profile: profile) let leanplum = LeanplumIntegration.sharedInstance leanplum.setup(profile: profile) leanplum.setEnabled(true) log.debug("Updating authentication keychain state to reflect system state") self.updateAuthenticationInfo() SystemUtils.onFirstRun() resetForegroundStartTime() if !(profile.prefs.boolForKey(InitialPingSentKey) ?? false) { // Try to send an initial core ping when the user first opens the app so that they're // "on the map". This lets us know they exist if they try the app once, crash, then uninstall. // sendCorePing() only sends the ping if the user is offline, so if the first ping doesn't // go through *and* the user crashes then uninstalls on the first run, then we're outta luck. profile.prefs.setBool(true, forKey: InitialPingSentKey) sendCorePing() } let fxaLoginHelper = FxALoginHelper.sharedInstance fxaLoginHelper.application(application, didLoadProfile: profile) setUpDeepLinks(application: application) log.debug("Done with setting up the application.") return true } func setUpDeepLinks(application: UIApplication) { let router = Router.shared let rootNav = rootViewController as! UINavigationController router.map("homepanel/:page", handler: { (params: [String: String]?) -> (Bool) in guard let page = params?["page"] else { return false } assert(Thread.isMainThread, "Opening homepanels requires being invoked on the main thread") switch page { case "bookmarks": self.browserViewController.openURLInNewTab(HomePanelType.bookmarks.localhostURL, isPrivileged: true) case "history": self.browserViewController.openURLInNewTab(HomePanelType.history.localhostURL, isPrivileged: true) case "new-private-tab": self.browserViewController.openBlankNewTab(focusLocationField: false, isPrivate: true) default: break } return true }) // Route to general settings page like this: "...settings/general" router.map("settings/:page", handler: { (params: [String: String]?) -> (Bool) in guard let page = params?["page"] else { return false } assert(Thread.isMainThread, "Opening settings requires being invoked on the main thread") let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = self.profile settingsTableViewController.tabManager = self.tabManager settingsTableViewController.settingsDelegate = self.browserViewController let controller = SettingsNavigationController(rootViewController: settingsTableViewController) controller.popoverDelegate = self.browserViewController controller.modalPresentationStyle = UIModalPresentationStyle.formSheet rootNav.present(controller, animated: true, completion: nil) switch page { case "newtab": let viewController = NewTabChoiceViewController(prefs: self.getProfile(application).prefs) controller.pushViewController(viewController, animated: true) case "homepage": let viewController = HomePageSettingsViewController() viewController.profile = self.getProfile(application) viewController.tabManager = self.tabManager controller.pushViewController(viewController, animated: true) case "mailto": let viewController = OpenWithSettingsViewController(prefs: self.getProfile(application).prefs) controller.pushViewController(viewController, animated: true) case "search": let viewController = SearchSettingsTableViewController() viewController.model = self.getProfile(application).searchEngines viewController.profile = self.getProfile(application) controller.pushViewController(viewController, animated: true) case "clear-private-data": let viewController = ClearPrivateDataTableViewController() viewController.profile = self.getProfile(application) viewController.tabManager = self.tabManager controller.pushViewController(viewController, animated: true) case "fxa": self.browserViewController.presentSignInViewController() default: break } return true }) } func applicationWillTerminate(_ application: UIApplication) { log.debug("Application will terminate.") // We have only five seconds here, so let's hope this doesn't take too long. self.profile?.shutdown() // Allow deinitializers to close our database connections. self.profile = nil self.tabManager = nil self.browserViewController = nil self.rootViewController = nil } /** * We maintain a weak reference to the profile so that we can pause timed * syncs when we're backgrounded. * * The long-lasting ref to the profile lives in BrowserViewController, * which we set in application:willFinishLaunchingWithOptions:. * * If that ever disappears, we won't be able to grab the profile to stop * syncing... but in that case the profile's deinit will take care of things. */ func getProfile(_ application: UIApplication) -> Profile { if let profile = self.profile { return profile } let p = BrowserProfile(localName: "profile", syncDelegate: application.syncDelegate) self.profile = p return p } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. var shouldPerformAdditionalDelegateHandling = true log.debug("Did finish launching.") log.debug("Setting up Adjust") self.adjustIntegration?.triggerApplicationDidFinishLaunchingWithOptions(launchOptions) #if BUDDYBUILD log.debug("Setting up BuddyBuild SDK") BuddyBuildSDK.setup() #endif log.debug("Making window key and visible…") self.window!.makeKeyAndVisible() // Now roll logs. log.debug("Triggering log roll.") DispatchQueue.global(qos: DispatchQoS.background.qosClass).async { Logger.syncLogger.deleteOldLogsDownToSizeLimit() Logger.browserLogger.deleteOldLogsDownToSizeLimit() } // If a shortcut was launched, display its information and take the appropriate action if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem { QuickActions.sharedInstance.launchedShortcutItem = shortcutItem // This will block "performActionForShortcutItem:completionHandler" from being called. shouldPerformAdditionalDelegateHandling = false } log.debug("Done with applicationDidFinishLaunching.") return shouldPerformAdditionalDelegateHandling } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false } guard let urlTypes = Bundle.main.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [AnyObject], let urlSchemes = urlTypes.first?["CFBundleURLSchemes"] as? [String] else { // Something very strange has happened; org.mozilla.Client should be the zeroeth URL type. log.error("Custom URL schemes not available for validating") return false } guard let scheme = components.scheme, urlSchemes.contains(scheme) else { log.warning("Cannot handle \(components.scheme ?? "nil") URL scheme") return false } guard let host = url.host else { log.warning("Cannot handle nil URL host") return false } let query = url.getQuery() switch host { case "open-url": let url = query["url"]?.unescape() ?? "" let isPrivate = NSString(string: query["private"] ?? "false").boolValue let params = LaunchParams(url: URL(string: url), isPrivate: isPrivate) if application.applicationState == .active { // If we are active then we can ask the BVC to open the new tab right away. // Otherwise, we remember the URL and we open it in applicationDidBecomeActive. launchFromURL(params) } else { openInFirefoxParams = params } return true case "deep-link": guard let url = query["url"], Bundle.main.bundleIdentifier == sourceApplication else { break } Router.shared.routeURL(url) return true case "fxa-signin": if AppConstants.MOZ_FXA_DEEP_LINK_FORM_FILL { // FxA form filling requires a `signin` query param and host = fxa-signin // Ex. firefox://fxa-signin?signin=<token>&someQuery=<data>... guard let signinQuery = query["signin"] else { break } let fxaParams: FxALaunchParams fxaParams = FxALaunchParams(query: query) launchFxAFromURL(fxaParams) return true } break default: () } return false } func launchFxAFromURL(_ params: FxALaunchParams) { guard params.query != nil else { return } self.browserViewController.presentSignInViewController(params) } func launchFromURL(_ params: LaunchParams) { let isPrivate = params.isPrivate ?? false if let newURL = params.url { self.browserViewController.switchToTabForURLOrOpen(newURL, isPrivate: isPrivate, isPrivileged: false) } else { self.browserViewController.openBlankNewTab(focusLocationField: true, isPrivate: isPrivate) } LeanplumIntegration.sharedInstance.track(eventName: .openedNewTab, withParameters: ["Source": "External App or Extension" as AnyObject]) } // We sync in the foreground only, to avoid the possibility of runaway resource usage. // Eventually we'll sync in response to notifications. func applicationDidBecomeActive(_ application: UIApplication) { guard !DebugSettingsBundleOptions.launchIntoEmailComposer else { return } // // We are back in the foreground, so set CleanlyBackgrounded to false so that we can detect that // the application was cleanly backgrounded later. // let defaults = UserDefaults() defaults.set(false, forKey: "ApplicationCleanlyBackgrounded") defaults.synchronize() if let profile = self.profile { profile.reopen() if profile.prefs.boolForKey(PendingAccountDisconnectedKey) ?? false { FxALoginHelper.sharedInstance.applicationDidDisconnect(application) } NightModeHelper.restoreNightModeBrightness(profile.prefs, toForeground: true) profile.syncManager.applicationDidBecomeActive() } // We could load these here, but then we have to futz with the tab counter // and making NSURLRequests. self.browserViewController.loadQueuedTabs(receivedURLs: self.receivedURLs) self.receivedURLs = nil application.applicationIconBadgeNumber = 0 // handle quick actions is available let quickActions = QuickActions.sharedInstance if let shortcut = quickActions.launchedShortcutItem { // dispatch asynchronously so that BVC is all set up for handling new tabs // when we try and open them quickActions.handleShortCutItem(shortcut, withBrowserViewController: browserViewController) quickActions.launchedShortcutItem = nil } // Check if we have a URL from an external app or extension waiting to launch, // then launch it on the main thread. if let params = openInFirefoxParams { openInFirefoxParams = nil DispatchQueue.main.async { self.launchFromURL(params) } } } func applicationDidEnterBackground(_ application: UIApplication) { // // At this point we are happy to mark the app as CleanlyBackgrounded. If a crash happens in background // sync then that crash will still be reported. But we won't bother the user with the Restore Tabs // dialog. We don't have to because at this point we already saved the tab state properly. // let defaults = UserDefaults() defaults.set(true, forKey: "ApplicationCleanlyBackgrounded") defaults.synchronize() syncOnDidEnterBackground(application: application) let elapsed = Int(Date().timeIntervalSince1970) - foregroundStartTime Telemetry.recordEvent(UsageTelemetry.makeEvent(elapsed)) sendCorePing() } fileprivate func syncOnDidEnterBackground(application: UIApplication) { guard let profile = self.profile else { return } profile.syncManager.applicationDidEnterBackground() var taskId: UIBackgroundTaskIdentifier = 0 taskId = application.beginBackgroundTask (expirationHandler: { _ in log.warning("Running out of background time, but we have a profile shutdown pending.") self.shutdownProfileWhenNotActive(application) application.endBackgroundTask(taskId) }) if profile.hasSyncableAccount() { profile.syncManager.syncEverything(why: .backgrounded).uponQueue(DispatchQueue.main) { _ in self.shutdownProfileWhenNotActive(application) application.endBackgroundTask(taskId) } } else { profile.shutdown() application.endBackgroundTask(taskId) } } fileprivate func shutdownProfileWhenNotActive(_ application: UIApplication) { // Only shutdown the profile if we are not in the foreground guard application.applicationState != UIApplicationState.active else { return } profile?.shutdown() } func applicationWillResignActive(_ application: UIApplication) { NightModeHelper.restoreNightModeBrightness((self.profile?.prefs)!, toForeground: false) } func applicationWillEnterForeground(_ application: UIApplication) { // The reason we need to call this method here instead of `applicationDidBecomeActive` // is that this method is only invoked whenever the application is entering the foreground where as // `applicationDidBecomeActive` will get called whenever the Touch ID authentication overlay disappears. self.updateAuthenticationInfo() resetForegroundStartTime() } fileprivate func resetForegroundStartTime() { foregroundStartTime = Int(Date().timeIntervalSince1970) } /// Send a telemetry ping if the user hasn't disabled reporting. /// We still create and log the ping for non-release channels, but we don't submit it. fileprivate func sendCorePing() { guard let profile = profile, (profile.prefs.boolForKey("settings.sendUsageData") ?? true) else { log.debug("Usage sending is disabled. Not creating core telemetry ping.") return } DispatchQueue.global(qos: DispatchQoS.background.qosClass).async { // The core ping resets data counts when the ping is built, meaning we'll lose // the data if the ping doesn't go through. To minimize loss, we only send the // core ping if we have an active connection. Until we implement a fault-handling // telemetry layer that can resend pings, this is the best we can do. guard DeviceInfo.hasConnectivity() else { log.debug("No connectivity. Not creating core telemetry ping.") return } let ping = CorePing(profile: profile) Telemetry.send(ping: ping, docType: .core) } } fileprivate func updateAuthenticationInfo() { if let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() { if !LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { authInfo.useTouchID = false KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authInfo) } } } fileprivate func setUpWebServer(_ profile: Profile) { let server = WebServer.sharedInstance ReaderModeHandlers.register(server, profile: profile) ErrorPageHelper.register(server, certStore: profile.certStore) AboutHomeHandler.register(server) AboutLicenseHandler.register(server) SessionRestoreHandler.register(server) // Bug 1223009 was an issue whereby CGDWebserver crashed when moving to a background task // catching and handling the error seemed to fix things, but we're not sure why. // Either way, not implicitly unwrapping a try is not a great way of doing things // so this is better anyway. do { try server.start() } catch let err as NSError { log.error("Unable to start WebServer \(err)") } } fileprivate func setUserAgent() { let firefoxUA = UserAgent.defaultUserAgent() // Set the UA for WKWebView (via defaults), the favicon fetcher, and the image loader. // This only needs to be done once per runtime. Note that we use defaults here that are // readable from extensions, so they can just use the cached identifier. let defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)! defaults.register(defaults: ["UserAgent": firefoxUA]) SDWebImageDownloader.shared().setValue(firefoxUA, forHTTPHeaderField: "User-Agent") // Record the user agent for use by search suggestion clients. SearchViewController.userAgent = firefoxUA // Some sites will only serve HTML that points to .ico files. // The FaviconFetcher is explicitly for getting high-res icons, so use the desktop user agent. FaviconFetcher.userAgent = UserAgent.desktopUserAgent() } func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, for notification: UILocalNotification, completionHandler: @escaping () -> Void) { if let actionId = identifier { if let action = SentTabAction(rawValue: actionId) { viewURLInNewTab(notification) switch action { case .bookmark: addBookmark(notification) break case .readingList: addToReadingList(notification) break default: break } } else { print("ERROR: Unknown notification action received") } } else { print("ERROR: Unknown notification received") } } func application(_ application: UIApplication, didReceive notification: UILocalNotification) { viewURLInNewTab(notification) } fileprivate func presentEmailComposerWithLogs() { if let buildNumber = Bundle.main.object(forInfoDictionaryKey: String(kCFBundleVersionKey)) as? NSString { let mailComposeViewController = MFMailComposeViewController() mailComposeViewController.mailComposeDelegate = self mailComposeViewController.setSubject("Debug Info for iOS client version v\(appVersion) (\(buildNumber))") if DebugSettingsBundleOptions.attachLogsToDebugEmail { do { let logNamesAndData = try Logger.diskLogFilenamesAndData() logNamesAndData.forEach { nameAndData in if let data = nameAndData.1 { mailComposeViewController.addAttachmentData(data, mimeType: "text/plain", fileName: nameAndData.0) } } } catch _ { print("Failed to retrieve logs from device") } } if DebugSettingsBundleOptions.attachTabStateToDebugEmail { if let tabStateDebugData = TabManager.tabRestorationDebugInfo().data(using: String.Encoding.utf8) { mailComposeViewController.addAttachmentData(tabStateDebugData, mimeType: "text/plain", fileName: "tabState.txt") } if let tabStateData = TabManager.tabArchiveData() { mailComposeViewController.addAttachmentData(tabStateData as Data, mimeType: "application/octet-stream", fileName: "tabsState.archive") } } self.window?.rootViewController?.present(mailComposeViewController, animated: true, completion: nil) } } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool { // If the `NSUserActivity` has a `webpageURL`, it is either a deep link or an old history item // reached via a "Spotlight" search before we began indexing visited pages via CoreSpotlight. if let url = userActivity.webpageURL { // Per Adjust documenation, https://docs.adjust.com/en/universal-links/#running-campaigns-through-universal-links, // it is recommended that links contain the `deep_link` query parameter. This link will also // be url encoded. let query = url.getQuery() if let deepLink = query["deep_link"]?.removingPercentEncoding, let url = URL(string: deepLink) { browserViewController.switchToTabForURLOrOpen(url, isPrivileged: true) return true } browserViewController.switchToTabForURLOrOpen(url, isPrivileged: true) return true } // Otherwise, check if the `NSUserActivity` is a CoreSpotlight item and switch to its tab or // open a new one. if userActivity.activityType == CSSearchableItemActionType { if let userInfo = userActivity.userInfo, let urlString = userInfo[CSSearchableItemActivityIdentifier] as? String, let url = URL(string: urlString) { browserViewController.switchToTabForURLOrOpen(url, isPrivileged: true) return true } } return false } fileprivate func viewURLInNewTab(_ notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String { if let urlToOpen = URL(string: alertURL) { browserViewController.openURLInNewTab(urlToOpen, isPrivileged: true) } } } fileprivate func addBookmark(_ notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String, let title = notification.userInfo?[TabSendTitleKey] as? String { let tabState = TabState(isPrivate: false, desktopSite: false, isBookmarked: false, url: URL(string: alertURL), title: title, favicon: nil) browserViewController.addBookmark(tabState) let userData = [QuickActions.TabURLKey: alertURL, QuickActions.TabTitleKey: title] QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.openLastBookmark, withUserData: userData, toApplication: UIApplication.shared) } } fileprivate func addToReadingList(_ notification: UILocalNotification) { if let alertURL = notification.userInfo?[TabSendURLKey] as? String, let title = notification.userInfo?[TabSendTitleKey] as? String { if let urlToOpen = URL(string: alertURL) { NotificationCenter.default.post(name: NSNotification.Name.FSReadingListAddReadingListItem, object: self, userInfo: ["URL": urlToOpen, "Title": title]) } } } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { let handledShortCutItem = QuickActions.sharedInstance.handleShortCutItem(shortcutItem, withBrowserViewController: browserViewController) completionHandler(handledShortCutItem) } } // MARK: - Root View Controller Animations extension AppDelegate: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == UINavigationControllerOperation.push { return BrowserToTrayAnimator() } else if operation == UINavigationControllerOperation.pop { return TrayToBrowserAnimator() } else { return nil } } } extension AppDelegate: TabManagerStateDelegate { func tabManagerWillStoreTabs(_ tabs: [Tab]) { // It is possible that not all tabs have loaded yet, so we filter out tabs with a nil URL. let storedTabs: [RemoteTab] = tabs.flatMap( Tab.toTab ) // Don't insert into the DB immediately. We tend to contend with more important // work like querying for top sites. let queue = DispatchQueue.global(qos: DispatchQoS.background.qosClass) queue.asyncAfter(deadline: DispatchTime.now() + Double(Int64(ProfileRemoteTabsSyncDelay * Double(NSEC_PER_MSEC))) / Double(NSEC_PER_SEC)) { self.profile?.storeTabs(storedTabs) } } } extension AppDelegate: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { // Dismiss the view controller and start the app up controller.dismiss(animated: true, completion: nil) startApplication(application!, withLaunchOptions: self.launchOptions) } } extension AppDelegate { func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) { FxALoginHelper.sharedInstance.application(application, didRegisterUserNotificationSettings: notificationSettings) } } extension AppDelegate { func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { FxALoginHelper.sharedInstance.apnsRegisterDidSucceed(deviceToken) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("failed to register. \(error)") FxALoginHelper.sharedInstance.apnsRegisterDidFail() } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { if Logger.logPII && log.isEnabledFor(level: .info) { NSLog("APNS NOTIFICATION \(userInfo)") } // At this point, we know that NotificationService has been run. // We get to this point if the notification was received while the app was in the foreground // OR the app was backgrounded and now the user has tapped on the notification. // Either way, if this method is being run, then the app is foregrounded. // Either way, we should zero the badge number. application.applicationIconBadgeNumber = 0 guard let profile = self.profile else { return completionHandler(.noData) } // NotificationService will have decrypted the push message, and done some syncing // activity. If the `client` collection was synced, and there are `displayURI` commands (i.e. sent tabs) // NotificationService will have collected them for us in the userInfo. if let serializedTabs = userInfo["sentTabs"] as? [[String: String]] { // Let's go ahead and open those. let receivedURLs = serializedTabs.flatMap { item -> URL? in guard let tabURL = item["url"] else { return nil } return URL(string: tabURL) } if receivedURLs.count > 0 { // Remember which URLs we received so we can filter them out later when // loading the queued tabs. self.receivedURLs = receivedURLs // If we're in the foreground, load the queued tabs now. if application.applicationState == UIApplicationState.active { DispatchQueue.main.async { self.browserViewController.loadQueuedTabs(receivedURLs: self.receivedURLs) self.receivedURLs = nil } } return completionHandler(.newData) } } // By now, we've dealt with any sent tab notifications. // // The only thing left to do now is to perform actions that can only be performed // while the app is foregrounded. // // Use the push message handler to re-parse the message, // this time with a BrowserProfile and processing the return // differently than in NotificationService. let handler = FxAPushMessageHandler(with: profile) handler.handle(userInfo: userInfo).upon { res in if let message = res.successValue { switch message { case .accountVerified: _ = handler.postVerification() case .thisDeviceDisconnected: FxALoginHelper.sharedInstance.applicationDidDisconnect(application) default: break } } completionHandler(res.isSuccess ? .newData : .failed) } } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) { let completionHandler: (UIBackgroundFetchResult) -> Void = { _ in } self.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler) } } struct FxALaunchParams { var query: [String: String] } struct LaunchParams { let url: URL? let isPrivate: Bool? } extension UIApplication { var syncDelegate: SyncDelegate { return AppSyncDelegate(app: self) } static var isInPrivateMode: Bool { let appDelegate = UIApplication.shared.delegate as? AppDelegate return appDelegate?.browserViewController.tabManager.selectedTab?.isPrivate ?? false } } class AppSyncDelegate: SyncDelegate { let app: UIApplication init(app: UIApplication) { self.app = app } open func displaySentTab(for url: URL, title: String, from deviceName: String?) { if let appDelegate = app.delegate as? AppDelegate, app.applicationState == .active { DispatchQueue.main.async { appDelegate.browserViewController.switchToTabForURLOrOpen(url, isPrivileged: false) } return } // check to see what the current notification settings are and only try and send a notification if // the user has agreed to them if let currentSettings = app.currentUserNotificationSettings { if currentSettings.types.rawValue & UIUserNotificationType.alert.rawValue != 0 { if Logger.logPII { log.info("Displaying notification for URL \(url.absoluteString)") } let notification = UILocalNotification() notification.fireDate = Date() notification.timeZone = NSTimeZone.default let title: String if let deviceName = deviceName { title = String(format: Strings.SentTab_TabArrivingNotification_WithDevice_title, deviceName) } else { title = Strings.SentTab_TabArrivingNotification_NoDevice_title } notification.alertTitle = title notification.alertBody = url.absoluteDisplayString notification.userInfo = [TabSendURLKey: url.absoluteString, TabSendTitleKey: title] notification.alertAction = nil // Restore this when we fix Bug 1364420. // notification.category = TabSendCategory app.presentLocalNotificationNow(notification) } } } }
mpl-2.0
81946d495a4a43dc31ae452a81a91e7b
43.241851
246
0.658079
5.73606
false
false
false
false
ryanbaldwin/RealmSwiftFHIR
firekit/fhir-parser-resources/fhir-1.6.0/swift-3.1/DateAndTime.swift
1
37510
// // DateAndTime.swift // SwiftFHIR // // Created by Pascal Pfiffner on 1/17/15. // 2015, SMART Health IT. // // Updated for Realm support by Ryan Baldwin on 2017-08-09 // Copyright @ 2017 Bunnyhug. All rights fall under Apache 2 // import Foundation import RealmSwift /** A protocol for all our date and time structs. */ protocol DateAndTime: CustomStringConvertible, Comparable, Equatable { var nsDate: Date { get } } /// A date for use in human communication. Named `FHIRDate` to avoid the numerous collisions with `Foundation.Date`. /// Month and day are optional and there are no timezones. final public class FHIRDate: Object, DateAndTime { /// The year. public dynamic var year: Int = Calendar.current.component(.year, from: Date()) private let _month = RealmOptional<Int8>() /// The month of the year, maximum of 12. public var month: Int8? { get { return _month.value } set { guard 1...12 ~= (newValue ?? 0) else { _month.value = nil return } _month.value = newValue } } private let _day = RealmOptional<Int8>() /// The day of the month; must be valid for the month (not enforced in code!). public var day: Int8? { get { return _day.value } set { guard 1...31 ~= (newValue ?? 0) else { _day.value = nil return } _day.value = newValue } } /** Dedicated initializer. Everything but the year is optional, invalid months or days will be ignored (however it is NOT checked whether the given month indeed contains the given day). - parameter year: The year of the date - parameter month: The month of the year - parameter day: The day of the month – your responsibility to ensure the month has the desired number of days; ignored if no month is given */ convenience public init(year: Int, month: Int8? = nil, day: Int8? = nil) { self.init() self.year = year self.month = month self.day = day } /** Initializes a date with our `DateAndTimeParser`. Will fail unless the string contains at least a valid year. - parameter string: The string to parse the date from */ convenience public init?(string: String) { self.init() let parsed = DateAndTimeParser.sharedParser.parse(string: string) if nil == parsed.date { return nil } year = parsed.date!.year month = parsed.date!.month day = parsed.date!.day } /** - returns: Today's date */ public static var today: FHIRDate { let (date, _, _) = DateNSDateConverter.sharedConverter.parse(date: Date()) return date } // MARK: Protocols public var nsDate: Date { return DateNSDateConverter.sharedConverter.create(fromDate: self) } override public var description: String { if let m = month { if let d = day { return String(format: "%04d-%02d-%02d", year, m, d) } return String(format: "%04d-%02d", year, m) } return String(format: "%04d", year) } public static func <(lhs: FHIRDate, rhs: FHIRDate) -> Bool { if lhs.year == rhs.year { guard let lhm = lhs.month else { return true } guard let rhm = rhs.month else { return false } if lhm == rhm { guard let lhd = lhs.day else { return true } guard let rhd = rhs.day else { return false } return lhd < rhd } return lhm < rhm } return lhs.year < rhs.year } public static func ==(lhs: FHIRDate, rhs: FHIRDate) -> Bool { return lhs.year == rhs.year && lhs.month == rhs.month && lhs.day == rhs.day } } /** A time during the day, optionally with seconds, usually for human communication. Named `FHIRTime` to match with `FHIRDate`. Minimum of 00:00 and maximum of < 24:00. There is no timezone. Since decimal precision has significance in FHIR, Time initialized from a string will remember the seconds string until it is manually set. */ final public class FHIRTime: Object, DateAndTime { /// The hour of the day; cannot be higher than 23. public dynamic var hour: Int8 = 0 { didSet { if hour < 0 { hour = 0 } if hour > 23 { hour = 23 } } } /// The minute of the hour; cannot be larger than 59 public dynamic var minute: Int8 = 0 { didSet { if minute < 0 { minute = 0 } if minute > 59 { minute = 59 } } } /// The second of the minute; must be smaller than 60 public dynamic var second: Double = 0.0 { didSet { if second < 0 { second = 0 } if second >= 60.0 { second = 59.999999999 } } } /// If initialized from string, this was the string for the seconds; we use this to remember precision. public internal(set) var tookSecondsFromString: String? /** Dedicated initializer. Overflows seconds and minutes to arrive at the final time, which must be less than 24:00:00 or it will be capped. The `secondsFromString` parameter will be discarded if it is negative or higher than 60. - parameter hour: Hour of day, cannot be greater than 23 (a time of 24:00 is illegal) - parameter minute: Minutes of the hour; if greater than 59 will roll over into hours - parameter second: Seconds of the minute; if 60 or more will roll over into minutes and discard `secondsFromString` - parameter secondsFromString: If time was initialized from a string, you can provide the seconds string here to ensure precision is kept. You are responsible to ensure that this string actually represents what's passed into `seconds`. */ public convenience init(hour: UInt8, minute: UInt8, second: Double, secondsFromString: String? = nil) { self.init() var overflowMinute: UInt = 0 var overflowHour: UInt = 0 if second >= 0.0 { if second >= 60.0 { self.second = second.truncatingRemainder(dividingBy: 60) overflowMinute = UInt((second - self.second) / 60) } else { self.second = second self.tookSecondsFromString = secondsFromString } } let mins = UInt(minute) + overflowMinute if mins > 59 { self.minute = Int8(UInt8(mins % 60)) overflowHour = (mins - (mins % 60)) / 60 } else { self.minute = Int8(mins) } let hrs = UInt(hour) + overflowHour if hrs > 23 { self.hour = 23 self.minute = 59 self.second = 59.999999999 self.tookSecondsFromString = nil } else { self.hour = Int8(hrs) } } /** Initializes a time from a time string by passing it through `DateAndTimeParser`. Will fail unless the string contains at least hour and minute. */ public convenience init?(string: String) { self.init() let parsed = DateAndTimeParser.sharedParser.parse(string: string, isTimeOnly: true) guard let time = parsed.time else { return nil } hour = time.hour minute = time.minute second = time.second tookSecondsFromString = time.tookSecondsFromString } /** The time right now. - returns: The clock time of right now. */ public static var now: FHIRTime { let (_, time, _) = DateNSDateConverter.sharedConverter.parse(date: Date()) return time } // MARK: Protocols public var nsDate: Date { return DateNSDateConverter.sharedConverter.create(fromTime: self) } // TODO: this implementation uses a workaround using string coercion instead of format: "%02d:%02d:%@" because %@ with String is not // supported on Linux (SR-957) public override var description: String { if let secStr = tookSecondsFromString { #if os(Linux) return String(format: "%02d:%02d:", hour, minute) + secStr #else return String(format: "%02d:%02d:%@", hour, minute, secStr) #endif } #if os(Linux) return String(format: "%02d:%02d:", hour, minute) + ((second < 10) ? "0" : "") + String(format: "%g", s) #else return String(format: "%02d:%02d:%@%g", hour, minute, (second < 10) ? "0" : "", second) #endif } public static func <(lhs: FHIRTime, rhs: FHIRTime) -> Bool { if lhs.hour == rhs.hour { if lhs.minute == rhs.minute { if lhs.second == rhs.second { return false } return lhs.second < rhs.second } return lhs.minute < rhs.minute } return lhs.hour < rhs.hour } public static func ==(lhs: FHIRTime, rhs: FHIRTime) -> Bool { return lhs.description == rhs.description } } /** A date, optionally with time, as used in human communication. If a time is specified there must be a timezone; defaults to the system reported local timezone. */ final public class DateTime: Object, DateAndTime { /// The original date string representing this DateTime. /// Could be as simple as just a year, such as "2017", or a full ISO8601 datetime string. public private(set) dynamic var dateString: String = "" /// The identifier for the timezone public private(set) dynamic var timeZoneIdentifier: String? /// The timezone string seen during deserialization; to be used on serialization unless the timezone changed. public private(set) dynamic var timeZoneString: String? /// The timezone. When set will update the `nsDate`, `timeZoneIdentifier`, and `timeZoneString` internals. public var timeZone: TimeZone? { get { if let identifier = timeZoneIdentifier { return TimeZone(identifier: identifier) } return nil } set { timeZoneIdentifier = newValue?.identifier timeZoneString = newValue?.offset(); updateDateIfNeeded() } } private dynamic var value: Date = Date() /// The actual Date object representing this DateTime under the hood. /// Since only a year is required for a DateTime, any missing value (such as month, or minute) /// will default to the lowest possible value. /// - Attention: When querying a DateTime via `nsDate`, use `value`. For example: /// /// ``` /// // this isn't going to return much unless you have DateTimes in the future /// realm.objects(DateTime.self).filter('value > %@', Date()) /// ``` public var nsDate: Date { get { return value } set { value = newValue dateString = makeFormatter(in: self.timeZone).string(from: value) } } /// The FHIRDate of this DateTime /// - Warning: If you wish to update a DateTime's `date` directly, you _must_ re-set /// the DateTime's `date` to itself afterwards. Failing to do so will fail to synchronize the DateTime /// internals and you will enter a world of pain. /// ``` /// // do this /// now.date!.year = 2015 /// now.date = now.date! /// print(now.nsDate) /// > 2015-06-15T17:52:17.764-04:00 /// /// // or this /// let now = DateTime.now /// let newDate = FHIRDate(year: 2017, month: 6, day: 15) /// let now.date = newDate /// print(now.nsDate) /// > 2017-06-15T17:52:17.764-04:00 /// // if the DateTime is already saved you'll need to delete the now.date before assigning now.date, /// // otherwise Realm will orphan that date time. /// /// // but don't just do this or else you will eventually cry at 2am. /// // note how the `nsDate` is now out of synch, and still sitting around in 2015 /// now.date!.year = 2013 /// print(now.nsDate) /// > 2015-06-15T17:52:17.764-04:00 /// ``` /// - Attention: This property is not persisted, and is instead computed from the DateTime internals. public var date: FHIRDate? { get { let (date, _, _, _) = DateAndTimeParser.sharedParser.parse(string: self.dateString) return date } set { let d = makeDate(newValue, time: time, timeZone: timeZone) nsDate = d } } /// The FHIRTime of this DateTime /// - Warning: If you wish to update a DateTime's `time` directly, you _must_ re-set /// the DateTime's `time` to itself afterwards. Failing to do so will fail to synchronize the DateTime /// internals and you will enter a world of pain. This works identically to `date`. /// See `date` for further details. /// - Attention: This property is not persisted, and is instead computed from the DateTime internals. public var time: FHIRTime? { get { let (_, time, _, _) = DateAndTimeParser.sharedParser.parse(string: self.dateString) return time } set { let d = makeDate(date, time: newValue, timeZone: timeZone) nsDate = d } } public override class func ignoredProperties() -> [String] { return ["date", "time", "timeZone", "nsDate"] } /// A DateTime instance representing current date and time, in the current timezone. public static var now: DateTime { // we need to shift the date over such that when assigned the local timezone // the date/time is actually right. Without doing this then we will be off by // whatever the actual timezone offset is. let comp = Calendar.current.dateComponents(in: TimeZone.current, from: Date()) let localDate = Calendar.current.date(from: comp)! return DateTime(string: localFormatter.string(from: localDate))! } /// Designated initializer, takes a date and optionally a time and a timezone. /// /// If time is given but no timezone, the instance is assigned the local time zone. /// /// - Parameters: /// - date: The date of the DateTime /// - time: The time of the DateTime /// - timeZone: The timezone. Will default to TimeZone.current if not provided. public convenience init(date: FHIRDate, time: FHIRTime? = nil, timeZone: TimeZone?) { self.init() if time != nil { let tz = timeZone ?? TimeZone.current timeZoneIdentifier = tz.identifier timeZoneString = tz.offset() } self.dateString = makeDescription(date: date, time: time) self.value = makeDate(date, time: time, timeZone: timeZone ?? TimeZone.current) } /** Uses `DateAndTimeParser` to initialize from a date-time string. If time is given but no timezone, the instance is assigned the local time zone. - parameter string: The string the date-time is parsed from */ public convenience init?(string: String) { let (date, time, tz, tzString) = DateAndTimeParser.sharedParser.parse(string: string) guard let d = date else { return nil } self.init(date: d, time: time, timeZone: tz) self.dateString = string self.timeZoneString = tzString } private func makeDescription(date: FHIRDate?, time: FHIRTime?) -> String { if let tm = time, let tz = timeZoneString ?? timeZone?.offset() { return "\((date ?? FHIRDate.today).description)T\(tm.description)\(tz)" } return (date ?? FHIRDate.today).description } public override var description: String { return makeDescription(date: date, time: time) } public static func <(lhs: DateTime, rhs: DateTime) -> Bool { let lhd = lhs.nsDate let rhd = rhs.nsDate return (lhd.compare(rhd) == .orderedAscending) } public static func ==(lhs: DateTime, rhs: DateTime) -> Bool { let lhd = lhs.nsDate let rhd = rhs.nsDate return (lhd.compare(rhd) == .orderedSame) } private func updateDateIfNeeded() { let d = makeDate(date, time: time, timeZone: timeZone) if d != nsDate { nsDate = d } } } /** An instant in time, known at least to the second and with a timezone, for machine times. */ final public class Instant: Object, DateAndTime { /// The original date string representing this DateTime. /// Could be as simple as just a year, such as "2017", or a full ISO8601 datetime string. public private(set) dynamic var dateString = "" /// The FHIRDate of this `Instant` /// - Warning: If you wish to update a DateTime's `date` directly, you _must_ re-set /// the DateTime's `date` to itself afterwards. Failing to do so will fail to synchronize the DateTime /// internals and you will enter a world of pain. /// ``` /// // do this /// now.date!.year = 2015 /// now.date = now.date! /// print(now.nsDate) /// > 2015-06-15T17:52:17.764-04:00 /// /// // or this /// let now = DateTime.now /// let newDate = FHIRDate(year: 2017, month: 6, day: 15) /// let now.date = newDate /// print(now.nsDate) /// > 2017-06-15T17:52:17.764-04:00 /// // if the DateTime is already saved you'll need to delete the now.date before assigning now.date, /// // otherwise Realm will orphan that date time. /// /// // but don't just do this or else you will eventually cry at 2am. /// // note how the `nsDate` is now out of synch, and still sitting around in 2015 /// now.date!.year = 2013 /// print(now.nsDate) /// > 2015-06-15T17:52:17.764-04:00 /// ``` /// - Attention: This property is not persisted, and is instead computed from the DateTime internals. public var date: FHIRDate { get { let (date, _, _, _) = DateAndTimeParser.sharedParser.parse(string: self.dateString) return date ?? FHIRDate.today } set { if nil == newValue.day { newValue.day = 1 } if nil == newValue.month { newValue.month = 1 } let d = makeDate(newValue, time: time, timeZone: timeZone) nsDate = d } } /// The FHIRTime of this `Instant` /// - Warning: If you wish to update a DateTime's `time` directly, you _must_ re-set /// the DateTime's `time` to itself afterwards. Failing to do so will fail to synchronize the DateTime /// internals and you will enter a world of pain. This works identically to `date`. /// See `date` for further details. /// - Attention: This property is not persisted, and is instead computed from the DateTime internals. public var time: FHIRTime { get { let (_, time, _, _) = DateAndTimeParser.sharedParser.parse(string: self.dateString) return time! } set { let d = makeDate(date, time: newValue, timeZone: timeZone) nsDate = d } } /// The identifier for the timezone public private(set) dynamic var timeZoneIdentifier: String = TimeZone.current.identifier /// The timezone string seen during deserialization; to be used on serialization unless the timezone changed. public private(set) dynamic var timeZoneString: String = TimeZone.current.offset() /// The timezone. When set will update the `nsDate`, `timeZoneIdentifier`, and `timeZoneString` internals. public var timeZone: TimeZone { get { return TimeZone(identifier: timeZoneIdentifier)! } set { timeZoneIdentifier = newValue.identifier timeZoneString = newValue.offset(); updateDateIfNeeded() } } private dynamic var value: Date = Date() /// The actual Date object representing this DateTime under the hood. /// Since only a year is required for a DateTime, any missing value (such as month, or minute) /// will default to the lowest possible value. /// - Attention: When querying a DateTime via `nsDate`, use `value`. For example: /// /// ``` /// // this isn't going to return much unless you have DateTimes in the future /// realm.objects(DateTime.self).filter('value > %@', Date()) /// ``` public var nsDate: Date { get { return value } set { value = newValue dateString = Instant.makeFormatter(in: self.timeZone).string(from: value) } } public override class func ignoredProperties() -> [String] { return ["date", "time", "timeZone", "nsDate"] } private static func makeFormatter(in timeZone: TimeZone?) -> DateFormatter { let f = DateFormatter() f.calendar = Calendar(identifier: .iso8601) f.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" if timeZone != nil { f.timeZone = timeZone } return f } private static var localFormatter: DateFormatter { return makeFormatter(in: TimeZone.current) } /** This very instant. - returns: An Instant instance representing current date and time in the current timezone. */ public static var now: Instant { // we need to shift the date over such that when assigned the local timezone // the date/time is actually right. Without doing this then we will be off by // twice as much as to whatever the actual timezone offset is. let comp = Calendar.current.dateComponents(in: TimeZone.current, from: Date()) let localDate = Calendar.current.date(from: comp)! return Instant(string: localFormatter.string(from: localDate))! } /** Designated initializer. - parameter date: The date of the instant; ensures to have month and day (which are optional in the `FHIRDate` construct) - parameter time: The time of the instant; ensures to have seconds (which are optional in the `FHIRTime` construct) - parameter timeZone: The timezone */ public convenience init(date: FHIRDate, time: FHIRTime, timeZone: TimeZone) { self.init() if date.month == nil { date.month = 1 } if date.day == nil { date.day = 1 } self.value = makeDate(date, time: time, timeZone: timeZone) self.timeZoneIdentifier = timeZone.identifier self.timeZoneString = timeZone.offset() if dateString == "" { self.dateString = makeDescription(date: date, time: time, timeZoneString: timeZoneString) } } /** Uses `DateAndTimeParser` to initialize from a date-time string. - parameter string: The string to parse the instant from */ public convenience init?(string: String) { self.init() let (d, t, tz, tzString) = DateAndTimeParser.sharedParser.parse(string: string) guard let date = d, date.month != nil, date.day != nil, let time = t, let timeZone = tz else { return nil } self.dateString = string self.value = makeDate(date, time: time, timeZone: timeZone) self.timeZoneIdentifier = timeZone.identifier self.timeZoneString = tzString! } private func updateDateIfNeeded() { let d = makeDate(date, time: time, timeZone: timeZone) if d != nsDate { nsDate = d } } private func makeDescription(date: FHIRDate, time: FHIRTime, timeZoneString: String) -> String{ return "\(date.description)T\(time.description)\(timeZoneString)" } public override var description: String { return makeDescription(date: date, time: time, timeZoneString: timeZoneString) } public static func <(lhs: Instant, rhs: Instant) -> Bool { let lhd = lhs.nsDate let rhd = rhs.nsDate return (lhd.compare(rhd) == .orderedAscending) } public static func ==(lhs: Instant, rhs: Instant) -> Bool { let lhd = lhs.nsDate let rhd = rhs.nsDate return (lhd.compare(rhd) == .orderedSame) } } extension Instant { /** Attempts to parse an Instant from RFC1123-formatted date strings, usually used by HTTP headers: - "EEE',' dd MMM yyyy HH':'mm':'ss z" - "EEEE',' dd'-'MMM'-'yy HH':'mm':'ss z" (RFC850) - "EEE MMM d HH':'mm':'ss yyyy" Created by taking liberally from Marcus Rohrmoser's blogpost at http://blog.mro.name/2009/08/nsdateformatter-http-header/ - parameter httpDate: The date string to parse - returns: An Instant if parsing was successful, nil otherwise */ public static func fromHttpDate(_ httpDate: String) -> Instant? { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(abbreviation: "GMT") formatter.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss z" if let date = formatter.date(from: httpDate) { return date.fhir_asInstant() } formatter.dateFormat = "EEEE',' dd'-'MMM'-'yy HH':'mm':'ss z" if let date = formatter.date(from: httpDate) { return date.fhir_asInstant() } formatter.dateFormat = "EEE MMM d HH':'mm':'ss yyyy" if let date = formatter.date(from: httpDate) { return date.fhir_asInstant() } return nil } } /** Converts between NSDate and our FHIRDate, FHIRTime, DateTime and Instance structs. */ class DateNSDateConverter { /// The singleton instance static var sharedConverter = DateNSDateConverter() let calendar: Calendar let utc: TimeZone init() { utc = TimeZone(abbreviation: "UTC")! var cal = Calendar(identifier: Calendar.Identifier.gregorian) cal.timeZone = utc calendar = cal } // MARK: Parsing /** Execute parsing. Will use `calendar` to split the Date into components. - parameter date: The Date to parse into structs - returns: A tuple with (FHIRDate, FHIRTime, TimeZone) */ func parse(date inDate: Date) -> (FHIRDate, FHIRTime, TimeZone) { let flags: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second, .nanosecond, .timeZone] let comp = calendar.dateComponents(flags, from: inDate) let date = FHIRDate(year: comp.year!, month: Int8(comp.month!), day: Int8(comp.day!)) let zone = comp.timeZone ?? utc let secs = Double(comp.second!) + (Double(comp.nanosecond!) / 1000000000) let time = FHIRTime(hour: UInt8(comp.hour!), minute: UInt8(comp.minute!), second: secs) return (date, time, zone) } // MARK: Creation func create(fromDate date: FHIRDate) -> Date { return _create(date: date, time: nil, timeZone: nil) } func create(fromTime time: FHIRTime) -> Date { return _create(date: nil, time: time, timeZone: nil) } func create(date: FHIRDate, time: FHIRTime, timeZone: TimeZone) -> Date { return _create(date: date, time: time, timeZone: timeZone) } func _create(date: FHIRDate?, time: FHIRTime?, timeZone: TimeZone?) -> Date { var comp = DateComponents() comp.timeZone = timeZone ?? utc if let yr = date?.year { comp.year = yr } if let mth = date?.month { comp.month = Int(mth) } if let d = date?.day { comp.day = Int(d) } if let hr = time?.hour { comp.hour = Int(hr) } if let min = time?.minute { comp.minute = Int(min) } if let sec = time?.second { comp.second = Int(floor(sec)) comp.nanosecond = Int(sec.truncatingRemainder(dividingBy: 1000000000)) } return calendar.date(from: comp) ?? Date() } } /** Parses Date and Time from strings in a narrow set of the extended ISO 8601 format. */ class DateAndTimeParser { /// The singleton instance static var sharedParser = DateAndTimeParser() /** Parses a date string in "YYYY[-MM[-DD]]" and a time string in "hh:mm[:ss[.sss]]" (extended ISO 8601) format, separated by "T" and followed by either "Z" or a valid time zone offset in the "±hh[:?mm]" format. Does not currently check if the day exists in the given month. - parameter string: The date string to parse - parameter isTimeOnly: If true assumes that the string describes time only - returns: A tuple with (FHIRDate?, FHIRTime?, TimeZone?, String? [for time zone]) */ func parse(string: String, isTimeOnly: Bool=false) -> (date: FHIRDate?, time: FHIRTime?, tz: TimeZone?, tzString: String?) { let scanner = Scanner(string: string) var date: FHIRDate? var time: FHIRTime? var tz: TimeZone? var tzString: String? // scan date (must have at least the year) if !isTimeOnly { if let year = scanner.fhir_scanInt(), year < 10000 { // dates above 9999 are considered special cases if nil != scanner.fhir_scanString("-"), let month = scanner.fhir_scanInt(), month <= 12 { if nil != scanner.fhir_scanString("-"), let day = scanner.fhir_scanInt(), day <= 31 { date = FHIRDate(year: Int(year), month: Int8(month), day: Int8(day)) } else { date = FHIRDate(year: Int(year), month: Int8(month), day: nil) } } else { date = FHIRDate(year: Int(year), month: nil, day: nil) } } } // scan time if isTimeOnly || nil != scanner.fhir_scanString("T") { if let hour = scanner.fhir_scanInt(), hour >= 0 && hour < 24 && nil != scanner.fhir_scanString(":"), let minute = scanner.fhir_scanInt(), minute >= 0 && minute < 60 { let digitSet = CharacterSet.decimalDigits var decimalSet = NSMutableCharacterSet.decimalDigits decimalSet.insert(".") if nil != scanner.fhir_scanString(":"), let secStr = scanner.fhir_scanCharacters(from: decimalSet as CharacterSet), let second = Double(secStr), second < 60.0 { time = FHIRTime(hour: UInt8(hour), minute: UInt8(minute), second: second, secondsFromString: secStr) } else { time = FHIRTime(hour: UInt8(hour), minute: UInt8(minute), second: 0) } // scan zone if !scanner.fhir_isAtEnd { if nil != scanner.fhir_scanString("Z") { tz = TimeZone(abbreviation: "UTC") tzString = "Z" } else if var tzStr = (scanner.fhir_scanString("-") ?? scanner.fhir_scanString("+")) { if let hourStr = scanner.fhir_scanCharacters(from: digitSet) { tzStr += hourStr var tzhour = 0 var tzmin = 0 if 2 == hourStr.characters.count { tzhour = Int(hourStr) ?? 0 if nil != scanner.fhir_scanString(":"), let tzm = scanner.fhir_scanInt() { tzStr += (tzm < 10) ? ":0\(tzm)" : ":\(tzm)" if tzm < 60 { tzmin = tzm } } } else if 4 == hourStr.characters.count { tzhour = Int(hourStr.substring(to: hourStr.index(hourStr.startIndex, offsetBy: 2)))! tzmin = Int(hourStr.substring(from: hourStr.index(hourStr.startIndex, offsetBy: 2)))! } let offset = tzhour * 3600 + tzmin * 60 tz = TimeZone(secondsFromGMT:tzStr.hasPrefix("+") ? offset : -1 * offset) tzString = tzStr } } } } } return (date, time, tz, tzString) } } /** Extend Date to be able to return DateAndTime instances. */ public extension Date { /** Create a `FHIRDate` instance from the receiver. */ func fhir_asDate() -> FHIRDate { let (date, _, _) = DateNSDateConverter.sharedConverter.parse(date: self) return date } /** Create a `Time` instance from the receiver. */ func fhir_asTime() -> FHIRTime { let (_, time, _) = DateNSDateConverter.sharedConverter.parse(date: self) return time } /** Create a `DateTime` instance from the receiver. */ func fhir_asDateTime() -> DateTime { let (date, time, tz) = DateNSDateConverter.sharedConverter.parse(date: self) return DateTime(date: date, time: time, timeZone: tz) } /** Create an `Instance` instance from the receiver. */ func fhir_asInstant() -> Instant { let (date, time, tz) = DateNSDateConverter.sharedConverter.parse(date: self) return Instant(date: date, time: time, timeZone: tz) } } /** Extend TimeZone to report the offset in "+00:00" or "Z" (for UTC/GMT) format. */ extension TimeZone { /** Return the offset as a string string. - returns: The offset as a string; uses "Z" if the timezone is UTC or GMT */ func offset() -> String { if "UTC" == identifier || "GMT" == identifier { return "Z" } let secsFromGMT = secondsFromGMT() let hr = abs((secsFromGMT / 3600) - (((secsFromGMT % 3600) / 3600) * 60)) let min = abs((secsFromGMT % 3600) / 60) return (secsFromGMT >= 0 ? "+" : "-") + String(format: "%02d:%02d", hr, min) } } /** Extend Scanner to account for interface differences between macOS and Linux (as of November 2016) */ extension Scanner { public var fhir_isAtEnd: Bool { #if os(Linux) return atEnd #else return isAtEnd #endif } public func fhir_scanString(_ searchString: String) -> String? { #if os(Linux) return scanString(string: searchString) #else var str: NSString? if scanString(searchString, into: &str) { return str as String? } return nil #endif } public func fhir_scanCharacters(from set: CharacterSet) -> String? { #if os(Linux) return scanCharactersFromSet(set) #else var str: NSString? if scanCharacters(from: set, into: &str) { return str as String? } return nil #endif } public func fhir_scanInt() -> Int? { var int = 0 #if os(Linux) let flag = scanInteger(&int) #else let flag = scanInt(&int) #endif return flag ? int : nil } } fileprivate func makeFormatter(in timeZone: TimeZone?) -> DateFormatter { let f = DateFormatter() f.calendar = Calendar(identifier: .iso8601) f.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" if timeZone != nil { f.timeZone = timeZone } return f } fileprivate var localFormatter: DateFormatter { return makeFormatter(in: TimeZone.current) } fileprivate func makeDate(_ date: FHIRDate?, time: FHIRTime?, timeZone: TimeZone?) -> Date { if let time = time, let tz = timeZone { return DateNSDateConverter.sharedConverter.create(date: date ?? FHIRDate.today, time: time, timeZone: tz) } return DateNSDateConverter.sharedConverter.create(fromDate: date ?? FHIRDate.today) }
apache-2.0
9d0622438dcb851480931757e262d9c1
34.58444
176
0.565483
4.425487
false
false
false
false
kesun421/firefox-ios
Client/Frontend/Browser/FaviconManager.swift
3
6047
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import Shared import Storage import SDWebImage import Deferred import Sync class FaviconManager: TabHelper { static let FaviconDidLoad = "FaviconManagerFaviconDidLoad" let profile: Profile! weak var tab: Tab? static let maximumFaviconSize = 1 * 1024 * 1024 // 1 MiB file size limit init(tab: Tab, profile: Profile) { self.profile = profile self.tab = tab if let path = Bundle.main.path(forResource: "Favicons", ofType: "js") { if let source = try? NSString(contentsOfFile: path, encoding: String.Encoding.utf8.rawValue) as String { let userScript = WKUserScript(source: source, injectionTime: WKUserScriptInjectionTime.atDocumentEnd, forMainFrameOnly: true) tab.webView!.configuration.userContentController.addUserScript(userScript) } } } class func name() -> String { return "FaviconsManager" } func scriptMessageHandlerName() -> String? { return "faviconsMessageHandler" } fileprivate func loadFavicons(_ tab: Tab, profile: Profile, favicons: [Favicon]) -> Deferred<[Maybe<Favicon>]> { var deferreds: [() -> Deferred<Maybe<Favicon>>] deferreds = favicons.map { favicon in return { [weak tab] () -> Deferred<Maybe<Favicon>> in if let tab = tab, let url = URL(string: favicon.url), let currentURL = tab.url { return self.getFavicon(tab, iconUrl: url, currentURL: currentURL, icon: favicon, profile: profile) } else { return deferMaybe(FaviconError()) } } } return all(deferreds.map({$0()})) } func getFavicon(_ tab: Tab, iconUrl: URL, currentURL: URL, icon: Favicon, profile: Profile) -> Deferred<Maybe<Favicon>> { let deferred = Deferred<Maybe<Favicon>>() let manager = SDWebImageManager.shared() let options: [SDWebImageOptions] = tab.isPrivate ? [.lowPriority, .cacheMemoryOnly] : [.lowPriority] let url = currentURL.absoluteString let site = Site(url: url, title: "") func loadImageCompleted(_ img: UIImage?, _ url: URL?) { guard let img = img, let urlString = url?.absoluteString else { deferred.fill(Maybe(failure: FaviconError())) return } let fav = Favicon(url: urlString, date: Date(), type: icon.type) fav.width = Int(img.size.width) fav.height = Int(img.size.height) if !tab.isPrivate { if tab.favicons.isEmpty { self.makeFaviconAvailable(tab, atURL: currentURL, favicon: fav, withImage: img) } tab.favicons.append(fav) self.profile.favicons.addFavicon(fav, forSite: site).upon { _ in deferred.fill(Maybe(success: fav)) } } else { tab.favicons.append(fav) deferred.fill(Maybe(success: fav)) } } var fetch: SDWebImageOperation? = nil fetch = manager.loadImage(with: iconUrl, options: SDWebImageOptions(options), progress: { (receivedSize, expectedSize, _) in if receivedSize > FaviconManager.maximumFaviconSize || expectedSize > FaviconManager.maximumFaviconSize { fetch?.cancel() } }, completed: { (img, _, _, _, _, url) in loadImageCompleted(img, url) }) return deferred } func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { self.tab?.favicons.removeAll(keepingCapacity: false) if let tab = self.tab, let currentURL = tab.url { var favicons = [Favicon]() if let icons = message.body as? [String: Int] { for icon in icons { if let _ = URL(string: icon.0), let iconType = IconType(rawValue: icon.1) { let favicon = Favicon(url: icon.0, date: Date(), type: iconType) favicons.append(favicon) } } } loadFavicons(tab, profile: profile, favicons: favicons).uponQueue(DispatchQueue.main) { result in let results = result.flatMap({ $0.successValue }) let faviconsReadOnly = favicons if results.count == 1 && faviconsReadOnly[0].type == .guess { // No favicon is indicated in the HTML self.noFaviconAvailable(tab, atURL: currentURL as URL) } NotificationCenter.default.post(name: NSNotification.Name(rawValue: FaviconManager.FaviconDidLoad), object: tab) } } } func makeFaviconAvailable(_ tab: Tab, atURL url: URL, favicon: Favicon, withImage image: UIImage) { // XXX: Bug 1390200 - Disable NSUserActivity/CoreSpotlight temporarily // let helper = tab.getHelper(name: "SpotlightHelper") as? SpotlightHelper // helper?.updateImage(image, forURL: url) } func noFaviconAvailable(_ tab: Tab, atURL url: URL) { // XXX: Bug 1390200 - Disable NSUserActivity/CoreSpotlight temporarily // let helper = tab.getHelper(name: "SpotlightHelper") as? SpotlightHelper // helper?.updateImage(forURL: url) } } class FaviconError: MaybeErrorType { internal var description: String { return "No Image Loaded" } }
mpl-2.0
43c31d16f7cd989665bef791b59477a5
41.286713
141
0.572185
5.022425
false
false
false
false
mfreiwald/RealDebridKit
RealDebridKit/Classes/Models/RDError.swift
1
985
// // Error.swift // Pods // // Created by Michael Freiwald on 24.11.16. // // import Foundation import Gloss public struct RDError : Decodable { public let error:String public let errorCode:ErrorCode public init(json: JSON) { if let error: String = "error" <~~ json { self.error = error } else { self.error = "Unknown Error" } if let errorCode: Int = "error_code" <~~ json { if let errorCodeEnum = ErrorCode(rawValue: errorCode) { self.errorCode = errorCodeEnum } else { self.errorCode = ErrorCode.UnknownError } } else { self.errorCode = ErrorCode.UnknownError } } public init() { self.error = "Unknown Error" self.errorCode = ErrorCode.UnknownError } public init(code:ErrorCode) { self.errorCode = code self.error = String(describing: code) } }
mit
ce6dbfebce534b42edde0403d6074c95
21.906977
67
0.548223
4.377778
false
false
false
false
logansease/SeaseAssist
Pod/Classes/String+CaseConversion.swift
1
1198
// // String+CaseConversion.swift // SeaseAssist // // Created by lsease on 10/27/16. // Copyright © 2016 Logan Sease. All rights reserved. // import Foundation public extension String{ func camelCaseToTitleCase() -> String! { var string = self string = string.replacingOccurrences(of: "([a-z])([A-Z,0-9])", with: "$1 $2", options: .regularExpression, range: nil) string = string.capitalized return string } func camelCaseToUnderscoreCase() -> String! { var string = self string = string.replacingOccurrences(of: "([a-z])([A-Z,0-9])", with: "$1_$2", options: .regularExpression, range: nil) string = string.lowercased() return string } func underscoreCaseToCamelCase() -> String! { var result = "" let pieces = self.components(separatedBy: "_") for piece in pieces { if piece != pieces.first { result = result + piece.capitalized } else{ result = result + piece } } return result } }
mit
6686c291600b187e4eab636ab22da690
22.019231
126
0.522139
4.534091
false
false
false
false
safx/TypetalkApp
TypetalkApp/Utils/MarkdownLite.swift
1
9202
// // MarkdownLite.swift // TypetalkApp // // Created by Safx Developer on 2015/04/18. // Copyright (c) 2015年 Safx Developers. All rights reserved. // import Foundation import Emoji typealias ContextClosure = (CGContext -> ()) -> () #if os(iOS) import UIKit let verticalDirection = CGFloat(1.0) typealias EdgeInsets = UIEdgeInsets typealias Color = UIColor typealias Font = UIFont func WithCurrentGraphicsContext(height: CGFloat, closure: CGContext -> ()) { let gfx = UIGraphicsGetCurrentContext() closure(gfx!) } extension NSAttributedString { func boundingRectWithSizeEx(size: CGSize, options: NSStringDrawingOptions, context: NSStringDrawingContext?) -> CGRect { return boundingRectWithSize(size, options: options, context: context) } } #else import AppKit let verticalDirection = CGFloat(-1.0) typealias EdgeInsets = NSEdgeInsets typealias Color = NSColor typealias Font = NSFont func UIEdgeInsetsMake(top: CGFloat, _ left: CGFloat, _ bottom: CGFloat, _ right: CGFloat) -> EdgeInsets { return NSEdgeInsetsMake(top, left, bottom, right) } func UIEdgeInsetsInsetRect(rect: CGRect, _ insets: EdgeInsets) -> CGRect { return CGRectMake(CGRectGetMinX(rect) + insets.left, CGRectGetMinY(rect) + insets.top, CGRectGetWidth(rect) - insets.left - insets.right, CGRectGetHeight(rect) - insets.top - insets.bottom); } class NSStringDrawingContext {} extension NSAttributedString { func boundingRectWithSizeEx(size: CGSize, options: NSStringDrawingOptions, context: NSStringDrawingContext?) -> CGRect { return boundingRectWithSize(size, options: options) } func drawWithRect(rect: CGRect, options: NSStringDrawingOptions, context: NSStringDrawingContext?) { drawWithRect(rect, options: options) } } func WithCurrentGraphicsContext(height: CGFloat) -> (CGContext -> ()) -> () { return { (closure: CGContext -> ()) in let ctx = NSGraphicsContext.currentContext()! ctx.saveGraphicsState() let gfx = ctx.CGContext let xform = NSAffineTransform() xform.translateXBy(0, yBy: height - 12) xform.scaleXBy(1, yBy: -1) xform.concat() closure(gfx) ctx.restoreGraphicsState() } } #endif let DefaultFont = Font.systemFontOfSize(15) let FixedFont = Font(name: "Menlo", size: 14)! let ParagraphMargin = UIEdgeInsetsMake(4, 4, 4, 4) let QuoteMargin = UIEdgeInsetsMake(4, 12, 4, 4) let QuotePadding = UIEdgeInsetsMake(0, 4, 0, 0) let QuoteBorderColor = Color(white: 0.7, alpha: 1).CGColor let QuoteLeftBorderWidth = CGFloat(2) let CodeMargin = UIEdgeInsetsMake(4, 8, 4, 8) let CodePadding = UIEdgeInsetsMake(4, 8, 4, 4) let CodeBackgroundColor = Color(white: 0.9, alpha: 1).CGColor func VerticalMargin(margin: EdgeInsets) -> CGFloat { return margin.top + margin.bottom } func VerticalMargin(margin1: EdgeInsets, margin2: EdgeInsets) -> CGFloat { return VerticalMargin(margin1) + VerticalMargin(margin2) } func HorizontalMargin(margin: EdgeInsets) -> CGFloat { return margin.left + margin.right } func HorizontalMargin(margin1: EdgeInsets, margin2: EdgeInsets) -> CGFloat { return HorizontalMargin(margin1) + HorizontalMargin(margin2) } enum MarkdownInline { case Link(String, NSURL?) case Text(String) } enum MarkdownBlock { case Document([MarkdownBlock]) case Quote([MarkdownBlock]) case Paragraph([MarkdownInline]) case Code(String, String) } extension MarkdownInline { internal var attributedString: NSMutableAttributedString { switch self { case .Link(let (text, url)): var attrs: [String:AnyObject] = [ NSFontAttributeName: DefaultFont, NSForegroundColorAttributeName: Color.blueColor(), NSUnderlineColorAttributeName: Color.blueColor(), NSUnderlineStyleAttributeName: 1 ] if let u = url { attrs[NSLinkAttributeName] = u //attrs[NSToolTipAttributeName] = u.absoluteString } return NSMutableAttributedString(string: text.emojiUnescapedString, attributes: attrs) case .Text(let text): let attrs: [String:AnyObject] = [ NSFontAttributeName: DefaultFont ] return NSMutableAttributedString(string: text.emojiUnescapedString, attributes: attrs) } } } extension MarkdownBlock { func getHeight(width: CGFloat) -> CGFloat { //let size = CGSize(width: CGFloat(width), height: CGFloat.max) switch self { case .Document(let blocks): return blocks.reduce(0) { a, e in let h = e.getHeight(width) return a + h } case .Quote(let blocks): return blocks.reduce(0) { a, e in let h = e.getHeight(width - HorizontalMargin(QuoteMargin, margin2: QuotePadding)) return a + h } + VerticalMargin(QuoteMargin, margin2: QuotePadding) case .Paragraph: let s = CGSize(width: width - HorizontalMargin(ParagraphMargin), height: CGFloat.max) let bounds = attributedString.boundingRectWithSizeEx(s, options: drawingOptions, context: nil) return bounds.height + VerticalMargin(ParagraphMargin) case .Code: let s = CGSize(width: width - HorizontalMargin(CodeMargin, margin2: CodePadding), height: CGFloat.max) let bounds = attributedString.boundingRectWithSizeEx(s, options: drawingOptions, context: nil) return bounds.height + VerticalMargin(CodeMargin, margin2: CodePadding) } } private var drawingOptions: NSStringDrawingOptions { return unsafeBitCast(NSStringDrawingOptions.UsesLineFragmentOrigin.rawValue | NSStringDrawingOptions.UsesFontLeading.rawValue, NSStringDrawingOptions.self) } private var attributedString: NSMutableAttributedString { switch self { case .Code(let (code, _/*lang*/)): let attrs: [String:AnyObject] = [ NSFontAttributeName: FixedFont ] return NSMutableAttributedString(string: code, attributes: attrs) case .Paragraph(let inlines): let es = inlines.map { $0.attributedString } var a = NSMutableAttributedString() a.beginEditing() a = es.reduce(a) { a, e in a.appendAttributedString(e) return a } a.endEditing() return a default: fatalError("Code block expected") } } private func drawChildrenInRect(elements: [MarkdownBlock], rect: CGRect, withCurrentGraphicsContext: ContextClosure, context: NSStringDrawingContext?) { _ = elements.reduce(CGFloat(0)) { top, elem in let offsetRect = rect.offsetBy(dx: 0, dy: top) elem.drawInRect(offsetRect, context: context, withCurrentGraphicsContext: withCurrentGraphicsContext) let height = elem.getHeight(rect.size.width) return top + height * verticalDirection } } func drawInRect(rect: CGRect, context: NSStringDrawingContext? = nil, withCurrentGraphicsContext: ContextClosure) { let height = self.getHeight(rect.size.width) switch self { case .Document(let blocks): drawChildrenInRect(blocks, rect: rect, withCurrentGraphicsContext: withCurrentGraphicsContext, context: context) case .Quote(let blocks): let rect1 = UIEdgeInsetsInsetRect(rect, QuoteMargin) withCurrentGraphicsContext { gfx -> () in CGContextSetFillColorWithColor(gfx, QuoteBorderColor) let leftRect = CGRectMake(rect1.origin.x, verticalDirection * rect1.origin.y, QuoteLeftBorderWidth, height - VerticalMargin(QuoteMargin)) CGContextFillRect(gfx, leftRect) () } let rect2 = UIEdgeInsetsInsetRect(rect1, QuotePadding) drawChildrenInRect(blocks, rect: rect2, withCurrentGraphicsContext: withCurrentGraphicsContext, context: context) case .Paragraph: //(let inlines): let r = UIEdgeInsetsInsetRect(rect, ParagraphMargin) attributedString.drawWithRect(r, options: drawingOptions, context: context) case .Code: //(let (code, lang)): let rect1 = UIEdgeInsetsInsetRect(rect, CodeMargin) withCurrentGraphicsContext { gfx -> () in CGContextSetFillColorWithColor(gfx, CodeBackgroundColor) let codeRect = CGRectMake(rect1.origin.x, verticalDirection * rect1.origin.y, rect1.size.width, height - VerticalMargin(CodeMargin)) CGContextFillRect(gfx, codeRect) () } let rect2 = UIEdgeInsetsInsetRect(rect1, CodePadding) attributedString.drawWithRect(rect2, options: drawingOptions, context: context) } } }
mit
ad492972830f597ca2a1965d12840d3a
38.484979
163
0.646304
4.816754
false
false
false
false
bogosmer/UnitKit
UnitKitTests/LengthUnitTests.swift
1
21924
// // LengthUnitTests.swift // UnitKit // // Created by Bo Gosmer on 10/02/2016. // Copyright © 2016 Deadlock Baby. All rights reserved. // import XCTest @testable import UnitKit class LengthUnitTests: XCTestCase { override func setUp() { super.setUp() LengthUnit.sharedDecimalNumberHandler = nil } override func tearDown() { super.tearDown() } // MARK: - LengthUnit func testDecimalNumberInitializationUsingBaseUnitType() { let decimalValue = NSDecimalNumber.double(1) let lengthUnitValue = NSDecimalNumber(decimal: LengthUnit(value: decimalValue, type: .Centimetre).baseUnitTypeValue) XCTAssert(lengthUnitValue == decimalValue, "expected \(decimalValue) - got \(lengthUnitValue)") } func testDoubleInitializationUsingBaseUnitType() { let value: Double = 1 let decimalValue = NSDecimalNumber.double(value) let lengthUnitValue = NSDecimalNumber(decimal: LengthUnit(value: value, type: .Centimetre).baseUnitTypeValue) XCTAssert(lengthUnitValue == decimalValue, "expected \(decimalValue) - got \(lengthUnitValue)") } func testIntInitializationUsingBaseUnitType() { let value: Int = 1 let decimalValue = NSDecimalNumber.integer(value) let lengthUnitValue = NSDecimalNumber(decimal: LengthUnit(value: value, type: .Centimetre).baseUnitTypeValue) XCTAssert(lengthUnitValue == decimalValue, "expected \(decimalValue) - got \(lengthUnitValue)") } func testIntInitializationUsingOtherUnitType() { let value: Int = 1 let decimalValue = NSDecimalNumber.integer(value).decimalNumberByMultiplyingBy(LengthUnitType.Metre.baseUnitTypePerUnit()) let lengthUnitValue = NSDecimalNumber(decimal: LengthUnit(value: value, type: .Metre).baseUnitTypeValue) XCTAssert(lengthUnitValue == decimalValue, "expected \(decimalValue) - got \(lengthUnitValue)") } func testDecimalNumberInitializationOthergBaseUnitType() { let value: Int = 1 let decimalValue = NSDecimalNumber.double(1).decimalNumberByMultiplyingBy(LengthUnitType.Yard.baseUnitTypePerUnit()) let lengthUnitValue = NSDecimalNumber(decimal: LengthUnit(value: value, type: .Yard).baseUnitTypeValue) XCTAssert(lengthUnitValue == decimalValue, "expected \(decimalValue) - got \(lengthUnitValue)") } func testDoubleInitializationUsingOtherUnitType() { let value: Double = 1 let decimalValue = NSDecimalNumber.double(value).decimalNumberByMultiplyingBy(LengthUnitType.Foot.baseUnitTypePerUnit()) let lengthUnitValue = NSDecimalNumber(decimal: LengthUnit(value: value, type: .Foot).baseUnitTypeValue) XCTAssert(lengthUnitValue == decimalValue, "expected \(decimalValue) - got \(lengthUnitValue)") } func testMillimetreValue() { let value: Double = 1 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(LengthUnitType.Millimetre.baseUnitTypePerUnit()) let lengthUnit = LengthUnit(value: value, type: .Centimetre).millimetreValue XCTAssert(lengthUnit == decimalValue, "expected \(decimalValue) - got \(lengthUnit)") } func testMetreValue() { let value: Double = 2 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(LengthUnitType.Metre.baseUnitTypePerUnit()) let lengthUnit = LengthUnit(value: value, type: .Centimetre).metreValue XCTAssert(lengthUnit == decimalValue, "expected \(decimalValue) - got \(lengthUnit)") } func testKilometreValue() { let value: Double = 3 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(LengthUnitType.Kilometre.baseUnitTypePerUnit()) let lengthUnit = LengthUnit(value: value, type: .Centimetre).kilometreValue XCTAssert(lengthUnit == decimalValue, "expected \(decimalValue) - got \(lengthUnit)") } func testInchValue() { let value: Double = 4 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(LengthUnitType.Inch.baseUnitTypePerUnit()) let lengthUnit = LengthUnit(value: value, type: .Centimetre).inchValue XCTAssert(lengthUnit == decimalValue, "expected \(decimalValue) - got \(lengthUnit)") } func testFootValue() { let value: Double = 5 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(LengthUnitType.Foot.baseUnitTypePerUnit()) let lengthUnit = LengthUnit(value: value, type: .Centimetre).footValue XCTAssert(lengthUnit == decimalValue, "expected \(decimalValue) - got \(lengthUnit)") } func testYardValue() { let value: Double = 6 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(LengthUnitType.Yard.baseUnitTypePerUnit()) let lengthUnit = LengthUnit(value: value, type: .Centimetre).yardValue XCTAssert(lengthUnit == decimalValue, "expected \(decimalValue) - got \(lengthUnit)") } func testMileValue() { let value: Double = 7 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(LengthUnitType.Mile.baseUnitTypePerUnit()) let lengthUnit = LengthUnit(value: value, type: .Centimetre).mileValue XCTAssert(lengthUnit == decimalValue, "expected \(decimalValue) - got \(lengthUnit)") } func testNauticalMileValue() { let value: Double = 8 let decimalValue = NSDecimalNumber.double(value).decimalNumberByDividingBy(LengthUnitType.NauticalMile.baseUnitTypePerUnit()) let lengthUnit = LengthUnit(value: value, type: .Centimetre).nauticalMileValue XCTAssert(lengthUnit == decimalValue, "expected \(decimalValue) - got \(lengthUnit)") } func testConversionExample() { let value: Double = 1 let decimalValue = NSDecimalNumber.double(value).decimalNumberByMultiplyingBy(LengthUnitType.NauticalMile.baseUnitTypePerUnit()).decimalNumberByDividingBy(LengthUnitType.Mile.baseUnitTypePerUnit()) let lengthUnit = LengthUnit(value: value, type: .NauticalMile).mileValue XCTAssert(lengthUnit == decimalValue, "expected \(decimalValue) - got \(lengthUnit)") } func testSharedDecimalNumberHandler() { LengthUnit.sharedDecimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) let value = 1.2345 let lengthUnitValue = LengthUnit(value: value, type: .Centimetre) XCTAssert(LengthUnit.sharedDecimalNumberHandler != nil) XCTAssert(NSDecimalNumber(decimal: lengthUnitValue.baseUnitTypeValue) == NSDecimalNumber.double(1.23), "expected 1.23 - got \(NSDecimalNumber(decimal: lengthUnitValue.baseUnitTypeValue))") } func testInstanceDecimalNumberHandler() { let value = 9.8765 var lengthUnit = LengthUnit(value: value, type: .Centimetre) lengthUnit.decimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false) let baseUnitTypeValue = NSDecimalNumber(decimal: lengthUnit.baseUnitTypeValue) XCTAssert(NSDecimalNumber.double(value) == baseUnitTypeValue, "expected \(value) - got \(baseUnitTypeValue)") } // MARK: - CustomStringConvertible func testDescription() { let unit = LengthUnit(value: 1, type: .Centimetre) XCTAssert(unit.description == "1 centimetre", "expected 1 centimetre - got \(unit.description)") } // MARK: - Localization func testLocalizedName() { let unitSingle = LengthUnit(value: 1, type: .Centimetre) XCTAssert(unitSingle.localizedNameOfUnitType(NSLocale(localeIdentifier: "en")) == "centimetre") XCTAssert(unitSingle.localizedNameOfUnitType(NSLocale(localeIdentifier: "da")) == "centimeter") let unitPlural = LengthUnit(value: 2, type: .Centimetre) XCTAssert(unitPlural.localizedNameOfUnitType(NSLocale(localeIdentifier: "en")) == "centimetres") XCTAssert(unitPlural.localizedNameOfUnitType(NSLocale(localeIdentifier: "da")) == "centimeter") } func testLocalizedAbbreviation() { let unitSingle = LengthUnit(value: 1, type: .Centimetre) XCTAssert(unitSingle.localizedAbbreviationOfUnitType(nil) == "cm") XCTAssert(unitSingle.localizedAbbreviationOfUnitType(NSLocale(localeIdentifier: "en")) == "cm") XCTAssert(unitSingle.localizedAbbreviationOfUnitType(NSLocale(localeIdentifier: "da")) == "cm") let unitPlural = LengthUnit(value: 2, type: .Centimetre) XCTAssert(unitPlural.localizedAbbreviationOfUnitType(nil) == "cm") XCTAssert(unitPlural.localizedAbbreviationOfUnitType(NSLocale(localeIdentifier: "en")) == "cm") XCTAssert(unitPlural.localizedAbbreviationOfUnitType(NSLocale(localeIdentifier: "da")) == "cm") } // MARK: - Arithmetic func testAdditionOfLengthUnits() { let metre = LengthUnit(value: 1, type: .Metre) let centimetre = LengthUnit(value: 1, type: .Centimetre) let addition = metre + centimetre let number = addition.metreValue XCTAssert(addition.unitType == LengthUnitType.Metre, "expected \(LengthUnitType.Metre) - got \(addition.unitType)") XCTAssert(number == NSDecimalNumber.double(1.01), "expected 1.01, got \(number)") } func testAdditionOfLengthUnitsWithSharedDecimalHandler() { LengthUnit.sharedDecimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 1, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) let addition2 = LengthUnit(value: 1, type: .Metre) + LengthUnit(value: 1, type: .Centimetre) XCTAssert(addition2.metreValue == NSDecimalNumber.double(1), "expected 1, got \(addition2.metreValue)") } // this one is actually correct since the addtion creates a new LengthUnit that is converted to base unit type using the sharedDecimalHandler func testAdditionOfLengthUnitsWithSharedDecimalHandlerAndHandlerOnLeftOperand() { LengthUnit.sharedDecimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 1, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) var metre2 = LengthUnit(value: 1, type: .Metre) metre2.decimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) let addition3 = metre2 + LengthUnit(value: 1, type: .Centimetre) XCTAssert(addition3.metreValue == NSDecimalNumber.double(1), "expected 1, got \(addition3.metreValue)") } func testAdditionOfLengthUnitsWithDecimalHandlerOnRightOperand() { var centimetre2 = LengthUnit(value: 1, type: .Centimetre) centimetre2.decimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) let addition4 = LengthUnit(value: 1, type: .Metre) + centimetre2 XCTAssert(addition4.metreValue == NSDecimalNumber.double(1), "expected 1, got \(addition4.metreValue)") } func testAdditionWithDouble() { let initialValue:Double = 1245 let additionValue = 2.5 let foot = LengthUnit(value: initialValue, type: .Foot) var addition = foot + additionValue var number = addition.footValue XCTAssert(number == NSDecimalNumber.double(initialValue + additionValue), "expected \(initialValue + additionValue) - got \(number)") addition = additionValue + foot number = addition.footValue XCTAssert(number == NSDecimalNumber.double(initialValue + additionValue), "expected \(initialValue + additionValue) - got \(number)") } func testAdditionWithInteger() { let initialValue:Int = 967235 let additionValue = 254 let foot = LengthUnit(value: initialValue, type: .Foot) var addition = foot + additionValue var number = addition.footValue XCTAssert(number == NSDecimalNumber.integer(initialValue + additionValue), "expected \(initialValue + additionValue) - got \(number)") addition = additionValue + foot number = addition.footValue XCTAssert(number == NSDecimalNumber.integer(initialValue + additionValue), "expected \(initialValue + additionValue) - got \(number)") } func testSubtractionOfLengthUnits() { let m2 = LengthUnit(value: 1, type: .Metre) let cm2 = LengthUnit(value: 1, type: .Centimetre) var subtraction = m2 - cm2 var number = subtraction.metreValue XCTAssert(subtraction.unitType == LengthUnitType.Metre, "expected \(LengthUnitType.Metre) - got \(subtraction.unitType)") XCTAssert(number == NSDecimalNumber.double(0.99), "expected 0.99, got \(number)") subtraction = cm2 - m2 number = subtraction.centimetreValue XCTAssert(subtraction.unitType == LengthUnitType.Centimetre, "expected \(LengthUnitType.Centimetre) - got \(subtraction.unitType)") XCTAssert(number == NSDecimalNumber.double(-99), "expected -99, got \(number)") } func testSubtractionWithDouble() { let initialValue:Double = 1245 let subtractionValue = 2.5 let foot = LengthUnit(value: initialValue, type: .Foot) let subtraction = foot - subtractionValue let number = subtraction.footValue XCTAssert(number == NSDecimalNumber.double(initialValue - subtractionValue), "expected \(initialValue - subtractionValue) - got \(number)") } func testSubtractionWithInteger() { let initialValue:Int = 967235 let subtractionValue = 254 let foot = LengthUnit(value: initialValue, type: .Foot) var subtraction = foot - subtractionValue var number = subtraction.footValue XCTAssert(number == NSDecimalNumber.integer(initialValue - subtractionValue), "expected \(initialValue - subtractionValue) - got \(number)") subtraction = subtractionValue - foot number = subtraction.footValue XCTAssert(number == NSDecimalNumber.integer(subtractionValue - initialValue), "expected \(subtractionValue - initialValue) - got \(number)") } func testSubtractionOfLengthUnitsWithSharedDecimalHandler() { LengthUnit.sharedDecimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 1, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) let addition2 = LengthUnit(value: 1, type: .Metre) - LengthUnit(value: 1, type: .Centimetre) XCTAssert(addition2.metreValue == NSDecimalNumber.double(1), "expected 1, got \(addition2.metreValue)") } // this one is actually correct since the addtion creates a new LengthUnit that is converted to base unit type using the sharedDecimalHandler func testSubtractionOfLengthUnitsWithSharedDecimalHandlerAndHandlerOnLeftOperand() { LengthUnit.sharedDecimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 1, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) var metre2 = LengthUnit(value: 1, type: .Metre) metre2.decimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) let addition3 = metre2 - LengthUnit(value: 1, type: .Centimetre) XCTAssert(addition3.metreValue == NSDecimalNumber.double(1), "expected 1, got \(addition3.metreValue)") } func testSubtractionOfLengthUnitsWithDecimalHandlerOnRightOperand() { var centimetre2 = LengthUnit(value: 1, type: .Centimetre) centimetre2.decimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) let addition4 = LengthUnit(value: 1, type: .Metre) - centimetre2 XCTAssert(addition4.metreValue == NSDecimalNumber.double(1), "expected 1, got \(addition4.metreValue)") } func testMultiplicationWithDouble() { let initialValue:Double = 1000 let factor = 2.5 let acre = LengthUnit(value: initialValue, type: .Foot) let mult = acre * factor let number = mult.footValue XCTAssert(number == NSDecimalNumber.double(initialValue * factor), "expected \(initialValue * factor) - got \(number)") } func testMultiplicationWithInteger() { let initialValue:Int = 1000 let multiplicationValue = 3 let foot = LengthUnit(value: initialValue, type: .Foot) var mult = foot * multiplicationValue var number = mult.footValue XCTAssert(number == NSDecimalNumber.integer(initialValue * multiplicationValue), "expected \(initialValue * multiplicationValue) - got \(number)") mult = multiplicationValue * foot number = mult.footValue XCTAssert(number == NSDecimalNumber.integer(initialValue * multiplicationValue), "expected \(initialValue * multiplicationValue) - got \(number)") } func testMultiplicationOfLengthUnitsWithSharedDecimalHandler() { LengthUnit.sharedDecimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 1, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) let result1 = LengthUnit(value: 1, type: .Metre) * 2 XCTAssert(result1.metreValue == NSDecimalNumber.double(2), "expected 1, got \(result1.metreValue)") let result2 = 4 * LengthUnit(value: 1, type: .Metre) XCTAssert(result2.metreValue == NSDecimalNumber.double(4), "expected 1, got \(result2.metreValue)") } func testMultiplicationOfLengthUnitsWithHandlerOnEitherOperand() { var metre = LengthUnit(value: 1, type: .Metre) metre.decimalNumberHandler = NSDecimalNumberHandler(roundingMode: .RoundPlain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) let mult1 = metre * 2 XCTAssert(mult1.metreValue == NSDecimalNumber.double(2), "expected 1, got \(mult1.metreValue)") let mult2 = 3 * metre XCTAssert(mult2.metreValue == NSDecimalNumber.double(3), "expected 1, got \(mult2.metreValue)") } func testDivisionWithDouble() { let initialValue:Double = 1000 let divValue = 2.5 let acre = LengthUnit(value: initialValue, type: .Foot) let div = acre / divValue let number = div.footValue XCTAssert(number == NSDecimalNumber.double(initialValue / divValue), "expected \(initialValue / divValue) - got \(number)") } func testDivisionWithInteger() { let initialValue:Int = 2000 let divValue = 4 let hectare = LengthUnit(value: initialValue, type: .Foot) let div = hectare / divValue let number = div.footValue XCTAssert(number == NSDecimalNumber.integer(initialValue / divValue), "expected \(initialValue / divValue) - got \(number)") } // MARK: - Double and Int extensions func testMillimetreExtension() { XCTAssert(1.0.millimetres().millimetreValue == LengthUnit(value: 1.0, type: .Millimetre).millimetreValue) XCTAssert(1.millimetres().millimetreValue == LengthUnit(value: 1, type: .Millimetre).millimetreValue) } func testCentimetreExtension() { XCTAssert(1.0.centimetres().centimetreValue == LengthUnit(value: 1.0, type: .Centimetre).centimetreValue) XCTAssert(1.centimetres().centimetreValue == LengthUnit(value: 1, type: .Centimetre).centimetreValue) } func testMeterExtension() { XCTAssert(1.0.metres().metreValue == LengthUnit(value: 1.0, type: .Metre).metreValue) XCTAssert(1.metres().metreValue == LengthUnit(value: 1, type: .Metre).metreValue) } func testKilometerExtension() { XCTAssert(1.0.kilometres().kilometreValue == LengthUnit(value: 1.0, type: .Kilometre).kilometreValue) XCTAssert(1.kilometres().kilometreValue == LengthUnit(value: 1, type: .Kilometre).kilometreValue) } func testInchExtension() { XCTAssert(1.0.inches().inchValue == LengthUnit(value: 1.0, type: .Inch).inchValue) XCTAssert(1.inches().inchValue == LengthUnit(value: 1, type: .Inch).inchValue) } func testFootExtension() { XCTAssert(1.0.feet().footValue == LengthUnit(value: 1.0, type: .Foot).footValue) XCTAssert(1.feet().footValue == LengthUnit(value: 1, type: .Foot).footValue) } func testYardExtension() { XCTAssert(1.0.yards().yardValue == LengthUnit(value: 1.0, type: .Yard).yardValue) XCTAssert(1.yards().yardValue == LengthUnit(value: 1, type: .Yard).yardValue) } func testMileExtension() { XCTAssert(1.0.miles().mileValue == LengthUnit(value: 1.0, type: .Mile).mileValue) XCTAssert(1.miles().mileValue == LengthUnit(value: 1, type: .Mile).mileValue) } func testNauticalMileExtension() { XCTAssert(1.0.nauticalMiles().nauticalMileValue == LengthUnit(value: 1.0, type: .NauticalMile).nauticalMileValue) XCTAssert(1.nauticalMiles().nauticalMileValue == LengthUnit(value: 1, type: .NauticalMile).nauticalMileValue) } }
mit
72e05f03a3f29c2af668a22ee786f0e4
54.082915
209
0.701866
4.453179
false
true
false
false
tispr/AKPickerView-Swift
AKPickerView/AKPickerView.swift
2
22814
// // AKPickerView.swift // AKPickerView // // Created by Akio Yasui on 1/29/15. // Copyright (c) 2015 Akkyie Y. All rights reserved. // import UIKit /** Styles of AKPickerView. - Wheel: Style with 3D appearance like UIPickerView. - Flat: Flat style. */ public enum AKPickerViewStyle { case Wheel case Flat } // MARK: - Protocols // MARK: AKPickerViewDataSource /** Protocols to specify the number and type of contents. */ @objc public protocol AKPickerViewDataSource { func numberOfItemsInPickerView(pickerView: AKPickerView) -> Int optional func pickerView(pickerView: AKPickerView, titleForItem item: Int) -> String optional func pickerView(pickerView: AKPickerView, imageForItem item: Int) -> UIImage } // MARK: AKPickerViewDelegate /** Protocols to specify the attitude when user selected an item, and customize the appearance of labels. */ @objc public protocol AKPickerViewDelegate: UIScrollViewDelegate { optional func pickerView(pickerView: AKPickerView, didSelectItem item: Int) optional func pickerView(pickerView: AKPickerView, marginForItem item: Int) -> CGSize optional func pickerView(pickerView: AKPickerView, configureLabel label: UILabel, forItem item: Int) } // MARK: - Private Classes and Protocols // MARK: AKCollectionViewLayoutDelegate /** Private. Used to deliver the style of the picker. */ private protocol AKCollectionViewLayoutDelegate { func pickerViewStyleForCollectionViewLayout(layout: AKCollectionViewLayout) -> AKPickerViewStyle } // MARK: AKCollectionViewCell /** Private. A subclass of UICollectionViewCell used in AKPickerView's collection view. */ private class AKCollectionViewCell: UICollectionViewCell { var label: UILabel! var imageView: UIImageView! var font = UIFont.systemFontOfSize(UIFont.systemFontSize()) var highlightedFont = UIFont.systemFontOfSize(UIFont.systemFontSize()) var lineView: UIView! override var selected: Bool { didSet { let animation = CATransition() animation.type = kCATransitionFade animation.duration = 0.15 self.label.layer.addAnimation(animation, forKey: "") self.label.font = self.selected ? self.highlightedFont : self.font lineView.layer.addAnimation(animation, forKey: "animation.alpha") lineView.alpha = selected ? 1.0 : 0.0 } } func setHighlightedTextColor(color: UIColor) { label.highlightedTextColor = color lineView.backgroundColor = color } func initialize() { self.layer.doubleSided = false self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.mainScreen().scale self.label = UILabel(frame: self.contentView.bounds) self.label.backgroundColor = UIColor.clearColor() self.label.textAlignment = .Center self.label.textColor = UIColor.grayColor() self.label.numberOfLines = 1 self.label.lineBreakMode = .ByTruncatingTail self.label.highlightedTextColor = UIColor.blackColor() self.label.font = self.font self.label.autoresizingMask = [.FlexibleTopMargin, .FlexibleLeftMargin, .FlexibleBottomMargin, .FlexibleRightMargin] self.contentView.addSubview(self.label) lineView = UIView(frame: CGRect(origin: CGPoint(x: 0, y: contentView.bounds.size.height - 2), size: CGSize(width: contentView.bounds.size.width, height: 2))) lineView.alpha = 0.0 lineView.backgroundColor = UIColor.blueColor() self.lineView.autoresizingMask = .FlexibleTopMargin | .FlexibleLeftMargin | .FlexibleBottomMargin | .FlexibleRightMargin; self.contentView.addSubview(self.lineView) self.imageView = UIImageView(frame: self.contentView.bounds) self.imageView.backgroundColor = UIColor.clearColor() self.imageView.contentMode = .Center self.imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] self.contentView.addSubview(self.imageView) } init() { super.init(frame: CGRectZero) self.initialize() } override init(frame: CGRect) { super.init(frame: frame) self.initialize() } required init!(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initialize() } } // MARK: AKCollectionViewLayout /** Private. A subclass of UICollectionViewFlowLayout used in the collection view. */ private class AKCollectionViewLayout: UICollectionViewFlowLayout { var delegate: AKCollectionViewLayoutDelegate! var width: CGFloat! var midX: CGFloat! var maxAngle: CGFloat! func initialize() { self.sectionInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0) self.scrollDirection = .Horizontal self.minimumLineSpacing = 0.0 } override init() { super.init() self.initialize() } required init!(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initialize() } private override func prepareLayout() { let visibleRect = CGRect(origin: self.collectionView!.contentOffset, size: self.collectionView!.bounds.size) self.midX = CGRectGetMidX(visibleRect); self.width = CGRectGetWidth(visibleRect) / 2; self.maxAngle = CGFloat(M_PI_2); } private override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } private override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { if let attributes = super.layoutAttributesForItemAtIndexPath(indexPath)?.copy() as? UICollectionViewLayoutAttributes { switch self.delegate.pickerViewStyleForCollectionViewLayout(self) { case .Flat: return attributes case .Wheel: let distance = CGRectGetMidX(attributes.frame) - self.midX; let currentAngle = self.maxAngle * distance / self.width / CGFloat(M_PI_2); var transform = CATransform3DIdentity; transform = CATransform3DTranslate(transform, -distance, 0, -self.width); transform = CATransform3DRotate(transform, currentAngle, 0, 1, 0); transform = CATransform3DTranslate(transform, 0, 0, self.width); attributes.transform3D = transform; attributes.alpha = fabs(currentAngle) < self.maxAngle ? 1.0 : 0.0; return attributes; } } return nil } private func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { switch self.delegate.pickerViewStyleForCollectionViewLayout(self) { case .Flat: return super.layoutAttributesForElementsInRect(rect) case .Wheel: var attributes = [AnyObject]() if self.collectionView!.numberOfSections() > 0 { for i in 0 ..< self.collectionView!.numberOfItemsInSection(0) { let indexPath = NSIndexPath(forItem: i, inSection: 0) attributes.append(self.layoutAttributesForItemAtIndexPath(indexPath)!) } } return attributes } } } // MARK: AKPickerViewDelegateIntercepter /** Private. Used to hook UICollectionViewDelegate and throw it AKPickerView, and if it conforms to UIScrollViewDelegate, also throw it to AKPickerView's delegate. */ private class AKPickerViewDelegateIntercepter: NSObject, UICollectionViewDelegate { weak var pickerView: AKPickerView? weak var delegate: UIScrollViewDelegate? init(pickerView: AKPickerView, delegate: UIScrollViewDelegate?) { self.pickerView = pickerView self.delegate = delegate } private override func forwardingTargetForSelector(aSelector: Selector) -> AnyObject? { if self.pickerView!.respondsToSelector(aSelector) { return self.pickerView } else if self.delegate != nil && self.delegate!.respondsToSelector(aSelector) { return self.delegate } else { return nil } } private override func respondsToSelector(aSelector: Selector) -> Bool { if self.pickerView!.respondsToSelector(aSelector) { return true } else if self.delegate != nil && self.delegate!.respondsToSelector(aSelector) { return true } else { return super.respondsToSelector(aSelector) } } } // MARK: - AKPickerView // TODO: Make these delegate conformation private /** Horizontal picker view. This is just a subclass of UIView, contains a UICollectionView. */ public class AKPickerView: UIView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, AKCollectionViewLayoutDelegate { // MARK: - Properties // MARK: Readwrite Properties /// Readwrite. Data source of picker view. public weak var dataSource: AKPickerViewDataSource? = nil /// Readwrite. Delegate of picker view. public weak var delegate: AKPickerViewDelegate? = nil { didSet(delegate) { self.intercepter.delegate = delegate } } /// Readwrite. A font which used in NOT selected cells. public lazy var font = UIFont.systemFontOfSize(20) /// Readwrite. A font which used in selected cells. public lazy var highlightedFont = UIFont.boldSystemFontOfSize(20) /// Readwrite. A color of the text on NOT selected cells. @IBInspectable public lazy var textColor: UIColor = UIColor.darkGrayColor() /// Readwrite. A color of the text on selected cells. @IBInspectable public lazy var highlightedTextColor: UIColor = UIColor.blackColor() /// Readwrite. A float value which indicates the spacing between cells. @IBInspectable public var interitemSpacing: CGFloat = 0.0 /// Readwrite. The style of the picker view. See AKPickerViewStyle. public var pickerViewStyle = AKPickerViewStyle.Wheel /// Readwrite. A float value which determines the perspective representation which used when using AKPickerViewStyle.Wheel style. @IBInspectable public var viewDepth: CGFloat = 1000.0 { didSet { self.collectionView.layer.sublayerTransform = self.viewDepth > 0.0 ? { var transform = CATransform3DIdentity; transform.m34 = -1.0 / self.viewDepth; return transform; }() : CATransform3DIdentity; } } /// Readwrite. A boolean value indicates whether the mask is disabled. @IBInspectable public var maskDisabled: Bool! = nil { didSet { self.collectionView.layer.mask = self.maskDisabled == true ? nil : { let maskLayer = CAGradientLayer() maskLayer.frame = self.collectionView.bounds maskLayer.colors = [ UIColor.clearColor().CGColor, UIColor.blackColor().CGColor, UIColor.blackColor().CGColor, UIColor.clearColor().CGColor] maskLayer.locations = [0.0, 0.33, 0.66, 1.0] maskLayer.startPoint = CGPointMake(0.0, 0.0) maskLayer.endPoint = CGPointMake(1.0, 0.0) return maskLayer }() } } // MARK: Readonly Properties /// Readonly. Index of currently selected item. public private(set) var selectedItem: Int = 0 /// Readonly. The point at which the origin of the content view is offset from the origin of the picker view. public var contentOffset: CGPoint { get { return self.collectionView.contentOffset } } // MARK: Private Properties /// Private. A UICollectionView which shows contents on cells. private var collectionView: UICollectionView! /// Private. An intercepter to hook UICollectionViewDelegate then throw it picker view and its delegate private var intercepter: AKPickerViewDelegateIntercepter! /// Private. A UICollectionViewFlowLayout used in picker view's collection view. private var collectionViewLayout: AKCollectionViewLayout { let layout = AKCollectionViewLayout() layout.delegate = self return layout } // MARK: - Functions // MARK: View Lifecycle /** Private. Initializes picker view's subviews and friends. */ private func initialize() { self.collectionView?.removeFromSuperview() self.collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: self.collectionViewLayout) self.collectionView.showsHorizontalScrollIndicator = false self.collectionView.backgroundColor = UIColor.clearColor() self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast self.collectionView.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight] self.collectionView.dataSource = self self.collectionView.registerClass( AKCollectionViewCell.self, forCellWithReuseIdentifier: NSStringFromClass(AKCollectionViewCell.self)) self.addSubview(self.collectionView) self.intercepter = AKPickerViewDelegateIntercepter(pickerView: self, delegate: self.delegate) self.collectionView.delegate = self.intercepter self.maskDisabled = self.maskDisabled == nil ? false : self.maskDisabled } public init() { super.init(frame: CGRectZero) self.initialize() } public override init(frame: CGRect) { super.init(frame: frame) self.initialize() } public required init!(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initialize() } deinit { self.collectionView.delegate = nil } // MARK: Layout public override func layoutSubviews() { super.layoutSubviews() if self.dataSource != nil && self.dataSource!.numberOfItemsInPickerView(self) > 0 { self.collectionView.collectionViewLayout = self.collectionViewLayout self.scrollToItem(self.selectedItem, animated: false) } self.collectionView.layer.mask?.frame = self.collectionView.bounds } public override func intrinsicContentSize() -> CGSize { return CGSizeMake(UIViewNoIntrinsicMetric, max(self.font.lineHeight, self.highlightedFont.lineHeight)) } // MARK: Calculation Functions /** Private. Used to calculate bounding size of given string with picker view's font and highlightedFont :param: string A NSString to calculate size :returns: A CGSize which contains given string just. */ private func sizeForString(string: NSString) -> CGSize { let size = string.sizeWithAttributes([NSFontAttributeName: self.font]) let highlightedSize = string.sizeWithAttributes([NSFontAttributeName: self.highlightedFont]) return CGSize( width: ceil(max(size.width, highlightedSize.width)), height: ceil(max(size.height, highlightedSize.height))) } /** Private. Used to calculate the x-coordinate of the content offset of specified item. :param: item An integer value which indicates the index of cell. :returns: An x-coordinate of the cell whose index is given one. */ private func offsetForItem(item: Int) -> CGFloat { var offset: CGFloat = 0 for i in 0 ..< item { let indexPath = NSIndexPath(forItem: i, inSection: 0) let cellSize = self.collectionView( self.collectionView, layout: self.collectionView.collectionViewLayout, sizeForItemAtIndexPath: indexPath) offset += cellSize.width } let firstIndexPath = NSIndexPath(forItem: 0, inSection: 0) let firstSize = self.collectionView( self.collectionView, layout: self.collectionView.collectionViewLayout, sizeForItemAtIndexPath: firstIndexPath) let selectedIndexPath = NSIndexPath(forItem: item, inSection: 0) let selectedSize = self.collectionView( self.collectionView, layout: self.collectionView.collectionViewLayout, sizeForItemAtIndexPath: selectedIndexPath) offset -= (firstSize.width - selectedSize.width) / 2.0 return offset } // MARK: View Controls /** Reload the picker view's contents and styles. Call this method always after any property is changed. */ public func reloadData() { self.invalidateIntrinsicContentSize() self.collectionView.collectionViewLayout.invalidateLayout() self.collectionView.reloadData() if self.dataSource != nil && self.dataSource!.numberOfItemsInPickerView(self) > 0 { self.selectItem(self.selectedItem, animated: false, notifySelection: false) } } /** Move to the cell whose index is given one without selection change. :param: item An integer value which indicates the index of cell. :param: animated True if the scrolling should be animated, false if it should be immediate. */ public func scrollToItem(item: Int, animated: Bool = false) { switch self.pickerViewStyle { case .Flat: self.collectionView.scrollToItemAtIndexPath( NSIndexPath( forItem: item, inSection: 0), atScrollPosition: .CenteredHorizontally, animated: animated) case .Wheel: self.collectionView.setContentOffset( CGPoint( x: self.offsetForItem(item), y: self.collectionView.contentOffset.y), animated: animated) } } /** Select a cell whose index is given one and move to it. :param: item An integer value which indicates the index of cell. :param: animated True if the scrolling should be animated, false if it should be immediate. */ public func selectItem(item: Int, animated: Bool = false) { self.selectItem(item, animated: animated, notifySelection: true) } /** Private. Select a cell whose index is given one and move to it, with specifying whether it calls delegate method. :param: item An integer value which indicates the index of cell. :param: animated True if the scrolling should be animated, false if it should be immediate. :param: notifySelection True if the delegate method should be called, false if not. */ private func selectItem(item: Int, animated: Bool, notifySelection: Bool) { self.collectionView.selectItemAtIndexPath( NSIndexPath(forItem: item, inSection: 0), animated: animated, scrollPosition: .None) self.scrollToItem(item, animated: animated) self.selectedItem = item if notifySelection { self.delegate?.pickerView?(self, didSelectItem: item) } } // MARK: Delegate Handling /** Private. */ private func didEndScrolling() { switch self.pickerViewStyle { case .Flat: let center = self.convertPoint(self.collectionView.center, toView: self.collectionView) if let indexPath = self.collectionView.indexPathForItemAtPoint(center) { self.selectItem(indexPath.item, animated: true, notifySelection: true) } case .Wheel: if let numberOfItems = self.dataSource?.numberOfItemsInPickerView(self) { for i in 0 ..< numberOfItems { let indexPath = NSIndexPath(forItem: i, inSection: 0) let cellSize = self.collectionView( self.collectionView, layout: self.collectionView.collectionViewLayout, sizeForItemAtIndexPath: indexPath) if self.offsetForItem(i) + cellSize.width / 2 > self.collectionView.contentOffset.x { self.selectItem(i, animated: true, notifySelection: true) break } } } } } // MARK: UICollectionViewDataSource public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return self.dataSource != nil && self.dataSource!.numberOfItemsInPickerView(self) > 0 ? 1 : 0 } public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.dataSource != nil ? self.dataSource!.numberOfItemsInPickerView(self) : 0 } public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(NSStringFromClass(AKCollectionViewCell.self), forIndexPath: indexPath) as! AKCollectionViewCell if let title = self.dataSource?.pickerView?(self, titleForItem: indexPath.item) { cell.setHighlightedTextColor(highlightedTextColor) cell.label.text = title cell.label.textColor = self.textColor cell.label.font = self.font cell.font = self.font cell.highlightedFont = self.highlightedFont cell.label.bounds = CGRect(origin: CGPointZero, size: self.sizeForString(title)) if let delegate = self.delegate { delegate.pickerView?(self, configureLabel: cell.label, forItem: indexPath.item) if let margin = delegate.pickerView?(self, marginForItem: indexPath.item) { cell.label.frame = CGRectInset(cell.label.frame, -margin.width, -margin.height) } } } else if let image = self.dataSource?.pickerView?(self, imageForItem: indexPath.item) { cell.imageView.image = image } cell.selected = (indexPath.item == self.selectedItem) return cell } // MARK: UICollectionViewDelegateFlowLayout public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { var size = CGSizeMake(self.interitemSpacing, collectionView.bounds.size.height) if let title = self.dataSource?.pickerView?(self, titleForItem: indexPath.item) { size.width += self.sizeForString(title).width if let margin = self.delegate?.pickerView?(self, marginForItem: indexPath.item) { size.width += margin.width * 2 } } else if let image = self.dataSource?.pickerView?(self, imageForItem: indexPath.item) { size.width += image.size.width } return size } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 0.0 } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 0.0 } public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { let number = self.collectionView(collectionView, numberOfItemsInSection: section) let firstIndexPath = NSIndexPath(forItem: 0, inSection: section) let firstSize = self.collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAtIndexPath: firstIndexPath) let lastIndexPath = NSIndexPath(forItem: number - 1, inSection: section) let lastSize = self.collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAtIndexPath: lastIndexPath) return UIEdgeInsetsMake( 0, (collectionView.bounds.size.width - firstSize.width) / 2, 0, (collectionView.bounds.size.width - lastSize.width) / 2 ) } // MARK: UICollectionViewDelegate public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { self.selectItem(indexPath.item, animated: true) } // MARK: UIScrollViewDelegate public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { self.delegate?.scrollViewDidEndDecelerating?(scrollView) self.didEndScrolling() } public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { self.delegate?.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate) if !decelerate { self.didEndScrolling() } } public func scrollViewDidScroll(scrollView: UIScrollView) { self.delegate?.scrollViewDidScroll?(scrollView) CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) self.collectionView.layer.mask?.frame = self.collectionView.bounds CATransaction.commit() } // MARK: AKCollectionViewLayoutDelegate private func pickerViewStyleForCollectionViewLayout(layout: AKCollectionViewLayout) -> AKPickerViewStyle { return self.pickerViewStyle } }
mit
9936dea2e70589eea676f0eb7f0a1fb0
35.385965
182
0.7484
4.336438
false
false
false
false
TMTBO/TTADataPickerView
TTADataPickerView/TTADataPickerViewController.swift
1
4586
// // TTADataPickerViewController.swift // TTAUtils_Swift // // Created by TobyoTenma on 12/03/2017. // Copyright © 2017 TobyoTenma. All rights reserved. // import UIKit /// This Controller is used for SHOW and DISMISS the DataPickerView instance /// User should NOT use it to show or dismiss internal final class TTADataPickerViewController: UIViewController { /// DataPickerView weak var pickerView: TTADataPickerView? = nil deinit { #if DEBUG print("\(NSStringFromClass(type(of: self))) deinit") #endif } override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } // MARK: - LifeCycle extension TTADataPickerViewController { override func loadView() { view = UIView(frame: UIScreen.main.bounds) view.backgroundColor = .clear let tap = UITapGestureRecognizer(target: self, action: #selector(tap(tap:))) view.addGestureRecognizer(tap) tap.delegate = self } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - Public Functions extension TTADataPickerViewController { /// Show pickerView animation /// /// - Parameters: /// - pickerView: pickerView /// - completion: complection handler public func showPickerView(pickerView: TTADataPickerView, completion: (() -> Void)? = nil) { // Get the top viewController self.pickerView = pickerView var topController = UIApplication.shared.keyWindow?.rootViewController while (topController?.presentedViewController != nil) { topController = topController?.presentedViewController } topController?.resignFirstResponder() // Put the pickerView at the bottom of the screen pickerView.frame.origin.y = view.bounds.size.height view.addSubview(pickerView) // Set this controller as a childViewController of the topController, // Add put it's view as a subView of the topController's view view.frame = CGRect(x: 0, y: 0, width: topController?.view.bounds.width ?? 0, height: topController?.view.bounds.height ?? 0) view.autoresizingMask = [.flexibleWidth, .flexibleHeight] topController?.addChild(self) topController?.view.addSubview(self.view) // Show anmiation UIView.animate(withDuration: 0.25, delay: 0, options: UIView.AnimationOptions.beginFromCurrentState, animations: { self.view.backgroundColor = UIColor(white: 0.0, alpha: 0.5) pickerView.frame.origin.y = self.view.bounds.size.height - pickerView.frame.size.height }) { (_) in guard let handle = completion else { return } handle() } } /// Dismiss the pickerView /// /// - Parameter completion: completion handler public func dismissWithCompletion(completion: (() -> Void)? = nil) { // Hide with animation. UIView.animate(withDuration: 0.25, delay: 0, options: UIView.AnimationOptions.beginFromCurrentState, animations: { self.view.backgroundColor = .clear self.pickerView?.frame.origin.y = self.view.bounds.size.height }) { (_) in // Remove pickerView, self.view and self self.pickerView?.removeFromSuperview() self.willMove(toParent: nil) self.view.removeFromSuperview() self.removeFromParent() guard let handle = completion else { return } handle() } } } // MARK: - Actions fileprivate extension TTADataPickerViewController { /// Tap gesture action /// /// - Parameter tap: Tap gesture @objc func tap(tap: UITapGestureRecognizer) { if (tap.state == UIGestureRecognizer.State.ended) { //Code to handle the gesture dismissWithCompletion() } } } // MARK: - UIGestureRecognizerDelegate extension TTADataPickerViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { guard let isContains = pickerView?.bounds.contains(touch.location(in: pickerView)), isContains == true else { return true } return false } }
mit
b738be351413375c87e01708b3c81a7c
31.985612
133
0.640567
5.066298
false
false
false
false
nbusy/nbusy-ios
NBusy/DetailViewController.swift
1
1672
import UIKit class DetailViewController: UIViewController, UITextFieldDelegate { // MARK: Properties @IBOutlet weak var messageTextField: UITextField! var detailItem: AnyObject? { didSet { // Update the view. self.configureView() } } func configureView() { // Update the user interface for the detail item. if let detail = self.detailItem { } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.configureView() // Handle the text field’s user input through delegate callbacks. messageTextField.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: UITextFieldDelegate func textFieldShouldReturn(textField: UITextField) -> Bool { // Hide the keyboard. textField.resignFirstResponder() return true } func textFieldDidEndEditing(textField: UITextField) { if let message = textField.text where !message.isEmpty { // todo: send the message to server textField.text = "" } } // MARK: Actions @IBAction func sendMessage(sender: UIButton) { if let messageTextField = self.messageTextField { if let message = messageTextField.text where !message.isEmpty { // todo: send the message to server messageTextField.text = "" } } } }
apache-2.0
9eacc0651db3ba930e6f297068ef7f0d
25.935484
80
0.598802
5.641892
false
false
false
false
steelwheels/Coconut
CoconutData/Source/Preference/CNPreferenceTable.swift
1
6279
/** * @file CNPrefereceParameter.swift * @brief Define CNPreferenceParameterTable class * @par Copyright * Copyright (C) 2020-2022 Steel Wheels Project */ import Foundation open class CNPreferenceTable { public typealias ListenerFunction = CNObserverDictionary.ListenerFunction public typealias ListnerHolder = CNObserverDictionary.ListnerHolder private var mSectionName: String private var mValueTable: CNObserverDictionary public init(sectionName name: String){ mSectionName = name mValueTable = CNObserverDictionary() } public func path(keyString key: String) -> String { return mSectionName + "." + key } public func set(objectValue val: NSObject, forKey key: String) { mValueTable.setValue(val, forKey: key) } public func objectValue(forKey key: String) -> NSObject? { return mValueTable.value(forKey: key) } /* * Int */ public func set(intValue val: Int, forKey key: String) { let num = NSNumber(integerLiteral: val) set(objectValue: num, forKey: key) } public func intValue(forKey key: String) -> Int? { if let val = objectValue(forKey: key) as? NSNumber { return val.intValue } else { return nil } } public func storeIntValue(intValue val: Int, forKey key: String) { let pathstr = path(keyString: key) let num = NSNumber(integerLiteral: val) UserDefaults.standard.set(number: num, forKey: pathstr) } public func loadIntValue(forKey key: String) -> Int? { let pathstr = path(keyString: key) if let numobj = UserDefaults.standard.number(forKey: pathstr) { return numobj.intValue } else { return nil } } /* * String */ public func set(stringValue val: String, forKey key: String) { set(objectValue: val as NSString, forKey: key) } public func stringValue(forKey key: String) -> String? { if let val = objectValue(forKey: key) as? NSString { return val as String } else { return nil } } public func storeStringValue(stringValue val: String, forKey key: String) { let pathstr = path(keyString: key) UserDefaults.standard.set(val, forKey: pathstr) } public func loadStringValue(forKey key: String) -> String? { let pathstr = path(keyString: key) if let path = UserDefaults.standard.string(forKey: pathstr) { return path } else { return nil } } /* * Color */ public func set(colorValue val: CNColor, forKey key: String) { set(objectValue: val, forKey: key) } public func colorValue(forKey key: String) -> CNColor? { if let val = objectValue(forKey: key) as? CNColor { return val } else { return nil } } public func storeColorValue(colorValue val: CNColor, forKey key: String) { let pathstr = path(keyString: key) UserDefaults.standard.set(color: val, forKey: pathstr) } public func loadColorValue(forKey key: String) -> CNColor? { let pathstr = path(keyString: key) if let color = UserDefaults.standard.color(forKey: pathstr) { return color } else { return nil } } /* * Font */ public func set(fontValue val: CNFont, forKey key: String) { set(objectValue: val, forKey: key) } public func fontValue(forKey key: String) -> CNFont? { if let val = objectValue(forKey: key) as? CNFont { return val } else { return nil } } public func storeFontValue(fontValue val: CNFont, forKey key: String) { let pathstr = path(keyString: key) UserDefaults.standard.set(font: val, forKey: pathstr) } public func loadFontValue(forKey key: String) -> CNFont? { let pathstr = path(keyString: key) if let font = UserDefaults.standard.font(forKey: pathstr) { return font } else { return nil } } /* * DataDictionary */ public func set(dataDictionaryValue val: Dictionary<String, Data>, forKey key: String) { let mval = val as NSDictionary set(objectValue: mval, forKey: key) } public func dataDictionaryValue(forKey key: String) -> Dictionary<String, Data>? { if let val = objectValue(forKey: key) as? NSDictionary { return val as? Dictionary<String, Data> } else { return nil } } public func storeDataDictionaryValue(dataDictionaryValue val: Dictionary<String, Data>, forKey key: String) { let pathstr = path(keyString: key) UserDefaults.standard.set(dataDictionary: val, forKey: pathstr) } public func loadDataDictionaryValue(forKey key: String) -> Dictionary<String, Data>? { let pathstr = path(keyString: key) if let dict = UserDefaults.standard.dataDictionary(forKey: pathstr) { return dict } else { return nil } } /* * Color Dictionary */ public func set(colorDictionaryValue val: Dictionary<CNInterfaceStyle, CNColor>, forKey key: String) { let dict = val as NSDictionary set(objectValue: dict, forKey: key) } public func colorDictionaryValue(forKey key: String) -> Dictionary<CNInterfaceStyle, CNColor>? { if let val = objectValue(forKey: key) as? NSDictionary { return val as? Dictionary<CNInterfaceStyle, CNColor> } else { return nil } } public func storeColorDictionaryValue(dataDictionaryValue val: Dictionary<CNInterfaceStyle, CNColor>, forKey key: String) { let pathstr = path(keyString: key) var stddict: Dictionary<String, Data> = [:] for (key, value) in val { if let data = value.toData() { stddict[key.description] = data } } UserDefaults.standard.set(stddict, forKey: pathstr) } public func loadColorDictionaryValue(forKey key: String) -> Dictionary<CNInterfaceStyle, CNColor>? { let pathstr = path(keyString: key) if let dict = UserDefaults.standard.dictionary(forKey: pathstr) as? Dictionary<String, Data> { var result: Dictionary<CNInterfaceStyle, CNColor> = [:] for (key, value) in dict { if let style = CNInterfaceStyle.decode(name: key), let col = CNColor.decode(fromData: value) { result[style] = col } else { CNLog(logLevel: .error, message: "Unknown interface: \(key)", atFunction: #function, inFile: #file) } } return result } else { return nil } } /* * Observer */ public func addObserver(forKey key: String, listnerFunction lfunc: @escaping ListenerFunction) -> ListnerHolder { mValueTable.addObserver(forKey: key, listnerFunction: lfunc) } public func removeObserver(listnerHolder holder: ListnerHolder?) { mValueTable.removeObserver(listnerHolder: holder) } }
lgpl-2.1
0040dec6fdb17961c597b416abe3300e
25.271967
124
0.704093
3.399567
false
false
false
false
quickthyme/PUTcat
PUTcat/Application/UseCase/Parser/UseCaseParseParser.swift
1
2864
import Foundation class UseCaseParseParser { final class func action(response: PCTransactionResponse, transaction: PCTransaction, projectID: String) -> Composed.Action<Any, Any> { return Composed .action(Composed.Action<Any, Any> { _, finalCompletion in guard let parsedData = response.parseEngine?.parse(data: response.rawBody) else { return finalCompletion(.failure(PCError(code: 127, text: "Failed to parse response"))) } Composed .action(PCParserRepository.fetchList(transactionID: transaction.id)) .action(Composed.Action<PCList<PCParser>, PCList<PCParser>> { parserList, parserCompletion in let parserList = parserList ?? PCList<PCParser>() Composed .action(UseCaseGetEnvironmentForProject.action(projectID: projectID)) .action(Composed.Action<PCEnvironment, PCEnvironment> { environment, environmentCompletion in let environment = environment ?? PCEnvironment() Composed .action(PCVariableRepository.fetchList(environmentID: environment.id)) .action(Composed.Action<PCList<PCVariable>, PCList<PCVariable>> { variableList, variableListCompletion in let variableList = variableList ?? PCList<PCVariable>() for parser in parserList.list { guard let variable = variableList.get(named: parser.name).first else { continue } let parsedValue = ParserParseJavaScript.parseString(javaScript: parser.value, data: parsedData) variableList.update(name: variable.name, value: parsedValue, forID: variable.id) } variableListCompletion(.success(variableList)) }) .action(PCVariableRepository.storeList(environmentID: environment.id)) .onFailure { environmentCompletion(.failure($0)) } .execute { _ in environmentCompletion(.success(environment)) } }) .onFailure { parserCompletion(.failure($0)) } .execute { _ in parserCompletion(.success(parserList)) } }) .onFailure { finalCompletion(.failure($0)) } .execute { _ in finalCompletion(.success((response, transaction))) } }) .wrap() } }
apache-2.0
206ef63b1e38456686de083ffccad4e2
59.93617
141
0.518855
6.226087
false
false
false
false
vitkuzmenko/Swiftex
Extensions/UIKit/UIView+Extensions.swift
1
2219
// // UIView+Shake.swift // Swiftex // // Created by Vitaliy Kuzmenko on 15/11/2016. // Copyright © 2016 KuzmenkoFamily. All rights reserved. // #if os(iOS) || os(watchOS) || os(tvOS) import UIKit fileprivate func delay(_ delay: TimeInterval, closure:@escaping () -> Void) { DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) } extension UIView { @IBInspectable public var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue } } public func shakeZ(scale: CGFloat = 0.8, _ completion: (() -> Void)? = nil) { UIView.animate(withDuration: 0.1, animations: { () -> Void in self.transform = CGAffineTransform(scaleX: scale, y: scale) }, completion: { (finished) -> Void in delay(0.3, closure: { () -> Void in completion?() }) UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 5, options: UIView.AnimationOptions.curveEaseOut, animations: { () -> Void in self.transform = CGAffineTransform(scaleX: 1, y: 1) }) { (finished: Bool) -> Void in } }) } public func shakeX(_ complete: ((Bool) -> Void)? = nil) { UIView.animate(withDuration: 0.05, animations: { () -> Void in self.transform = CGAffineTransform(translationX: 10, y: 0) }, completion: { (f) -> Void in UIView.animate(withDuration: 0.4, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0.7, options: UIView.AnimationOptions.allowUserInteraction, animations: { () -> Void in self.transform = .identity }, completion: complete) }) } } public protocol UIViewNibLoadable: AnyObject { static func loadFromNib() -> Self? } extension UIViewNibLoadable where Self: UIView { public static func loadFromNib() -> Self? { return Bundle.main.loadNibNamed(Self.nameOfClass, owner: nil, options: nil)?.first as? Self } } extension UIView: UIViewNibLoadable { } #endif
apache-2.0
14fa82b1cbefdbabf1e21648b9e569d8
34.206349
195
0.616772
4.200758
false
false
false
false
bsorrentino/slidesOnTV
slides/PDFReader/PDFReader+UIKit.swift
1
12698
// // PDFView+UIKit.swift // Samples // // Created by Bartolomeo Sorrentino on 06/03/2020. // Copyright © 2020 mytrus. All rights reserved. // import SwiftUI import Combine import GameController class PageContainerView: UIView, NameDescribable { override init(frame: CGRect) { super.init(frame: frame) setupView() } //initWithCode to init view from xib or storyboard required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } //common func to init our view private func setupView() { // backgroundColor = .red isUserInteractionEnabled = true // Setup Pointer // let tap = UITapGestureRecognizer(target: self, action: #selector(togglePointer) ) // // tap.numberOfTapsRequired = 2 // // addGestureRecognizer(tap) } // @objc private func togglePointer(_ sender: UITapGestureRecognizer) { // // print( "\(typeName).togglePointer \(showPointer)") // // showPointer.toggle() // // } // MARK: - Shadow management // MARRK: - private func addShadow(withHeight height: Int = 0) { if let page = self.subviews.first { page.layer.masksToBounds = false page.layer.shadowColor = UIColor.black.cgColor page.layer.shadowOpacity = 1 page.layer.shadowOffset = CGSize(width: 0 , height: height) page.layer.shadowRadius = 10 page.layer.cornerRadius = 0.0 } } private func removeShadow() { if let page = self.subviews.first { page.layer.masksToBounds = false page.layer.shadowColor = UIColor.clear.cgColor page.layer.shadowOpacity = 0.0 page.layer.shadowOffset = .zero page.layer.shadowRadius = 0.0 page.layer.cornerRadius = 0.0 } } // MARK: - Focus Management // MARK: - override var canBecomeFocused : Bool { return true } // // /// Asks whether the system should allow a focus update to occur. // override func shouldUpdateFocus(in context: UIFocusUpdateContext) -> Bool { // print( "PageView.shouldUpdateFocusInContext:" ) // return true // // } /// Called when the screen’s focusedView has been updated to a new view. Use the animation coordinator to schedule focus-related animations in response to the update. override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) { print( "\(type(of: self)).didUpdateFocusInContext: focused: \(self.isFocused)" ); coordinator.addCoordinatedAnimations(nil) { // Perform some task after item has received focus if context.nextFocusedView == self { self.addShadow() } else { self.removeShadow() } } } // MARK: - Pointer Management // MARK: - fileprivate lazy var pointer:UIView = { let pointer = UIView( frame: CGRect(x: 0, y: 0, width: 20, height: 20)) pointer.backgroundColor = UIColor.magenta pointer.isUserInteractionEnabled = false pointer.layer.cornerRadius = 10.0 // border pointer.layer.borderColor = UIColor.lightGray.cgColor pointer.layer.borderWidth = 1.5 // drop shadow pointer.layer.shadowColor = UIColor.black.cgColor pointer.layer.shadowOpacity = 0.8 pointer.layer.shadowRadius = 3.0 pointer.layer.shadowOffset = CGSize(width: 2.0, height: 2.0) return pointer }() let showPointerSubject = CurrentValueSubject<Bool, Never>(false) var showPointer:Bool = false { didSet { if !showPointer { pointer.removeFromSuperview() } else if !oldValue { pointer.frame.origin = self.center addSubview(pointer) } showPointerSubject.send( showPointer ) } } // MARK: - Touch Handling // MARK: - override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { print( "\(type(of: self)).touchesBegan: focused: \(self.isFocused)" ); guard showPointer, let firstTouch = touches.first else { return } let locationInView = firstTouch.location(in: firstTouch.view) var f = pointer.frame f.origin = locationInView pointer.frame = f } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { // print( "\(type(of: self)).touchesMoved: focused: \(self.isFocused)" ) guard showPointer, let firstTouch = touches.first else { return } let locationInView = firstTouch.location(in: firstTouch.view ) var f = pointer.frame f.origin = locationInView pointer.frame = f } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { print( "\(type(of: self)).touchesEnded: focused: \(self.isFocused)" ) showPointer = false } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { print( "\(type(of: self)).touchesCancelled: focused: \(self.isFocused)" ) showPointer = false } } public protocol PDFPageDelegate { func pointerStatedDidChange( show: Bool ) -> Void func pageDidChange( page: Int ) -> Void } /** PDFPageViewController */ class PDFPageViewController : UIViewController, NameDescribable { typealias Value = (newValue:Int,oldValue:Int) fileprivate var pagesCache = NSCache<NSNumber,PDFPageView>() fileprivate var document : PDFDocument fileprivate let currentPageIndexSubject = CurrentValueSubject<Value,Never>( (newValue:0,oldValue:0) ) var pageDelegate: PDFPageDelegate? var currentPageIndex:Int = 0 { didSet { guard currentPageIndex != oldValue else {return} currentPageIndexSubject.send( (newValue:currentPageIndex, oldValue:oldValue) ) } } init( document:PDFDocument ) { self.document = document super.init(nibName:nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } private var subscribers = Set<AnyCancellable>() override func loadView() { let mainView = PageContainerView() self.view = mainView mainView.showPointerSubject.sink { show in if let delegate = self.pageDelegate { delegate.pointerStatedDidChange(show: show) } }.store( in: &subscribers) } fileprivate func onUpdateCurrentPageIndex( newValue:Int, oldValue:Int ) { print( "current page index changed from \(oldValue) to \(newValue)") if( oldValue > 0 /*&& oldValue <= self.pages.count*/ ) { let zeroBasedIndex = NSNumber( value: oldValue - 1 ) if let view = self.pagesCache.object(forKey: zeroBasedIndex) { view.removeFromSuperview() print( "remove view at index \(zeroBasedIndex)" ) } } if( newValue > 0 /*&& oldValue <= self.pages.count*/ ) { let zeroBasedIndex = NSNumber( value: newValue - 1 ) guard let cachedView = self.pagesCache.object(forKey: zeroBasedIndex) else { print( "create view at index \(zeroBasedIndex)" ) let newView = PDFPageView( frame: self.view.frame, document: self.document, pageNumber: zeroBasedIndex.intValue, backgroundImage: nil, pageViewDelegate: nil) newView.isUserInteractionEnabled = false self.view.addSubview(newView) self.pagesCache.setObject(newView, forKey: zeroBasedIndex) return } print( "reuse view at index \(zeroBasedIndex)" ) self.view.addSubview(cachedView) } } var onUpdateCurrentPageIndexSubscriber:AnyCancellable? override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated:Bool) { super.viewWillAppear(animated) onUpdateCurrentPageIndexSubscriber = currentPageIndexSubject.sink { self.onUpdateCurrentPageIndex( newValue:$0.newValue, oldValue:$0.oldValue ) } } override func viewDidDisappear(_ animated:Bool) { super.viewDidDisappear(animated) if let subscriber = onUpdateCurrentPageIndexSubscriber { subscriber.cancel() } onUpdateCurrentPageIndexSubscriber = nil } // MARK: - Focus Engine // MARK: - // override var preferredFocusEnvironments: [UIFocusEnvironment] { // print( "\(type(of: self)).preferredFocusEnvironments") // // return [view] // } // MARK: - Presses Handling // MARK: - override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) { print("\(typeName).pressesBegan") if let press = presses.first { switch press.type { case .playPause: print( "playPause" ) break case .downArrow: print( "downArrow" ) break case .upArrow: print( "upArrow" ) break case .leftArrow: print( "leftArrow" ) pageDelegate?.pageDidChange(page: self.currentPageIndex - 1) break case .rightArrow: print( "rightArrow" ) pageDelegate?.pageDidChange(page: self.currentPageIndex + 1) break case .select: print( "select" ) if let view = self.view as? PageContainerView { view.showPointer.toggle() } break default: print("press.type=\(press.type.rawValue)") super.pressesBegan(presses, with: event) break } } } override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) { //print("\(typeName).pressesEnded") super.pressesEnded(presses, with: event) } override func pressesChanged(_ presses: Set<UIPress>, with event: UIPressesEvent?) { super.pressesChanged(presses, with: event) } override func pressesCancelled(_ presses: Set<UIPress>, with event: UIPressesEvent?) { super.pressesCancelled(presses, with: event) } } struct PDFDocumentView : UIViewControllerRepresentable, PDFPageDelegate { typealias UIViewControllerType = PDFPageViewController var document : PDFDocument @Binding var page:Int @Binding var isPointerVisible:Bool var isZoom:Bool func pointerStatedDidChange( show: Bool ) { DispatchQueue.main.async { print( "pointerStatedDidChange \(show)") isPointerVisible = show } } func pageDidChange(page: Int) { if isZoom && page > 0 && page <= document.pageCount { DispatchQueue.main.async { self.page = page } } } func makeUIViewController(context: UIViewControllerRepresentableContext<PDFDocumentView>) -> UIViewControllerType { let controller = PDFPageViewController( document: document ) controller.pageDelegate = self controller.currentPageIndex = page return controller } func updateUIViewController(_ uiViewController: UIViewControllerType, context: UIViewControllerRepresentableContext<PDFDocumentView>) { uiViewController.currentPageIndex = page } }
mit
fa2f117297e0332f8ea868a4399f5075
28.523256
170
0.563056
5.19648
false
false
false
false
zisko/swift
stdlib/public/Platform/POSIXError.swift
1
15422
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // FIXME: Only defining POSIXErrorCode for Darwin and Linux at the moment. #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS) /// Enumeration describing POSIX error codes. @_fixed_layout // FIXME(sil-serialize-all) @objc public enum POSIXErrorCode : Int32 { /// Operation not permitted. case EPERM = 1 /// No such file or directory. case ENOENT = 2 /// No such process. case ESRCH = 3 /// Interrupted system call. case EINTR = 4 /// Input/output error. case EIO = 5 /// Device not configured. case ENXIO = 6 /// Argument list too long. case E2BIG = 7 /// Exec format error. case ENOEXEC = 8 /// Bad file descriptor. case EBADF = 9 /// No child processes. case ECHILD = 10 /// Resource deadlock avoided. case EDEADLK = 11 /// 11 was EAGAIN. /// Cannot allocate memory. case ENOMEM = 12 /// Permission denied. case EACCES = 13 /// Bad address. case EFAULT = 14 /// Block device required. case ENOTBLK = 15 /// Device / Resource busy. case EBUSY = 16 /// File exists. case EEXIST = 17 /// Cross-device link. case EXDEV = 18 /// Operation not supported by device. case ENODEV = 19 /// Not a directory. case ENOTDIR = 20 /// Is a directory. case EISDIR = 21 /// Invalid argument. case EINVAL = 22 /// Too many open files in system. case ENFILE = 23 /// Too many open files. case EMFILE = 24 /// Inappropriate ioctl for device. case ENOTTY = 25 /// Text file busy. case ETXTBSY = 26 /// File too large. case EFBIG = 27 /// No space left on device. case ENOSPC = 28 /// Illegal seek. case ESPIPE = 29 /// Read-only file system. case EROFS = 30 /// Too many links. case EMLINK = 31 /// Broken pipe. case EPIPE = 32 /// math software. /// Numerical argument out of domain. case EDOM = 33 /// Result too large. case ERANGE = 34 /// non-blocking and interrupt i/o. /// Resource temporarily unavailable. case EAGAIN = 35 /// Operation would block. public static var EWOULDBLOCK: POSIXErrorCode { return EAGAIN } /// Operation now in progress. case EINPROGRESS = 36 /// Operation already in progress. case EALREADY = 37 /// ipc/network software -- argument errors. /// Socket operation on non-socket. case ENOTSOCK = 38 /// Destination address required. case EDESTADDRREQ = 39 /// Message too long. case EMSGSIZE = 40 /// Protocol wrong type for socket. case EPROTOTYPE = 41 /// Protocol not available. case ENOPROTOOPT = 42 /// Protocol not supported. case EPROTONOSUPPORT = 43 /// Socket type not supported. case ESOCKTNOSUPPORT = 44 /// Operation not supported. case ENOTSUP = 45 /// Protocol family not supported. case EPFNOSUPPORT = 46 /// Address family not supported by protocol family. case EAFNOSUPPORT = 47 /// Address already in use. case EADDRINUSE = 48 /// Can't assign requested address. case EADDRNOTAVAIL = 49 /// ipc/network software -- operational errors /// Network is down. case ENETDOWN = 50 /// Network is unreachable. case ENETUNREACH = 51 /// Network dropped connection on reset. case ENETRESET = 52 /// Software caused connection abort. case ECONNABORTED = 53 /// Connection reset by peer. case ECONNRESET = 54 /// No buffer space available. case ENOBUFS = 55 /// Socket is already connected. case EISCONN = 56 /// Socket is not connected. case ENOTCONN = 57 /// Can't send after socket shutdown. case ESHUTDOWN = 58 /// Too many references: can't splice. case ETOOMANYREFS = 59 /// Operation timed out. case ETIMEDOUT = 60 /// Connection refused. case ECONNREFUSED = 61 /// Too many levels of symbolic links. case ELOOP = 62 /// File name too long. case ENAMETOOLONG = 63 /// Host is down. case EHOSTDOWN = 64 /// No route to host. case EHOSTUNREACH = 65 /// Directory not empty. case ENOTEMPTY = 66 /// quotas & mush. /// Too many processes. case EPROCLIM = 67 /// Too many users. case EUSERS = 68 /// Disc quota exceeded. case EDQUOT = 69 /// Network File System. /// Stale NFS file handle. case ESTALE = 70 /// Too many levels of remote in path. case EREMOTE = 71 /// RPC struct is bad. case EBADRPC = 72 /// RPC version wrong. case ERPCMISMATCH = 73 /// RPC prog. not avail. case EPROGUNAVAIL = 74 /// Program version wrong. case EPROGMISMATCH = 75 /// Bad procedure for program. case EPROCUNAVAIL = 76 /// No locks available. case ENOLCK = 77 /// Function not implemented. case ENOSYS = 78 /// Inappropriate file type or format. case EFTYPE = 79 /// Authentication error. case EAUTH = 80 /// Need authenticator. case ENEEDAUTH = 81 /// Intelligent device errors. /// Device power is off. case EPWROFF = 82 /// Device error, e.g. paper out. case EDEVERR = 83 /// Value too large to be stored in data type. case EOVERFLOW = 84 // MARK: Program loading errors. /// Bad executable. case EBADEXEC = 85 /// Bad CPU type in executable. case EBADARCH = 86 /// Shared library version mismatch. case ESHLIBVERS = 87 /// Malformed Macho file. case EBADMACHO = 88 /// Operation canceled. case ECANCELED = 89 /// Identifier removed. case EIDRM = 90 /// No message of desired type. case ENOMSG = 91 /// Illegal byte sequence. case EILSEQ = 92 /// Attribute not found. case ENOATTR = 93 /// Bad message. case EBADMSG = 94 /// Reserved. case EMULTIHOP = 95 /// No message available on STREAM. case ENODATA = 96 /// Reserved. case ENOLINK = 97 /// No STREAM resources. case ENOSR = 98 /// Not a STREAM. case ENOSTR = 99 /// Protocol error. case EPROTO = 100 /// STREAM ioctl timeout. case ETIME = 101 /// No such policy registered. case ENOPOLICY = 103 /// State not recoverable. case ENOTRECOVERABLE = 104 /// Previous owner died. case EOWNERDEAD = 105 /// Interface output queue is full. case EQFULL = 106 /// Must be equal largest errno. public static var ELAST: POSIXErrorCode { return EQFULL } // FIXME: EOPNOTSUPP has different values depending on __DARWIN_UNIX03 and // KERNEL. } #elseif os(Linux) || os(Android) /// Enumeration describing POSIX error codes. @_fixed_layout // FIXME(sil-serialize-all) public enum POSIXErrorCode : Int32 { /// Operation not permitted. case EPERM = 1 /// No such file or directory. case ENOENT = 2 /// No such process. case ESRCH = 3 /// Interrupted system call. case EINTR = 4 /// Input/output error. case EIO = 5 /// Device not configured. case ENXIO = 6 /// Argument list too long. case E2BIG = 7 /// Exec format error. case ENOEXEC = 8 /// Bad file descriptor. case EBADF = 9 /// No child processes. case ECHILD = 10 /// Try again. case EAGAIN = 11 /// Cannot allocate memory. case ENOMEM = 12 /// Permission denied. case EACCES = 13 /// Bad address. case EFAULT = 14 /// Block device required. case ENOTBLK = 15 /// Device / Resource busy. case EBUSY = 16 /// File exists. case EEXIST = 17 /// Cross-device link. case EXDEV = 18 /// Operation not supported by device. case ENODEV = 19 /// Not a directory. case ENOTDIR = 20 /// Is a directory. case EISDIR = 21 /// Invalid argument. case EINVAL = 22 /// Too many open files in system. case ENFILE = 23 /// Too many open files. case EMFILE = 24 /// Inappropriate ioctl for device. case ENOTTY = 25 /// Text file busy. case ETXTBSY = 26 /// File too large. case EFBIG = 27 /// No space left on device. case ENOSPC = 28 /// Illegal seek. case ESPIPE = 29 /// Read-only file system. case EROFS = 30 /// Too many links. case EMLINK = 31 /// Broken pipe. case EPIPE = 32 /// Numerical argument out of domain. case EDOM = 33 /// Result too large. case ERANGE = 34 /// Resource deadlock would occur. case EDEADLK = 35 /// File name too long. case ENAMETOOLONG = 36 /// No record locks available case ENOLCK = 37 /// Function not implemented. case ENOSYS = 38 /// Directory not empty. case ENOTEMPTY = 39 /// Too many symbolic links encountered case ELOOP = 40 /// Operation would block. public static var EWOULDBLOCK: POSIXErrorCode { return .EAGAIN } /// No message of desired type. case ENOMSG = 42 /// Identifier removed. case EIDRM = 43 /// Channel number out of range. case ECHRNG = 44 /// Level 2 not synchronized. case EL2NSYNC = 45 /// Level 3 halted case EL3HLT = 46 /// Level 3 reset. case EL3RST = 47 /// Link number out of range. case ELNRNG = 48 /// Protocol driver not attached. case EUNATCH = 49 /// No CSI structure available. case ENOCSI = 50 /// Level 2 halted. case EL2HLT = 51 /// Invalid exchange case EBADE = 52 /// Invalid request descriptor case EBADR = 53 /// Exchange full case EXFULL = 54 /// No anode case ENOANO = 55 /// Invalid request code case EBADRQC = 56 /// Invalid slot case EBADSLT = 57 public static var EDEADLOCK: POSIXErrorCode { return .EDEADLK } /// Bad font file format case EBFONT = 59 /// Device not a stream case ENOSTR = 60 /// No data available case ENODATA = 61 /// Timer expired case ETIME = 62 /// Out of streams resources case ENOSR = 63 /// Machine is not on the network case ENONET = 64 /// Package not installed case ENOPKG = 65 /// Object is remote case EREMOTE = 66 /// Link has been severed case ENOLINK = 67 /// Advertise error case EADV = 68 /// Srmount error case ESRMNT = 69 /// Communication error on send case ECOMM = 70 /// Protocol error case EPROTO = 71 /// Multihop attempted case EMULTIHOP = 72 /// RFS specific error case EDOTDOT = 73 /// Not a data message case EBADMSG = 74 /// Value too large for defined data type case EOVERFLOW = 75 /// Name not unique on network case ENOTUNIQ = 76 /// File descriptor in bad state case EBADFD = 77 /// Remote address changed case EREMCHG = 78 /// Can not access a needed shared library case ELIBACC = 79 /// Accessing a corrupted shared library case ELIBBAD = 80 /// .lib section in a.out corrupted case ELIBSCN = 81 /// Attempting to link in too many shared libraries case ELIBMAX = 82 /// Cannot exec a shared library directly case ELIBEXEC = 83 /// Illegal byte sequence case EILSEQ = 84 /// Interrupted system call should be restarted case ERESTART = 85 /// Streams pipe error case ESTRPIPE = 86 /// Too many users case EUSERS = 87 /// Socket operation on non-socket case ENOTSOCK = 88 /// Destination address required case EDESTADDRREQ = 89 /// Message too long case EMSGSIZE = 90 /// Protocol wrong type for socket case EPROTOTYPE = 91 /// Protocol not available case ENOPROTOOPT = 92 /// Protocol not supported case EPROTONOSUPPORT = 93 /// Socket type not supported case ESOCKTNOSUPPORT = 94 /// Operation not supported on transport endpoint case EOPNOTSUPP = 95 /// Protocol family not supported case EPFNOSUPPORT = 96 /// Address family not supported by protocol case EAFNOSUPPORT = 97 /// Address already in use case EADDRINUSE = 98 /// Cannot assign requested address case EADDRNOTAVAIL = 99 /// Network is down case ENETDOWN = 100 /// Network is unreachable case ENETUNREACH = 101 /// Network dropped connection because of reset case ENETRESET = 102 /// Software caused connection abort case ECONNABORTED = 103 /// Connection reset by peer case ECONNRESET = 104 /// No buffer space available case ENOBUFS = 105 /// Transport endpoint is already connected case EISCONN = 106 /// Transport endpoint is not connected case ENOTCONN = 107 /// Cannot send after transport endpoint shutdown case ESHUTDOWN = 108 /// Too many references: cannot splice case ETOOMANYREFS = 109 /// Connection timed out case ETIMEDOUT = 110 /// Connection refused case ECONNREFUSED = 111 /// Host is down case EHOSTDOWN = 112 /// No route to host case EHOSTUNREACH = 113 /// Operation already in progress case EALREADY = 114 /// Operation now in progress case EINPROGRESS = 115 /// Stale NFS file handle case ESTALE = 116 /// Structure needs cleaning case EUCLEAN = 117 /// Not a XENIX named type file case ENOTNAM = 118 /// No XENIX semaphores available case ENAVAIL = 119 /// Is a named type file case EISNAM = 120 /// Remote I/O error case EREMOTEIO = 121 /// Quota exceeded case EDQUOT = 122 /// No medium found case ENOMEDIUM = 123 /// Wrong medium type case EMEDIUMTYPE = 124 /// Operation Canceled case ECANCELED = 125 /// Required key not available case ENOKEY = 126 /// Key has expired case EKEYEXPIRED = 127 /// Key has been revoked case EKEYREVOKED = 128 /// Key was rejected by service case EKEYREJECTED = 129 /// Owner died case EOWNERDEAD = 130 /// State not recoverable case ENOTRECOVERABLE = 131 } #endif
apache-2.0
b16ad375d47c574fb6a0430f4d667c52
26.588551
80
0.573856
4.558676
false
false
false
false
talentsparkio/CloudNote
CloudNote/NoteCell.swift
1
1140
// // NoteCell.swift // CloudNote // // Created by Nick Chen on 8/8/15. // Copyright © 2015 TalentSpark. All rights reserved. // import UIKit class NoteCell: UITableViewCell { @IBOutlet weak var notePhoto: UIImageView! @IBOutlet weak var noteTitle: UILabel! @IBOutlet weak var noteBody: UILabel! var note: PFObject? { didSet { if let setNote = note { noteTitle.text = setNote["Title"] as? String noteBody.text = setNote["Body"] as? String let image = setNote["Photo"] as? PFFile image?.getDataInBackgroundWithBlock {(imageData, error) -> Void in if error == nil { if let imageData = imageData { self.notePhoto.image = UIImage(data:imageData) } } } } } } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
bsd-3-clause
5272b972a4649479fb9ad4e8f20db221
26.119048
82
0.528534
4.76569
false
false
false
false
FutureKit/FutureKit
Welcome To FutureKit - The Playground.playground/Pages/Composition.xcplaygroundpage/Contents.swift
1
10940
//: [Previous](@previous) import FutureKit import XCPlayground XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: # Futures are composable. //: adding a block handler to a Future via onComplete/onSuccess doesn't just give you a way to get a result from a future. It's also a way to create a new Future. let stringFuture = Future<String>(success: "5") let intOptFuture : Future<Int?> intOptFuture = stringFuture.onSuccess { (stringResult) -> Int? in let i = Int(stringResult) return i } intOptFuture.onSuccess { (intResult : Int?) -> Void in let i = intResult } //: Knowing this we can "chain" futures together to make a complex set of dependencies... stringFuture.onSuccess { (stringResult:String) -> Int in let i = Int(stringResult)! return i } .onSuccess { (intResult:Int) -> [Int] in let array = [intResult] return array } .onSuccess { (arrayResult : [Int]) -> Void in let a = arrayResult.first! } //: You can see how we can use the result of the first future, to generate the result of the second, etc. //: This is such a common and powerful feature of futures there is an alternate version of the same command called 'map'. The generic signature of map looks like: //: 'func map<S>((T) -> S) -> Future<S>' let futureInt = stringFuture.map { (stringResult) -> Int in Int(stringResult)! } //: `futureInt` is automatically be inferred as Future<Int>. //: when "chaining" futures together via onSuccess (or map), Failures and Cancellations will automatically be 'forwarded' to any dependent tasks. So if the first future returns Fail, than all of the dependent futures will automatically fail. //: this can make error handling for a list of actions very easy. let gonnaTryHardAndNotFail = Promise<String>() let futureThatHopefullyWontFail = gonnaTryHardAndNotFail.future futureThatHopefullyWontFail .onSuccess { (s:String) -> Int in return Int(s)! } .map { (intResult:Int) -> [Int] in // 'map' is same as 'onSuccess'. // Use whichever you like. let i = intResult return [i] } .map { (arrayResult : [Int]) -> Void in let a = arrayResult.first } .onFail { (error) -> Void in let e = error } gonnaTryHardAndNotFail.completeWithFail("Sorry. Maybe Next time.") //: None of the blocks inside of onSuccess/map methods executed. since the first Future failed. A good way to think about it is, that the "last" future failed because the future it depended upon for an input value, also failed. //: # Completion //: Sometimes you want to create a dependent Future but conditionally decide inside the block whether the dependent block should Succeed or Fail, etc. For this we have use a handler block with a different generic signature: //: 'func onComplete<S>((FutureResult<T>) -> Completion<S>) -> Future<S>' //: Don't worry if that seems hard to understand. It's actually pretty straightforward. //: A Completion is a enumeration that is used to 'complete' a future. A Future has a var //: `var result : FutureResult<T>?` //: this var stores the result of the Future. Note that it's optional. That's because a Future may not be 'completed' yet. When it's in an uncompleted state, it's `result` var will be nil. //: If you examine the contents of a completed Future<T>, you will find a Completion<T> enumeration that must be one of the 3 possible values: `.Success(Result<T>)`, `.Fail(NSError)`, `.Cancel(Any?)` let anotherFuture5 = Future(success: 5) switch anotherFuture5.result! { case let .Success(x): let y = x default: break } //: But completion has a fourth enumeration case `.CompleteUsing(Future<T>)`. This is very useful when you have a handler that wants to use some other Future to complete itself. This completion value is only used as a return value from a handler method. //: First let's create an unreliable Future, that fails most of the time (80%) func iMayFailRandomly() -> Future<String> { let p = Promise<String>() Executor.Default.execute { () -> Void in // This is a random number from 0..4. // So we only have a 20% of success! let randomNumber = arc4random_uniform(5) if (randomNumber == 0) { p.completeWithSuccess("Yay") } else { p.completeWithFail("Not lucky Enough this time") } } return p.future } //: Here is a function that will call itself recurisvely until it finally succeeds. typealias keepTryingPayload = (tries:Int,result:String) func iWillKeepTryingTillItWorks(attemptNo: Int) -> Future<Int> { let numberOfAttempts = attemptNo + 1 return iMayFailRandomly().onComplete { (result) -> Completion<Int> in switch result { case let .Success(value): _ = value return .Success(numberOfAttempts) default: // we didn't succeed! let nextFuture = iWillKeepTryingTillItWorks(numberOfAttempts) return .CompleteUsing(nextFuture) } } } let keepTrying = iWillKeepTryingTillItWorks(0) keepTrying.onSuccess { (tries) -> Void in let howManyTries = tries } //: If you select "Editor -> Execute Playground" you can see this number change. //: ## CompletionState //: since onComplete will get a Completion<Int>, the natural idea would be to use switch (completion) futureInt.onComplete { (result) -> Void in switch result { case let .Success(value): let five = value case let .Fail(error): let e = error case .Cancelled: break } } //: If all you care about is success or fail, you can use the isSuccess var futureInt.onComplete { (result : FutureResult<Int>) -> Void in if result.isSuccess { let five = result.asResult() } else { // must have failed or was cancelled } } //: # onComplete handler varients //: There are actually 4 different variants of onComplete() handler //: - 'func onComplete(block:(FutureResult<T>) -> Completion<__Type>)' //: - 'func onComplete(block:(FutureResult<T>) -> Void)' //: - 'func onComplete(block:(FutureResult<T>) -> __Type)' //: - 'func onComplete(block:(FutureResult<T>) -> Future<S>)' // we are gonna use this future for the next few examples. let sampleFuture = Future(success: 5) //: 'func onComplete(block:(FutureResult<T>) -> Completion<__Type>)' //: The first version we have already seen. It let's you receive a completion value from a target future, and return any sort of new result it wants (maybe it want's to Fail certain 'Success' results from it's target, or visa-versa). It is very flexible. You can compose a new future that returns anything you want. //: Here we will convert a .Fail into a .Success, but we still want to know if the Future was Cancelled: sampleFuture.onComplete { (result) -> Completion<String> in switch result { case let .Success(value): return .Success(String(value)) case .Fail(_): return .Success("Some Default String we send when things Fail") case .Cancelled: return .Cancelled } } //: 'func onComplete(block:(FutureResult<T>) -> Void)' //: We been using this one without me even mentioning it. This block always returns a type of Future<Void> that always returns success. So it can be composed and chained if needed. let f = sampleFuture.onComplete { (result) -> Void in if (result.isSuccess) { // store this great result in a database or something. } } print(f) //: 'func onComplete(block:(FutureResult<T>) -> __Type)' //: This is almost identical to the 'Void' version EXCEPT you want to return a result of a different Type. This block will compose a new future that returns .Success(result) where result is the value returned from the block. let futureString = sampleFuture.onComplete { (result) -> String in switch result { case let .Success(value): return String(value) default: return "Some Default String we send when things Fail" } } let string = futureString.result! //: 'func onComplete(block:(ResultValue<T>) -> Future<__Type>)' //: This version is equivilant to returning a Completion<__Type>.ContinueUsing(f) (using the first varient on onComplete). It just looks cleaner: func coolFunctionThatAddsOneInBackground(num : Int) -> Future<Int> { // let's dispatch this to the low priority background queue return Future(.Background) { () -> Int in let ret = num + 1 return ret } } func coolFunctionThatAddsOneAtHighPriority(num : Int) -> Future<Int> { // let's dispatch this to the high priority UserInteractive queue return Future(.UserInteractive) { () -> Int in // so much work here to get a 2. let ret = num + 1 return ret } } let coolFuture = sampleFuture.onComplete { (c1) -> Future<Int> in let beforeAdd = c1.asResult() return coolFunctionThatAddsOneInBackground(c1.value) .onComplete { (c2) -> Future<Int> in let afterFirstAdd = c2.asResult() return coolFunctionThatAddsOneAtHighPriority(c2.value) } } coolFuture.onSuccess { (value) -> Void in let x = value } //: # Documentation TODO: //: (..Before we ship 1.0 pretty please..) //: - onSuccess Handlers (it's pretty much just like onComplete handlers, but easier). //: - onFail/onCancel and how they DON'T return a new future! (They aren't as composable as onComplete/onSuccess for some very good reasons). //: - Executors - and how to dispatch your code quickly and easy in any queue or thread you want. And how to guarantee that your code always executes in the dispatch queue you require, //: - Cancel - How to write a Future that supports cancel(). And how cancel() can chain through composed futures. //: FutureBatch - how to get your Futures to run in parallel and wait for them all to complete. //: As() - what Future.As() does and how to use it, and how doing it wrong will crash your code (and that's a good thing). (Hint: it just calls `as!`) //: - How to give your Objective-C code a Future it can use (cause it doesn't like swift generic classes!) (Hint: FTask). //: - CoacoPods and Carthage support. //: - How to play super friendly integrate with the Bolt Framework (BFTask <--> Future conversion in a few easy lines!). //: # Eventually //: cause I have so much free time to write more things //: Advanced topics like: //: - Get to 100% test coverage please. //: - Configuring the Primary Executors (and the endless debate between Immediate vs Async execution).. //: - how to tune synchronization. (NSLock vs dispatch barrier queues). //: - add a real var to a swift extension in a few lines. //: - write code that can switch at runtime between Locks/Barriers and any other snychronization strategy you can bake up. //: [Next](@next)
mit
da99e1887ce7b5044002db01e5faa37c
39.369004
318
0.681261
4.068427
false
false
false
false
mshhmzh/firefox-ios
Client/Frontend/Browser/ErrorPageHelper.swift
4
18153
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import WebKit import GCDWebServers import Shared import Storage class ErrorPageHelper { static let MozDomain = "mozilla" static let MozErrorDownloadsNotEnabled = 100 private static let MessageOpenInSafari = "openInSafari" private static let MessageCertVisitOnce = "certVisitOnce" // When an error page is intentionally loaded, its added to this set. If its in the set, we show // it as an error page. If its not, we assume someone is trying to reload this page somehow, and // we'll instead redirect back to the original URL. private static var redirecting = [NSURL]() private static weak var certStore: CertStore? // Regardless of cause, NSURLErrorServerCertificateUntrusted is currently returned in all cases. // Check the other cases in case this gets fixed in the future. private static let CertErrors = [ NSURLErrorServerCertificateUntrusted, NSURLErrorServerCertificateHasBadDate, NSURLErrorServerCertificateHasUnknownRoot, NSURLErrorServerCertificateNotYetValid ] // Error codes copied from Gecko. The ints corresponding to these codes were determined // by inspecting the NSError in each of these cases. private static let CertErrorCodes = [ -9813: "SEC_ERROR_UNKNOWN_ISSUER", -9814: "SEC_ERROR_EXPIRED_CERTIFICATE", -9843: "SSL_ERROR_BAD_CERT_DOMAIN", ] class func cfErrorToName(err: CFNetworkErrors) -> String { switch err { case .CFHostErrorHostNotFound: return "CFHostErrorHostNotFound" case .CFHostErrorUnknown: return "CFHostErrorUnknown" case .CFSOCKSErrorUnknownClientVersion: return "CFSOCKSErrorUnknownClientVersion" case .CFSOCKSErrorUnsupportedServerVersion: return "CFSOCKSErrorUnsupportedServerVersion" case .CFSOCKS4ErrorRequestFailed: return "CFSOCKS4ErrorRequestFailed" case .CFSOCKS4ErrorIdentdFailed: return "CFSOCKS4ErrorIdentdFailed" case .CFSOCKS4ErrorIdConflict: return "CFSOCKS4ErrorIdConflict" case .CFSOCKS4ErrorUnknownStatusCode: return "CFSOCKS4ErrorUnknownStatusCode" case .CFSOCKS5ErrorBadState: return "CFSOCKS5ErrorBadState" case .CFSOCKS5ErrorBadResponseAddr: return "CFSOCKS5ErrorBadResponseAddr" case .CFSOCKS5ErrorBadCredentials: return "CFSOCKS5ErrorBadCredentials" case .CFSOCKS5ErrorUnsupportedNegotiationMethod: return "CFSOCKS5ErrorUnsupportedNegotiationMethod" case .CFSOCKS5ErrorNoAcceptableMethod: return "CFSOCKS5ErrorNoAcceptableMethod" case .CFFTPErrorUnexpectedStatusCode: return "CFFTPErrorUnexpectedStatusCode" case .CFErrorHTTPAuthenticationTypeUnsupported: return "CFErrorHTTPAuthenticationTypeUnsupported" case .CFErrorHTTPBadCredentials: return "CFErrorHTTPBadCredentials" case .CFErrorHTTPConnectionLost: return "CFErrorHTTPConnectionLost" case .CFErrorHTTPParseFailure: return "CFErrorHTTPParseFailure" case .CFErrorHTTPRedirectionLoopDetected: return "CFErrorHTTPRedirectionLoopDetected" case .CFErrorHTTPBadURL: return "CFErrorHTTPBadURL" case .CFErrorHTTPProxyConnectionFailure: return "CFErrorHTTPProxyConnectionFailure" case .CFErrorHTTPBadProxyCredentials: return "CFErrorHTTPBadProxyCredentials" case .CFErrorPACFileError: return "CFErrorPACFileError" case .CFErrorPACFileAuth: return "CFErrorPACFileAuth" case .CFErrorHTTPSProxyConnectionFailure: return "CFErrorHTTPSProxyConnectionFailure" case .CFStreamErrorHTTPSProxyFailureUnexpectedResponseToCONNECTMethod: return "CFStreamErrorHTTPSProxyFailureUnexpectedResponseToCONNECTMethod" case .CFURLErrorBackgroundSessionInUseByAnotherProcess: return "CFURLErrorBackgroundSessionInUseByAnotherProcess" case .CFURLErrorBackgroundSessionWasDisconnected: return "CFURLErrorBackgroundSessionWasDisconnected" case .CFURLErrorUnknown: return "CFURLErrorUnknown" case .CFURLErrorCancelled: return "CFURLErrorCancelled" case .CFURLErrorBadURL: return "CFURLErrorBadURL" case .CFURLErrorTimedOut: return "CFURLErrorTimedOut" case .CFURLErrorUnsupportedURL: return "CFURLErrorUnsupportedURL" case .CFURLErrorCannotFindHost: return "CFURLErrorCannotFindHost" case .CFURLErrorCannotConnectToHost: return "CFURLErrorCannotConnectToHost" case .CFURLErrorNetworkConnectionLost: return "CFURLErrorNetworkConnectionLost" case .CFURLErrorDNSLookupFailed: return "CFURLErrorDNSLookupFailed" case .CFURLErrorHTTPTooManyRedirects: return "CFURLErrorHTTPTooManyRedirects" case .CFURLErrorResourceUnavailable: return "CFURLErrorResourceUnavailable" case .CFURLErrorNotConnectedToInternet: return "CFURLErrorNotConnectedToInternet" case .CFURLErrorRedirectToNonExistentLocation: return "CFURLErrorRedirectToNonExistentLocation" case .CFURLErrorBadServerResponse: return "CFURLErrorBadServerResponse" case .CFURLErrorUserCancelledAuthentication: return "CFURLErrorUserCancelledAuthentication" case .CFURLErrorUserAuthenticationRequired: return "CFURLErrorUserAuthenticationRequired" case .CFURLErrorZeroByteResource: return "CFURLErrorZeroByteResource" case .CFURLErrorCannotDecodeRawData: return "CFURLErrorCannotDecodeRawData" case .CFURLErrorCannotDecodeContentData: return "CFURLErrorCannotDecodeContentData" case .CFURLErrorCannotParseResponse: return "CFURLErrorCannotParseResponse" case .CFURLErrorInternationalRoamingOff: return "CFURLErrorInternationalRoamingOff" case .CFURLErrorCallIsActive: return "CFURLErrorCallIsActive" case .CFURLErrorDataNotAllowed: return "CFURLErrorDataNotAllowed" case .CFURLErrorRequestBodyStreamExhausted: return "CFURLErrorRequestBodyStreamExhausted" case .CFURLErrorFileDoesNotExist: return "CFURLErrorFileDoesNotExist" case .CFURLErrorFileIsDirectory: return "CFURLErrorFileIsDirectory" case .CFURLErrorNoPermissionsToReadFile: return "CFURLErrorNoPermissionsToReadFile" case .CFURLErrorDataLengthExceedsMaximum: return "CFURLErrorDataLengthExceedsMaximum" case .CFURLErrorSecureConnectionFailed: return "CFURLErrorSecureConnectionFailed" case .CFURLErrorServerCertificateHasBadDate: return "CFURLErrorServerCertificateHasBadDate" case .CFURLErrorServerCertificateUntrusted: return "CFURLErrorServerCertificateUntrusted" case .CFURLErrorServerCertificateHasUnknownRoot: return "CFURLErrorServerCertificateHasUnknownRoot" case .CFURLErrorServerCertificateNotYetValid: return "CFURLErrorServerCertificateNotYetValid" case .CFURLErrorClientCertificateRejected: return "CFURLErrorClientCertificateRejected" case .CFURLErrorClientCertificateRequired: return "CFURLErrorClientCertificateRequired" case .CFURLErrorCannotLoadFromNetwork: return "CFURLErrorCannotLoadFromNetwork" case .CFURLErrorCannotCreateFile: return "CFURLErrorCannotCreateFile" case .CFURLErrorCannotOpenFile: return "CFURLErrorCannotOpenFile" case .CFURLErrorCannotCloseFile: return "CFURLErrorCannotCloseFile" case .CFURLErrorCannotWriteToFile: return "CFURLErrorCannotWriteToFile" case .CFURLErrorCannotRemoveFile: return "CFURLErrorCannotRemoveFile" case .CFURLErrorCannotMoveFile: return "CFURLErrorCannotMoveFile" case .CFURLErrorDownloadDecodingFailedMidStream: return "CFURLErrorDownloadDecodingFailedMidStream" case .CFURLErrorDownloadDecodingFailedToComplete: return "CFURLErrorDownloadDecodingFailedToComplete" case .CFHTTPCookieCannotParseCookieFile: return "CFHTTPCookieCannotParseCookieFile" case .CFNetServiceErrorUnknown: return "CFNetServiceErrorUnknown" case .CFNetServiceErrorCollision: return "CFNetServiceErrorCollision" case .CFNetServiceErrorNotFound: return "CFNetServiceErrorNotFound" case .CFNetServiceErrorInProgress: return "CFNetServiceErrorInProgress" case .CFNetServiceErrorBadArgument: return "CFNetServiceErrorBadArgument" case .CFNetServiceErrorCancel: return "CFNetServiceErrorCancel" case .CFNetServiceErrorInvalid: return "CFNetServiceErrorInvalid" case .CFNetServiceErrorTimeout: return "CFNetServiceErrorTimeout" case .CFNetServiceErrorDNSServiceFailure: return "CFNetServiceErrorDNSServiceFailure" default: return "Unknown" } } class func register(server: WebServer, certStore: CertStore?) { self.certStore = certStore server.registerHandlerForMethod("GET", module: "errors", resource: "error.html", handler: { (request) -> GCDWebServerResponse! in guard let url = ErrorPageHelper.originalURLFromQuery(request.URL) else { return GCDWebServerResponse(statusCode: 404) } guard let index = self.redirecting.indexOf(url) else { return GCDWebServerDataResponse(redirect: url, permanent: false) } self.redirecting.removeAtIndex(index) guard let code = request.query["code"] as? String, let errCode = Int(code), let errDescription = request.query["description"] as? String, let errURLString = request.query["url"] as? String, let errURLDomain = NSURL(string: errURLString)?.host, var errDomain = request.query["domain"] as? String else { return GCDWebServerResponse(statusCode: 404) } var asset = NSBundle.mainBundle().pathForResource("NetError", ofType: "html") var variables = [ "error_code": "\(errCode ?? -1)", "error_title": errDescription ?? "", "short_description": errDomain, ] let tryAgain = NSLocalizedString("Try again", tableName: "ErrorPages", comment: "Shown in error pages on a button that will try to load the page again") var actions = "<button onclick='webkit.messageHandlers.localRequestHelper.postMessage({ type: \"reload\" })'>\(tryAgain)</button>" if errDomain == kCFErrorDomainCFNetwork as String { if let code = CFNetworkErrors(rawValue: Int32(errCode)) { errDomain = self.cfErrorToName(code) } } else if errDomain == ErrorPageHelper.MozDomain { if errCode == ErrorPageHelper.MozErrorDownloadsNotEnabled { let downloadInSafari = NSLocalizedString("Open in Safari", tableName: "ErrorPages", comment: "Shown in error pages for files that can't be shown and need to be downloaded.") // Overwrite the normal try-again action. actions = "<button onclick='webkit.messageHandlers.errorPageHelperMessageManager.postMessage({type: \"\(MessageOpenInSafari)\"})'>\(downloadInSafari)</button>" } errDomain = "" } else if CertErrors.contains(errCode) { guard let certError = request.query["certerror"] as? String else { return GCDWebServerResponse(statusCode: 404) } asset = NSBundle.mainBundle().pathForResource("CertError", ofType: "html") actions = "<button onclick='history.back()'>\(Strings.ErrorPagesGoBackButton)</button>" variables["error_title"] = Strings.ErrorPagesCertWarningTitle variables["cert_error"] = certError variables["long_description"] = String(format: Strings.ErrorPagesCertWarningDescription, "<b>\(errURLDomain)</b>") variables["advanced_button"] = Strings.ErrorPagesAdvancedButton variables["warning_description"] = Strings.ErrorPagesCertWarningDescription variables["warning_advanced1"] = Strings.ErrorPagesAdvancedWarning1 variables["warning_advanced2"] = Strings.ErrorPagesAdvancedWarning2 variables["warning_actions"] = "<p><a href='javascript:webkit.messageHandlers.errorPageHelperMessageManager.postMessage({type: \"\(MessageCertVisitOnce)\"})'>\(Strings.ErrorPagesVisitOnceButton)</button></p>" } variables["actions"] = actions let response = GCDWebServerDataResponse(HTMLTemplate: asset, variables: variables) response.setValue("no cache", forAdditionalHeader: "Pragma") response.setValue("no-cache,must-revalidate", forAdditionalHeader: "Cache-Control") response.setValue(NSDate().description, forAdditionalHeader: "Expires") return response }) server.registerHandlerForMethod("GET", module: "errors", resource: "NetError.css", handler: { (request) -> GCDWebServerResponse! in let path = NSBundle(forClass: self).pathForResource("NetError", ofType: "css")! return GCDWebServerDataResponse(data: NSData(contentsOfFile: path), contentType: "text/css") }) server.registerHandlerForMethod("GET", module: "errors", resource: "CertError.css", handler: { (request) -> GCDWebServerResponse! in let path = NSBundle(forClass: self).pathForResource("CertError", ofType: "css")! return GCDWebServerDataResponse(data: NSData(contentsOfFile: path), contentType: "text/css") }) } func showPage(error: NSError, forUrl url: NSURL, inWebView webView: WKWebView) { // Don't show error pages for error pages. if ErrorPageHelper.isErrorPageURL(url) { if let previousURL = ErrorPageHelper.originalURLFromQuery(url), let index = ErrorPageHelper.redirecting.indexOf(previousURL) { ErrorPageHelper.redirecting.removeAtIndex(index) } return } // Add this page to the redirecting list. This will cause the server to actually show the error page // (instead of redirecting to the original URL). ErrorPageHelper.redirecting.append(url) let components = NSURLComponents(string: WebServer.sharedInstance.base + "/errors/error.html")! var queryItems = [ NSURLQueryItem(name: "url", value: url.absoluteString), NSURLQueryItem(name: "code", value: String(error.code)), NSURLQueryItem(name: "domain", value: error.domain), NSURLQueryItem(name: "description", value: error.localizedDescription) ] // If this is an invalid certificate, show a certificate error allowing the // user to go back or continue. The certificate itself is encoded and added as // a query parameter to the error page URL; we then read the certificate from // the URL if the user wants to continue. if ErrorPageHelper.CertErrors.contains(error.code), let certChain = error.userInfo["NSErrorPeerCertificateChainKey"] as? [SecCertificateRef], let cert = certChain.first, let underlyingError = error.userInfo[NSUnderlyingErrorKey] as? NSError, let certErrorCode = underlyingError.userInfo["_kCFStreamErrorCodeKey"] as? Int { let encodedCert = (SecCertificateCopyData(cert) as NSData).base64EncodedString queryItems.append(NSURLQueryItem(name: "badcert", value: encodedCert)) let certError = ErrorPageHelper.CertErrorCodes[certErrorCode] ?? "" queryItems.append(NSURLQueryItem(name: "certerror", value: String(certError))) } components.queryItems = queryItems webView.loadRequest(PrivilegedRequest(URL: components.URL!)) } class func isErrorPageURL(url: NSURL) -> Bool { if let host = url.host, path = url.path { return url.scheme == "http" && host == "localhost" && path == "/errors/error.html" } return false } class func originalURLFromQuery(url: NSURL) -> NSURL? { let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) if let queryURL = components?.queryItems?.find({ $0.name == "url" })?.value { return NSURL(string: queryURL) } return nil } } extension ErrorPageHelper: TabHelper { static func name() -> String { return "ErrorPageHelper" } func scriptMessageHandlerName() -> String? { return "errorPageHelperMessageManager" } func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) { if let errorURL = message.frameInfo.request.URL where ErrorPageHelper.isErrorPageURL(errorURL), let res = message.body as? [String: String], let originalURL = ErrorPageHelper.originalURLFromQuery(errorURL), let type = res["type"] { switch type { case ErrorPageHelper.MessageOpenInSafari: UIApplication.sharedApplication().openURL(originalURL) case ErrorPageHelper.MessageCertVisitOnce: if let cert = certFromErrorURL(errorURL), let host = originalURL.host { let origin = "\(host):\(originalURL.port ?? 443)" ErrorPageHelper.certStore?.addCertificate(cert, forOrigin: origin) message.webView?.reload() } default: assertionFailure("Unknown error message") } } } private func certFromErrorURL(url: NSURL) -> SecCertificateRef? { let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) if let encodedCert = components?.queryItems?.filter({ $0.name == "badcert" }).first?.value, certData = NSData(base64EncodedString: encodedCert, options: []) { return SecCertificateCreateWithData(nil, certData) } return nil } }
mpl-2.0
588c435b402fd3a4218431c5ccb6fd08
56.812102
197
0.708588
5.618384
false
false
false
false
ccqpein/Arithmetic-Exercises
Date-Arithmetic/DA2.swift
1
1638
// Use different design let monthDay:[Int] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,] let monthDayL:[Int] = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,] let yzero = 2000 func leapYear(_ y:Int) -> Bool { if (y % 4 == 0) && (y % 400 == 0 || y % 100 != 0) { return true } else { return false } } class Date { var d:Int var m:Int var y:Int init(days:Int, month:Int, year:Int) { self.d = days self.m = month self.y = year } func addDate(days:Int) { var daysLeft:Int = days + self.d while daysLeft > 0 { var monthTable:[Int] = leapYear(self.y) ? monthDayL : monthDay if daysLeft > monthTable[self.m - 1] { daysLeft = daysLeft - monthTable[self.m - 1] self.m += 1 self.d = 1 if self.m > 12 { self.y += 1 self.m -= 12 } } else { self.d = daysLeft daysLeft = 0 } } } func reduceDate(days:Int) { var daysLeft:Int = self.d - days while daysLeft <= 0 { var monthTable:[Int] = leapYear(self.y) ? monthDayL : monthDay self.m -= 1 if self.m < 1 { self.y -= 1 self.m = 12 } daysLeft += monthTable[self.m - 1] } self.d = daysLeft } } var testa = Date(days:25, month:2, year:2004) testa.addDate(days:370) testa.reduceDate(days:370)
apache-2.0
3b047016ba226b8a58cc565ce30537c2
21.438356
74
0.434066
3.463002
false
false
false
false
BrisyIOS/zhangxuWeiBo
zhangxuWeiBo/zhangxuWeiBo/AppDelegate.swift
1
4007
// // AppDelegate.swift // zhangxuWeiBo // // Created by zhangxu on 16/6/10. // Copyright © 2016年 zhangxu. All rights reserved. // import UIKit import AFNetworking import SDWebImage @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var isConnectStatus: Bool?; func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // 打印版本号 print(UIDevice.currentDevice().systemVersion); // 创建window window = UIWindow(frame: UIScreen.mainScreen().bounds); // 设置窗口颜色 window?.backgroundColor = UIColor.whiteColor(); // 延迟加载启动图 NSThread.sleepForTimeInterval(1); // 让window成为主窗口 window?.makeKeyAndVisible(); // 获取账户 let account = ZXAccountManager.account(); // 打印沙盒路径 print(kDocumentPath); if account != nil { // 上次登陆授权过 ZXChooseVc.chooseRootViewController(); } else { // 没有授权过 window?.rootViewController = ZXOAuthViewController(); } // 监听网络状态 let mgr = AFNetworkReachabilityManager.sharedManager(); mgr.setReachabilityStatusChangeBlock { (status) in if status == AFNetworkReachabilityStatus.NotReachable { // 没有网络 self.isConnectStatus = false; print("没有网络"); } else { // 有网络 self.isConnectStatus = true; print("有网络"); } } // 设置网络加载状态 AFNetworkActivityIndicatorManager.sharedManager().enabled = true; return true } // 当发生内存警告的时候调用此方法 func applicationDidReceiveMemoryWarning(application: UIApplication) { // 停止所有下载 SDWebImageManager.sharedManager().cancelAll(); // 清除内存缓存 SDWebImageManager.sharedManager().imageCache.clearMemory(); } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
apache-2.0
52443a4c2d062ee4f77640cf850df445
34.166667
285
0.647183
5.685629
false
false
false
false
halo/LinkLiar
LinkLiar/MACVendors.swift
1
2080
/* * Copyright (C) 2012-2021 halo https://io.github.com/halo/LinkLiar * * 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 struct MACVendors { private static var dictionary: [String: String] = [:] static func load() { Log.debug("Loading MAC vendors asynchronously...") DispatchQueue.global(qos: .background).async(execute: { () -> Void in dictionary = JSONReader(filePath: path).dictionary as! [String : String] Log.debug("MAC vendors loading completed. I got \(dictionary.count) prefixes.") }) } static func name(address: MACAddress) -> String { Log.debug("Looking up vendor of MAC \(address.formatted)") guard let name = dictionary[address.prefix] else { return "No Vendor" } return name } private static var path = Bundle.main.url(forResource: "oui", withExtension: "json")!.path /* let bundle = Bundle(for: type(of: self)) let filename = name.components(separatedBy: ".") return bundle .url(forResource: filename.first, withExtension: filename.last)!.path }() */ }
mit
915236726322182398c09326a8e90a31
40.6
133
0.725962
4.397463
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/DataAndStorageViewController.swift
1
28843
// // DataAndStorageViewController.swift // Telegram // // Created by keepcoder on 18/04/2017. // Copyright © 2017 Telegram. All rights reserved. // import Cocoa import TGUIKit import Postbox import TelegramCore import InAppSettings import SwiftSignalKit enum DataAndStorageEntryTag : ItemListItemTag { case automaticDownloadReset case autoplayGifs case autoplayVideos func isEqual(to other: ItemListItemTag) -> Bool { if let other = other as? DataAndStorageEntryTag, self == other { return true } else { return false } } var stableId: Int32 { switch self { case .automaticDownloadReset: return 10 case .autoplayGifs: return 13 case .autoplayVideos: return 14 } } } public func autodownloadDataSizeString(_ size: Int64) -> String { if size >= 1024 * 1024 * 1024 { let remainder = (size % (1024 * 1024 * 1024)) / (1024 * 1024 * 102) if remainder != 0 { return "\(size / (1024 * 1024 * 1024)),\(remainder) GB" } else { return "\(size / (1024 * 1024 * 1024)) GB" } } else if size >= 1024 * 1024 { let remainder = (size % (1024 * 1024)) / (1024 * 102) if size < 10 * 1024 * 1024 { return "\(size / (1024 * 1024)),\(remainder) MB" } else { return "\(size / (1024 * 1024)) MB" } } else if size >= 1024 { return "\(size / 1024) KB" } else { return "\(size) B" } } private struct AutomaticDownloadPeers { let privateChats: Bool let groups: Bool let channels: Bool let size: Int32? init(category: AutomaticMediaDownloadCategoryPeers) { self.privateChats = category.privateChats self.groups = category.groupChats self.channels = category.channels self.size = category.fileSize } } private func stringForAutomaticDownloadPeers(peers: AutomaticDownloadPeers, category: AutomaticDownloadCategory) -> String { var size: String? if var peersSize = peers.size, category == .video || category == .file { if peersSize == Int32.max { peersSize = 1536 * 1024 * 1024 } size = autodownloadDataSizeString(Int64(peersSize)) } if peers.privateChats && peers.groups && peers.channels { if let size = size { return strings().autoDownloadSettingsUpToForAll(size) } else { return strings().autoDownloadSettingsOnForAll } } else { var types: [String] = [] if peers.privateChats { types.append(strings().autoDownloadSettingsTypePrivateChats) } if peers.groups { types.append(strings().autoDownloadSettingsTypeGroupChats) } if peers.channels { types.append(strings().autoDownloadSettingsTypeChannels) } if types.isEmpty { return strings().autoDownloadSettingsOffForAll } var string: String = "" for i in 0 ..< types.count { if !string.isEmpty { if i == types.count - 1 { string.append(strings().autoDownloadSettingsLastDelimeter) } else { string.append(strings().autoDownloadSettingsDelimeter) } } string.append(types[i]) } if let size = size { return strings().autoDownloadSettingsUpToFor(size, string) } else { return strings().autoDownloadSettingsOnFor(string) } } } enum AutomaticDownloadCategory { case photo case video case file } private enum AutomaticDownloadPeerType { case contact case otherPrivate case group case channel } private final class DataAndStorageControllerArguments { let openStorageUsage: () -> Void let openNetworkUsage: () -> Void let openCategorySettings: (AutomaticMediaDownloadCategoryPeers, String) -> Void let toggleAutomaticDownload:(Bool) -> Void let resetDownloadSettings:()->Void let selectDownloadFolder: ()->Void let toggleAutoplayGifs:(Bool) -> Void let toggleAutoplayVideos:(Bool) -> Void let toggleAutoplaySoundOnHover:(Bool) -> Void let openProxySettings:()->Void init(openStorageUsage: @escaping () -> Void, openNetworkUsage: @escaping () -> Void, openCategorySettings: @escaping(AutomaticMediaDownloadCategoryPeers, String) -> Void, toggleAutomaticDownload:@escaping(Bool) -> Void, resetDownloadSettings:@escaping()->Void, selectDownloadFolder: @escaping() -> Void, toggleAutoplayGifs: @escaping(Bool) -> Void, toggleAutoplayVideos:@escaping(Bool) -> Void, toggleAutoplaySoundOnHover:@escaping(Bool) -> Void, openProxySettings: @escaping()->Void) { self.openStorageUsage = openStorageUsage self.openNetworkUsage = openNetworkUsage self.openCategorySettings = openCategorySettings self.toggleAutomaticDownload = toggleAutomaticDownload self.resetDownloadSettings = resetDownloadSettings self.selectDownloadFolder = selectDownloadFolder self.toggleAutoplayGifs = toggleAutoplayGifs self.toggleAutoplayVideos = toggleAutoplayVideos self.toggleAutoplaySoundOnHover = toggleAutoplaySoundOnHover self.openProxySettings = openProxySettings } } private enum DataAndStorageSection: Int32 { case usage case automaticPhotoDownload case automaticVoiceDownload case automaticInstantVideoDownload case voiceCalls case other } private enum DataAndStorageEntry: TableItemListNodeEntry { case storageUsage(Int32, String, viewType: GeneralViewType) case networkUsage(Int32, String, viewType: GeneralViewType) case automaticMediaDownloadHeader(Int32, String, viewType: GeneralViewType) case automaticDownloadMedia(Int32, Bool, viewType: GeneralViewType) case photos(Int32, AutomaticMediaDownloadCategoryPeers, Bool, viewType: GeneralViewType) case videos(Int32, AutomaticMediaDownloadCategoryPeers, Bool, Int32?, viewType: GeneralViewType) case files(Int32, AutomaticMediaDownloadCategoryPeers, Bool, Int32?, viewType: GeneralViewType) case voice(Int32, AutomaticMediaDownloadCategoryPeers, Bool, viewType: GeneralViewType) case instantVideo(Int32, AutomaticMediaDownloadCategoryPeers, Bool, viewType: GeneralViewType) case gifs(Int32, AutomaticMediaDownloadCategoryPeers, Bool, viewType: GeneralViewType) case autoplayHeader(Int32, viewType: GeneralViewType) case autoplayGifs(Int32, Bool, viewType: GeneralViewType) case autoplayVideos(Int32, Bool, viewType: GeneralViewType) case soundOnHover(Int32, Bool, viewType: GeneralViewType) case soundOnHoverDesc(Int32, viewType: GeneralViewType) case resetDownloadSettings(Int32, Bool, viewType: GeneralViewType) case downloadFolder(Int32, String, viewType: GeneralViewType) case proxyHeader(Int32) case proxySettings(Int32, String, viewType: GeneralViewType) case sectionId(Int32) var stableId: Int32 { switch self { case .storageUsage: return 0 case .networkUsage: return 1 case .automaticMediaDownloadHeader: return 2 case .automaticDownloadMedia: return 3 case .photos: return 4 case .videos: return 5 case .files: return 6 case .voice: return 7 case .instantVideo: return 8 case .gifs: return 9 case .resetDownloadSettings: return 10 case .downloadFolder: return 11 case .autoplayHeader: return 12 case .autoplayGifs: return 13 case .autoplayVideos: return 14 case .soundOnHover: return 15 case .soundOnHoverDesc: return 16 case .proxyHeader: return 17 case .proxySettings: return 18 case let .sectionId(sectionId): return (sectionId + 1) * 1000 - sectionId } } var index:Int32 { switch self { case .storageUsage(let sectionId, _, _): return (sectionId * 1000) + stableId case .networkUsage(let sectionId, _, _): return (sectionId * 1000) + stableId case .automaticMediaDownloadHeader(let sectionId, _, _): return (sectionId * 1000) + stableId case .automaticDownloadMedia(let sectionId, _, _): return (sectionId * 1000) + stableId case let .photos(sectionId, _, _, _): return (sectionId * 1000) + stableId case let .videos(sectionId, _, _, _, _): return (sectionId * 1000) + stableId case let .files(sectionId, _, _, _, _): return (sectionId * 1000) + stableId case let .voice(sectionId, _, _, _): return (sectionId * 1000) + stableId case let .instantVideo(sectionId, _, _, _): return (sectionId * 1000) + stableId case let .gifs(sectionId, _, _, _): return (sectionId * 1000) + stableId case let .resetDownloadSettings(sectionId, _, _): return (sectionId * 1000) + stableId case let .autoplayHeader(sectionId, _): return (sectionId * 1000) + stableId case let .autoplayGifs(sectionId, _, _): return (sectionId * 1000) + stableId case let .autoplayVideos(sectionId, _, _): return (sectionId * 1000) + stableId case let .soundOnHover(sectionId, _, _): return (sectionId * 1000) + stableId case let .soundOnHoverDesc(sectionId, _): return (sectionId * 1000) + stableId case let .downloadFolder(sectionId, _, _): return (sectionId * 1000) + stableId case let .proxyHeader(sectionId): return sectionId case let .proxySettings(sectionId, _, _): return sectionId case let .sectionId(sectionId): return (sectionId + 1) * 1000 - sectionId } } static func <(lhs: DataAndStorageEntry, rhs: DataAndStorageEntry) -> Bool { return lhs.index < rhs.index } func item(_ arguments: DataAndStorageControllerArguments, initialSize: NSSize) -> TableRowItem { switch self { case let .storageUsage(_, text, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: text, type: .next, viewType: viewType, action: { arguments.openStorageUsage() }) case let .networkUsage(_, text, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: text, type: .next, viewType: viewType, action: { arguments.openNetworkUsage() }) case let .automaticMediaDownloadHeader(_, text, viewType): return GeneralTextRowItem(initialSize, stableId: stableId, text: text, viewType: viewType) case let .automaticDownloadMedia(_ , value, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().dataAndStorageAutomaticDownload, type: .switchable(value), viewType: viewType, action: { arguments.toggleAutomaticDownload(!value) }) case let .photos(_, category, enabled, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().dataAndStorageAutomaticDownloadPhoto, description: stringForAutomaticDownloadPeers(peers: AutomaticDownloadPeers(category: category), category: .photo), type: .next, viewType: viewType, action: { arguments.openCategorySettings(category, strings().dataAndStorageAutomaticDownloadPhoto) }, enabled: enabled) case let .videos(_, category, enabled, _, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().dataAndStorageAutomaticDownloadVideo, description: stringForAutomaticDownloadPeers(peers: AutomaticDownloadPeers(category: category), category: .video), type: .next, viewType: viewType, action: { arguments.openCategorySettings(category, strings().dataAndStorageAutomaticDownloadVideo) }, enabled: enabled) case let .files(_, category, enabled, _, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().dataAndStorageAutomaticDownloadFiles, description: stringForAutomaticDownloadPeers(peers: AutomaticDownloadPeers(category: category), category: .file), type: .next, viewType: viewType, action: { arguments.openCategorySettings(category, strings().dataAndStorageAutomaticDownloadFiles) }, enabled: enabled) case let .voice(_, category, enabled, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().dataAndStorageAutomaticDownloadVoice, type: .next, viewType: viewType, action: { arguments.openCategorySettings(category, strings().dataAndStorageAutomaticDownloadVoice) }, enabled: enabled) case let .instantVideo(_, category, enabled, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().dataAndStorageAutomaticDownloadInstantVideo, type: .next, viewType: viewType, action: { arguments.openCategorySettings(category, strings().dataAndStorageAutomaticDownloadInstantVideo) }, enabled: enabled) case let .gifs(_, category, enabled, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().dataAndStorageAutomaticDownloadGIFs, type: .next, viewType: viewType, action: { arguments.openCategorySettings(category, strings().dataAndStorageAutomaticDownloadGIFs) }, enabled: enabled) case let .resetDownloadSettings(_, enabled, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().dataAndStorageAutomaticDownloadReset, nameStyle: ControlStyle(font: .normal(.title), foregroundColor: theme.colors.accent), type: .none, viewType: viewType, action: { arguments.resetDownloadSettings() }, enabled: enabled) case let .downloadFolder(_, path, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().dataAndStorageDownloadFolder, type: .context(path), viewType: viewType, action: { arguments.selectDownloadFolder() }) case let .autoplayHeader(_, viewType): return GeneralTextRowItem(initialSize, stableId: stableId, text: strings().dataAndStorageAutoplayHeader, viewType: viewType) case let .autoplayGifs(_, value, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().dataAndStorageAutoplayGIFs, type: .switchable(value), viewType: viewType, action: { arguments.toggleAutoplayGifs(!value) }) case let .autoplayVideos(_, value, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().dataAndStorageAutoplayVideos, type: .switchable(value), viewType: viewType, action: { arguments.toggleAutoplayVideos(!value) }) case let .soundOnHover(_, value, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().dataAndStorageAutoplaySoundOnHover, type: .switchable(value), viewType: viewType, action: { arguments.toggleAutoplaySoundOnHover(!value) }) case let .soundOnHoverDesc(_, viewType): return GeneralTextRowItem(initialSize, stableId: stableId, text: strings().dataAndStorageAutoplaySoundOnHoverDesc, viewType: viewType) case .proxyHeader: return GeneralTextRowItem(initialSize, stableId: stableId, text: strings().privacySettingsProxyHeader, viewType: .textTopItem) case let .proxySettings(_, text, viewType): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: strings().privacySettingsUseProxy, type: .nextContext(text), viewType: viewType, action: { arguments.openProxySettings() }) default: return GeneralRowItem(initialSize, height: 30, stableId: stableId, viewType: .separator) } } } private struct DataAndStorageControllerState: Equatable { static func ==(lhs: DataAndStorageControllerState, rhs: DataAndStorageControllerState) -> Bool { return true } } private struct DataAndStorageData: Equatable { let automaticMediaDownloadSettings: AutomaticMediaDownloadSettings let voiceCallSettings: VoiceCallSettings init(automaticMediaDownloadSettings: AutomaticMediaDownloadSettings, voiceCallSettings: VoiceCallSettings) { self.automaticMediaDownloadSettings = automaticMediaDownloadSettings self.voiceCallSettings = voiceCallSettings } static func ==(lhs: DataAndStorageData, rhs: DataAndStorageData) -> Bool { return lhs.automaticMediaDownloadSettings == rhs.automaticMediaDownloadSettings && lhs.voiceCallSettings == rhs.voiceCallSettings } } private func dataAndStorageControllerEntries(state: DataAndStorageControllerState, data: DataAndStorageData, proxy: ProxySettings, autoplayMedia: AutoplayMediaPreferences) -> [DataAndStorageEntry] { var entries: [DataAndStorageEntry] = [] var sectionId:Int32 = 1 entries.append(.sectionId(sectionId)) sectionId += 1 entries.append(.storageUsage(sectionId, strings().dataAndStorageStorageUsage, viewType: .firstItem)) entries.append(.networkUsage(sectionId, strings().dataAndStorageNetworkUsage, viewType: .lastItem)) entries.append(.sectionId(sectionId)) sectionId += 1 entries.append(.automaticMediaDownloadHeader(sectionId, strings().dataAndStorageAutomaticDownloadHeader, viewType: .textTopItem)) entries.append(.automaticDownloadMedia(sectionId, data.automaticMediaDownloadSettings.automaticDownload, viewType: .firstItem)) entries.append(.photos(sectionId, data.automaticMediaDownloadSettings.categories.photo, data.automaticMediaDownloadSettings.automaticDownload, viewType: .innerItem)) entries.append(.videos(sectionId, data.automaticMediaDownloadSettings.categories.video, data.automaticMediaDownloadSettings.automaticDownload, data.automaticMediaDownloadSettings.categories.video.fileSize, viewType: .innerItem)) entries.append(.files(sectionId, data.automaticMediaDownloadSettings.categories.files, data.automaticMediaDownloadSettings.automaticDownload, data.automaticMediaDownloadSettings.categories.files.fileSize, viewType: .innerItem)) entries.append(.resetDownloadSettings(sectionId, data.automaticMediaDownloadSettings != AutomaticMediaDownloadSettings.defaultSettings, viewType: .lastItem)) entries.append(.sectionId(sectionId)) sectionId += 1 entries.append(.downloadFolder(sectionId, data.automaticMediaDownloadSettings.downloadFolder, viewType: .singleItem)) entries.append(.sectionId(sectionId)) sectionId += 1 entries.append(.autoplayHeader(sectionId, viewType: .textTopItem)) entries.append(.autoplayGifs(sectionId, autoplayMedia.gifs, viewType: .firstItem)) entries.append(.autoplayVideos(sectionId, autoplayMedia.videos, viewType: .lastItem)) entries.append(.sectionId(sectionId)) sectionId += 1 entries.append(.proxyHeader(sectionId)) let text: String if let active = proxy.activeServer, proxy.enabled { switch active.connection { case .socks5: text = strings().proxySettingsSocks5 case .mtp: text = strings().proxySettingsMTP } } else { text = strings().proxySettingsDisabled } entries.append(.proxySettings(sectionId, text, viewType: .singleItem)) entries.append(.sectionId(sectionId)) sectionId += 1 return entries } private func prepareTransition(left:[AppearanceWrapperEntry<DataAndStorageEntry>], right: [AppearanceWrapperEntry<DataAndStorageEntry>], initialSize: NSSize, arguments: DataAndStorageControllerArguments) -> TableUpdateTransition { let (removed, inserted, updated) = proccessEntriesWithoutReverse(left, right: right) { entry -> TableRowItem in return entry.entry.item(arguments, initialSize: initialSize) } return TableUpdateTransition(deleted: removed, inserted: inserted, updated: updated, animated: true) } class DataAndStorageViewController: TableViewController { private let disposable = MetaDisposable() private var focusOnItemTag: DataAndStorageEntryTag? init(_ context: AccountContext, focusOnItemTag: DataAndStorageEntryTag? = nil) { self.focusOnItemTag = focusOnItemTag super.init(context) } override func viewDidLoad() { super.viewDidLoad() let context = self.context let initialState = DataAndStorageControllerState() let initialSize = self.atomicSize let statePromise = ValuePromise(initialState, ignoreRepeated: true) let stateValue = Atomic(value: initialState) let updateState: ((DataAndStorageControllerState) -> DataAndStorageControllerState) -> Void = { f in statePromise.set(stateValue.modify { f($0) }) } let pushControllerImpl:(ViewController)->Void = { [weak self] controller in self?.navigationController?.push(controller) } let previous:Atomic<[AppearanceWrapperEntry<DataAndStorageEntry>]> = Atomic(value: []) let actionsDisposable = DisposableSet() let dataAndStorageDataPromise = Promise<DataAndStorageData>() dataAndStorageDataPromise.set(combineLatest(context.account.postbox.preferencesView(keys: [ApplicationSpecificPreferencesKeys.automaticMediaDownloadSettings]), voiceCallSettings(context.sharedContext.accountManager)) |> map { view, voiceCallSettings -> DataAndStorageData in let automaticMediaDownloadSettings: AutomaticMediaDownloadSettings = view.values[ApplicationSpecificPreferencesKeys.automaticMediaDownloadSettings]?.get(AutomaticMediaDownloadSettings.self) ?? AutomaticMediaDownloadSettings.defaultSettings return DataAndStorageData(automaticMediaDownloadSettings: automaticMediaDownloadSettings, voiceCallSettings: voiceCallSettings) }) let arguments = DataAndStorageControllerArguments(openStorageUsage: { pushControllerImpl(StorageUsageController(context)) }, openNetworkUsage: { pushControllerImpl(networkUsageStatsController(context: context)) }, openCategorySettings: { category, title in pushControllerImpl(DownloadSettingsViewController(context, category, title, updateCategory: { category in _ = updateMediaDownloadSettingsInteractively(postbox: context.account.postbox, { current -> AutomaticMediaDownloadSettings in switch title { case strings().dataAndStorageAutomaticDownloadPhoto: return current.withUpdatedCategories(current.categories.withUpdatedPhoto(category)) case strings().dataAndStorageAutomaticDownloadVideo: return current.withUpdatedCategories(current.categories.withUpdatedVideo(category)) case strings().dataAndStorageAutomaticDownloadFiles: return current.withUpdatedCategories(current.categories.withUpdatedFiles(category)) case strings().dataAndStorageAutomaticDownloadVoice: return current.withUpdatedCategories(current.categories.withUpdatedVoice(category)) case strings().dataAndStorageAutomaticDownloadInstantVideo: return current.withUpdatedCategories(current.categories.withUpdatedInstantVideo(category)) case strings().dataAndStorageAutomaticDownloadGIFs: return current.withUpdatedCategories(current.categories.withUpdatedGif(category)) default: return current } }).start() })) }, toggleAutomaticDownload: { enabled in _ = updateMediaDownloadSettingsInteractively(postbox: context.account.postbox, { current -> AutomaticMediaDownloadSettings in return current.withUpdatedAutomaticDownload(enabled) }).start() }, resetDownloadSettings: { _ = (confirmSignal(for: context.window, header: appName, information: strings().dataAndStorageConfirmResetSettings, okTitle: strings().modalOK, cancelTitle: strings().modalCancel) |> filter {$0} |> mapToSignal { _ -> Signal<Void, NoError> in return updateMediaDownloadSettingsInteractively(postbox: context.account.postbox, { _ -> AutomaticMediaDownloadSettings in return AutomaticMediaDownloadSettings.defaultSettings }) }).start() }, selectDownloadFolder: { selectFolder(for: context.window, completion: { newPath in _ = updateMediaDownloadSettingsInteractively(postbox: context.account.postbox, { current -> AutomaticMediaDownloadSettings in return current.withUpdatedDownloadFolder(newPath) }).start() }) }, toggleAutoplayGifs: { enable in _ = updateAutoplayMediaSettingsInteractively(postbox: context.account.postbox, { return $0.withUpdatedAutoplayGifs(enable) }).start() }, toggleAutoplayVideos: { enable in _ = updateAutoplayMediaSettingsInteractively(postbox: context.account.postbox, { return $0.withUpdatedAutoplayVideos(enable) }).start() }, toggleAutoplaySoundOnHover: { enable in _ = updateAutoplayMediaSettingsInteractively(postbox: context.account.postbox, { return $0.withUpdatedAutoplaySoundOnHover(enable) }).start() }, openProxySettings: { let controller = proxyListController(accountManager: context.sharedContext.accountManager, network: context.account.network, share: { servers in var message: String = "" for server in servers { message += server.link + "\n\n" } message = message.trimmed showModal(with: ShareModalController(ShareLinkObject(context, link: message)), for: context.window) }, pushController: { controller in pushControllerImpl(controller) }) pushControllerImpl(controller) }) let proxy:Signal<ProxySettings, NoError> = proxySettings(accountManager: context.sharedContext.accountManager) let signal = combineLatest(queue: .mainQueue(), statePromise.get(), dataAndStorageDataPromise.get(), appearanceSignal, proxy, autoplayMediaSettings(postbox: context.account.postbox)) |> map { state, dataAndStorageData, appearance, proxy, autoplayMediaSettings -> TableUpdateTransition in let entries = dataAndStorageControllerEntries(state: state, data: dataAndStorageData, proxy: proxy, autoplayMedia: autoplayMediaSettings).map {AppearanceWrapperEntry(entry: $0, appearance: appearance)} return prepareTransition(left: previous.swap(entries), right: entries, initialSize: initialSize.modify({$0}), arguments: arguments) } |> beforeNext { [weak self] _ in self?.readyOnce() } |> afterDisposed { actionsDisposable.dispose() } |> deliverOnMainQueue self.disposable.set(signal.start(next: { [weak self] transition in self?.genericView.merge(with: transition) self?.readyOnce() if let focusOnItemTag = self?.focusOnItemTag { self?.genericView.scroll(to: .center(id: focusOnItemTag.stableId, innerId: nil, animated: true, focus: .init(focus: true), inset: 0), inset: NSEdgeInsets()) self?.focusOnItemTag = nil } })) } deinit { disposable.dispose() } override func getRightBarViewOnce() -> BarView { return BarView(20, controller: self) } }
gpl-2.0
a510442eb7a4850278cbb774173d765a
46.672727
490
0.669891
5.10207
false
false
false
false
Witcast/witcast-ios
Pods/Material/Sources/iOS/BottomNavigationController.swift
1
5326
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit extension UIViewController { /** A convenience property that provides access to the BottomNavigationController. This is the recommended method of accessing the BottomNavigationController through child UIViewControllers. */ public var bottomNavigationController: BottomNavigationController? { var viewController: UIViewController? = self while nil != viewController { if viewController is BottomNavigationController { return viewController as? BottomNavigationController } viewController = viewController?.parent } return nil } } open class BottomNavigationController: UITabBarController { /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** An initializer that initializes the object with an Optional nib and bundle. - Parameter nibNameOrNil: An Optional String for the nib. - Parameter bundle: An Optional NSBundle where the nib is located. */ public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } /// An initializer that accepts no parameters. public init() { super.init(nibName: nil, bundle: nil) } /** An initializer that initializes the object an Array of UIViewControllers. - Parameter viewControllers: An Array of UIViewControllers. */ public init(viewControllers: [UIViewController]) { super.init(nibName: nil, bundle: nil) self.viewControllers = viewControllers } open override func viewDidLoad() { super.viewDidLoad() prepare() } open override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() layoutSubviews() } /** To execute in the order of the layout chain, override this method. `layoutSubviews` should be called immediately, unless you have a certain need. */ open func layoutSubviews() { if let v = tabBar.items { for item in v { if .phone == Device.userInterfaceIdiom { if nil == item.title { let inset: CGFloat = 7 item.imageInsets = UIEdgeInsetsMake(inset, 0, -inset, 0) } else { let inset: CGFloat = 6 item.titlePositionAdjustment.vertical = -inset } } else { if nil == item.title { let inset: CGFloat = 9 item.imageInsets = UIEdgeInsetsMake(inset, 0, -inset, 0) } else { let inset: CGFloat = 3 item.imageInsets = UIEdgeInsetsMake(inset, 0, -inset, 0) item.titlePositionAdjustment.vertical = -inset } } } } tabBar.layoutDivider() } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open func prepare() { view.clipsToBounds = true view.backgroundColor = .white view.contentScaleFactor = Screen.scale prepareTabBar() } } fileprivate extension BottomNavigationController { /// Prepares the tabBar. func prepareTabBar() { tabBar.isTranslucent = false tabBar.heightPreset = .normal tabBar.dividerColor = Color.grey.lighten3 tabBar.dividerAlignment = .top let image = UIImage() tabBar.shadowImage = image tabBar.backgroundImage = image tabBar.backgroundColor = .white } }
apache-2.0
2996ed84a778982563454fd27fba1984
33.584416
88
0.697146
4.763864
false
false
false
false
tectijuana/patrones
Bloque1SwiftArchivado/PracticasSwift/OrtegaAshley/Practica4.swift
1
1048
// "Instituto Tecnologico de Tijuana", // "Semestre Enero-Junio 2017", // "Patrones de Diseño", // "Ortega Rodriguez Ashley Karina 12211430", // "Encontrar los angulos de un triangulo rectangulo de lados 3, 4 y 5, llegando hasta el minuto mas cercano" //Librería para utilizar funciones trigonométricas import Foundation //Declaración de variables var lado1: Float = 3 var lado2: Float = 4 var lado3: Float = 5 var angulo3: Float = 90 //Operaciones para calcular ángulo 1 var angulo1 = asin(lado1/lado3) * 180 / Float.pi var min1 = (angulo1 - 36) * 60 var seg1 = (min1 - 52) * 60 //Operaciones para calcular ángulo 2 var angulo2 = 90 - angulo1 var min2 = (angulo2 - 53) * 60 var seg2 = (min2 - 7) * 60 //Desliegue de resultados print("Ángulo 1: \(String(format:"%.0f", angulo1))° \(String(format:"%.0f", min1))\" \(String(format:"%.0f", seg1))\'") print("Ángulo 2: \(String(format:"%.0f", angulo2))° \(String(format:"%.0f", min2))\" \(String(format:"%.0f", seg2))\'") print("Ángulo 3: \(String(format:"%.0f", angulo3))°")
gpl-3.0
154d2160c78e5f878121e6e785143d26
34.724138
119
0.67278
2.663239
false
false
false
false
leancloud/objc-sdk
AVOS/LeanCloudObjcTests/IMMessageTestCase.swift
1
8572
// // IMMessageTestCase.swift // LeanCloudObjcTests // // Created by pzheng on 2021/01/25. // Copyright © 2021 LeanCloud Inc. All rights reserved. // import XCTest @testable import LeanCloudObjc class IMMessageTestCase: RTMBaseTestCase { func testSendMessageToChatRoom() { guard let client1 = newOpenedClient(clientIDSuffix: "1") else { XCTFail() return } IMMessageTestCase.purgeConnectionRegistry() guard let client2 = newOpenedClient(clientIDSuffix: "2"), let client3 = newOpenedClient(clientIDSuffix: "3") else { XCTFail() return } RTMBaseTestCase.purgeConnectionRegistry() guard let client4 = newOpenedClient(clientIDSuffix: "4") else { XCTFail() return } let delegator1 = LCIMClientDelegator() client1.delegate = delegator1 let delegator2 = LCIMClientDelegator() client2.delegate = delegator2 let delegator3 = LCIMClientDelegator() client3.delegate = delegator3 let delegator4 = LCIMClientDelegator() client4.delegate = delegator4 var chatRoom1: LCIMChatRoom? var chatRoom2: LCIMChatRoom? var chatRoom3: LCIMChatRoom? var chatRoom4: LCIMChatRoom? expecting(count: 7) { (exp) in client1.createChatRoom() { (chatRoom, error) in XCTAssertNil(error) chatRoom1 = chatRoom exp.fulfill() if let ID = chatRoom1?.conversationId { client2.conversationQuery().getConversationById(ID) { (conv, error) in XCTAssertNil(error) chatRoom2 = conv as? LCIMChatRoom exp.fulfill() chatRoom2?.join(callback: { (success, error) in XCTAssertTrue(success) XCTAssertNil(error) exp.fulfill() client3.conversationQuery().getConversationById(ID) { (conv, error) in XCTAssertNil(error) chatRoom3 = conv as? LCIMChatRoom exp.fulfill() chatRoom3?.join(callback: { (success, error) in XCTAssertTrue(success) XCTAssertNil(error) exp.fulfill() client4.conversationQuery().getConversationById(ID) { (conv, error) in XCTAssertNil(error) chatRoom4 = conv as? LCIMChatRoom exp.fulfill() chatRoom4?.join(callback: { (success, error) in XCTAssertTrue(success) XCTAssertNil(error) exp.fulfill() }) } }) } }) } } } } delay() expecting(count: 8) { (exp) in delegator1.didReceiveTypedMessage = { _, _ in exp.fulfill() } delegator2.didReceiveTypedMessage = { _, _ in exp.fulfill() } delegator3.didReceiveTypedMessage = { _, _ in exp.fulfill() } delegator4.didReceiveTypedMessage = { _, _ in exp.fulfill() } let options = LCIMMessageOption() options.priority = .high chatRoom1?.send(LCIMTextMessage(text: "1", attributes: nil), option: options, callback: { (success, error) in XCTAssertTrue(success) XCTAssertNil(error) exp.fulfill() chatRoom2?.send(LCIMTextMessage(text: "2", attributes: nil), option: options, callback: { (success, error) in XCTAssertTrue(success) XCTAssertNil(error) exp.fulfill() }) }) } delegator1.reset() delegator2.reset() delegator3.reset() delegator4.reset() } func testUpdateAndRecallMessage() { guard let client1 = newOpenedClient(clientIDSuffix: "1"), let client2 = newOpenedClient(clientIDSuffix: "2") else { XCTFail() return } let delegator1 = LCIMClientDelegator() client1.delegate = delegator1 let delegator2 = LCIMClientDelegator() client2.delegate = delegator2 var conv: LCIMConversation? expecting { exp in client1.createConversation(withClientIds: [client2.clientId]) { conversation, error in if let conversation = conversation { conv = conversation exp.fulfill() } else { XCTAssertNil(error) } } } let oldMessage = LCIMTextMessage(text: "old") expecting(description: "send message", count: 2) { exp in delegator2.didReceiveTypedMessage = { conversation, message in exp.fulfill() } conv?.send(oldMessage, callback: { succeeded, error in if succeeded { exp.fulfill() } else { XCTAssertNil(error) } }) } delay() let newMessage = LCIMTextMessage(text: "new") expecting(description: "update message", count: 2) { exp in delegator2.messageHasBeenUpdated = { conversation, message, _ in exp.fulfill() } conv?.update(oldMessage, toNewMessage: newMessage, callback: { succeeded, error in if succeeded { exp.fulfill() } else { XCTAssertNil(error) } }) } delay() expecting(description: "recall message", count: 2) { exp in delegator2.messageHasBeenRecalled = { conversation, message, _ in exp.fulfill() } conv?.recall(newMessage, callback: { succeeded, error, recalledMessage in if succeeded { XCTAssertNotNil(recalledMessage) exp.fulfill() } else { XCTAssertNil(error) } }) } } func testMessageCache() { guard let client1 = newOpenedClient(clientIDSuffix: "1") else { XCTFail() return } var conv: LCIMConversation? expecting { exp in client1.createConversation(withClientIds: [uuid]) { conversation, error in if let conversation = conversation { conv = conversation exp.fulfill() } else { XCTAssertNil(error) } } } delay() let failedMessage = LCIMTextMessage(text: "failed") failedMessage.status = .failed conv?.addMessage(toCache: failedMessage) let result = conv?.queryMessagesFromCache(withLimit: 10) XCTAssertEqual(result?.count, 1) XCTAssertEqual((result?.first as? LCIMMessage)?.status, .failed) } } extension IMMessageTestCase { func newOpenedClient( clientID: String? = nil, clientIDSuffix: String? = nil) -> LCIMClient? { var ID = clientID ?? uuid if let suffix = clientIDSuffix { ID += "-\(suffix)" } var client: LCIMClient? = try! LCIMClient(clientId: ID) expecting { (exp) in client?.open(callback: { (success, error) in XCTAssertTrue(success) XCTAssertNil(error) if !success { client = nil } exp.fulfill() }) } return client } }
apache-2.0
80f5689443cb3a701c874af0b2d189d5
34.271605
125
0.47299
5.383794
false
false
false
false
huonw/swift
stdlib/public/core/FlatMap.swift
2
5200
//===--- FlatMap.swift ----------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension LazySequenceProtocol { /// Returns the concatenated results of mapping the given transformation over /// this sequence. /// /// Use this method to receive a single-level sequence when your /// transformation produces a sequence or collection for each element. /// Calling `flatMap(_:)` on a sequence `s` is equivalent to calling /// `s.map(transform).joined()`. /// /// - Complexity: O(1) @inlinable // FIXME(sil-serialize-all) public func flatMap<SegmentOfResult>( _ transform: @escaping (Elements.Element) -> SegmentOfResult ) -> LazySequence< FlattenSequence<LazyMapSequence<Elements, SegmentOfResult>>> { return self.map(transform).joined() } /// Returns the non-`nil` results of mapping the given transformation over /// this sequence. /// /// Use this method to receive a sequence of nonoptional values when your /// transformation produces an optional value. /// /// - Parameter transform: A closure that accepts an element of this sequence /// as its argument and returns an optional value. /// /// - Complexity: O(1) @inlinable // FIXME(sil-serialize-all) public func compactMap<ElementOfResult>( _ transform: @escaping (Elements.Element) -> ElementOfResult? ) -> LazyMapSequence< LazyFilterSequence< LazyMapSequence<Elements, ElementOfResult?>>, ElementOfResult > { return self.map(transform).filter { $0 != nil }.map { $0! } } /// Returns the non-`nil` results of mapping the given transformation over /// this sequence. /// /// Use this method to receive a sequence of nonoptional values when your /// transformation produces an optional value. /// /// - Parameter transform: A closure that accepts an element of this sequence /// as its argument and returns an optional value. /// /// - Complexity: O(1) @inline(__always) @available(swift, deprecated: 4.1, renamed: "compactMap(_:)", message: "Please use compactMap(_:) for the case where closure returns an optional value") public func flatMap<ElementOfResult>( _ transform: @escaping (Elements.Element) -> ElementOfResult? ) -> LazyMapSequence< LazyFilterSequence< LazyMapSequence<Elements, ElementOfResult?>>, ElementOfResult > { return self.compactMap(transform) } } extension LazyCollectionProtocol { /// Returns the concatenated results of mapping the given transformation over /// this collection. /// /// Use this method to receive a single-level collection when your /// transformation produces a collection for each element. /// Calling `flatMap(_:)` on a collection `c` is equivalent to calling /// `c.map(transform).joined()`. /// /// - Complexity: O(1) @inlinable // FIXME(sil-serialize-all) public func flatMap<SegmentOfResult>( _ transform: @escaping (Elements.Element) -> SegmentOfResult ) -> LazyCollection< FlattenCollection< LazyMapCollection<Elements, SegmentOfResult>> > { return self.map(transform).joined() } /// Returns the non-`nil` results of mapping the given transformation over /// this collection. /// /// Use this method to receive a collection of nonoptional values when your /// transformation produces an optional value. /// /// - Parameter transform: A closure that accepts an element of this /// collection as its argument and returns an optional value. /// /// - Complexity: O(1) @inlinable // FIXME(sil-serialize-all) public func compactMap<ElementOfResult>( _ transform: @escaping (Elements.Element) -> ElementOfResult? ) -> LazyMapCollection< LazyFilterCollection< LazyMapCollection<Elements, ElementOfResult?>>, ElementOfResult > { return self.map(transform).filter { $0 != nil }.map { $0! } } /// Returns the non-`nil` results of mapping the given transformation over /// this collection. /// /// Use this method to receive a collection of nonoptional values when your /// transformation produces an optional value. /// /// - Parameter transform: A closure that accepts an element of this /// collection as its argument and returns an optional value. /// /// - Complexity: O(1) @available(swift, deprecated: 4.1, renamed: "compactMap(_:)", message: "Please use compactMap(_:) for the case where closure returns an optional value") @inlinable // FIXME(sil-serialize-all) public func flatMap<ElementOfResult>( _ transform: @escaping (Elements.Element) -> ElementOfResult? ) -> LazyMapCollection< LazyFilterCollection< LazyMapCollection<Elements, ElementOfResult?>>, ElementOfResult > { return self.map(transform).filter { $0 != nil }.map { $0! } } }
apache-2.0
008402a6091dc97337eed1fb0261da32
36.410072
94
0.676154
4.748858
false
false
false
false
ifyoudieincanada/above-average
CoursesListViewController.swift
1
4811
// // CoursesListViewController.swift // above-average // // Created by Kyra Drake on 1/15/16. // Copyright © 2016 Kyra Drake. All rights reserved. // import UIKit //semesterArrayIndex class CoursesListViewController: UIViewController, UITableViewDelegate { @IBOutlet weak var menuButton: UIBarButtonItem! @IBOutlet weak var semesterCoursesTable: UITableView! @IBOutlet weak var semesterNameLabel: UILabel! func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if semesterArray.count == 0 { return 0 } else { return semesterArray[semesterArrayIndex].courses.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") cell.accessoryType = .DetailDisclosureButton cell.textLabel?.text = semesterArray[semesterArrayIndex].courses[indexPath.row].name + " " + String(semesterArray[semesterArrayIndex].courses[indexPath.row].overallPercent) return cell } func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) { let index = indexPath.row print(index) print("jkalsnvkdlsankldvkmsaksdnvdlsaksnvkldsnaklsnkglnasklcmlajewkn") courseIndex = index performSegueWithIdentifier("goToCourse", sender: self) } /* func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { //swipee to the left (delete) toDoList.removeAtIndex(indexPath.row) NSUserDefaults.standardUserDefaults().setObject(toDoList, forKey: "toDoList") toDoListTable.reloadData() } } */ override func viewDidAppear(animated: Bool) { semesterCoursesTable.reloadData() //semesterNameLabel.text = semesterArray[semesterArrayIndex].term } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if self.revealViewController() != nil { menuButton.target = self.revealViewController() menuButton.action = "revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } /* import UIKit //var courseArray = [Course]() class CoursesListViewController: UIViewController { //@IBOutlet weak var semesterMenuButton: UIBarButtonItem! @IBOutlet weak var semesterCoursesTable: UITableView! //SEMESTER COURSES TABLE STUFF func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 // return courseArray.count //return number of courses in the semester } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell") cell.textLabel?.text = "cell" //cell.textLabel?.text = courseArray[indexPath.row].name + " " + String(courseArray[indexPath.row].overallPercent) return cell } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == UITableViewCellEditingStyle.Delete { //swipee to the left (delete) //toDoList.removeAtIndex(indexPath.row) //semesterCoursesTable.reloadData() } } override func viewDidAppear(animated: Bool) { semesterCoursesTable.reloadData() } //OTHER STUFF override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. /* if self.revealViewController() != nil { semesterMenuButton.target = self.revealViewController() semesterMenuButton.action = "revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) }*/ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } */
gpl-3.0
b401f3df763b71e2d7b227618d1d5ddf
28.691358
181
0.666112
5.459705
false
false
false
false
mpatelCAS/MDAlamofireCheck
Tests/ResponseTests.swift
1
18896
// ResponseTests.swift // // Copyright (c) 2014–2015 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 class ResponseDataTestCase: BaseTestCase { func testThatResponseDataReturnsSuccessResultWithValidData() { // Given let URLString = "https://httpbin.org/get" let expectation = expectationWithDescription("request should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<NSData>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseData { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertTrue(result.isSuccess, "result should be success") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.data, "result data should be nil") XCTAssertNil(result.error, "result error should be nil") } func testThatResponseDataReturnsFailureResultWithOptionalDataAndError() { // Given let URLString = "https://invalid-url-here.org/this/does/not/exist" let expectation = expectationWithDescription("request should fail with 404") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<NSData>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseData { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNil(response, "response should be nil") XCTAssertTrue(result.isFailure, "result should be a failure") XCTAssertNil(result.value, "result value should not be nil") XCTAssertNotNil(result.data, "result data should be nil") XCTAssertNotNil(result.error, "result error should be nil") } } // MARK: - class ResponseStringTestCase: BaseTestCase { func testThatResponseStringReturnsSuccessResultWithValidString() { // Given let URLString = "https://httpbin.org/get" let expectation = expectationWithDescription("request should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<String>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseString { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertTrue(result.isSuccess, "result should be success") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.data, "result data should be nil") XCTAssertNil(result.error, "result error should be nil") } func testThatResponseStringReturnsFailureResultWithOptionalDataAndError() { // Given let URLString = "https://invalid-url-here.org/this/does/not/exist" let expectation = expectationWithDescription("request should fail with 404") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<String>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseString { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNil(response, "response should be nil") XCTAssertTrue(result.isFailure, "result should be a failure") XCTAssertNil(result.value, "result value should not be nil") XCTAssertNotNil(result.data, "result data should be nil") XCTAssertNotNil(result.error, "result error should be nil") } } // MARK: - class ResponseJSONTestCase: BaseTestCase { func testThatResponseJSONReturnsSuccessResultWithValidJSON() { // Given let URLString = "https://httpbin.org/get" let expectation = expectationWithDescription("request should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<AnyObject>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseJSON { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertTrue(result.isSuccess, "result should be success") XCTAssertNotNil(result.value, "result value should not be nil") XCTAssertNil(result.data, "result data should be nil") XCTAssertNil(result.error, "result error should be nil") } func testThatResponseStringReturnsFailureResultWithOptionalDataAndError() { // Given let URLString = "https://invalid-url-here.org/this/does/not/exist" let expectation = expectationWithDescription("request should fail with 404") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<AnyObject>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseJSON { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNil(response, "response should be nil") XCTAssertTrue(result.isFailure, "result should be a failure") XCTAssertNil(result.value, "result value should not be nil") XCTAssertNotNil(result.data, "result data should be nil") XCTAssertNotNil(result.error, "result error should be nil") } func testThatResponseJSONReturnsSuccessResultForGETRequest() { // Given let URLString = "https://httpbin.org/get" let expectation = expectationWithDescription("request should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<AnyObject>! // When Alamofire.request(.GET, URLString, parameters: ["foo": "bar"]) .responseJSON { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertTrue(result.isSuccess, "result should be success") // The `as NSString` cast is necessary due to a compiler bug. See the following rdar for more info. // - https://openradar.appspot.com/radar?id=5517037090635776 if let args = result.value?["args" as NSString] as? [String: String] { XCTAssertEqual(args, ["foo": "bar"], "args should match parameters") } else { XCTFail("args should not be nil") } } func testThatResponseJSONReturnsSuccessResultForPOSTRequest() { // Given let URLString = "https://httpbin.org/post" let expectation = expectationWithDescription("request should succeed") var request: NSURLRequest? var response: NSHTTPURLResponse? var result: Result<AnyObject>! // When Alamofire.request(.POST, URLString, parameters: ["foo": "bar"]) .responseJSON { responseRequest, responseResponse, responseResult in request = responseRequest response = responseResponse result = responseResult expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertTrue(result.isSuccess, "result should be success") // The `as NSString` cast is necessary due to a compiler bug. See the following rdar for more info. // - https://openradar.appspot.com/radar?id=5517037090635776 if let form = result.value?["form" as NSString] as? [String: String] { XCTAssertEqual(form, ["foo": "bar"], "form should match parameters") } else { XCTFail("form should not be nil") } } } // MARK: - class RedirectResponseTestCase: BaseTestCase { func testThatRequestWillPerformHTTPRedirectionByDefault() { // Given let redirectURLString = "https://www.apple.com" let URLString = "https://httpbin.org/redirect-to?url=\(redirectURLString)" let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)") var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: NSError? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL") XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code") } func testThatRequestWillPerformRedirectionMultipleTimesByDefault() { // Given let redirectURLString = "https://httpbin.org/get" let URLString = "https://httpbin.org/redirect/5" let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)") var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: NSError? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL") XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code") } func testThatTaskOverrideClosureCanPerformHTTPRedirection() { // Given let redirectURLString = "https://www.apple.com" let URLString = "https://httpbin.org/redirect-to?url=\(redirectURLString)" let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)") let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate delegate.taskWillPerformHTTPRedirection = { _, _, _, request in return request } var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: NSError? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL") XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code") } func testThatTaskOverrideClosureCanCancelHTTPRedirection() { // Given let redirectURLString = "https://www.apple.com" let URLString = "https://httpbin.org/redirect-to?url=\(redirectURLString)" let expectation = expectationWithDescription("Request should not redirect to \(redirectURLString)") let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate delegate.taskWillPerformHTTPRedirection = { _, _, _, _ in return nil } var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: NSError? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", URLString, "response URL should match the origin URL") XCTAssertEqual(response?.statusCode ?? -1, 302, "response should have a 302 status code") } func testThatTaskOverrideClosureIsCalledMultipleTimesForMultipleHTTPRedirects() { // Given let redirectURLString = "https://httpbin.org/get" let URLString = "https://httpbin.org/redirect/5" let expectation = expectationWithDescription("Request should redirect to \(redirectURLString)") let delegate: Alamofire.Manager.SessionDelegate = Alamofire.Manager.sharedInstance.delegate var totalRedirectCount = 0 delegate.taskWillPerformHTTPRedirection = { _, _, _, request in ++totalRedirectCount return request } var request: NSURLRequest? var response: NSHTTPURLResponse? var data: NSData? var error: NSError? // When Alamofire.request(.GET, URLString) .response { responseRequest, responseResponse, responseData, responseError in request = responseRequest response = responseResponse data = responseData error = responseError expectation.fulfill() } waitForExpectationsWithTimeout(defaultTimeout, handler: nil) // Then XCTAssertNotNil(request, "request should not be nil") XCTAssertNotNil(response, "response should not be nil") XCTAssertNotNil(data, "data should not be nil") XCTAssertNil(error, "error should be nil") XCTAssertEqual(response?.URL?.URLString ?? "", redirectURLString, "response URL should match the redirect URL") XCTAssertEqual(response?.statusCode ?? -1, 200, "response should have a 200 status code") XCTAssertEqual(totalRedirectCount, 5, "total redirect count should be 5") } }
mit
e027a6508e75b2c2bb08bdf5eb30abfa
38.19917
119
0.652323
5.568523
false
false
false
false
RLovelett/langserver-swift
Sources/BaseProtocol/Types/RequestBuffer.swift
1
2473
// // RequestBuffer.swift // langserver-swift // // Created by Ryan Lovelett on 12/8/16. // // import Foundation #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import os.log private let log = OSLog(subsystem: "me.lovelett.langserver-swift", category: "RequestBuffer") #endif private let terminatorPattern = Data(bytes: [0x0D, 0x0A, 0x0D, 0x0A]) // "\r\n\r\n" public class RequestBuffer { fileprivate var buffer: Data public init(_ data: Data? = nil) { buffer = data ?? Data() } public func append(_ data: Data) { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) os_log("Adding %{iec-bytes}d to the request buffer which has %{iec-bytes}d", log: log, type: .default, data.count, buffer.count) #endif buffer.append(data) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) if let new = String(bytes: data, encoding: .utf8), let buffer = String(bytes: buffer, encoding: .utf8) { os_log("Added: %{public}@", log: log, type: .default, new) os_log("Buffer: %{public}@", log: log, type: .default, buffer) } #endif } public func append(_ data: DispatchData) { data.withUnsafeBytes { [count = data.count] in buffer.append($0, count: count) } } } extension RequestBuffer : IteratorProtocol { public func next() -> Data? { guard !buffer.isEmpty else { return nil } let separatorRange = buffer.range(of: terminatorPattern) ?? (buffer.endIndex..<buffer.endIndex) let extractedData = buffer.subdata(in: buffer.startIndex..<separatorRange.lowerBound) let distance = Header(extractedData).contentLength ?? 0 guard let index = buffer.index(separatorRange.upperBound, offsetBy: distance, limitedBy: buffer.endIndex) else { return nil } defer { buffer.removeSubrange(Range<Data.Index>(buffer.startIndex..<index)) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) let bytes = buffer.startIndex.distance(to: index) os_log("Removing %{iec-bytes}d from the request buffer which has %{iec-bytes}d", log: log, type: .default, bytes, buffer.count) #endif } return buffer.subdata(in: Range<Data.Index>(separatorRange.upperBound..<index)) } } extension RequestBuffer : Sequence { public func makeIterator() -> RequestBuffer { return self } }
apache-2.0
3945641587cf55cebc96d8b6043306aa
31.973333
143
0.612212
3.68006
false
false
false
false
damouse/riffle-swift
Example/Tests/Tests.swift
1
1173
// https://github.com/Quick/Quick import Quick import Nimble import Riffle 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
b2ddee9cd1e98dad0731ed35724cbcd5
22.34
63
0.361611
5.478873
false
false
false
false
schrismartin/dont-shoot-the-messenger
Sources/Library/Services/SCMGameStateManager.swift
1
19616
// // SCMGameManager.swift // the-narrator // // Created by Chris Martin on 11/18/16. // // import Vapor import MongoKitten import HTTP import Foundation public class SCMGameStateManager { public init() { } public func handleIncomingMessage(_ message: FBIncomingMessage) throws { let id = message.senderId guard let manager = SCMDatabaseInstance() else { return } // TODO: Make this unfailable if let messageText = message.text { guard let player = try? manager.retrievePlayer(withId: id) else { try makeNewGame(manager: manager, id: id) return } if messageText == "Buttons" { let buttons = [ FBButton(type: .postback, title: "Button 1", payload: "Button1"), FBButton(type: .postback, title: "Button 2", payload: "Button2"), FBButton(type: .postback, title: "Button 3", payload: "Button3") ] let message = FBOutgoingMessage(text: "This message has buttons!", recipientId: id) for button in buttons { try? message.addButton(button: button) } message.send(handler: { (response) -> (Void) in console.log("Button Message Response: \(response?.bodyString)") }) } else if let num = Int(messageText) { let responses = [ FBQuickReply(title: "One"), FBQuickReply(title: "Two"), FBQuickReply(title: "Three"), FBQuickReply(title: "Four"), FBQuickReply(title: "Five"), FBQuickReply(title: "Six"), FBQuickReply(title: "Seven"), FBQuickReply(title: "Eight"), FBQuickReply(title: "Nine"), FBQuickReply(title: "Ten"), FBQuickReply(title: "Eleven") ] let message = FBOutgoingMessage(text: "This message has quick responses!", recipientId: id) for (index, response) in responses.enumerated() where index < num { try? message.addQuickReply(reply: response) } message.send(handler: { (response) -> (Void) in console.log("Button Message Response: \(response?.bodyString)") }) } else if messageText == "buttons qr" { let buttons = [ FBButton(type: .postback, title: "Button 1", payload: "Button1"), FBButton(type: .postback, title: "Button 2", payload: "Button2"), FBButton(type: .postback, title: "Button 3", payload: "Button3") ] let responses = [ FBQuickReply(title: "One"), FBQuickReply(title: "Two"), FBQuickReply(title: "Three"), FBQuickReply(title: "Four"), FBQuickReply(title: "Five"), FBQuickReply(title: "Six"), FBQuickReply(title: "Seven"), FBQuickReply(title: "Eight"), FBQuickReply(title: "Nine"), FBQuickReply(title: "Ten"), FBQuickReply(title: "Eleven") ] let message = FBOutgoingMessage(text: "This message has buttons!", recipientId: id) for button in buttons { try? message.addButton(button: button) } for response in responses{ try? message.addQuickReply(reply: response) } message.send(handler: { (response) -> (Void) in console.log("Button Message Response: \(response?.bodyString)") }) } else if messageText == "story" { let story = ["I used to work as pizza delivery guy in Detroit for several years. I'm not going to tell you what part of the city I used to live in or the name of the pizza chain that employed me. It's not important, and besides it has absolutely no bearing on the story I'm about to tell.", "The neighbourhoods I used to work in were fairly safe, but sometimes I was sent to areas that had been truly devastated by the recession. If you've ever visited Detroit, or done a Google image search on \"urban blight\", you know what I'm talking about.", "The incident occurred late in the fall a few years ago, and the memory of it will stay with me until the day I die. It doesn't matter how hard I try to suppress it, or force it out of my consciousness. It always floats back up to the surface, like a dead bloated fish and lets me know that it's still there.", "Anyway here’s what happened.", "It was a Thursday evening. It had been a hectic shift and I was making the last delivery for the night. The order was going to a residence in one of the less savoury parts of town. That didn't really shock me. It was to be expected every now and again. Even folks in rough areas order pizzas and have cellphones. After all this is the US we're talking about.", "But I have to admit, I wasn't too thrilled about the possibility of getting mugged or shot. Any half decent car in a poor section of town is fair game for the local gangbangers. And believe me, there are plenty of those in Detroit.", "The house was just a tiny little fibro shack on a big corner block. There were no lights on inside, and for a brief moment I prayed that I had the wrong address. But a quick look at the mailbox out front quashed my hopes of a safe getaway.", "I cursed silently as I gazed out over the desolate property. The moon was out and that made it even creepier. I could see the grass on the lawn was knee high, and there was rubbish everywhere. The fibro sheets were riddled with holes, and the windows were boarded up with plywood and adorned with graffiti and bullet holes.", "Needless to say, I had a very bad feeling about what was about to happen, and if it had been up to me, I would have just kept on driving. But that was out of the question. I couldn't afford to lose my job, and career opportunities weren't exactly growing on trees in this city. So I stayed where I was.", "I took a few deep breaths to try to calm myself, and said a quick prayer, even though I don’t believe in God.", "Then I grabbed the pizza boxes and reached for the Coke Zero bottle next to me in the passenger seat.", "Then I found myself walking up to the house.", "The cold evening air gushing through the area was racing in and out of my lungs like pistons in a car engine. The gravel made loud crunching noises every time I put my feet down, and I kept looking around nervously, convinced that some psycho was going to jump me any second. But no one came. I was all alone.", "As I climbed the concrete stoop leading up to the porch, I noticed the front door was ajar and I stopped dead in my tracks and just stared at it. For some strange reason it scared the crap out of me, and I could feel my heart start to race along even faster.", "A voice inside my head kept telling me to get the fuck out of there, and I have to admit I seriously entertained the idea of just leaving the pizzas on the porch and take off. But I knew I couldn't. I had to follow protocol. Leaving food outside a residence was a sackable offence.", "So I walked the rest of the way to the door, and gave it a quick knock.", "The force of my fist striking the old timber made it move, and a loud guttural sound escaped from somewhere deep inside me as the squeaky hinges gave off a high pitched wail.", "But no one came to the door.", "I swallowed hard, braced myself and put my knuckles up to the door again, and this time I shouted the words 'pizza is here' into the dark void. But still there was no answer, and I foolishly believed I was off the hook.", "Then as I was about to turn around and leave, a faint, cold, raspy voice coming from somewhere deep inside the house told me to enter. I stood absolutely still, staring at the gap in the door with eyes that were ready to pop out of their sockets. And for a brief second I started wondering if I’d just imagined it.", "But then the voice called out again, and this time it kept repeating the words over and over, like it was reciting an incantation. It had a menacing quality to it, and my whole body started shaking. And that’s when I made up my mind.", "I threw the pizzas down, not really given a fuck about whether I had a job to go to the next day or not. Then I legged it.", "I jumped from the top of the stoop and ran like a lunatic down the driveway back to my car, and almost ripped the door off its hinges as I threw myself inside. My hands were shaking so badly that it took me a good ten seconds just to get the engine started.", "Then I raced out of the neighbourhood as fast as I could, gasping for air all the way back to the restaurant.", "Maybe it was the effect of the adrenaline wearing off, or maybe it was just a delayed reaction, but when I opened the door and got out of the car I threw up. A whole gutful of yellow disgusting puke.", "But at least I was alive, and that was all that mattered.", "The next morning I woke up to someone banging on my door.", "When I opened up, two police officers greeted me with stony expressions. After asking me a few questions, one of them took a step forward, looked me straight in the eyes and informed me that two pizza delivery guys had been found dead inside the house that I'd ran away from the previous evening. Both of them had been hung by the neck from an exposed joist in the lounge.", "He then pulled out a picture from the inside pocket of his jacket and handed it to me. He gave me a few seconds to study it, and then he told me that they had found the picture taped to one of the bodies. It contained three faces. Two had a big red X draw across them. The last one didn't. The last face was mine.", "I managed to look up at the officer and shake my head, before I passed out and hit the floor.", "The next day I left Detroit, and I've never been back since.", "But even now, after all this time, I always look over my shoulder when I’m out and about. I’m also pedantic about staying indoors after dark, and I always make sure my doors and windows are locked.", "The killer in Detroit was never caught, and as long as he’s out there, I’m on my guard.", "And why shouldn’t I be? He obviously knows who I am. But does he know where I live?", "Hervey Copeland"] let messages = story.map { FBOutgoingMessage(text: $0, recipientId: id) } let handler = SCMMessageHandler() handler.sendGroupedMessages(messages) } else { let outgoingMessage = FBOutgoingMessage(text: "Echo: \(messageText)", recipientId: id) console.log("\(try? outgoingMessage.makeJSON())") outgoingMessage.send(handler: { (response) -> (Void) in console.log("Response: \(response?.bodyString)") }) } } if let postback = message.postback { guard let recognizedPostback = Postback(rawValue: postback) else { // We got a postback, but it is unrecognized. let message = FBOutgoingMessage(text: "Received Postback: \(postback)", recipientId: id) message.send(handler: { (response) -> (Void) in print("Postback Sent") }) return } switch recognizedPostback { case .getStartedButtonPressed: do { try makeNewGame(manager: manager, id: id) return } catch let error { let message = FBOutgoingMessage(text: "Received Error: \(error.localizedDescription). Please report this on our page!", recipientId: id) message.send(handler: { (response) -> (Void) in console.log("Error message sent with response: \(response)") }) } } } } func makeNewGame(manager: SCMDatabaseInstance, id: SCMIdentifier) throws { // Create a new game var player = Player(id: id) // Create initial location guard let initialLocation = try buildAreas(using: manager) else { return } player.currentArea = initialLocation.id let introductoryText = "You wake up in a forest. You know not who you are, where you're going, nor where you've been." let message = FBOutgoingMessage(text: introductoryText, recipientId: player.id) message.send { (response) -> (Void) in console.log("New Game Created, Response Received: \(response)") } try? manager.savePlayer(player: player) } public func createNewPlayer(usingIdentifier id: SCMIdentifier) -> Player { return Player(id: id) } } extension SCMGameStateManager { func buildAreas(using manager: SCMDatabaseInstance) throws -> Area? { //Create all area objects let forest = Area() let cave = Area() let riddleRoom = Area() let spiritTree = Area() let building = Area() let cellar = Area() //Set names forest.name = "The Forest" cave.name = "The Dark Cavern" riddleRoom.name = "The Chamber of the Riddle Master" spiritTree.name = "The Sacred Grove" building.name = "Old Shack" cellar.name = "The Dank Cellar" //Set paths between areas forest.paths.insert(spiritTree.id) forest.paths.insert(cave.id) forest.paths.insert(building.id) building.paths.insert(cellar.id) building.paths.insert(forest.id) cellar.paths.insert(cellar.id) cave.paths.insert(riddleRoom.id) cave.paths.insert(forest.id) riddleRoom.paths.insert(cave.id) /*---set enter conditions---*/ //No Forest Enter Conditions //building building.eConditionI = Key(quantity: 1); //cave cave.eConditionI = LitTorch(quantity: 1) //riddleRoom riddleRoom.eConditionW = "franky" //cellar cellar.eConditionE = Stick(quantity: 5) //spiritTree spiritTree.eConditionI = Map(quantity: 1) /*-----Fill First Entery Flavor Text------*/ //Forest forest.enterText = "You find yourself in a wooded area. The sun shines bright through the leaves and warms your face. What brought you here? You can't remember. You should LOOK AROUND and try to get a lay of the land." //building building.enterText = "You insert the key you found into the shacks lock. The rusty sounds of tumblers turning is music to your ears. The door opens to reveal a small dusty room." //cave cave.enterText = "You enter into the cave. It twists and turns for some time before opening opening into a large chamber. As you step forward the earth shakes while the wall shifts to form a rocky face.\n\nGreetings small one! It has been some time since someone has visited me." //riddleRoom riddleRoom.enterText = "The mouth of the door opens wide making a gateway for you to enter. Upon entering you find yourself in a quant study." //cellar cellar.enterText = "You climb down a rotting staircase into the cellar. The air is stale and tickles your throat as you inhale." //spiritTree spiritTree.enterText = "You win the game." /*-----Fill Look around Flavor Text------*/ //Forest forest.lookText = "A survey of the area reveals a small shack with curtained windows, a cave near the cliffside, and a path leading deeper into a heavily overgrown part of the woods." //building building.lookText = "Looking around you see tattered sheets covering the windows. The floor looks to be made out of loose sticks. As you walk around you get the feel that you could easily pick up some of the sticks." //cave cave.lookText = "When you look around you notice a skeleton propped against the wall with a glimmering key hanging from its neck." //riddleRoom riddleRoom.lookText = "You notice a scroll on a desk in the study" //cellar cellar.lookText = "The cellar is filled with barrels. Most of which are broken. The ones that aren't are unfortuantely empty. On the " //spiritTree spiritTree.lookText = "You done now. Leave" /*---Initialize Rejection text---*/ //Forest forest.rejectionText = "This shouldn't happen." //building building.rejectionText = "The door is locked" //cave cave.rejectionText = "I'm not going in there it's too dark" //riddleRoom riddleRoom.rejectionText = "HA! Wrong! C'mon give it another go!" //cellar cellar.rejectionText = "You can't do that." //spiritTree spiritTree.rejectionText = "You walk down the path for what feels like hours before stepping out of the woods seemingly right where you started. You must have gotten turned around somewhere." /*---Initialize Setting Enventory---*/ //Forest forest.inventory.insert(Item.new(item: "flint", quantity: 1)!) forest.inventory.insert(Item.new(item: "stick", quantity: 1)!) forest.inventory.insert(Item.new(item: "cloth", quantity: 1)!) //building building.inventory.insert(Item.new(item: "stick", quantity: 15)!) //cave cave.inventory.insert(Item.new(item: "key", quantity: 1)!) //riddleRoom riddleRoom.inventory.insert(Item.new(item: "map", quantity: 1)!) //cellar cellar.inventory.insert(Item.new(item: "journal", quantity: 1)!) //spiritTree // Save Areas try manager.saveArea(area: forest) try manager.saveArea(area: building) try manager.saveArea(area: riddleRoom) try manager.saveArea(area: cave) try manager.saveArea(area: cellar) try manager.saveArea(area: spiritTree) return forest } }
mit
074bf0bcd8408c23c4b552931810e106
58.568389
395
0.601439
4.46729
false
false
false
false
iAladdin/SwiftyFORM
Example/TextField/TextFieldKeyboardTypesViewController.swift
1
1720
// // TextFieldKeyboardTypesViewController.swift // SwiftyFORM // // Created by Simon Strandgaard on 18/11/14. // Copyright (c) 2014 Simon Strandgaard. All rights reserved. // import UIKit import SwiftyFORM class TextFieldKeyboardTypesViewController: FormViewController { override func populate(builder: FormBuilder) { builder.navigationTitle = "Keyboard Types" builder.toolbarMode = .None builder.demo_showInfo("Shows all the UIKeyboardType variants") builder += TextFieldFormItem().styleClass("align").title("ASCIICapable").placeholder("Lorem Ipsum").keyboardType(.ASCIICapable) builder += TextFieldFormItem().title("NumbersAndPunctuation").placeholder("123.45").keyboardType(.NumbersAndPunctuation) builder += TextFieldFormItem().styleClass("align").title("URL").placeholder("example.com/blog").keyboardType(.URL) builder += TextFieldFormItem().styleClass("align").title("NumberPad").placeholder("0123456789").keyboardType(.NumberPad) builder += TextFieldFormItem().styleClass("align").title("PhonePad").placeholder("+999#22;123456,27").keyboardType(.PhonePad) builder += TextFieldFormItem().styleClass("align").title("EmailAddress").placeholder("[email protected]").keyboardType(.EmailAddress) builder += TextFieldFormItem().styleClass("align").title("DecimalPad").placeholder("1234.5678").keyboardType(.DecimalPad) builder += TextFieldFormItem().styleClass("align").title("Twitter").placeholder("@user or #hashtag").keyboardType(.Twitter) builder += TextFieldFormItem().styleClass("align").title("WebSearch").placeholder("how to do this.").keyboardType(.WebSearch) builder.alignLeftElementsWithClass("align") builder += SectionFooterTitleFormItem().title("Footer text") } }
mit
848ba4838064316081aec96cd1c07c2f
60.428571
141
0.770349
4.725275
false
false
false
false
tristanchu/FlavorFinder
FlavorFinder/FlavorFinder/SearchResultsViewController.swift
1
7314
// // SearchResultsViewController.swift // FlavorFinder // // Created by Jaki Kimball on 1/31/16. // Copyright © 2016 TeamFive. All rights reserved. // // Controls LandingPage when search is in progress. // Manages subviews responsible for different aspects of search results view. // import Foundation import UIKit class SearchResultsViewController : UIViewController { // MARK: Properties // strings for display let NEED_LOGIN_TITLE = "Not Signed In" let NEED_LOGIN_MSG = "You need to sign in to do this!" // segues corresponding to embedded subviews let segueEmbedSearchResults = "goToSearchResults" let segueEmbedFilterBar = "goToFilterBar" let segueEmbedHotpot = "goToHotpot" // variables to hold the subview controllers (SVCs) var searchResultsSVC : SearchResultsSubviewController? var filterBarSVC : FilterBarSubviewController? var hotpotSVC : HotpotSubviewController? // containers of subviews @IBOutlet weak var searchResultsContainer: UIView! @IBOutlet weak var filterBarContainer: UIView! @IBOutlet weak var hotpotContainer: UIView! // Segues: let segueToAddHotpotToList = "segueToAddHotpotToList" // Buttons: let clearSearchBtn = UIBarButtonItem() let addToListBtn = UIBarButtonItem() // Button Text: let clearSearchText = String.fontAwesomeIconWithName(.ChevronLeft) + " New Search" let addToListText = String.fontAwesomeIconWithName(.Plus) + " Save Search to List" // Button Actions: let clearSearchSelector : Selector = "clearSearch" let addToListSelector : Selector = "addToListBtnClicked" // MARK: Actions // SETUP FUNCTIONS override func viewDidLoad() { super.viewDidLoad() configureUIBarButtons() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // Setup navigation bar if let navi = self.tabBarController?.navigationController as? MainNavigationController { self.tabBarController?.navigationItem.setLeftBarButtonItems([clearSearchBtn], animated: true) self.tabBarController?.navigationItem.setRightBarButtonItems([addToListBtn], animated: true) navi.reset_navigationBar() self.tabBarController?.navigationItem.title = "Search" } // disable/enable add to list button if user: if isUserLoggedIn() { self.addToListBtn.enabled = true } else { self.addToListBtn.enabled = false } } /* configureUIBarButtons - generates the UIBarButtonItem objects for the top nav bar */ func configureUIBarButtons() { configureUIBarButtonItem(clearSearchBtn, title: clearSearchText, action: clearSearchSelector) configureUIBarButtonItem(addToListBtn, title: addToListText, action: addToListSelector) } /* configureUIBarButtonItem - sets attributes on a UIBarButtonItem to the preferred configuration */ func configureUIBarButtonItem(button: UIBarButtonItem, title: String, action: Selector) { button.setTitleTextAttributes(attributes, forState: .Normal) button.title = title button.tintColor = NAVI_BUTTON_COLOR button.target = self button.action = action } // SUBVIEW MANAGEMENT FUNCTIONS /* prepareForSegue - prepares for segue - sets variables to keep track of embedded SVCs */ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // keep track of the embedded subview controllers let vc = segue.destinationViewController switch segue.identifier! { case segueEmbedSearchResults: searchResultsSVC = vc as? SearchResultsSubviewController break case segueEmbedFilterBar: filterBarSVC = vc as? FilterBarSubviewController break case segueEmbedHotpot: hotpotSVC = vc as? HotpotSubviewController break default: break } } // SUBVIEW RESPONSE FUNCTIONS /* newSearchTermWasAddded - refreshes hotpot to reflect changes to search query */ func newSearchTermWasAdded() { hotpotSVC?.collectionView?.reloadData() searchResultsSVC?.getSearchResults() filterBarSVC?.newSearchTermWasAdded() } /* hotpotIngredientWasRemoved - checks if hotpot is empty and if so, tells page to load new search view */ func hotpotIngredientWasRemoved() { if currentSearch.isEmpty { if let parent = parentViewController as? ContainerViewController { if let page = parent.parentViewController as? LandingPageController { resetNavBar() page.goToNewSearch() } } else { print("ERROR: Landing page hierarchy broken for Search Results VC.") } } else { searchResultsSVC?.getNewSearchResults() } } /* clearSearch - executed when clearSearchButton is clicked - clears hotpot ingredients and goes back to landing page */ func clearSearch() { currentSearch.removeAll() if let parent = parentViewController as? ContainerViewController { if let page = parent.parentViewController as? LandingPageController { resetNavBar() page.goToNewSearch() } } else { print("ERROR: Landing page hierarchy broken for Search Results VC.") } } /* resetNavBar - executed in hotpotIngredientWasRemoved() and clearSearch() - resets navbar to have no title nor buttons */ func resetNavBar() { if let navi = self.tabBarController?.navigationController as? MainNavigationController { self.tabBarController?.navigationItem.setLeftBarButtonItems([], animated: true) self.tabBarController?.navigationItem.setRightBarButtonItems([], animated: true) navi.reset_navigationBar() self.tabBarController?.navigationItem.title = "" } } /* mustBeSignedIn - subview controllers call this to indicate user attempted action that required login but was not logged in - creates sign-in alert (may at later date delegate alert to something else) */ func mustBeSignedIn() { alertPopup(self.NEED_LOGIN_TITLE, msg: self.NEED_LOGIN_MSG as String, actionTitle: OK_TEXT, currController: self) } /* filterButtonWasToggled - coordinates view response after child says filter buttons were toggled */ func filterButtonWasToggled(filters: [String: Bool], searchText: String) { searchResultsSVC?.filterButtonWasToggled(filters, searchText: searchText) } func filterSearchTextDidChange(searchText: String) { searchResultsSVC?.filterResults(searchText) } /* addToListBtnClicked - presents modal view to then select a list */ func addToListBtnClicked() { self.performSegueWithIdentifier(segueToAddHotpotToList, sender: self) } }
mit
f23f1b70a990b3f5982b7534f05ae103
33.5
105
0.656502
5.291606
false
false
false
false
k-o-d-e-n/CGLayout
Example/CGLayoutPlayground.playground/Pages/Stack.xcplaygroundpage/Contents.swift
1
1017
//: [Previous](@previous) import Foundation import PlaygroundSupport import CGLayout let sourceView = UIView(frame: UIScreen.main.bounds) sourceView.backgroundColor = .black let stackLayoutGuide = StackLayoutGuide<UIView>() sourceView.add(layoutGuide: stackLayoutGuide) // view let view = UIView() view.backgroundColor = .lightGray stackLayoutGuide.addArranged(element: .uiView(view)) // layer let layer = CALayer() layer.backgroundColor = UIColor.gray.cgColor stackLayoutGuide.addArranged(element: .caLayer(layer)) // layout guide let stack = StackLayoutGuide<UIView>() stack.scheme.axis = CGRectAxis.vertical let view2 = UILabel() view2.backgroundColor = .lightGray view2.text = "Stack" let layer2 = CALayer() layer.backgroundColor = UIColor.gray.cgColor stack.addArranged(element: .uiView(view2)) stack.addArranged(element: .caLayer(layer2)) stackLayoutGuide.addArranged(element: .layoutGuide(stack)) PlaygroundPage.current.liveView = sourceView let layout = stackLayoutGuide.layoutBlock() layout.layout()
mit
0e50a1d7d28e18ce4e038e8772fefed9
25.763158
58
0.794494
3.972656
false
false
false
false
Kagami-src/MerusutoChristina
ios/MerusutoChristina/Menu/MenuViewController.swift
1
3796
// // MenuViewController.swift // MerusutoChristina // // Created by 莫锹文 on 16/2/22. // Copyright © 2016年 bbtfr. All rights reserved. // import UIKit //菜单栏 public enum MenuList : Int { case Character // 人物图鉴 case Monster // 魔宠图鉴 case Simulator // 模拟抽卡 case Download // 下载 case CleanCache // 清除缓存 case Help // 帮助 } class MenuViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK:属性列表 var tableView: UITableView? // 菜单栏 let title1 = (icon : "icon_character.png", name: "人物图鉴", menuType: MenuList.Character) let title2 = (icon: "icon_monster.png", name: "魔宠图鉴", menuType: MenuList.Monster) let title3 = (icon: "icon_simulator.png", name: "模拟抽卡", menuType: MenuList.Simulator) let title4 = (icon: "icon_download.png", name: "下载资源包", menuType: MenuList.Download) let title5 = (icon: "icon_help.png", name: "帮助", menuType: MenuList.Help) let title6 = (icon: "icon_help.png", name: "清除缓存", menuType: MenuList.CleanCache) typealias TitleType = (icon: String, name: String, menuType: MenuList) typealias ArrayType = Array <TitleType> var titles: Array <ArrayType>? // MARK:方法 override func viewDidLoad() { super.viewDidLoad() self.tableView = UITableView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width * 0.6, UIScreen.mainScreen().bounds.height), style: UITableViewStyle.Plain) self.tableView?.center = CGPointMake(tableView!.center.x, UIScreen.mainScreen().bounds.height / 2 + 20) // self.titles = [[title1, title2], [title3, title4, title5], [title6]] self.titles = [[title1,title2], [title4, title5], [title6]] self.tableView?.delegate = self self.tableView?.dataSource = self self.tableView?.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "test") self.tableView?.separatorInset = UIEdgeInsetsMake(0, 10, 0, 0) self.tableView?.tableFooterView = UIView(frame: CGRectZero) self.tableView?.scrollEnabled = false self.view.addSubview(self.tableView!) } // MARK:UITableViewDelegate func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.titles!.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.titles![section].count } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 0 ? 0 : 20 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("test", forIndexPath: indexPath) let title = self.titles![indexPath.section][indexPath.row].name cell?.textLabel?.text = title let iconName = self.titles![indexPath.section][indexPath.row].icon cell?.imageView?.image = UIImage(named: iconName) return cell! } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) cell?.selected = false let clickMenu = self.titles![indexPath.section][indexPath.row].menuType let mainController = self.sideMenuViewController as! RootViewController switch (clickMenu) { case MenuList.Character: mainController.switchToController(0) case MenuList.Monster: mainController.switchToController(1) case MenuList.Simulator: mainController.switchToController(2) case MenuList.Download: mainController.downloadAllResource() case MenuList.CleanCache: mainController.clearAllResource() case MenuList.Help: UIApplication.sharedApplication().openURL(NSURL(string: "http://bbtfr.github.io/MerusutoChristina/jump/about.html")!) default: break } } }
gpl-3.0
0ae0588914f808f561cd722a6846f4bf
30.42735
165
0.740005
3.573372
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/NUX/SignupUsernameTableViewController.swift
1
10408
import SVProgressHUD import WordPressAuthenticator class SignupUsernameTableViewController: UITableViewController, SearchTableViewCellDelegate { open var currentUsername: String? open var displayName: String? open var delegate: SignupUsernameViewControllerDelegate? open var suggestions: [String] = [] private var service: AccountSettingsService? private var isSearching: Bool = false private var selectedCell: UITableViewCell? override func awakeFromNib() { super.awakeFromNib() registerNibs() setupBackgroundTapGestureRecognizer() } override func viewDidLoad() { super.viewDidLoad() WPStyleGuide.configureColors(view: view, tableView: tableView) tableView.layoutMargins = WPStyleGuide.edgeInsetForLoginTextFields() navigationItem.title = NSLocalizedString("Pick username", comment: "Title for selecting a new username in the site creation flow.") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // only procede with initial search if we don't have site title suggestions yet (hopefully only the first time) guard suggestions.count < 1, let nameToSearch = displayName else { return } suggestUsernames(for: nameToSearch) { [weak self] (suggestions) in self?.suggestions = suggestions self?.reloadSections() } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) SVProgressHUD.dismiss() } func registerNibs() { let bundle = WordPressAuthenticator.bundle tableView.register(UINib(nibName: "SearchTableViewCell", bundle: bundle), forCellReuseIdentifier: SearchTableViewCell.reuseIdentifier) } func reloadSections(includingAllSections: Bool = true) { DispatchQueue.main.async { let set = includingAllSections ? IndexSet(integersIn: Sections.searchField.rawValue...Sections.suggestions.rawValue) : IndexSet(integer: Sections.suggestions.rawValue) self.tableView.reloadSections(set, with: .automatic) } } func setupBackgroundTapGestureRecognizer() { let gestureRecognizer = UITapGestureRecognizer() gestureRecognizer.on(call: { [weak self] (gesture) in self?.view.endEditing(true) }) gestureRecognizer.cancelsTouchesInView = false view.addGestureRecognizer(gestureRecognizer) } func buildHeaderDescription() -> NSAttributedString { guard let currentUsername = currentUsername, let displayName = displayName else { return NSAttributedString(string: "") } let baseDescription = String(format: NSLocalizedString("Your current username is %@. With few exceptions, others will only ever see your display name, %@.", comment: "Instructional text that displays the current username and display name."), currentUsername, displayName) guard let rangeOfUsername = baseDescription.range(of: currentUsername), let rangeOfDisplayName = baseDescription.range(of: displayName) else { return NSAttributedString(string: baseDescription) } let boldFont = WPStyleGuide.mediumWeightFont(forStyle: .subheadline) let plainFont = UIFont.preferredFont(forTextStyle: .subheadline) let description = NSMutableAttributedString(string: baseDescription, attributes: [.font: plainFont]) description.addAttribute(.font, value: boldFont, range: baseDescription.nsRange(from: rangeOfUsername)) description.addAttribute(.font, value: boldFont, range: baseDescription.nsRange(from: rangeOfDisplayName)) return description } // MARK: - SearchTableViewCellDelegate func startSearch(for searchTerm: String) { guard searchTerm.count > 0 else { return } suggestUsernames(for: searchTerm) { [weak self] suggestions in self?.suggestions = suggestions self?.reloadSections(includingAllSections: false) } } } // MARK: UITableViewDataSource extension SignupUsernameTableViewController { fileprivate enum Sections: Int { case titleAndDescription = 0 case searchField = 1 case suggestions = 2 static var count: Int { return suggestions.rawValue + 1 } } private enum SuggestionStyles { static let indentationWidth: CGFloat = 20.0 static let indentationLevel = 1 } override func numberOfSections(in tableView: UITableView) -> Int { return Sections.count } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case Sections.titleAndDescription.rawValue: return 1 case Sections.searchField.rawValue: return 1 case Sections.suggestions.rawValue: return suggestions.count + 1 default: return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell switch indexPath.section { case Sections.titleAndDescription.rawValue: cell = titleAndDescriptionCell() case Sections.searchField.rawValue: cell = searchFieldCell() case Sections.suggestions.rawValue: fallthrough default: if indexPath.row == 0 { cell = suggestionCell(username: currentUsername ?? "username not found", checked: true) selectedCell = cell } else { cell = suggestionCell(username: suggestions[indexPath.row - 1], checked: false) } } return cell } override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if section == Sections.suggestions.rawValue { let footer = UIView() footer.backgroundColor = .neutral(.shade10) return footer } return nil } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if section == Sections.suggestions.rawValue { return 0.5 } return 0 } // MARK: table view cells private func titleAndDescriptionCell() -> UITableViewCell { let descriptionStyled = buildHeaderDescription() let cell = LoginSocialErrorCell(title: "", description: descriptionStyled) cell.selectionStyle = .none return cell } private func searchFieldCell() -> SearchTableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: SearchTableViewCell.reuseIdentifier) as? SearchTableViewCell else { fatalError() } cell.placeholder = NSLocalizedString("Type a keyword for more ideas", comment: "Placeholder text for domain search during site creation.") cell.delegate = self cell.selectionStyle = .none cell.textField.leftViewImage = UIImage(named: "icon-post-search-highlight") return cell } private func suggestionCell(username: String, checked: Bool) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = username cell.textLabel?.textColor = .neutral(.shade70) cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = .byCharWrapping cell.indentationWidth = SuggestionStyles.indentationWidth cell.indentationLevel = SuggestionStyles.indentationLevel if checked { cell.accessoryType = .checkmark } return cell } private func suggestUsernames(for searchTerm: String, addSuggestions: @escaping ([String]) ->()) { guard !isSearching else { return } isSearching = true let context = ContextManager.sharedInstance().mainContext let accountService = AccountService(managedObjectContext: context) guard let account = accountService.defaultWordPressComAccount(), let api = account.wordPressComRestApi else { return } showLoader() let service = AccountSettingsService(userID: account.userID.intValue, api: api) service.suggestUsernames(base: searchTerm) { [weak self] (newSuggestions) in if newSuggestions.count == 0 { WordPressAuthenticator.track(.signupEpilogueUsernameSuggestionsFailed) } self?.isSearching = false self?.hideLoader() addSuggestions(newSuggestions) } } } // MARK: - Loader extension SignupUsernameTableViewController { func showLoader() { searchCell?.showLoader() } func hideLoader() { searchCell?.hideLoader() } private var searchCell: SearchTableViewCell? { tableView.cellForRow(at: IndexPath(row: 0, section: 1)) as? SearchTableViewCell } } extension String { private func nsRange(from range: Range<Index>) -> NSRange { let from = range.lowerBound let to = range.upperBound let location = distance(from: startIndex, to: from) let length = distance(from: from, to: to) return NSRange(location: location, length: length) } } extension SignupUsernameTableViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedUsername: String switch indexPath.section { case Sections.suggestions.rawValue: if indexPath.row == 0 { selectedUsername = currentUsername ?? "" } else { selectedUsername = suggestions[indexPath.row - 1] } default: return } delegate?.usernameSelected(selectedUsername) tableView.deselectSelectedRowWithAnimation(true) // Uncheck the previously selected cell. if let selectedCell = selectedCell { selectedCell.accessoryType = .none } // Check the currently selected cell. if let cell = self.tableView.cellForRow(at: indexPath) { cell.accessoryType = .checkmark selectedCell = cell } } }
gpl-2.0
03f2d9ec0de089dcf2e1190b3d9253e1
34.043771
279
0.656514
5.568753
false
false
false
false
ruanjunhao/RJWeiBo
RJWeiBo/RJWeiBo/Classes/Home/Model/Status.swift
1
1324
// // Status.swift // RJWeiBo // // Created by ruanjh on 2017/3/9. // Copyright © 2017年 app. All rights reserved. // import UIKit class Status: NSObject { // MARK:- 属性 var created_at : String? // 微博创建时间 var source : String? // 微博来源 var text : String? // 微博的正文 var mid : Int = 0 // 微博的ID var user : User? // 微博对应的用户 var pic_urls : [[String : String]]? // 微博的配图 var retweeted_status : Status? // 微博对应的转发的微博 // // MARK:- 自定义构造函数 // init(dict : [String : AnyObject]) { // super.init() // // setValuesForKeys(dict) // // // 1.将用户字典转成用户模型对象 // if let userDict = dict["user"] as? [String : AnyObject] { // user = User(dict: userDict) // } // // // 2.将转发微博字典转成转发微博模型对象 // if let retweetedStatusDict = dict["retweeted_status"] as? [String : AnyObject] { // retweeted_status = Status(dict: retweetedStatusDict) // } // } // override func setValue(_ value: Any?, forUndefinedKey key: String) {} }
apache-2.0
48714e40bdd397c931cc44f5da20afc4
26.690476
90
0.494411
3.727564
false
false
false
false
ProcedureKit/ProcedureKit
Tests/ProcedureKitCloudTests/CKFetchAllChangesTests.swift
2
1227
// // ProcedureKit // // Copyright © 2015-2018 ProcedureKit. All rights reserved. // import XCTest import ProcedureKit import TestingProcedureKit @testable import ProcedureKitCloud class TestCKFetchAllChangesOperation: TestCKOperation, CKFetchAllChanges { var fetchAllChanges: Bool = true } class CKFetchAllChangesOperationTests: CKProcedureTestCase { var target: TestCKFetchAllChangesOperation! var operation: CKProcedure<TestCKFetchAllChangesOperation>! override func setUp() { super.setUp() target = TestCKFetchAllChangesOperation() operation = CKProcedure(operation: target) } override func tearDown() { target = nil operation = nil super.tearDown() } func test__set_get__fetchAllChanges() { var fetchAllChanges = false operation.fetchAllChanges = fetchAllChanges XCTAssertEqual(operation.fetchAllChanges, fetchAllChanges) XCTAssertEqual(target.fetchAllChanges, fetchAllChanges) fetchAllChanges = true operation.fetchAllChanges = fetchAllChanges XCTAssertEqual(operation.fetchAllChanges, fetchAllChanges) XCTAssertEqual(target.fetchAllChanges, fetchAllChanges) } }
mit
bb54432b223542c98dbd3b742e002130
27.511628
74
0.726754
5.129707
false
true
false
false
hakan4/LineGraphKit
LineGraphKit/LineGraphKit/Classes/ViewElements/PlotLayer.swift
1
1810
// // PlotLayer.swift // GraphKit // // Created by Håkan Andersson on 27/06/15. // Copyright (c) 2015 Fineline. All rights reserved. // import UIKit class PlotLayer: CALayer { fileprivate var leftBorderLayer: BorderLayer! fileprivate var bottomBorderLayer: BorderLayer! override init() { super.init() leftBorderLayer = BorderLayer() bottomBorderLayer = BorderLayer() addSublayer(bottomBorderLayer) addSublayer(leftBorderLayer) backgroundColor = UIColor.clear.cgColor } override func layoutSublayers() { super.layoutSublayers() leftBorderLayer.frame = CGRect(x: 0, y: 0, width: 0.5, height: self.frame.size.height) bottomBorderLayer.frame = CGRect(x: 0, y: self.frame.size.height, width: self.frame.size.width, height: 0.5) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(layer: Any) { super.init(layer: layer) if let _ = layer as? PlotLayer { } } func addLineLayer(_ lineLayer: LineLayer) { lineLayer.frame = bounds addSublayer(lineLayer) } func clearLineLayers() { if let subs = sublayers { for layer in subs { if let sublayer = layer as? LineLayer { sublayer.removeFromSuperlayer() } } } } } class BorderLayer: CALayer { override init() { super.init() backgroundColor = UIColor.lightGray.cgColor } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(layer: Any) { super.init(layer: layer) if let _ = layer as? BorderLayer { } } }
mit
0879b0312a86ef4abf773b5bb592d912
23.12
116
0.58209
4.380145
false
false
false
false
3lvis/TextField
Custom/UIColor+Hex.swift
2
2451
import UIKit public extension UIColor { /// Base initializer, it creates an instance of `UIColor` using an HEX string. /// /// - Parameter hex: The base HEX string to create the color. convenience init(hex: String) { let noHashString = hex.replacingOccurrences(of: "#", with: "") let scanner = Scanner(string: noHashString) scanner.charactersToBeSkipped = CharacterSet.symbols var hexInt: UInt32 = 0 if (scanner.scanHexInt32(&hexInt)) { let red = (hexInt >> 16) & 0xFF let green = (hexInt >> 8) & 0xFF let blue = (hexInt) & 0xFF self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } else { self.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0) } } /// Convenience initializers for RGB colors. /// /// - Parameters: /// - red: The red part, ranging from 0 to 255. /// - green: The green part, ranging from 0 to 255. /// - blue: The blue part, ranging from 0 to 255. /// - alpha: The alpha part, ranging from 0 to 100. convenience init(r red: Double, g green: Double, b blue: Double, a alpha: Double = 100) { self.init(red: CGFloat(red)/CGFloat(255.0), green: CGFloat(green)/CGFloat(255.0), blue: CGFloat(blue)/CGFloat(255.0), alpha: CGFloat(alpha)/CGFloat(100.0)) } /// Compares if two colors are equal. /// /// - Parameter color: A UIColor to compare. /// - Returns: A boolean, true if same (or very similar) and false otherwise. func isEqual(to color: UIColor) -> Bool { let currentRGBA = self.RGBA let comparedRGBA = color.RGBA return self.compareColorComponents(a: currentRGBA[0], b: comparedRGBA[0]) && self.compareColorComponents(a: currentRGBA[1], b: comparedRGBA[1]) && self.compareColorComponents(a: currentRGBA[2], b: comparedRGBA[2]) && self.compareColorComponents(a: currentRGBA[3], b: comparedRGBA[3]) } /// Get the red, green, blue and alpha values. private var RGBA: [CGFloat] { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: &a) return [r, g, b, a] } private func compareColorComponents(a: CGFloat, b: CGFloat) -> Bool { return abs(b - a) <= 0 } }
mit
bec1277032423e47b8cc4d0c2c593789
37.904762
163
0.593227
3.68018
false
false
false
false
macmade/AtomicKit
AtomicKit/Source/Mutex.swift
1
3116
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2017 Jean-David Gadina - www.xs-labs.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 /** * Swift wrapper class for `pthread_mutex_t`. * Note that this is a non-recursive version. * * - seealso: Locakble */ public class Mutex: Lockable { /** * `Mutex` errors. */ public enum Error: Swift.Error { /** * Thrown when a failure occurs trying to initialize the native * mutex type. */ case CannotCreateMutex /** * Thrown when a failure occurs trying to initialize the native * mutex attributes type. */ case CannotCreateMutexAttributes } /** * Initializes a mutex object. * * - throws: `Mutex.Error` on failure. */ public required init() throws { var attr = pthread_mutexattr_t() if( pthread_mutexattr_init( &attr ) != 0 ) { throw Error.CannotCreateMutexAttributes } defer { pthread_mutexattr_destroy( &attr ) } if( pthread_mutex_init( &( self._mutex ), &attr ) != 0 ) { throw Error.CannotCreateMutex } } deinit { pthread_mutex_destroy( &( self._mutex ) ) } /** * Locks the mutex. */ public func lock() { pthread_mutex_lock( &( self._mutex ) ) } /** * Unlocks the mutex. */ public func unlock() { pthread_mutex_unlock( &( self._mutex ) ) } /** * Tries to lock the mutex. * * - returns: `true` if the mutex was successfully locked, otherwise `false`. */ public func tryLock() -> Bool { return pthread_mutex_trylock( &( self._mutex ) ) == 0 } private var _mutex = pthread_mutex_t() }
mit
2aac06aec107552dacd0686d270c31f2
27.327273
83
0.570282
4.630015
false
false
false
false
Anviking/Chromatism
Chromatism/JLIndentator.swift
1
1667
// // JLIndentator.swift // Chromatism // // Created by Johannes Lund on 2015-06-05. // Copyright (c) 2015 anviking. All rights reserved. // import Foundation // //class JLIndentator: NSObject, UITextViewDelegate { // // // let expression = NSRegularExpression(pattern: "[\\t| ]*", options: nil, error: nil)! // // func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { // let oldString: String? // // if text == "\n" { // // Return // // Start the new line with as many tabs or white spaces as the previous one. // let lineRange = [textView.text lineRangeForRange:range]; // let prefixRange = expression.firstMatchInString(textView.text, options: nil, range: lineRange) // NSString *prefixString = [textView.text substringWithRange:prefixRange]; // // UITextPosition *beginning = textView.beginningOfDocument; // UITextPosition *start = [textView positionFromPosition:beginning offset:range.location]; // UITextPosition *stop = [textView positionFromPosition:start offset:range.length]; // // UITextRange *textRange = [textView textRangeFromPosition:start toPosition:stop]; // // [textView replaceRange:textRange withText:[NSString stringWithFormat:@"\n%@",prefixString]]; // // return NO; // } // // if (range.length > 0) // { // _oldString = [textView.text substringWithRange:range]; // } // // return YES; // } // } //}
mit
da9657a0a87aad40495c75d92065cad8
35.26087
121
0.595081
4.363874
false
false
false
false
padawan/smartphone-app
MT_iOS/MT_iOS/Classes/ViewController/FolderListTableViewController.swift
1
6014
// // FolderListTableViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/06/08. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit import SwiftyJSON class FolderList: CategoryList { override func toModel(json: JSON)->BaseObject { return Folder(json: json) } override func fetch(offset: Int, success: ((items:[JSON]!, total:Int!) -> Void)!, failure: (JSON! -> Void)!) { if working {return} self.working = true UIApplication.sharedApplication().networkActivityIndicatorVisible = true let api = DataAPI.sharedInstance let app = UIApplication.sharedApplication().delegate as! AppDelegate let authInfo = app.authInfo var success: (([JSON]!, Int!)-> Void) = { (result: [JSON]!, total: Int!)-> Void in LOG("\(result)") if self.refresh { self.items = [] } self.totalCount = total self.parseItems(result) self.makeLevel() success(items: result, total: total) self.postProcess() UIApplication.sharedApplication().networkActivityIndicatorVisible = false } var failure: (JSON!-> Void) = { (error: JSON!)-> Void in LOG("failure:\(error.description)") failure(error) self.postProcess() UIApplication.sharedApplication().networkActivityIndicatorVisible = false } api.authentication(authInfo.username, password: authInfo.password, remember: true, success:{_ in var params = ["limit":"9999", "sortOrder":"ascend"] api.listFolders(siteID: self.blog.id, options: params, success: success, failure: failure) }, failure: failure ) } } class FolderListTableViewController: BaseCategoryListTableViewController { override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString("Select folders", comment: "Select folders") list = FolderList() (list as! FolderList).blog = self.blog // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() actionMessage = NSLocalizedString("Fetch folders", comment: "Fetch folders") self.fetch() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedItem = self.list[indexPath.row] as! Folder object.isDirty = true if let sel = selected[selectedItem.id] { selected[selectedItem.id] = !sel } else { selected[selectedItem.id] = true } for item in self.list.items { if item.id != selectedItem.id { selected[item.id] = false } } self.tableView.reloadData() } @IBAction override func saveButtonPushed(sender: UIBarButtonItem) { var selectedObjects = [BaseObject]() for (id, value) in selected { if value { if !id.isEmpty { selectedObjects.append(list.objectWithID(id)!) } } } (object as! PageFolderItem).selected = selectedObjects as! [Folder] self.navigationController?.popViewControllerAnimated(true) } }
mit
5f3d23afb54bca9bfbf4c78f1ac04411
33.354286
157
0.617764
5.387097
false
false
false
false
shahmishal/swift
test/IDE/print_omit_needless_words.swift
5
14295
// RUN: %empty-directory(%t) // REQUIRES: objc_interop // FIXME: this is failing on simulators // REQUIRES: OS=macosx // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift -disable-objc-attr-requires-foundation-module // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/Foundation.swift // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=ObjectiveC -function-definitions=false -prefer-type-repr=true > %t.ObjectiveC.txt // RUN: %FileCheck %s -check-prefix=CHECK-OBJECTIVEC -strict-whitespace < %t.ObjectiveC.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=Foundation -function-definitions=false -prefer-type-repr=true -skip-unavailable -skip-parameter-names > %t.Foundation.txt // RUN: %FileCheck %s -check-prefix=CHECK-FOUNDATION -strict-whitespace < %t.Foundation.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t -I %S/../ClangImporter/Inputs/custom-modules) -print-module -source-filename %s -module-to-print=CoreCooling -function-definitions=false -prefer-type-repr=true -skip-parameter-names > %t.CoreCooling.txt // RUN: %FileCheck %s -check-prefix=CHECK-CORECOOLING -strict-whitespace < %t.CoreCooling.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t -I %S/Inputs/custom-modules) -print-module -source-filename %s -module-to-print=OmitNeedlessWords -function-definitions=false -prefer-type-repr=true -skip-parameter-names > %t.OmitNeedlessWords.txt 2> %t.OmitNeedlessWords.diagnostics.txt // RUN: %FileCheck %s -check-prefix=CHECK-OMIT-NEEDLESS-WORDS -strict-whitespace < %t.OmitNeedlessWords.txt // RUN: %FileCheck %s -check-prefix=CHECK-OMIT-NEEDLESS-WORDS-DIAGS -strict-whitespace < %t.OmitNeedlessWords.diagnostics.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=errors -function-definitions=false -prefer-type-repr=true -skip-parameter-names > %t.errors.txt // RUN: %FileCheck %s -check-prefix=CHECK-ERRORS -strict-whitespace < %t.errors.txt // Note: SEL -> "Selector" // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector) // Note: "with" parameters. // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector, with: Any?) // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector, with: Any?, with: Any?) // Note: don't prefix-strip swift_bridged classes or their subclasses. // CHECK-FOUNDATION: func mutableCopy() -> NSMutableArray // Note: id -> "Object". // CHECK-FOUNDATION: func index(of: Any) -> Int // Note: Class -> "Class" // CHECK-OBJECTIVEC: func isKind(of aClass: AnyClass) -> Bool // Note: Pointer-to-struct name matching; preposition splitting. // // CHECK-FOUNDATION: func copy(with: NSZone? = nil) -> Any! // Note: Objective-C type parameter names. // CHECK-FOUNDATION: func object(forKey: Any) -> Any? // CHECK-FOUNDATION: func removeObject(forKey: NSCopying) // Note: Don't drop the name of the first parameter in an initializer entirely. // CHECK-FOUNDATION: init(array: [Any]) // Note: struct name matching; don't drop "With". // CHECK-FOUNDATION: func withRange(_: NSRange) -> NSValue // Note: built-in types. // CHECK-FOUNDATION: func add(_: Double) -> NSNumber // Note: built-in types. // CHECK-FOUNDATION: func add(_: Bool) -> NSNumber // Note: builtin-types. // CHECK-FOUNDATION: func add(_: UInt16) -> NSNumber // Note: builtin-types. // CHECK-FOUNDATION: func add(_: Int32) -> NSNumber // Note: Typedefs with a "_t" suffix". // CHECK-FOUNDATION: func subtract(_: Int32) -> NSNumber // Note: Respect the getter name for BOOL properties. // CHECK-FOUNDATION: var isMakingHoney: Bool // Note: multi-word enum name matching; "with" splits the first piece. // CHECK-FOUNDATION: func someMethod(deprecatedOptions: NSDeprecatedOptions = []) // Note: class name matching; don't drop "With". // CHECK-FOUNDATION: func withString(_: String!) -> Self! // Note: lowercasing enum constants. // CHECK-FOUNDATION: enum CountStyle : Int { // CHECK-FOUNDATION: case file // CHECK-FOUNDATION-NEXT: case memory // CHECK-FOUNDATION-NEXT: case decimal // CHECK-FOUNDATION-NEXT: case binary // Note: Make sure initialisms work in various places // CHECK-FOUNDATION: open(_: URL!, completionHandler: ((Bool) -> Void)!) // CHECK-FOUNDATION: open(_: NSGUID!, completionHandler: ((Bool) -> Void)!) // Note: property name stripping property type. // CHECK-FOUNDATION: var uppercased: String // Note: ok to map base name down to a keyword. // CHECK-FOUNDATION: func `do`(_: Selector!) // Note: Strip names preceded by a gerund. // CHECK-FOUNDATION: func startSquashing(_: Bee) // CHECK-FOUNDATION: func startSoothing(_: Bee) // CHECK-FOUNDATION: func startShopping(_: Bee) // Note: Removing plural forms when working with collections // CHECK-FOUNDATION: func add(_: [Any]) // Note: Int and Index match. // CHECK-FOUNDATION: func slice(from: Int, to: Int) -> String // Note: <context type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: func appending(_: String) -> String // Note: <context type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: func withString(_: String) -> String // Note: Noun phrase puts preposition inside. // CHECK-FOUNDATION: func url(withAddedString: String) -> URL? // CHECK-FOUNDATION: func guid(withAddedString: String) -> NSGUID? // Note: NSCalendarUnits is not a set of "Options". // CHECK-FOUNDATION: func forCalendarUnits(_: NSCalendar.Unit) -> String! // Note: <property type>By<gerund> --> <gerund>. // Note: <property type><preposition> --> <preposition>. // CHECK-FOUNDATION: var deletingLastPathComponent: URL? { get } // CHECK-FOUNDATION: var withHTTPS: URL { get } // CHECK-FOUNDATION: var canonicalizing: NSGUID? { get } // CHECK-FOUNDATION: var withContext: NSGUID { get } // Note: lowercasing option set values // CHECK-FOUNDATION: struct NSEnumerationOptions // CHECK-FOUNDATION: static var concurrent: NSEnumerationOptions // CHECK-FOUNDATION: static var reverse: NSEnumerationOptions // Note: usingBlock -> body // CHECK-FOUNDATION: func enumerateObjects(_: ((Any?, Int, UnsafeMutablePointer<ObjCBool>?) -> Void)!) // CHECK-FOUNDATION: func enumerateObjects(options: NSEnumerationOptions = [], using: ((Any?, Int, UnsafeMutablePointer<ObjCBool>?) -> Void)!) // Note: WithBlock -> body, nullable closures default to nil. // CHECK-FOUNDATION: func enumerateObjectsRandomly(block: ((Any?, Int, UnsafeMutablePointer<ObjCBool>?) -> Void)? = nil) // Note: id<Proto> treated as "Proto". // CHECK-FOUNDATION: func doSomething(with: NSCopying) // Note: NSObject<Proto> treated as "Proto". // CHECK-FOUNDATION: func doSomethingElse(with: NSCopying & NSObjectProtocol) // Note: Function type -> "Function". // CHECK-FOUNDATION: func sort(_: @convention(c) (Any, Any) -> Int) // Note: Plural: NSArray without type arguments -> "Objects". // CHECK-FOUNDATION: func remove(_: [Any]) // Note: Skipping "Type" suffix. // CHECK-FOUNDATION: func doSomething(with: NSUnderlyingType) // Don't introduce default arguments for lone parameters to setters. // CHECK-FOUNDATION: func setDefaultEnumerationOptions(_: NSEnumerationOptions) // CHECK-FOUNDATION: func normalizingXMLPreservingComments(_: Bool) // Collection element types. // CHECK-FOUNDATION: func adding(_: Any) -> Set<AnyHashable> // Boolean properties follow the getter. // CHECK-FOUNDATION: var empty: Bool { get } // CHECK-FOUNDATION: func nonEmpty() -> Bool // CHECK-FOUNDATION: var isStringSet: Bool { get } // CHECK-FOUNDATION: var wantsAUnion: Bool { get } // CHECK-FOUNDATION: var watchesItsLanguage: Bool { get } // CHECK-FOUNDATION: var appliesForAJob: Bool { get } // CHECK-FOUNDATION: var setShouldBeInfinite: Bool { get } // "UTF8" initialisms. // CHECK-FOUNDATION: init?(utf8String: UnsafePointer<Int8>!) // Don't strip prefixes from globals. // CHECK-FOUNDATION: let NSGlobalConstant: String // CHECK-FOUNDATION: func NSGlobalFunction() // Cannot strip because we end up with something that isn't an identifier // CHECK-FOUNDATION: func NS123() // CHECK-FOUNDATION: func NSYELLING() // CHECK-FOUNDATION: func NS_SCREAMING() // CHECK-FOUNDATION: func NS_() // CHECK-FOUNDATION: let NSHTTPRequestKey: String // Lowercasing initialisms with plurals. // CHECK-FOUNDATION: var urlsInText: [URL] { get } // CHECK-FOUNDATION: var guidsInText: [NSGUID] { get } // Don't strip prefixes from macro names. // CHECK-FOUNDATION: var NSTimeIntervalSince1970: Double { get } // CHECK-FOUNDATION: var NS_DO_SOMETHING: Int // Note: no lowercasing of initialisms when there might be a prefix. // CHECK-CORECOOLING: func CFBottom() -> // Note: Skipping over "Ref" // CHECK-CORECOOLING: func replace(_: CCPowerSupply!) // CHECK-OMIT-NEEDLESS-WORDS: struct OMWWobbleOptions // CHECK-OMIT-NEEDLESS-WORDS: static var sideToSide: OMWWobbleOptions // CHECK-OMIT-NEEDLESS-WORDS: static var backAndForth: OMWWobbleOptions // CHECK-OMIT-NEEDLESS-WORDS: static var toXMLHex: OMWWobbleOptions // CHECK-OMIT-NEEDLESS-WORDS: func jump(to: URL) // CHECK-OMIT-NEEDLESS-WORDS: func jump(to: NSGUID) // CHECK-OMIT-NEEDLESS-WORDS: func jumpAgain(to: NSGUID) // CHECK-OMIT-NEEDLESS-WORDS: func objectIs(compatibleWith: Any) -> Bool // CHECK-OMIT-NEEDLESS-WORDS: func insetBy(x: Int, y: Int) // CHECK-OMIT-NEEDLESS-WORDS: func setIndirectlyToValue(_: Any) // CHECK-OMIT-NEEDLESS-WORDS: func jumpToTop(_: Any) // CHECK-OMIT-NEEDLESS-WORDS: func removeWithNoRemorse(_: Any) // CHECK-OMIT-NEEDLESS-WORDS: func bookmark(with: [URL]) // CHECK-OMIT-NEEDLESS-WORDS: func save(to: URL, forSaveOperation: Int) // CHECK-OMIT-NEEDLESS-WORDS: func save(to: NSGUID, forSaveOperation: Int) // CHECK-OMIT-NEEDLESS-WORDS: func index(withItemNamed: String) // CHECK-OMIT-NEEDLESS-WORDS: func methodAndReturnError(_: AutoreleasingUnsafeMutablePointer<NSError?>!) // CHECK-OMIT-NEEDLESS-WORDS: func type(of: String) // CHECK-OMIT-NEEDLESS-WORDS: func type(ofNamedString: String) // CHECK-OMIT-NEEDLESS-WORDS: func type(ofTypeNamed: String) // Look for preposition prior to "of". // CHECK-OMIT-NEEDLESS-WORDS: func append(withContentsOf: String) // Leave subscripts alone // CHECK-OMIT-NEEDLESS-WORDS: subscript(_: UInt) -> Any { get } // CHECK-OMIT-NEEDLESS-WORDS: func objectAtIndexedSubscript(_: UInt) -> Any // CHECK-OMIT-NEEDLESS-WORDS: func exportPresets(bestMatching: String) // CHECK-OMIT-NEEDLESS-WORDS: func `is`(compatibleWith: String) // CHECK-OMIT-NEEDLESS-WORDS: func add(_: Any) // CHECK-OMIT-NEEDLESS-WORDS: func slobbering(_: String) -> OmitNeedlessWords // Elements of C array types // CHECK-OMIT-NEEDLESS-WORDS: func drawPolygon(with: UnsafePointer<NSPoint>!, count: Int) // Typedef ending in "Array". // CHECK-OMIT-NEEDLESS-WORDS: func drawFilledPolygon(with: NSPointArray!, count: Int) // Non-parameterized Objective-C class ending in "Array". // CHECK-OMIT-NEEDLESS-WORDS: func draw(_: SEGreebieArray) // "bound by" // CHECK-OMIT-NEEDLESS-WORDS: func doSomething(boundBy: Int) // "separated by" // CHECK-OMIT-NEEDLESS-WORDS: func doSomething(separatedBy: Int) // "Property"-like stripping for "set" methods. // CHECK-OMIT-NEEDLESS-WORDS: class func current() -> OmitNeedlessWords // CHECK-OMIT-NEEDLESS-WORDS: class func setCurrent(_: OmitNeedlessWords) // Don't split "PlugIn". // CHECK-OMIT-NEEDLESS-WORDS: func compilerPlugInValue(_: Int) // Don't strip away argument label completely when there is a default // argument. // CHECK-OMIT-NEEDLESS-WORDS: func wobble(options: OMWWobbleOptions = []) // Property-name sensitivity in the base name "Self" stripping. // CHECK-OMIT-NEEDLESS-WORDS: func addDoodle(_: ABCDoodle) // Protocols as contexts // CHECK-OMIT-NEEDLESS-WORDS-LABEL: protocol OMWLanding { // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func flip() // Verify that we get the Swift name from the original declaration. // CHECK-OMIT-NEEDLESS-WORDS-LABEL: protocol OMWWiggle // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func joinSub() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func wiggle1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "wiggle1()") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func conflicting1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var wiggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "wiggleProp1") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var conflictingProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-LABEL: protocol OMWWaggle // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func waggle1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "waggle1()") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func conflicting1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var waggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "waggleProp1") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var conflictingProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-LABEL: class OMWSuper // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jump() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "jump()") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jumpSuper() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var wiggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS-LABEL: class OMWSub // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jump() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: @available(swift, obsoleted: 3, renamed: "jump()") // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jumpSuper() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func joinSub() // CHECK-OMIT-NEEDLESS-WORDS-DIAGS: inconsistent Swift name for Objective-C method 'conflicting1' in 'OMWSub' ('waggle1()' in 'OMWWaggle' vs. 'wiggle1()' in 'OMWWiggle') // CHECK-OMIT-NEEDLESS-WORDS-DIAGS: inconsistent Swift name for Objective-C property 'conflictingProp1' in 'OMWSub' ('waggleProp1' in 'OMWWaggle' vs. 'wiggleProp1' in 'OMWSuper') // Don't drop the 'error'. // CHECK-ERRORS: func tryAndReturnError(_: ()) throws
apache-2.0
9e31539b8da1cc3564f5dae27fbba165
45.563518
322
0.732354
3.257748
false
false
false
false
roambotics/swift
test/Interop/SwiftToCxx/methods/mutating-method-in-cxx.swift
2
4113
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -typecheck -module-name Methods -clang-header-expose-decls=all-public -emit-clang-header-path %t/methods.h // RUN: %FileCheck %s < %t/methods.h // RUN: %check-interop-cxx-header-in-clang(%t/methods.h) public struct LargeStruct { var x1, x2, x3, x4, x5, x6: Int public func dump() { print("\(x1), \(x2), \(x3), \(x4), \(x5), \(x6)") } public mutating func double() { x1 *= 2 x2 *= 2 x3 *= 2 x4 *= 2 x5 *= 2 x6 *= 2 } public mutating func scale(_ x: Int, _ y: Int) -> LargeStruct { x1 *= x x2 *= y x3 *= x x4 *= y x5 *= x x6 *= y return self } } public struct SmallStruct { var x: Float public func dump() { print("small x = \(x);") } public mutating func scale(_ y: Float) -> SmallStruct { x *= y return SmallStruct(x: x / y) } public mutating func invert() { x = -x } } // CHECK: SWIFT_EXTERN void $s7Methods11LargeStructV4dumpyyF(SWIFT_CONTEXT const void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // dump() // CHECK: SWIFT_EXTERN void $s7Methods11LargeStructV6doubleyyF(SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // double() // CHECK: SWIFT_EXTERN void $s7Methods11LargeStructV5scaleyACSi_SitF(SWIFT_INDIRECT_RESULT void * _Nonnull, ptrdiff_t x, ptrdiff_t y, SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // scale(_:_:) // CHECK: SWIFT_EXTERN void $s7Methods11SmallStructV4dumpyyF(struct swift_interop_passStub_Methods_float_0_4 _self) SWIFT_NOEXCEPT SWIFT_CALL; // dump() // CHECK: SWIFT_EXTERN struct swift_interop_returnStub_Methods_float_0_4 $s7Methods11SmallStructV5scaleyACSfF(float y, SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // scale(_:) // CHECK: SWIFT_EXTERN void $s7Methods11SmallStructV6invertyyF(SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // invert() // CHECK: class LargeStruct final { // CHECK: inline LargeStruct(LargeStruct &&) // CHECK-NEXT: inline void dump() const; // CHECK-NEXT: inline void double_(); // CHECK-NEXT: inline LargeStruct scale(swift::Int x, swift::Int y); // CHECK-NEXT: private // CHECK: class SmallStruct final { // CHECK: inline SmallStruct(SmallStruct &&) // CHECK-NEXT: inline void dump() const; // CHECK-NEXT: inline SmallStruct scale(float y); // CHECK-NEXT: inline void invert(); // CHECK-NEXT: private: public func createLargeStruct() -> LargeStruct { return LargeStruct(x1: 1, x2: -5, x3: 9, x4: 11, x5: 0xbeef, x6: -77) } public func createSmallStruct(x: Float) -> SmallStruct { return SmallStruct(x: x) } // CHECK: inline void LargeStruct::dump() const { // CHECK-NEXT: return _impl::$s7Methods11LargeStructV4dumpyyF(_getOpaquePointer()); // CHECK-NEXT: } // CHECK-NEXT: inline void LargeStruct::double_() { // CHECK-NEXT: return _impl::$s7Methods11LargeStructV6doubleyyF(_getOpaquePointer()); // CHECK-NEXT: } // CHECK-NEXT: inline LargeStruct LargeStruct::scale(swift::Int x, swift::Int y) { // CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::$s7Methods11LargeStructV5scaleyACSi_SitF(result, x, y, _getOpaquePointer()); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK: inline void SmallStruct::dump() const { // CHECK-NEXT: return _impl::$s7Methods11SmallStructV4dumpyyF(_impl::swift_interop_passDirect_Methods_float_0_4(_getOpaquePointer())); // CHECK-NEXT: } // CHECK-NEXT: inline SmallStruct SmallStruct::scale(float y) { // CHECK-NEXT: return _impl::_impl_SmallStruct::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::swift_interop_returnDirect_Methods_float_0_4(result, _impl::$s7Methods11SmallStructV5scaleyACSfF(y, _getOpaquePointer())); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK-NEXT: inline void SmallStruct::invert() { // CHECK-NEXT: return _impl::$s7Methods11SmallStructV6invertyyF(_getOpaquePointer()); // CHECK-NEXT: }
apache-2.0
690e07d9199b5c936f766e8c70697b96
38.548077
212
0.658886
3.390767
false
false
false
false
spweau/Test_DYZB
Test_DYZB/Test_DYZB/Classes/Home/Controller/HomeViewController.swift
1
5430
// // HomeViewController.swift // Test_DYZB // // Created by 欧亚美 on 2017/1/6. // Copyright © 2017年 sp. All rights reserved. // import UIKit private let kTitleViewH : CGFloat = 40 class HomeViewController: UIViewController { // 懒加载 pageTitleView fileprivate lazy var pageTitleview : PageTitleview = { [weak self] in let titleFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH) let titles : [String] = ["推荐" , "游戏" , "娱乐" , "趣玩"] let titleView = PageTitleview(frame: titleFrame, titles: titles) titleView.backgroundColor = UIColor.white // 设置代理 titleView.delegate = self return titleView }() fileprivate lazy var pageContentView : PageContainView = { [weak self] in // 1. 确定内容的frame let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH - kTabbarH let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH) // 2. 确定所有的子控制器 var childVcs = [UIViewController]() childVcs.append(RecommendViewController()) for _ in 0..<3 { let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childVcs.append(vc) } let contentView = PageContainView(frame: contentFrame, childVcs: childVcs, paretentViewController: self) contentView.delegate = self return contentView }() override func viewDidLoad() { super.viewDidLoad() // 设置 UI 界面 setupUI() } /* 1. 首页界面的titleView 封装 1> 自定义view,并且自定义构造函数 2> 添加子控件:1>UIScrollView 2>设置UIcollectionView 3>设置顶部的线段 2. pageController 的封装 1> 自定义View并且自定义构造函数 2> 添加子控件 1>UICollectionView 2>给UICollectionView设置内容 3. 处理titleView 与 pageController的逻辑 1> PageTitleView发生点击事件 1.1> 将PageTitleView中逻辑进行处理 1.2> 告知PageTitleView滚动到正确的控制器 2>PageContentView的滚动 */ } // MARK:- 设置UI界面 extension HomeViewController { fileprivate func setupUI() { // 0.不需要调整UIScrollView的内边距 automaticallyAdjustsScrollViewInsets = false // 1. 设置导航栏 setupNavigationBar() // 2. 添加pageTitleview view.addSubview(pageTitleview) // 3. 添加 pageContentVikew view.addSubview(pageContentView) pageContentView.backgroundColor = UIColor.purple } // 设置 导航栏 private func setupNavigationBar() { // 设置左侧按键 // let btn = UIButton() // btn.setImage(UIImage(named:"logo"), for: .normal) // btn.sizeToFit() navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo") /* 1. 直接 添加 2. 扩充类方法 3. 扩充构造方法 */ let size = CGSize(width: 40, height: 40); // 设置右侧的item // let historyBtn = UIButton() // historyBtn.setImage(UIImage(named:""), for: .normal) // historyBtn.setImage(UIImage(named:""), for: .highlighted) // historyBtn.backgroundColor = UIColor.red //// historyBtn.sizeToFit() // // CGPointZero 报错 ,不能使用 // historyBtn.frame = CGRect(origin: CGPoint(x:0,y:0), size: size) // print("historyBtn.frame = \(historyBtn.frame)") // let historyItem = UIBarButtonItem(customView: historyBtn) // let historyItem = UIBarButtonItem.createItem(imageName: "", hightImageName: "", size: size) // let searchItem = UIBarButtonItem.createItem(imageName: "", hightImageName: "", size: size) // let qrcodeItem = UIBarButtonItem.createItem(imageName: "", hightImageName: "", size: size) let historyItem = UIBarButtonItem(imageName: "", hightImageName: "", size: size) let searchItem = UIBarButtonItem(imageName: "", hightImageName: "", size: size) let qrcodeItem = UIBarButtonItem(imageName: "", hightImageName: "", size: size) navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem]; } } // mark - 遵守PageTitleviewDelegate协议 extension HomeViewController : PageTitleviewDelegate { func pageTitleView(titleView: PageTitleview, selectIndex index: Int) { print(index) pageContentView.setCurrentIndex(currentIndex: index) } } // mark- 遵守PageContainViewDelegate协议 extension HomeViewController : PageContainViewDelegate { func pageContainView(contentView: PageContainView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleview.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
mit
3597fd88d54d7cbdf49dc0b35f00e237
27.748571
156
0.611608
4.791429
false
false
false
false
austinzmchen/guildOfWarWorldBosses
GoWWorldBosses/Models/APIs/JSONModels/WBJsonBase.swift
1
740
// // WBJsonBase.swift // GoWWorldBosses // // Created by Austin Chen on 2016-11-27. // Copyright © 2016 Austin Chen. All rights reserved. // import Foundation import ObjectMapper import AlamofireObjectMapper class WBJsonBase: Mappable, WBRemoteRecordSyncableType { var id: String = "" required init?(map: Map) {} func mapping(map: Map) { var idInt: Int? idInt <- map["id"] // use String as identifier type, no matter what type it is converted from if let i = idInt { self.id = String(format:"%ld",i) } } } extension WBJsonBase: Equatable { static func ==(lhs: WBJsonBase, rhs: WBJsonBase) -> Bool { return lhs.id == rhs.id } }
mit
3aaebaa066addd2bdc15e5fb13d97d63
21.393939
82
0.607578
3.604878
false
false
false
false
Asky314159/jrayfm-controlboard
ios/JRay FM/SecondViewController.swift
1
4041
// // SecondViewController.swift // JRay FM // // Created by Jonathan Ray on 4/10/16. // Copyright © 2016 Jonathan Ray. All rights reserved. // import MediaPlayer import UIKit class SecondViewController: UITableViewController, MPMediaPickerControllerDelegate { @IBOutlet var editButton: UIBarButtonItem! @IBOutlet var doneButton: UIBarButtonItem! private var engine: JRayFMEngine! private var defaultEntryImage: UIImage! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let appDelegate = UIApplication.shared.delegate as! AppDelegate self.engine = appDelegate.engine self.defaultEntryImage = UIImage(systemName: "tv.music.note.fill") self.editButtonVisible(animate: false); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func addLibraryItem(_ sender: AnyObject) { let mediaPicker = MPMediaPickerController(mediaTypes: MPMediaType.music) mediaPicker.allowsPickingMultipleItems = true mediaPicker.showsCloudItems = true mediaPicker.delegate = self mediaPicker.prompt = "Add songs to library" self.present(mediaPicker, animated: true, completion: nil) } func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) { self.dismiss(animated: true, completion: nil) engine.addItemsToLibrary(items: mediaItemCollection.items) tableView.reloadData() } func mediaPickerDidCancel(_ mediaPicker: MPMediaPickerController) { self.dismiss(animated: true, completion: nil) } override func numberOfSections(in tableView: UITableView) -> Int { return engine.getSectionCount() } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return engine.getSectionTitle(section: section) } override func sectionIndexTitles(for tableView: UITableView) -> [String]? { return engine.getSectionTitles() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return engine.getItemCount(section: section) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let entry = engine.getItemAtIndex(section: indexPath.section, index: indexPath.item) cell.textLabel?.text = entry.name cell.detailTextLabel?.text = entry.artist if entry.image != nil { cell.imageView?.image = entry.image } else { cell.imageView?.image = self.defaultEntryImage cell.imageView?.tintColor = UIColor.label } return cell } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == UITableViewCell.EditingStyle.delete { engine.removeItemAtIndex(section: indexPath.section, index: indexPath.item) tableView.reloadData() } } @IBAction func editButtonPressed(_ sender: Any) { self.doneButtonVisible(animate: true) tableView.setEditing(true, animated: true) } @IBAction func doneButtonPressed(_ sender: Any) { self.editButtonVisible(animate: true) tableView.setEditing(false, animated: true) } func editButtonVisible(animate: Bool) { self.navigationItem.setLeftBarButtonItems([editButton], animated: animate) } func doneButtonVisible(animate:Bool) { self.navigationItem.setLeftBarButtonItems([doneButton], animated: animate) } }
mit
c794f2d73e9291eeca5d3d4cfdbc5608
34.438596
137
0.679208
5.253576
false
false
false
false
sjsoad/SKUtils
SKUtils/Core/Services/DefaultServiceRepository.swift
1
1582
// // DefaultServiceRepository.swift // SKUtils // // Created by Sergey on 04.09.2018. // Copyright © 2018 Sergey Kostyan. All rights reserved. // import UIKit import SKNetworkingLib protocol ServicesRepository { var defaultNetworkService: NetworkService { get } func networkErrorParser() -> ErrorParsable func networkService(with reAuthorizer: ReAuthorizable?) -> NetworkService func authentificationService() -> ReAuthorizable func ipDetectingService() -> IpDetectingService } struct DefaultServiceRepository: ServicesRepository { static let shared: ServicesRepository = DefaultServiceRepository() let defaultNetworkService: NetworkService init() { let networkService = DefaultNetworkService(errorParser: NetworkErrorParser()) let authService = AuthentificationService(networkService: networkService) defaultNetworkService = DefaultNetworkService(reAuthorizer: authService, errorParser: NetworkErrorParser()) } func networkErrorParser() -> ErrorParsable { return NetworkErrorParser() } func networkService(with reAuthorizer: ReAuthorizable? = nil) -> NetworkService { return DefaultNetworkService(reAuthorizer: reAuthorizer, errorParser: networkErrorParser()) } func authentificationService() -> ReAuthorizable { return AuthentificationService(networkService: networkService()) } func ipDetectingService() -> IpDetectingService { return DefaultIpDetectingService(networkService: defaultNetworkService) } }
mit
f7e6376d8326a743db08d273729b9ac8
30.62
115
0.734978
5.235099
false
false
false
false
TH-Brandenburg/University-Evaluation-iOS
Pods/EVReflection/EVReflection/pod/EVReflection.swift
1
60296
// // EVReflection.swift // // Created by Edwin Vermeer on 28-09-14. // Copyright (c) 2014 EVICT BV. All rights reserved. // import Foundation /** Reflection methods */ final public class EVReflection { // MARK: - From and to Dictrionary parsing /** Create an object from a dictionary - parameter dictionary: The dictionary that will be converted to an object - parameter anyobjectTypeString: The string representation of the object type that will be created - parameter conversionOptions: Option set for the various conversion options. - returns: The object that is created from the dictionary */ public class func fromDictionary(dictionary: NSDictionary, anyobjectTypeString: String, conversionOptions: ConversionOptions = .DefaultDeserialize) -> NSObject? { if var nsobject = swiftClassFromString(anyobjectTypeString) { if let evResult = nsobject as? EVObject { nsobject = evResult.getSpecificType(dictionary) } nsobject = setPropertiesfromDictionary(dictionary, anyObject: nsobject, conversionOptions: conversionOptions) return nsobject } return nil } /** Set object properties from a dictionary - parameter dictionary: The dictionary that will be converted to an object - parameter anyObject: The object where the properties will be set - parameter conversionOptions: Option set for the various conversion options. - returns: The object that is created from the dictionary */ public class func setPropertiesfromDictionary<T where T: NSObject>(dictionary: NSDictionary, anyObject: T, conversionOptions: ConversionOptions = .DefaultDeserialize) -> T { autoreleasepool { (anyObject as? EVObject)?.initValidation(dictionary) let (keyMapping, _, types) = getKeyMapping(anyObject, dictionary: dictionary, conversionOptions: .PropertyMapping) for (k, v) in dictionary { var skipKey = false if conversionOptions.contains(.PropertyMapping) { if let evObject = anyObject as? EVObject { if let mapping = evObject.propertyMapping().filter({$0.0 == k as? String}).first { if mapping.1 == nil { skipKey = true } } } } if !skipKey { let mapping = keyMapping[k as? String ?? ""] let useKey: String = (mapping ?? k ?? "") as? String ?? "" let original: NSObject? = getValue(anyObject, key: useKey) let (dictValue, valid) = dictionaryAndArrayConversion(anyObject, key: k as? String ?? "", fieldType: types[k as? String ?? ""] as? String ?? types[useKey] as? String, original: original, theDictValue: v, conversionOptions: conversionOptions) if dictValue != nil { if let key: String = keyMapping[k as? String ?? ""] as? String { setObjectValue(anyObject, key: key, theValue: (valid ? dictValue: v), typeInObject: types[key] as? String, valid: valid, conversionOptions: conversionOptions) } else { setObjectValue(anyObject, key: k as? String ?? "", theValue: (valid ? dictValue : v), typeInObject: types[k as? String ?? ""] as? String, valid: valid, conversionOptions: conversionOptions) } } } } } return anyObject } public class func getValue(fromObject: NSObject, key: String) -> NSObject? { if let mapping = (Mirror(reflecting: fromObject).children.filter({$0.0 == key}).first) { if let value = mapping.value as? NSObject { return value } } return nil } /** Based on an object and a dictionary create a keymapping plus a dictionary of properties plus a dictionary of types - parameter anyObject: the object for the mapping - parameter dictionary: the dictionary that has to be mapped - parameter conversionOptions: Option set for the various conversion options. - returns: The mapping, keys and values of all properties to items in a dictionary */ private static func getKeyMapping<T where T: NSObject>(anyObject: T, dictionary: NSDictionary, conversionOptions: ConversionOptions = .DefaultDeserialize) -> (keyMapping: NSDictionary, properties: NSDictionary, types: NSDictionary) { let (properties, types) = toDictionary(anyObject, conversionOptions: conversionOptions, isCachable: true) var keyMapping: Dictionary<String, String> = Dictionary<String, String>() for (objectKey, _) in properties { if conversionOptions.contains(.PropertyMapping) { if let evObject = anyObject as? EVObject { if let mapping = evObject.propertyMapping().filter({$0.1 == objectKey as? String}).first { keyMapping[objectKey as? String ?? ""] = mapping.0 } } } if let dictKey = cleanupKey(anyObject, key: objectKey as? String ?? "", tryMatch: dictionary) { if dictKey != objectKey as? String { keyMapping[dictKey] = objectKey as? String } } } return (keyMapping, properties, types) } static var properiesCache = NSMutableDictionary() static var typesCache = NSMutableDictionary() /** Convert an object to a dictionary while cleaning up the keys - parameter theObject: The object that will be converted to a dictionary - parameter conversionOptions: Option set for the various conversion options. - returns: The dictionary that is created from theObject plus a dictionary of propery types. */ public class func toDictionary(theObject: NSObject, conversionOptions: ConversionOptions = .DefaultSerialize, isCachable: Bool = false, parents: [NSObject] = []) -> (NSDictionary, NSDictionary) { var pdict: NSDictionary? var tdict: NSDictionary? var i = 1 for parent in parents { if parent === theObject { pdict = NSMutableDictionary() pdict!.setValue("\(i)", forKey: "_EVReflection_parent_") tdict = NSMutableDictionary() tdict!.setValue("NSString", forKey: "_EVReflection_parent_") return (pdict!, tdict!) } i = i + 1 } var theParents = parents theParents.append(theObject) let key: String = "\(theObject.dynamicType).\(conversionOptions.rawValue)" if isCachable { if let p = properiesCache[key] as? NSDictionary, let t = typesCache[key] as? NSDictionary { return (p, t) } } autoreleasepool { let reflected = Mirror(reflecting: theObject) var (properties, types) = reflectedSub(theObject, reflected: reflected, conversionOptions: conversionOptions, isCachable: isCachable, parents: theParents) if conversionOptions.contains(.KeyCleanup) { (properties, types) = cleanupKeysAndValues(theObject, properties:properties, types:types) } pdict = properties tdict = types } if isCachable && typesCache[key] == nil { properiesCache[key] = pdict! typesCache[key] = tdict! } return (pdict!, tdict!) } // MARK: - From and to JSON parsing /** Return a dictionary representation for the json string - parameter json: The json string that will be converted - returns: The dictionary representation of the json */ public class func dictionaryFromJson(json: String?) -> NSDictionary { var result = NSDictionary() if json == nil { return result } if let jsonData = json!.dataUsingEncoding(NSUTF8StringEncoding) { do { if let jsonDic = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary { result = jsonDic } } catch _ as NSError { } } return result } /** Return an array representation for the json string - parameter type: An instance of the type where the array will be created of. - parameter json: The json string that will be converted - parameter conversionOptions: Option set for the various conversion options. - returns: The array of dictionaries representation of the json */ public class func arrayFromJson<T>(theObject: NSObject? = nil, type: T, json: String?, conversionOptions: ConversionOptions = .DefaultDeserialize) -> [T] { var result = [T]() if json == nil { return result } let jsonData = json!.dataUsingEncoding(NSUTF8StringEncoding)! do { if let jsonDic: [Dictionary<String, AnyObject>] = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers) as? [Dictionary<String, AnyObject>] { let nsobjectype: NSObject.Type? = T.self as? NSObject.Type if nsobjectype == nil { print("WARNING: EVReflection can only be used with types with NSObject as it's minimal base type") return result } result = jsonDic.map({ let nsobject: NSObject = nsobjectype!.init() return (setPropertiesfromDictionary($0, anyObject: nsobject, conversionOptions: conversionOptions) as? T)! }) } } catch _ as NSError {} return result } /** Return a Json string representation of this object - parameter theObject: The object that will be loged - parameter conversionOptions: Option set for the various conversion options. - returns: The string representation of the object */ public class func toJsonString(theObject: NSObject, conversionOptions: ConversionOptions = .DefaultSerialize) -> String { var result: String = "" autoreleasepool { var (dict, _) = EVReflection.toDictionary(theObject, conversionOptions: conversionOptions) dict = convertDictionaryForJsonSerialization(dict, theObject: theObject) do { let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted) if let jsonString = NSString(data:jsonData, encoding:NSUTF8StringEncoding) { result = jsonString as String } } catch { } } return result } // MARK: - Adding functionality to objects /** Dump the content of this object to the output - parameter theObject: The object that will be loged */ public class func logObject(theObject: NSObject) { NSLog(description(theObject)) } /** Return a string representation of this object - parameter theObject: The object that will be loged - parameter conversionOptions: Option set for the various conversion options. - returns: The string representation of the object */ public class func description(theObject: NSObject, conversionOptions: ConversionOptions = .DefaultSerialize) -> String { let (hasKeys, _) = toDictionary(theObject, conversionOptions: conversionOptions) var description: String = (swiftStringFromClass(theObject) ?? "?") + " {\n hash = \(hashValue(theObject))" description = description + hasKeys.map {" \($0) = \($1)"}.reduce("") {"\($0)\n\($1)"} + "\n}\n" return description } /** Create a hashvalue for the object - parameter theObject: The object for what you want a hashvalue - returns: the hashvalue for the object */ public class func hashValue(theObject: NSObject) -> Int { let (hasKeys, _) = toDictionary(theObject, conversionOptions: .DefaultComparing) return Int(hasKeys.map {$1}.reduce(0) {(31 &* $0) &+ $1.hash}) } /** Encode any object - parameter theObject: The object that we want to encode. - parameter aCoder: The NSCoder that will be used for encoding the object. - parameter conversionOptions: Option set for the various conversion options. */ public class func encodeWithCoder(theObject: EVObject, aCoder: NSCoder, conversionOptions: ConversionOptions = .DefaultNSCoding) { let (hasKeys, _) = toDictionary(theObject, conversionOptions: conversionOptions) for (key, value) in hasKeys { aCoder.encodeObject(value, forKey: key as? String ?? "") } } /** Decode any object - parameter theObject: The object that we want to decode. - parameter aDecoder: The NSCoder that will be used for decoding the object. - parameter conversionOptions: Option set for the various conversion options. */ public class func decodeObjectWithCoder(theObject: EVObject, aDecoder: NSCoder, conversionOptions: ConversionOptions = .DefaultNSCoding) { let (hasKeys, _) = toDictionary(theObject, conversionOptions: conversionOptions, isCachable: true) let dict = NSMutableDictionary() for (key, _) in hasKeys { if aDecoder.containsValueForKey((key as? String)!) { let newValue: AnyObject? = aDecoder.decodeObjectForKey((key as? String)!) if !(newValue is NSNull) { dict[(key as? String)!] = newValue } } } EVReflection.setPropertiesfromDictionary(dict, anyObject: theObject, conversionOptions: conversionOptions) } /** Compare all fields of 2 objects - parameter lhs: The first object for the comparisson - parameter rhs: The second object for the comparisson - returns: true if the objects are the same, otherwise false */ public class func areEqual(lhs: NSObject, rhs: NSObject) -> Bool { if swiftStringFromClass(lhs) != swiftStringFromClass(rhs) { return false } let (lhsdict, _) = toDictionary(lhs, conversionOptions: .DefaultComparing) let (rhsdict, _) = toDictionary(rhs, conversionOptions: .DefaultComparing) return dictionariesAreEqual(lhsdict, rhsdict: rhsdict) } /** Compare 2 dictionaries - parameter lhsdict: Compare this dictionary - parameter rhsdict: Compare with this dictionary - returns: Are the dictionaries equal or not */ public class func dictionariesAreEqual(lhsdict: NSDictionary, rhsdict: NSDictionary) -> Bool { for (key, value) in rhsdict { if let compareTo = lhsdict[(key as? String)!] { if let dateCompareTo = compareTo as? NSDate, dateValue = value as? NSDate { let t1 = Int64(dateCompareTo.timeIntervalSince1970) let t2 = Int64(dateValue.timeIntervalSince1970) if t1 != t2 { return false } } else if let array = compareTo as? NSArray, arr = value as? NSArray { if arr.count != array.count { return false } for (index, arrayValue) in array.enumerate() { if arrayValue as? NSDictionary != nil { if !dictionariesAreEqual((arrayValue as? NSDictionary)!, rhsdict: (arr[index] as? NSDictionary)!) { return false } } else { if !arrayValue.isEqual(arr[index]) { return false } } } } else if !compareTo.isEqual(value) { return false } } } return true } // MARK: - Reflection helper functions /** Get the app name from the 'Bundle name' and if that's empty, then from the 'Bundle identifier' otherwise we assume it's a EVReflection unit test and use that bundle identifier - parameter forObject: Pass an object to this method if you know a class from the bundele where you want the name for. - returns: A cleaned up name of the app. */ public class func getCleanAppName(forObject: NSObject? = nil) -> String { var bundle = NSBundle.mainBundle() if forObject != nil { bundle = NSBundle(forClass: forObject!.dynamicType) } if forObject == nil && EVReflection.bundleIdentifier != nil { return EVReflection.bundleIdentifier! } var appName = bundle.infoDictionary?["CFBundleName"] as? String ?? "" if appName == "" { if bundle.bundleIdentifier == nil { bundle = NSBundle(forClass: EVReflection().dynamicType) } appName = (bundle.bundleIdentifier!).characters.split(isSeparator: {$0 == "."}).map({ String($0) }).last ?? "" } let cleanAppName = appName .stringByReplacingOccurrencesOfString(" ", withString: "_", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) .stringByReplacingOccurrencesOfString("-", withString: "_", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) return cleanAppName } /// Variable that can be set using setBundleIdentifier private static var bundleIdentifier: String? = nil /// Variable that can be set using setBundleIdentifiers private static var bundleIdentifiers: [String]? = nil /** This method can be used in unit tests to force the bundle where classes can be found - parameter forClass: The class that will be used to find the appName for in which we can find classes by string. */ public class func setBundleIdentifier(forClass: AnyClass) { if let bundle: NSBundle = NSBundle(forClass:forClass) { EVReflection.bundleIdentifier = bundleForClass(forClass, bundle: bundle) } } /** This method can be used in project where models are split between multiple modules. - parameter classes: classes that that will be used to find the appName for in which we can find classes by string. */ public class func setBundleIdentifiers(classes: Array<AnyClass>) { bundleIdentifiers = [] for aClass in classes { if let bundle: NSBundle = NSBundle(forClass: aClass) { bundleIdentifiers?.append(bundleForClass(aClass, bundle: bundle)) } } } private static func bundleForClass(forClass: AnyClass, bundle: NSBundle) -> String { let appName = (bundle.infoDictionary![kCFBundleNameKey as String] as? String)!.characters.split(isSeparator: {$0 == "."}).map({ String($0) }).last ?? "" let cleanAppName = appName .stringByReplacingOccurrencesOfString(" ", withString: "_", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) .stringByReplacingOccurrencesOfString("-", withString: "_", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) return cleanAppName } /// This dateformatter will be used when a conversion from string to NSDate is required private static var dateFormatter: NSDateFormatter? = nil /** This function can be used to force using an alternat dateformatter for converting String to NSDate - parameter formatter: The new DateFormatter */ public class func setDateFormatter(formatter: NSDateFormatter?) { dateFormatter = formatter } /** This function is used for getting the dateformatter and defaulting to a standard if it's not set - returns: The dateformatter */ private class func getDateFormatter() -> NSDateFormatter { if let formatter = dateFormatter { return formatter } dateFormatter = NSDateFormatter() dateFormatter!.locale = NSLocale(localeIdentifier: "en_US_POSIX") dateFormatter!.timeZone = NSTimeZone(forSecondsFromGMT: 0) dateFormatter!.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZ" return dateFormatter! } /** Get the swift Class type from a string - parameter className: The string representation of the class (name of the bundle dot name of the class) - returns: The Class type */ public class func swiftClassTypeFromString(className: String) -> AnyClass? { if let c = NSClassFromString(className) { return c } // The default did not work. try a combi of appname and classname if className.rangeOfString(".", options: NSStringCompareOptions.CaseInsensitiveSearch) == nil { let appName = getCleanAppName() if let c = NSClassFromString("\(appName).\(className)") { return c } } if let bundleIdentifiers = bundleIdentifiers { for aBundle in bundleIdentifiers { if let existingClass = NSClassFromString("\(aBundle).\(className)") { return existingClass } } } return nil } /** Get the swift Class from a string - parameter className: The string representation of the class (name of the bundle dot name of the class) - returns: The Class type */ public class func swiftClassFromString(className: String) -> NSObject? { return (swiftClassTypeFromString(className) as? NSObject.Type)?.init() } /** Get the class name as a string from a swift class - parameter theObject: An object for whitch the string representation of the class will be returned - returns: The string representation of the class (name of the bundle dot name of the class) */ public class func swiftStringFromClass(theObject: NSObject) -> String! { return NSStringFromClass(theObject.dynamicType).stringByReplacingOccurrencesOfString(getCleanAppName(theObject) + ".", withString: "", options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil) } /** Helper function to convert an Any to AnyObject - parameter parentObject: Only needs to be set to the object that has this property when the value is from a property that is an array of optional values - parameter key: Only needs to be set to the name of the property when the value is from a property that is an array of optional values - parameter anyValue: Something of type Any is converted to a type NSObject - parameter conversionOptions: Option set for the various conversion options. - returns: The value where the Any is converted to AnyObject plus the type of that value as a string */ public class func valueForAny(parentObject: Any? = nil, key: String? = nil, anyValue: Any, conversionOptions: ConversionOptions = .DefaultDeserialize, isCachable: Bool = false, parents: [NSObject] = []) -> (value: AnyObject, type: String, isObject: Bool) { var theValue = anyValue var valueType = "EVObject" var mi: Mirror = Mirror(reflecting: theValue) if mi.displayStyle == .Optional { if mi.children.count == 1 { theValue = mi.children.first!.value mi = Mirror(reflecting: theValue) if "\(theValue.dynamicType)".hasPrefix("_TtC") { valueType = "\(theValue)".componentsSeparatedByString(" ")[0] } else { valueType = "\(theValue.dynamicType)" } } else if mi.children.count == 0 { var subtype: String = "\(mi)" subtype = subtype.substringFromIndex((subtype.componentsSeparatedByString("<") [0] + "<").endIndex) subtype = subtype.substringToIndex(subtype.endIndex.predecessor()) return (NSNull(), subtype, false) } } if mi.displayStyle == .Enum { valueType = "\(theValue.dynamicType)" if let value = theValue as? EVRawString { return (value.rawValue, "\(mi.subjectType)", false) } else if let value = theValue as? EVRawInt { return (NSNumber(int: Int32(value.rawValue)), "\(mi.subjectType)", false) } else if let value = theValue as? EVRaw { theValue = value.anyRawValue } else if let value = theValue as? EVAssociated { let (enumValue, enumType, _) = valueForAny(theValue, key: value.associated.label, anyValue: value.associated.value, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) valueType = enumType theValue = enumValue } else { theValue = "\(theValue)" } } else if mi.displayStyle == .Collection { valueType = "\(mi.subjectType)" if valueType.hasPrefix("Array<Optional<") { if let arrayConverter = parentObject as? EVArrayConvertable { let convertedValue = arrayConverter.convertArray(key!, array: theValue) return (convertedValue, valueType, false) } (parentObject as? EVObject)?.addStatusMessage(.MissingProtocol, message: "An object with a property of type Array with optional objects should implement the EVArrayConvertable protocol. type = \(valueType) for key \(key)") print("WARNING: An object with a property of type Array with optional objects should implement the EVArrayConvertable protocol. type = \(valueType) for key \(key)") return (NSNull(), "NSNull", false) } } else if mi.displayStyle == .Dictionary { valueType = "\(mi.subjectType)" if let dictionaryConverter = parentObject as? EVObject { let convertedValue = dictionaryConverter.convertDictionary(key!, dict: theValue) return (convertedValue, valueType, false) } } else if mi.displayStyle == .Struct { valueType = "\(mi.subjectType)" if valueType.containsString("_NativeDictionaryStorage") { if let dictionaryConverter = parentObject as? EVObject { let convertedValue = dictionaryConverter.convertDictionary(key!, dict: theValue) return (convertedValue, valueType, false) } } let structAsDict = convertStructureToDictionary(theValue, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) return (structAsDict, "Struct", false) } else { valueType = "\(mi.subjectType)" } return valueForAnyDetail(parentObject, theValue: theValue, valueType: valueType) } public class func valueForAnyDetail(parentObject: Any? = nil, theValue: Any, valueType: String) -> (value: AnyObject, type: String, isObject: Bool) { if theValue is NSNumber { return (theValue as! NSNumber, "NSNumber", false) } if theValue is Int64 { return (NSNumber(longLong: theValue as! Int64), "NSNumber", false) } if theValue is UInt64 { return (NSNumber(unsignedLongLong: theValue as! UInt64), "NSNumber", false) } if theValue is Int32 { return (NSNumber(int: theValue as! Int32), "NSNumber", false) } if theValue is UInt32 { return (NSNumber(unsignedInt: theValue as! UInt32), "NSNumber", false) } if theValue is Int16 { return (NSNumber(short: theValue as! Int16), "NSNumber", false) } if theValue is UInt16 { return (NSNumber(unsignedShort: theValue as! UInt16), "NSNumber", false) } if theValue is Int8 { return (NSNumber(char: theValue as! Int8), "NSNumber", false) } if theValue is UInt8 { return (NSNumber(unsignedChar: theValue as! UInt8), "NSNumber", false) } if theValue is NSString { return (theValue as! NSString, "NSString", false) } if theValue is NSDate { return (theValue as! NSDate, "NSDate", false) } if theValue is NSArray { return (theValue as! NSArray, valueType, false) } if theValue is EVObject { if valueType.containsString("<") { return (theValue as! EVObject, swiftStringFromClass(theValue as! EVObject), true) } return (theValue as! EVObject, valueType, true) } if theValue is NSObject { if valueType.containsString("<") { return (theValue as! NSObject, swiftStringFromClass(theValue as! NSObject), true) } // isObject is false to prevent parsing of objects like CKRecord, CKRecordId and other objects. return (theValue as! NSObject, valueType, false) } (parentObject as? EVObject)?.addStatusMessage(.InvalidType, message: "valueForAny unkown type \(valueType) for value: \(theValue).") print("ERROR: valueForAny unkown type \(valueType) for value: \(theValue).") return (NSNull(), "NSNull", false) } private static func convertStructureToDictionary(theValue: Any, conversionOptions: ConversionOptions, isCachable: Bool, parents: [NSObject] = []) -> NSDictionary { let reflected = Mirror(reflecting: theValue) let (addProperties, _) = reflectedSub(theValue, reflected: reflected, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) return addProperties } /** Try to set a value of a property with automatic String to and from Number conversion - parameter anyObject: the object where the value will be set - parameter key: the name of the property - parameter theValue: the value that will be set - parameter typeInObject: the type of the value - parameter valid: False if a vaue is expected and a dictionary - parameter conversionOptions: Option set for the various conversion options. */ public static func setObjectValue<T where T: NSObject>(anyObject: T, key: String, theValue: AnyObject?, typeInObject: String? = nil, valid: Bool, conversionOptions: ConversionOptions = .DefaultDeserialize, parents: [NSObject] = []) { guard var value = theValue where (value as? NSNull) == nil else { return } if conversionOptions.contains(.PropertyConverter) { if let (_, propertySetter, _) = (anyObject as? EVObject)?.propertyConverters().filter({$0.0 == key}).first { guard let propertySetter = propertySetter else { return // if the propertySetter is nil, skip setting the property } propertySetter(value) return } } // Let us put a number into a string property by taking it's stringValue let (_, type, _) = valueForAny("", key: key, anyValue: value, conversionOptions: conversionOptions, isCachable: false, parents: parents) if (typeInObject == "String" || typeInObject == "NSString") && type == "NSNumber" { if let convertedValue = value as? NSNumber { value = convertedValue.stringValue } } else if typeInObject == "NSNumber" && (type == "String" || type == "NSString") { if let convertedValue = (value as? String)?.lowercaseString { if convertedValue == "true" || convertedValue == "yes" { value = 1 } else if convertedValue == "false" || convertedValue == "no" { value = 0 } else { value = NSNumber(double: Double(convertedValue) ?? 0) } } } else if typeInObject == "NSDate" && (type == "String" || type == "NSString") { if let convertedValue = value as? String { guard let date = getDateFormatter().dateFromString(convertedValue) else { (anyObject as? EVObject)?.addStatusMessage(.InvalidValue, message: "The dateformatter returend nil for value \(convertedValue)") print("WARNING: The dateformatter returend nil for value \(convertedValue)") return } value = date } } if typeInObject == "Struct" { anyObject.setValue(value, forUndefinedKey: key) } else { if !valid { anyObject.setValue(theValue, forUndefinedKey: key) return } // Call your own object validators that comply to the format: validate<Key>:Error: do { var setValue: AnyObject? = value try anyObject.validateValue(&setValue, forKey: key) anyObject.setValue(setValue, forKey: key) } catch _ { (anyObject as? EVObject)?.addStatusMessage(.InvalidValue, message: "Not a valid value for object `\(anyObject.dynamicType)`, type `\(type)`, key `\(key)`, value `\(value)`") print("INFO: Not a valid value for object `\(anyObject.dynamicType)`, type `\(type)`, key `\(key)`, value `\(value)`") } /* TODO: Do I dare? ... For nullable types like Int? we could use this instead of the workaround. // Asign pointerToField based on specific type // Look up the ivar, and it's offset let ivar: Ivar = class_getInstanceVariable(anyObject.dynamicType, key) let fieldOffset = ivar_getOffset(ivar) // Pointer arithmetic to get a pointer to the field let pointerToInstance = unsafeAddressOf(anyObject) let pointerToField = UnsafeMutablePointer<Int?>(pointerToInstance + fieldOffset) // Set the value using the pointer pointerToField.memory = value! */ } } // MARK: - Private helper functions /** Create a dictionary of all property - key mappings - parameter theObject: the object for what we want the mapping - parameter properties: dictionairy of all the properties - parameter types: dictionairy of all property types. - returns: dictionairy of the property mappings */ private class func cleanupKeysAndValues(theObject: NSObject, properties: NSDictionary, types: NSDictionary) -> (NSDictionary, NSDictionary) { let newProperties = NSMutableDictionary() let newTypes = NSMutableDictionary() for (key, _) in properties { if let newKey = cleanupKey(theObject, key: (key as? String)!, tryMatch: nil) { newProperties[newKey] = properties[(key as? String)!] newTypes[newKey] = types[(key as? String)!] } } return (newProperties, newTypes) } /** Try to map a property name to a json/dictionary key by applying some rules like property mapping, snake case conversion or swift keyword fix. - parameter anyObject: the object where the key is part of - parameter key: the key to clean up - parameter tryMatch: dictionary of keys where a mach will be tried to - returns: the cleaned up key */ private class func cleanupKey(anyObject: NSObject, key: String, tryMatch: NSDictionary?) -> String? { var newKey: String = key if tryMatch?[newKey] != nil { return newKey } // Step 1 - clean up keywords if newKey.characters.first == "_" { if keywords.contains(newKey.substringFromIndex(newKey.startIndex.advancedBy(1))) { newKey = newKey.substringFromIndex(newKey.startIndex.advancedBy(1)) if tryMatch?[newKey] != nil { return newKey } } } // Step 2 - replace illegal characters if let t = tryMatch { for (key, _) in t { var k = key if let kIsString = k as? String { k = processIllegalCharacters(kIsString) } if k as? String == newKey { return key as? String } } } // Step 3 - from PascalCase or camelCase to snakeCase newKey = camelCaseToUnderscores(newKey) if tryMatch?[newKey] != nil { return newKey } if tryMatch != nil { return nil } return newKey } /// Character that will be replaced by _ from the keys in a dictionary / json private static let illegalCharacterSet = NSCharacterSet(charactersInString: " -&%#@!$^*()<>?.,:;") /// processIllegalCharacters Cache private static var processIllegalCharactersCache = [ String : String ]() /** Replace illegal characters to an underscore - parameter input: key - returns: processed string with illegal characters converted to underscores */ internal static func processIllegalCharacters(input: String) -> String { if let cacheHit = processIllegalCharactersCache[input] { return cacheHit } let output = input.componentsSeparatedByCharactersInSet(illegalCharacterSet).joinWithSeparator("_") processIllegalCharactersCache[input] = output return output } /// camelCaseToUnderscoresCache Cache private static var camelCaseToUnderscoresCache = [ String : String ]() /** Convert a CamelCase to Underscores - parameter input: the CamelCase string - returns: the underscore string */ internal static func camelCaseToUnderscores(input: String) -> String { if let cacheHit = camelCaseToUnderscoresCache[input] { return cacheHit } var output: String = String(input.characters.first!).lowercaseString let uppercase: NSCharacterSet = NSCharacterSet.uppercaseLetterCharacterSet() for character in input.substringFromIndex(input.startIndex.advancedBy(1)).characters { if uppercase.characterIsMember(String(character).utf16.first!) { output += "_\(String(character).lowercaseString)" } else { output += "\(String(character))" } } camelCaseToUnderscoresCache[input] = output return output } /// List of swift keywords for cleaning up keys private static let keywords = ["self", "description", "class", "deinit", "enum", "extension", "func", "import", "init", "let", "protocol", "static", "struct", "subscript", "typealias", "var", "break", "case", "continue", "default", "do", "else", "fallthrough", "if", "in", "for", "return", "switch", "where", "while", "as", "dynamicType", "is", "new", "super", "Self", "Type", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__", "associativity", "didSet", "get", "infix", "inout", "left", "mutating", "none", "nonmutating", "operator", "override", "postfix", "precedence", "prefix", "right", "set", "unowned", "unowned", "safe", "unowned", "unsafe", "weak", "willSet", "private", "public", "internal", "zone"] /** Convert a value in the dictionary to the correct type for the object - parameter anyObject: The object where this dictionary is a property - parameter key: The property name that is the dictionary - parameter fieldType: type of the field in object - parameter original: the original value - parameter theDictValue: the value from the dictionary - parameter conversionOptions: Option set for the various conversion options. - returns: The converted value plus a boolean indicating if it's an object */ private static func dictionaryAndArrayConversion(anyObject: NSObject, key: String, fieldType: String?, original: NSObject?, theDictValue: AnyObject?, conversionOptions: ConversionOptions = .DefaultDeserialize) -> (AnyObject?, Bool) { var dictValue = theDictValue var valid = true if let type = fieldType { if type.hasPrefix("Array<") && dictValue as? NSDictionary != nil { if (dictValue as? NSDictionary)?.count == 1 { // XMLDictionary fix let onlyElement = (dictValue as? NSDictionary)?.generate().next() let t: String = (onlyElement?.key as? String) ?? "" if onlyElement?.value as? NSArray != nil && type.lowercaseString == "array<\(t)>" { dictValue = onlyElement?.value as? NSArray dictValue = dictArrayToObjectArray(type, array: (dictValue as? [NSDictionary]) ?? [NSDictionary](), conversionOptions: conversionOptions) as NSArray } else { // Single object array fix var array: [NSDictionary] = [NSDictionary]() array.append(dictValue as? NSDictionary ?? NSDictionary()) dictValue = dictArrayToObjectArray(type, array: array, conversionOptions: conversionOptions) as NSArray } } else { // Single object array fix var array: [NSDictionary] = [NSDictionary]() array.append(dictValue as? NSDictionary ?? NSDictionary()) dictValue = dictArrayToObjectArray(type, array: array, conversionOptions: conversionOptions) as NSArray } } else if let _ = type.rangeOfString("_NativeDictionaryStorageOwner"), let dict = dictValue as? NSDictionary, let org = anyObject as? EVObject { dictValue = org.convertDictionary(key, dict: dict) } else if type != "NSDictionary" && dictValue as? NSDictionary != nil { let (dict, isValid) = dictToObject(type, original: original, dict: dictValue as? NSDictionary ?? NSDictionary(), conversionOptions: conversionOptions) dictValue = dict ?? dictValue valid = isValid } else if type.rangeOfString("<NSDictionary>") == nil && dictValue as? [NSDictionary] != nil { // Array of objects dictValue = dictArrayToObjectArray(type, array: dictValue as? [NSDictionary] ?? [NSDictionary](), conversionOptions: conversionOptions) as NSArray } else if original is EVObject && dictValue is String { // fixing the conversion from XML without properties let (dict, isValid) = dictToObject(type, original:original, dict: ["__text": dictValue as? String ?? ""], conversionOptions: conversionOptions) dictValue = dict ?? dictValue valid = isValid } } return (dictValue, valid) } /** Set sub object properties from a dictionary - parameter type: The object type that will be created - parameter original: The original value in the object which is used to create a return object - parameter dict: The dictionary that will be converted to an object - parameter conversionOptions: Option set for the various conversion options. - returns: The object that is created from the dictionary */ private class func dictToObject<T where T:NSObject>(type: String, original: T?, dict: NSDictionary, conversionOptions: ConversionOptions = .DefaultDeserialize) -> (T?, Bool) { if var returnObject = original { if type != "NSNumber" && type != "NSString" && type != "NSDate" && type.containsString("Dictionary<") == false { returnObject = setPropertiesfromDictionary(dict, anyObject: returnObject, conversionOptions: conversionOptions) } else { if type.containsString("Dictionary<") == false { (original as? EVObject)?.addStatusMessage(.InvalidClass, message: "Cannot set values on type \(type) from dictionary \(dict)") print("WARNING: Cannot set values on type \(type) from dictionary \(dict)") } return (returnObject, false) } return (returnObject, true) } if var returnObject: NSObject = swiftClassFromString(type) { if let evResult = returnObject as? EVObject { returnObject = evResult.getSpecificType(dict) } returnObject = setPropertiesfromDictionary(dict, anyObject: returnObject, conversionOptions: conversionOptions) return (returnObject as? T, true) } if type != "Struct" { (original as? EVObject)?.addStatusMessage(.InvalidClass, message: "Could not create an instance for type \(type)\ndict:\(dict)") print("ERROR: Could not create an instance for type \(type)\ndict:\(dict)") } return (nil, false) } /** Create an Array of objects from an array of dictionaries - parameter type: The object type that will be created - parameter array: The array of dictionaries that will be converted to the array of objects - parameter conversionOptions: Option set for the various conversion options. - returns: The array of objects that is created from the array of dictionaries */ private class func dictArrayToObjectArray(type: String, array: NSArray, conversionOptions: ConversionOptions = .DefaultDeserialize) -> NSArray { var subtype = "EVObject" if type.componentsSeparatedByString("<").count > 1 { // Remove the Array prefix subtype = type.substringFromIndex((type.componentsSeparatedByString("<") [0] + "<").endIndex) subtype = subtype.substringToIndex(subtype.endIndex.predecessor()) // Remove the optional prefix from the subtype if subtype.hasPrefix("Optional<") { subtype = subtype.substringFromIndex((subtype.componentsSeparatedByString("<") [0] + "<").endIndex) subtype = subtype.substringToIndex(subtype.endIndex.predecessor()) } } var result = [NSObject]() for item in array { var org = swiftClassFromString(subtype) if let evResult = org as? EVObject { org = evResult.getSpecificType(item as? NSDictionary ?? NSDictionary()) } let (arrayObject, valid) = dictToObject(subtype, original:org, dict: item as? NSDictionary ?? NSDictionary(), conversionOptions: conversionOptions) if arrayObject != nil && valid { result.append(arrayObject!) } } return result } /** for parsing an object to a dictionary. including properties from it's super class (recursive) - parameter theObject: The object as is - parameter reflected: The object parsed using the reflect method. - parameter conversionOptions: Option set for the various conversion options. - returns: The dictionary that is created from the object plus an dictionary of property types. */ private class func reflectedSub(theObject: Any, reflected: Mirror, conversionOptions: ConversionOptions = .DefaultDeserialize, isCachable: Bool, parents: [NSObject] = []) -> (NSDictionary, NSDictionary) { let propertiesDictionary = NSMutableDictionary() let propertiesTypeDictionary = NSMutableDictionary() // First add the super class propperties if let superReflected = reflected.superclassMirror() { let (addProperties, addPropertiesTypes) = reflectedSub(theObject, reflected: superReflected, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) for (k, v) in addProperties { if k as? String != "evReflectionStatuses" { propertiesDictionary.setValue(v, forKey: k as? String ?? "") propertiesTypeDictionary[k as? String ?? ""] = addPropertiesTypes[k as? String ?? ""] } } } for property in reflected.children { if let originalKey: String = property.label { var skipThisKey = false var mapKey = originalKey if originalKey == "evReflectionStatuses" { skipThisKey = true } if conversionOptions.contains(.PropertyMapping) { if let evObject = theObject as? EVObject { if let mapping = evObject.propertyMapping().filter({$0.0 == originalKey}).first { if mapping.1 == nil { skipThisKey = true } else { mapKey = mapping.1! } } } } if !skipThisKey { var value = property.value // Convert the Any value to a NSObject value var (unboxedValue, valueType, isObject) = valueForAny(theObject, key: originalKey, anyValue: value, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) if conversionOptions.contains(.PropertyConverter) { // If there is a properyConverter, then use the result of that instead. if let (_, _, propertyGetter) = (theObject as? EVObject)?.propertyConverters().filter({$0.0 == originalKey}).first { guard let propertyGetter = propertyGetter else { continue // if propertyGetter is nil, skip getting the property } value = propertyGetter() let (unboxedValue2, _, _) = valueForAny(theObject, key: originalKey, anyValue: value, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) unboxedValue = unboxedValue2 } } if isObject { // sub objects will be added as a dictionary itself. let (dict, _) = toDictionary(unboxedValue as? NSObject ?? NSObject(), conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) unboxedValue = dict } else if let array = unboxedValue as? [NSObject] { if unboxedValue as? [String] != nil || unboxedValue as? [NSString] != nil || unboxedValue as? [NSDate] != nil || unboxedValue as? [NSNumber] != nil || unboxedValue as? [NSArray] != nil || unboxedValue as? [NSDictionary] != nil { // Arrays of standard types will just be set } else { // Get the type of the items in the array let item: NSObject if array.count > 0 { item = array[0] } else { item = array.getArrayTypeInstance(array) } let (_, _, isObject) = valueForAny(anyValue: item, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) if isObject { // If the items are objects, than add a dictionary of each to the array var tempValue = [NSDictionary]() for av in array { let (dict, _) = toDictionary(av, conversionOptions: conversionOptions, isCachable: isCachable, parents: parents) tempValue.append(dict) } unboxedValue = tempValue } } } if conversionOptions.contains(.SkipPropertyValue) { if let evObject = theObject as? EVObject { if !evObject.skipPropertyValue(unboxedValue, key: mapKey) { propertiesDictionary.setValue(unboxedValue, forKey: mapKey) propertiesTypeDictionary[mapKey] = valueType } } else { propertiesDictionary.setValue(unboxedValue, forKey: mapKey) propertiesTypeDictionary[mapKey] = valueType } } else { propertiesDictionary.setValue(unboxedValue, forKey: mapKey) propertiesTypeDictionary[mapKey] = valueType } } } } return (propertiesDictionary, propertiesTypeDictionary) } /** Clean up dictionary so that it can be converted to json - parameter dict: The dictionairy that - returns: The cleaned up dictionairy */ private class func convertDictionaryForJsonSerialization(dict: NSDictionary, theObject: NSObject) -> NSDictionary { let dict2: NSMutableDictionary = NSMutableDictionary() for (key, value) in dict { dict2.setValue(convertValueForJsonSerialization(value, theObject: theObject), forKey: key as? String ?? "") } return dict2 } /** Clean up a value so that it can be converted to json - parameter value: The value to be converted - returns: The converted value */ private class func convertValueForJsonSerialization(value: AnyObject, theObject: NSObject) -> AnyObject { switch value { case let stringValue as NSString: return stringValue case let numberValue as NSNumber: return numberValue case let nullValue as NSNull: return nullValue case let arrayValue as NSArray: let tempArray: NSMutableArray = NSMutableArray() for value in arrayValue { tempArray.addObject(convertValueForJsonSerialization(value, theObject: theObject)) } return tempArray case let date as NSDate: return (getDateFormatter().stringFromDate(date) ?? "") case let ok as NSDictionary: return convertDictionaryForJsonSerialization(ok, theObject: theObject) default: (theObject as? EVObject)?.addStatusMessage(.InvalidType, message: "Unexpected type while converting value for JsonSerialization: \(value)") NSLog("ERROR: Unexpected type while converting value for JsonSerialization") return "\(value)" } } } /** For specifying what conversion options should be executed */ public struct ConversionOptions: OptionSetType, CustomStringConvertible { /// The numeric representation of the options public let rawValue: Int /** Initialize with a raw value - parameter rawValue: the numeric representation - returns: The ConversionOptions */ public init(rawValue: Int) { self.rawValue = rawValue } /// No conversion options public static let None = ConversionOptions(rawValue: 0) /// Execute property converters public static let PropertyConverter = ConversionOptions(rawValue: 1) /// Execute property mapping public static let PropertyMapping = ConversionOptions(rawValue: 2) /// Skip specific property values public static let SkipPropertyValue = ConversionOptions(rawValue: 4) /// Do a key cleanup (CameCase, snake_case) public static let KeyCleanup = ConversionOptions(rawValue: 8) /// Default used for NSCoding public static var DefaultNSCoding: ConversionOptions = [None] /// Default used for comparing / hashing functions public static var DefaultComparing: ConversionOptions = [PropertyConverter, PropertyMapping, SkipPropertyValue] /// Default used for deserialisation public static var DefaultDeserialize: ConversionOptions = [PropertyConverter, PropertyMapping, SkipPropertyValue, KeyCleanup] /// Default used for serialisation public static var DefaultSerialize: ConversionOptions = [PropertyConverter, PropertyMapping, SkipPropertyValue] /// Get a nice description of the ConversionOptions public var description: String { let strings = ["PropertyConverter", "PropertyMapping", "SkipPropertyValue", "KeyCleanup"] var members = [String]() for (flag, string) in strings.enumerate() where contains(ConversionOptions(rawValue:1<<(flag + 1))) { members.append(string) } if members.count == 0 { members.append("None") } return members.description } } /** Type of status messages after deserialisation */ public struct DeserialisationStatus: OptionSetType, CustomStringConvertible { /// The numeric representation of the options public let rawValue: Int /** Initialize with a raw value - parameter rawValue: the numeric representation - returns: the DeserialisationStatus */ public init(rawValue: Int) { self.rawValue = rawValue } /// No status message public static let None = DeserialisationStatus(rawValue: 0) /// Incorrect key error public static let IncorrectKey = DeserialisationStatus(rawValue: 1) /// Missing key error public static let MissingKey = DeserialisationStatus(rawValue: 2) /// Invalid type error public static let InvalidType = DeserialisationStatus(rawValue: 4) /// Invalid value error public static let InvalidValue = DeserialisationStatus(rawValue: 8) /// Invalid class error public static let InvalidClass = DeserialisationStatus(rawValue: 16) /// Missing protocol error public static let MissingProtocol = DeserialisationStatus(rawValue: 32) /// Custom status message public static let Custom = DeserialisationStatus(rawValue: 64) /// Get a nice description of the DeserialisationStatus public var description: String { let strings = ["IncorrectKey", "MissingKey", "InvalidType", "InvalidValue", "InvalidClass", "MissingProtocol", "Custom"] var members = [String]() for (flag, string) in strings.enumerate() where contains(DeserialisationStatus(rawValue:1<<(flag))) { members.append(string) } if members.count == 0 { members.append("None") } return members.description } }
apache-2.0
72c682e6b9cc0fb8a3f1111b057edf61
45.668731
715
0.598614
5.310084
false
false
false
false
sungkipyung/CodeSample
SimpleCameraApp/SimpleCameraApp/EditViewController.swift
1
2732
// // EditViewController.swift // SimpleCameraApp // // Created by 성기평 on 2016. 4. 7.. // Copyright © 2016년 hothead. All rights reserved. // import UIKit class EditViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var pictureImageView: UIImageView! @IBOutlet weak var textView: UITextField! override func viewDidLoad() { super.viewDidLoad() self.textView.delegate = self // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func textFieldDidEndEditing(_ textField: UITextField) { let text:String = textField.text! if (text.characters.count > 0) { self.pictureImageView.image = drawText(text, image: self.pictureImageView.image!, atPoint: self.pictureImageView.center) NSLog("write text : \(text)") textView.isHidden = true } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if (string == "\n") { textView.resignFirstResponder() textView.isHidden = true; return false } return true } func drawText(_ text: String, image:UIImage, atPoint point:CGPoint) -> UIImage { // var textStyle:NSMutableAttributedString = NSMutableParagraphStyle.defaultParagraphStyle() let textStyle = NSMutableAttributedString.init(string: text) textStyle.addAttribute(NSForegroundColorAttributeName, value: UIColor.black, range: NSMakeRange(0, textStyle.length)) textStyle.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 20.0), range: NSMakeRange(0, textStyle.length)) UIGraphicsBeginImageContext(image.size) image.draw(in: CGRect(x: 0, y: 0, width: image.size.width, height: image.size.height)) let rect: CGRect = CGRect(x: point.x, y: point.y, width: image.size.width, height: image.size.height) UIColor.white.set() textStyle.draw(in: rect.integral) let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return newImage } }
apache-2.0
3f6ea287e435b30ba511db374bee1402
37.352113
132
0.669482
5.014733
false
false
false
false
software123inc/Software123LumberJack
Software123LumberJack/S123LogFormatter.swift
1
2172
// // S123LogFormatter.swift // Software123LumberJack // // Created by Tim Newton on 8/11/17. // Copyright © 2017 EduServe, Inc. All rights reserved. // import Foundation import CocoaLumberjack public class S123LogFormatter:NSObject, DDLogFormatter { public private(set) var dateFormatter:DateFormatter = { let dateFormatter = DateFormatter.init() dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss" return dateFormatter }() //MARK:- DDLogFormatter methods open func format(message logMessage: DDLogMessage) -> String? { var logLevel:String var outputString:String? switch logMessage.flag { case DDLogFlag.error: logLevel = " ERROR:" case DDLogFlag.warning: logLevel = " WARNING:" case DDLogFlag.info: logLevel = " INFO:" case DDLogFlag.debug: logLevel = " DEBUG:" default: logLevel = ""; } let function = logMessage.function ?? "¿fuction?" let timestamp = self.dateFormatter.string(from: logMessage.timestamp) outputString = "\(timestamp) <\(logMessage.fileName)|Line: \(logMessage.line)::\(function)>\(logLevel) \(logMessage.message)" return outputString } } public class S123ThreadedLogFormatter:S123LogFormatter { //MARK:- DDLogFormatter methods open override func format(message logMessage: DDLogMessage) -> String? { var logLevel:String var outputString:String? switch logMessage.flag { case DDLogFlag.error: logLevel = " ERROR:" case DDLogFlag.warning: logLevel = " WARNING:" case DDLogFlag.info: logLevel = " INFO:" case DDLogFlag.debug: logLevel = " DEBUG:" default: logLevel = ""; } let timestamp = self.dateFormatter.string(from: logMessage.timestamp) outputString = "\(timestamp) <\(logMessage.fileName)::\(logMessage.queueLabel)>\(logLevel) \(logMessage.message)" return outputString } }
mit
dc838338d52d5b46d155f22c49d1947e
27.181818
133
0.596774
5.046512
false
false
false
false
gaowanli/PinGo
PinGo/PinGo/Main/TabBarController.swift
1
1262
// // TabBarController.swift // PinGo // // Created by GaoWanli on 16/1/16. // Copyright © 2016年 GWL. All rights reserved. // import UIKit class TabBarController: UITabBarController { @IBOutlet fileprivate weak var aTabBar: TabBar! override func viewDidLoad() { super.viewDidLoad() aTabBar.aDelegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) removeSystemTabbarSubviews() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() removeSystemTabbarSubviews() } fileprivate func removeSystemTabbarSubviews() { for v in tabBar.subviews { if v.superclass == UIControl.self { v.removeFromSuperview() } } } } extension TabBarController: TabBarDelegate { func tabBar(_ tabBar: TabBar, didClickButton index: Int) { var index = index if index == 2 { let showVC = UIStoryboard.initialViewController("Show") present(showVC, animated: true, completion: nil) return }else if index >= 2 { index -= 1 } selectedIndex = index } }
mit
cbcf6b56366f4b2958160ede997a98e3
21.890909
67
0.591739
4.937255
false
false
false
false
Avenroot/Yaz
Source/SharedProject/DiceSet.swift
1
3397
// 5 dice are returned in DiceSet public class DiceSet { struct Dice { var Value = 0 } var dice1 = Dice() var dice2 = Dice() var dice3 = Dice() var dice4 = Dice() var dice5 = Dice() func HowManyOnes() -> Int { var r = 0 if dice1.Value == 1 {r = r+1} if dice2.Value == 1 {r = r+1} if dice3.Value == 1 {r = r+1} if dice4.Value == 1 {r = r+1} if dice5.Value == 1 {r = r+1} return r } func HowManyTwos() -> Int { var r = 0 if dice1.Value == 2 {r = r+1} if dice2.Value == 2 {r = r+1} if dice3.Value == 2 {r = r+1} if dice4.Value == 2 {r = r+1} if dice5.Value == 2 {r = r+1} return r } func HowManyThrees() -> Int { var r = 0 if dice1.Value == 3 {r = r+1} if dice2.Value == 3 {r = r+1} if dice3.Value == 3 {r = r+1} if dice4.Value == 3 {r = r+1} if dice5.Value == 3 {r = r+1} return r } func HowManyFours() -> Int { var r = 0 if dice1.Value == 4 {r = r+1} if dice2.Value == 4 {r = r+1} if dice3.Value == 4 {r = r+1} if dice4.Value == 4 {r = r+1} if dice5.Value == 4 {r = r+1} return r } func HowManyFives() -> Int { var r = 0 if dice1.Value == 5 {r = r+1} if dice2.Value == 5 {r = r+1} if dice3.Value == 5 {r = r+1} if dice4.Value == 5 {r = r+1} if dice5.Value == 5 {r = r+1} return r } func HowManySixes() -> Int { var r = 0 if dice1.Value == 6 {r = r+1} if dice2.Value == 6 {r = r+1} if dice3.Value == 6 {r = r+1} if dice4.Value == 6 {r = r+1} if dice5.Value == 6 {r = r+1} return r } func IsTwoOfSameKind() -> DiceResults { let r = DiceResults() // Handles how many ones if HowManyOnes() == 2 { r.Value1 = 1 } // Handles how many twos if HowManyTwos() == 2 { r.TrueFalse = true if r.Value1 > 0 { r.Value2 = 2 } else { r.Value1 = 2 } } // Handles how many threes if HowManyThrees() == 2 { r.TrueFalse = true if r.Value1 > 0 { r.Value2 = 3 } else { r.Value1 = 3 } } // Handles how many fours if HowManyFours() == 2 { r.TrueFalse = true if r.Value1 > 0 { r.Value2 = 4 } else { r.Value1 = 4 } } // Handles how many fives if HowManyFives() == 2 { r.TrueFalse = true if r.Value1 > 0 { r.Value2 = 5 } else { r.Value1 = 5 } } // Handles how many sixes if HowManySixes() == 2 { r.TrueFalse = true if r.Value1 > 0 { r.Value2 = 6 } else { r.Value1 = 6 } } return r } func IsThreeOfSameKind() -> DiceResults { let r = DiceResults() // Handles how many ones if HowManyOnes() == 3 { r.TrueFalse = true r.Value1 = 1 } // Handles how many twos if HowManyTwos() == 3 { r.TrueFalse = true if r.Value1 > 0 { r.Value2 = 2 } else { r.Value1 = 2 } } // Handles how may threes if HowManyThrees() == 3 { r.TrueFalse = true if r.Value1 > 0 { r.Value2 = 3 } else { r.Value1 = 3 } } // Handles how many fours if HowManyFours() == 3 { r.TrueFalse = true if r.Value1 > 0 { r.Value2 = 4 } else { r.Value1 = 4 } } // Handles how many fives if HowManyFives() == 3 { r.TrueFalse = true if r.Value1 > 0 { r.Value2 = 5 } else { r.Value1 = 5 } } // Handles how many sixes if HowManySixes() == 3 { r.TrueFalse = true if r.Value1 > 0 { r.Value2 = 6 } else { r.Value1 = 6 } } return r } }
mit
6a1062d80023073432cb779405df7545
14.297297
42
0.520177
2.347856
false
false
false
false
yukiasai/Gecco
Classes/SpotlightView.swift
1
6468
// // SpotlightView.swift // Gecco // // Created by yukiasai on 2016/01/16. // Copyright (c) 2016 yukiasai. All rights reserved. // import UIKit public protocol SpotlightViewDelegate: AnyObject { func spotlightWillAppear(spotlightView: SpotlightView, spotlight: SpotlightType) func spotlightDidAppear(spotlightView: SpotlightView, spotlight: SpotlightType) func spotlightWillDisappear(spotlightView: SpotlightView, spotlight: SpotlightType) func spotlightDidDisappear(spotlightView: SpotlightView, spotlight: SpotlightType) func spotlightWillMove(spotlightView: SpotlightView, spotlight: (from: SpotlightType, to: SpotlightType), moveType: SpotlightMoveType) func spotlightDidMove(spotlightView: SpotlightView, spotlight: (from: SpotlightType, to: SpotlightType), moveType: SpotlightMoveType) } public extension SpotlightViewDelegate { func spotlightWillAppear(spotlightView: SpotlightView, spotlight: SpotlightType) { } func spotlightDidAppear(spotlightView: SpotlightView, spotlight: SpotlightType) { } func spotlightWillDisappear(spotlightView: SpotlightView, spotlight: SpotlightType) { } func spotlightDidDisappear(spotlightView: SpotlightView, spotlight: SpotlightType) { } func spotlightWillMove(spotlightView: SpotlightView, spotlight: (from: SpotlightType, to: SpotlightType), moveType: SpotlightMoveType) { } func spotlightDidMove(spotlightView: SpotlightView, spotlight: (from: SpotlightType, to: SpotlightType), moveType: SpotlightMoveType) { } } open class SpotlightView: UIView { public static let defaultAnimateDuration: TimeInterval = 0.25 private lazy var maskLayer: CAShapeLayer = { let layer = CAShapeLayer() layer.fillRule = .evenOdd layer.fillColor = UIColor.black.cgColor return layer }() internal var spotlights: [SpotlightType] = [] public weak var delegate: SpotlightViewDelegate? public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { layer.mask = maskLayer } open override func layoutSubviews() { super.layoutSubviews() maskLayer.frame = frame } open func appear(_ spotlight: SpotlightType, duration: TimeInterval = SpotlightView.defaultAnimateDuration) { appear([spotlight], duration: duration) } open func appear(_ spotlights: [SpotlightType], duration: TimeInterval = SpotlightView.defaultAnimateDuration) { spotlights.forEach { delegate?.spotlightWillAppear(spotlightView: self, spotlight: $0) } defer { spotlights.forEach { delegate?.spotlightDidAppear(spotlightView: self, spotlight: $0) } } maskLayer.add(appearAnimation(duration, spotlights: spotlights), forKey: nil) self.spotlights.append(contentsOf: spotlights) } open func disappear(_ duration: TimeInterval = SpotlightView.defaultAnimateDuration) { spotlights.forEach { delegate?.spotlightWillDisappear(spotlightView: self, spotlight: $0) } defer { spotlights.forEach { delegate?.spotlightDidDisappear(spotlightView: self, spotlight: $0) } } maskLayer.add(disappearAnimation(duration), forKey: nil) } open func move(_ toSpotlight: SpotlightType, duration: TimeInterval = SpotlightView.defaultAnimateDuration, moveType: SpotlightMoveType = .direct) { spotlights.forEach { delegate?.spotlightWillMove(spotlightView: self, spotlight: (from: $0, to: toSpotlight), moveType: moveType) } defer { spotlights.forEach { delegate?.spotlightDidMove(spotlightView: self, spotlight: (from: $0, to: toSpotlight), moveType: moveType) } } switch moveType { case .direct: moveDirect(toSpotlight, duration: duration) case .disappear: moveDisappear(toSpotlight, duration: duration) } } } extension SpotlightView { private func moveDirect(_ toSpotlight: SpotlightType, duration: TimeInterval = SpotlightView.defaultAnimateDuration) { maskLayer.add(moveAnimation(duration, toSpotlight: toSpotlight), forKey: nil) spotlights = [toSpotlight] } private func moveDisappear(_ toSpotlight: SpotlightType, duration: TimeInterval = SpotlightView.defaultAnimateDuration) { CATransaction.begin() CATransaction.setCompletionBlock { self.appear(toSpotlight, duration: duration) self.spotlights = [toSpotlight] } disappear(duration) CATransaction.commit() } private func maskPath(_ path: UIBezierPath) -> UIBezierPath { [path].reduce(into: UIBezierPath(rect: frame)) { $0.append($1) } } private func appearAnimation(_ duration: TimeInterval, spotlights: [SpotlightType]) -> CAAnimation { typealias PathAnimationPair = (begin: UIBezierPath?, end: UIBezierPath) let pair = spotlights.reduce(into: PathAnimationPair(begin: .init(rect: frame), end: .init(rect: frame))) { (result, spotlight) in result.begin?.append(spotlight.infinitesmalPath) result.end.append(spotlight.path) } return pathAnimation(duration, beginPath: pair.begin, endPath: pair.end) } private func disappearAnimation(_ duration: TimeInterval) -> CAAnimation { let convergence = spotlights.removeLast() return pathAnimation(duration, beginPath: nil, endPath: maskPath(convergence.infinitesmalPath)) } private func moveAnimation(_ duration: TimeInterval, toSpotlight: SpotlightType) -> CAAnimation { let endPath = maskPath(toSpotlight.path) return pathAnimation(duration, beginPath: nil, endPath: endPath) } private func pathAnimation(_ duration: TimeInterval, beginPath: UIBezierPath?, endPath: UIBezierPath) -> CAAnimation { let animation = CABasicAnimation(keyPath: "path") animation.duration = duration animation.timingFunction = CAMediaTimingFunction(controlPoints: 0.66, 0, 0.33, 1) if let path = beginPath { animation.fromValue = path.cgPath } animation.toValue = endPath.cgPath animation.isRemovedOnCompletion = false animation.fillMode = .forwards return animation } } public enum SpotlightMoveType { case direct case disappear }
mit
dc9544fc74581bc363fccf483fb3626c
43
152
0.706246
4.457615
false
false
false
false
mssun/passforios
pass/Helpers/PasswordAlertPresenter.swift
2
1283
// // PasswordAlertPresenter.swift // pass // // Created by Danny Moesch on 23.08.20. // Copyright © 2020 Bob Sun. All rights reserved. // import SVProgressHUD protocol PasswordAlertPresenter { func present(message: String, lastPassword: String?) -> String? } extension PasswordAlertPresenter where Self: UIViewController { func present(message: String, lastPassword: String?) -> String? { let sem = DispatchSemaphore(value: 0) var password: String? DispatchQueue.main.async { SVProgressHUD.dismiss() let alert = UIAlertController(title: "Password".localize(), message: message, preferredStyle: .alert) alert.addTextField { $0.text = lastPassword ?? "" $0.isSecureTextEntry = true } alert.addAction( .ok { _ in password = alert.textFields?.first?.text sem.signal() } ) alert.addAction( .cancel { _ in password = nil sem.signal() } ) self.present(alert, animated: true) } _ = sem.wait(timeout: .distantFuture) return password } }
mit
ac16f7db3054a4c14866b5de94521c02
27.488889
113
0.537441
4.930769
false
false
false
false
mingxianzyh/D3View
D3View/D3View/D3RadioBtn.swift
1
2669
// // D3RadioBtn.swift // Neighborhood // // Created by mozhenhau on 15/6/11. // Copyright (c) 2015年 Ray. All rights reserved. // 在storyboard的界面设计时,此类内部的所有UIButton都会在被此类控制 // import UIKit class D3RadioBtn: UIView { private var btns:Array<UIButton> = [] private var norImg = "radio_btn_nor.png" private var preImg = "radio_btn_pre.png" //选中的图片 private var block:(UIButton->Void)? var isBackgroundImg = false //用背景图setBackgroundImage还是用图setImage.默认使用setImage required init(coder aDecoder: NSCoder) { super.init(coder:aDecoder)! //初始化,把子视图的所有btn for view in self.subviews{ if let btn = view as? UIButton{ btns.append(btn) btn.tag = btns.count btn.addTarget(self, action: "clickBtn:", forControlEvents: UIControlEvents.TouchUpInside) } } if btns.count > 0{ initValue(0) } } /** 初始化值,比如性别:男女,默认初始化选择第一个 */ func initValue(index:Int){ for btn in btns{ setBtnImg(btn, img: norImg) } setBtnImg(btns[index], img: preImg) } /** 要改变选中和没选中的图则调用此方法 */ func initRadioImg(norImg:String,preImg:String){ self.norImg = norImg self.preImg = preImg } /** 添加点击的回调事件,回调返回参数为点击的按钮 */ func addBlock(block:(UIButton->Void)){ self.block = block } /** 点中按钮事件 :param: sender 点中的按钮 */ func clickBtn(sender:UIButton){ for btn in btns{ setBtnImg(btn, img: norImg) if btn == sender{ setBtnImg(btn, img: preImg) btn.pulse() block?(btn) } } } /** 设置radioBtn的图片 :param: btn 需要设置的radio :param: img 设置preimg还是norimg */ private func setBtnImg(btn:UIButton,img:String){ if isBackgroundImg{ btn.setBackgroundImage(UIImage(named: img), forState: UIControlState.Normal) } else{ btn.setImage(UIImage(named: img), forState: UIControlState.Normal) } } /** 设置成选中状态 */ func setBtnPre(btn:UIButton){ setBtnImg(btn, img: preImg) } /** 设置成没选状态 */ func setBtnNor(btn:UIButton){ setBtnImg(btn, img: norImg) } }
mit
f65889d0b5cd0bfa76e5a694839a8c15
21.740385
105
0.550529
3.678072
false
false
false
false
appfoundry/DRYLogging
Pod/Classes/BaseFormattingAppender.swift
1
1967
// // BaseFormattingAppender.swift // Pods // // Created by Michael Seghers on 28/10/2016. // // import Foundation /// Abstract base class for logging appenders which format messages through a MessageFormatter. /// /// - since: 3.0 public protocol BaseFormattingAppender: class, LoggingAppender { /// The filters that will be consulted do decide wether a message will be appended or not var filters: [AppenderFilter] { get set } /// The message formatter used to format a LoggingMessage to a String var formatter: MessageFormatter { get } /// Called when the append method has consulted the filters wheter or not /// to accept the message. /// /// - parameter acceptedAndFormattedMessage: The message which was formatted using the MessageFormatter func append(acceptedAndFormattedMessage: String) } public extension BaseFormattingAppender { public func append(message: LoggingMessage) { if self.filterDecision(message: message) != .deny { self.append(acceptedAndFormattedMessage: self.formatter.format(message)) } } /// Add an AppenderFilter to the formatting appender /// /// - parameter filter: The filter to be added public func add(filter: AppenderFilter) { self.filters.append(filter) } /// Remove an AppenderFilter from the formatting appender /// /// - parameter filter: The filter to be removed public func remove(filter: AppenderFilter) { if let index = self.filters.index(where: { $0 === filter }) { self.filters.remove(at: index) } } private func filterDecision(message: LoggingMessage) -> AppenderFilterDecission { var result: AppenderFilterDecission = .neutral for filter in self.filters { result = filter.decide(message) if (result != .neutral) { break } } return result } }
mit
08b83fabaf07cd2a7b3ebb2fca66a80e
29.734375
107
0.654296
4.542725
false
false
false
false
pajai/JSQCoreDataKit
Example/ExampleModel/Album.swift
1
1103
// // Created by Jesse Squires // http://www.jessesquires.com // // // Documentation // http://www.jessesquires.com/JSQCoreDataKit // // // GitHub // https://github.com/jessesquires/JSQCoreDataKit // // // License // Copyright (c) 2015 Jesse Squires // Released under an MIT license: http://opensource.org/licenses/MIT // import Foundation import CoreData public final class Album: NSManagedObject { @NSManaged public var title: String @NSManaged public var dateReleased: NSDate @NSManaged public var price: NSDecimalNumber @NSManaged public var band: Band public init(context: NSManagedObjectContext, title: String, dateReleased: NSDate, price: NSDecimalNumber, band: Band) { let entity = NSEntityDescription.entityForName(ExampleModelEntity.Album, inManagedObjectContext: context)! super.init(entity: entity, insertIntoManagedObjectContext: context) self.title = title self.dateReleased = dateReleased self.price = price self.band = band } }
mit
d4cd423b22b4dcd435c60dd8844ac08c
22.468085
118
0.665458
4.673729
false
false
false
false
kNeerajPro/Swift-Video-tutorial-Series
Tutorial2/SwiftContacts/SwiftContacts/ViewControllers/AddContactsViewController/AddContactsViewController.swift
1
8664
// // AddContactsViewController.swift // SwiftContacts // // Created by Neeraj Kumar on 05/11/14. // Copyright (c) 2014 Neeraj Kumar. All rights reserved. // import UIKit // MARK: Protocol. // Important: With inheriting from class this protocol can only be adopteb by classes and not structures and enumerations protocol AddContactCellDelegate:class { func didResignNextResponder(cell:AddContactTableViewCell) func textFieldDidEndEditing(cell:AddContactTableViewCell) } // MARK: AddContactTableViewCell class AddContactTableViewCell: UITableViewCell { @IBOutlet weak var label: UILabel! @IBOutlet weak var textField: UITextField! weak var delegate:AddContactCellDelegate? override func awakeFromNib() { self.selectionStyle = UITableViewCellSelectionStyle.None self.textField.returnKeyType = UIReturnKeyType.Next self.textField.delegate = self super.awakeFromNib() } func populateCellWithData(dict:[String:String]) { self.label.text = dict["label"] } func textFieldBecomeFirstResponder() { self.textField.becomeFirstResponder() } func textFieldText() -> String { return self.textField.text } } extension AddContactTableViewCell:UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() delegate?.didResignNextResponder(self) // optional chaining return true } func textFieldDidEndEditing(textField: UITextField) { delegate?.textFieldDidEndEditing(self) } } // MARK: AddContacts view controller. class AddContactsViewController: UITableViewController { var name:Name = Name() var address:Address = Address() var phoneNumber:PhoneNumber = PhoneNumber() override func viewDidLoad() { super.viewDidLoad() self.title = "Add Contact" self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag self.tableView.reloadData() let barButton:UIBarButtonItem = UIBarButtonItem(title: "Submit", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("didTapSubmitButton")) self.navigationItem.rightBarButtonItem = barButton } func didTapSubmitButton() { self.view.endEditing(true) let person:Person = Person(name: self.name, address: self.address, phoneNumber: self.phoneNumber) // person object. // Check if person is valid. if person.isValid() { // Notify that a person object is added. let userInfo:[NSObject : AnyObject] = ["object": person] NSNotificationCenter.defaultCenter().postNotificationName(NEW_PERSON_NOTIFICATION, object: nil, userInfo: userInfo) self.navigationController?.popViewControllerAnimated(true) } else { let alertView:UIAlertView = UIAlertView(title: "Invalid entries!!", message: "Please fill all required component", delegate: nil, cancelButtonTitle: "OK") alertView.show() } } deinit { println("AddContacts view controller deinits") } } // MARK: Sample Data. private extension AddContactsViewController { var data: [String:[String]] { return [ "Name":[ "First Name *", "Middle Name", "Last Name *" ], "Address":[ "flatNo *", "locality *", "city *", "pincode *", "landmark" ], "Phone Number":[ "diallingCode *", "phoneNo *" ], ] } // Extracting the values form indexPath to properties. func saveValueForIndexpath(indexPath:(section:Int,row:Int), cell:AddContactTableViewCell) { switch (indexPath) { case (0,0): self.name.firstName = cell.textFieldText() case (0,1): self.name.middleName = cell.textFieldText() case (0,2): self.name.lastName = cell.textFieldText() case (1,0): self.address.flatNo = cell.textFieldText() case (1,1): self.address.locality = cell.textFieldText() case (1,2): self.address.city = cell.textFieldText() case (1,3): self.address.pindcode = cell.textFieldText() case (1,4): self.address.landmark = cell.textFieldText() case (2,0): self.phoneNumber.diallingCode = cell.textFieldText() case (2,1): self.phoneNumber.phoneNumber = cell.textFieldText() default: assertionFailure("wrong indexPath please check.") } } } // MARK: TableViewDataSource extension AddContactsViewController:UITableViewDataSource { override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.data.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var sectionName: String = "Name" switch(section) { case 0: sectionName = "Name" case 1: sectionName = "Address" case 2: sectionName = "Phone Number" default: sectionName = "Name" } if let sectionArr = self.data[sectionName] { return sectionArr.count } else { return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("AddContactCellReuseIdentifier", forIndexPath: indexPath) as AddContactTableViewCell cell.delegate = self var sectionName: String = "Name" switch(indexPath.section) { case 0: sectionName = "Name" case 1: sectionName = "Address" case 2: sectionName = "Phone Number" default: sectionName = "Name" } if let sectionArr = self.data[sectionName] { let str:String = sectionArr[indexPath.row] cell.populateCellWithData(["label":str]) } return cell } } // MARK: TableViewDelegate extension AddContactsViewController:UITableViewDelegate { override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 20 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { var sectionName: String = "Name" switch(section) { case 0: sectionName = "Name" case 1: sectionName = "Address" case 2: sectionName = "Phone Number" default: sectionName = "Name" } return sectionName } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { } } // MARK: Protocol AddContactCellDelegate extension AddContactsViewController:AddContactCellDelegate { func didResignNextResponder(cell:AddContactTableViewCell) { let indexPath:NSIndexPath? = self.tableView.indexPathForCell(cell) if let uwIndexPath = indexPath { self.saveValueForIndexpath((uwIndexPath.section, uwIndexPath.row), cell: cell) let newIndexPath:NSIndexPath = self.nextIndexPath(uwIndexPath) let cell:AddContactTableViewCell? = self.tableView.cellForRowAtIndexPath(newIndexPath) as? AddContactTableViewCell cell?.textFieldBecomeFirstResponder() } } func textFieldDidEndEditing(cell:AddContactTableViewCell) { let indexPath:NSIndexPath? = self.tableView.indexPathForCell(cell) if let uwIndexPath = indexPath { self.saveValueForIndexpath((uwIndexPath.section, uwIndexPath.row), cell: cell) } } func nextIndexPath(currentIndexPath:NSIndexPath) -> NSIndexPath { let numRows = self.tableView.numberOfRowsInSection(currentIndexPath.section) if currentIndexPath.row == (numRows-1) { return NSIndexPath(forRow: 0, inSection: (currentIndexPath.section+1)) } else { return NSIndexPath(forRow:(currentIndexPath.row + 1), inSection:currentIndexPath.section) } } }
apache-2.0
2d64209079178517f5a427b0ccf40fa3
31.571429
166
0.627424
5.222423
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/InputBar/ConversationInputBarViewController+Language.swift
1
1604
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // 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 WireSyncEngine extension ConversationInputBarViewController { func setupInputLanguageObserver() { NotificationCenter.default.addObserver(self, selector: #selector(inputModeDidChange(_:)), name: UITextInputMode.currentInputModeDidChangeNotification, object: nil) } @objc func inputModeDidChange(_ notification: Notification?) { guard let conversation = conversation as? ZMConversation else { return } guard let keyboardLanguage = self.inputBar.textView.originalTextInputMode?.primaryLanguage else { return } ZMUserSession.shared()?.enqueue { conversation.language = keyboardLanguage self.setInputLanguage() } } func setInputLanguage() { guard let conversation = conversation as? ZMConversation else { return } inputBar.textView.language = conversation.language } }
gpl-3.0
90771177c2d7f0de712892ffb7d919ce
33.869565
171
0.727556
4.890244
false
false
false
false
danielsaidi/KeyboardKit
Sources/KeyboardKit/Views/KeyboardGrid.swift
1
2526
// // KeyboardGrid.swift // KeyboardKit // // Created by Daniel Saidi on 2020-02-20. // Copyright © 2021 Daniel Saidi. All rights reserved. // import SwiftUI /** A `KeyboardGrid` can be used to list actions in a grid with a certain number of `columns`. The grid supports a custom item `spacing` and will fill the provided `actions` with enough `none` actions to evenly fit the grid, given the number of `columns`. `buttonBuilder` is then used to generate a button for each action. The grid doesn't modify the buttons you provide it with. If you want your buttons to share the available width, you can apply `.frame(maxWidth: .infinity)` to each button. */ public struct KeyboardGrid<Button: View>: View { public init( actions: [KeyboardAction], columns: Int, spacing: CGFloat = 10, @ViewBuilder buttonBuilder: @escaping (KeyboardAction) -> Button) { let actions = actions.evened(for: columns) self.actions = actions self.rows = actions.batched(withBatchSize: columns) self.spacing = spacing self.buttonBuilder = buttonBuilder } private let actions: [KeyboardAction] private let rows: KeyboardActionRows private let spacing: CGFloat private let buttonBuilder: (KeyboardAction) -> Button public var body: some View { VStack(spacing: spacing) { ForEach(Array(rows.enumerated()), id: \.offset) { self.gridRow(for: $0.element) } } } } private extension KeyboardGrid { func gridRow(for row: KeyboardActions) -> some View { HStack(spacing: self.spacing) { ForEach(Array(row.enumerated()), id: \.offset) { item in self.buttonBuilder(item.element) } } } } struct KeyboardGrid_Previews: PreviewProvider { static let image = KeyboardAction.image(description: "", keyboardImageName: "david", imageName: "david") static var actions: [KeyboardAction] = [ image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image, image ] static var previews: some View { KeyboardGrid(actions: actions, columns: 6) { _ in Image(systemName: "sun.max.fill") .resizable() .scaledToFit() } } }
mit
e898a5d561b03ae9590e0a095e85c279
29.421687
108
0.628515
4.243697
false
false
false
false
loganSims/wsdot-ios-app
wsdot/AmtrakCascadesStationItem.swift
2
1171
// // AmtrakStationItem.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/> // // Data about an Amtrak station, it's name, code, location and distance from user. class AmtrakCascadesStationItem { let id: String let name: String let lat: Double let lon: Double var distance: Int = -1 init(id: String, name: String, lat: Double, lon: Double){ self.id = id self.name = name self.lat = lat self.lon = lon } }
gpl-3.0
1026d513c7adc425db45a1b3f40f9ed7
31.527778
82
0.685739
3.877483
false
false
false
false
zhihuitang/Apollo
Apollo/CalculatorViewController.swift
1
1421
// // CalculatorViewController.swift // Apollo // // Created by Zhihui Tang on 2016-12-16. // Copyright © 2016 Zhihui Tang. All rights reserved. // import UIKit class CalculatorViewController: BaseViewController { @IBOutlet private weak var display: UILabel! private var userIsInTheMiddleOfTyping = false private var brain = CalculatorBrain() @IBAction private func touchDigit(_ sender: UIButton) { let digit = sender.currentTitle! if userIsInTheMiddleOfTyping { let textCurrentlyDisplay = display.text! display.text = textCurrentlyDisplay + digit } else { display.text = digit } userIsInTheMiddleOfTyping = true } private var displayValue: Double { get { return Double(display.text!)! } set { display.text = String(newValue) } } @IBAction private func performOperation(_ sender: UIButton) { if userIsInTheMiddleOfTyping { brain.setOperand(operand: displayValue) userIsInTheMiddleOfTyping = false } if let mathematicalSymbol = sender.currentTitle { brain.performOperation(symbol: mathematicalSymbol) } displayValue = brain.result } } extension CalculatorViewController { override var name: String { return "Calculator" } }
apache-2.0
b9e119d70dcf2ce76c202009f214693c
24.818182
65
0.622535
5.298507
false
false
false
false
CryptoKitten/CryptoEssentials
Sources/BytesSequence.swift
1
1572
// Originally based on CryptoSwift by Marcin Krzyżanowski <[email protected]> // Copyright (C) 2014 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. import Foundation public struct BytesSequence: Sequence { let chunkSize: Int let data: [UInt8] public init(chunkSize: Int, data: [UInt8]) { self.chunkSize = chunkSize self.data = data } public func makeIterator() -> AnyIterator<ArraySlice<UInt8>> { var offset:Int = 0 return AnyIterator { let end = Swift.min(self.chunkSize, self.data.count - offset) let result = self.data[offset..<offset + end] offset += result.count return result.count > 0 ? result : nil } } }
mit
effa166e456cf14a5e2a53370fe34692
45.176471
216
0.704459
4.631268
false
false
false
false
raphaelseher/HorizontalCalendarView
HorizontalCalendar/HorizontalCalendarView.swift
1
9604
// // HorizontalCalendarView.swift // HorizontalCalendar // // Created by Raphael Seher on 27/12/15. // Copyright © 2015 Raphael Seher. All rights reserved. // import UIKit fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } open class HorizontalCalendarView: UIView { let cellReuseIdentifier = "CalendarCellReuseIdentifier" let horizontalCalendar = HorizontalCalendar() open var delegate : HorizontalCalendarDelegate? open var collectionView : UICollectionView? open var mininumLineSpacing : CGFloat = 0.0 open var minimumInterItemSpacing : CGFloat = 0.0 var dates : [Date] = [] var displayedYears : [Int] = [] var startingYear : Int? var cellWidth : CGFloat = 80 var activeIndexPath : IndexPath? var collectionViewTopConstraint : NSLayoutConstraint? var collectionViewBottomConstraint : NSLayoutConstraint? var collectionViewLeadingConstraint : NSLayoutConstraint? var collectionViewTrailingConstraint : NSLayoutConstraint? /** Create a instance of HorizontalCalendarView with rect. - Parameter frame: CGRect for frame. */ public override init(frame: CGRect) { super.init(frame: frame) collectionView = UICollectionView(frame: CGRect(origin: CGPoint.zero, size: frame.size), collectionViewLayout: CalendarFlowLayout(cellWidth: CGFloat(cellWidth))) collectionView!.register(UINib(nibName: "CalendarCollectionViewCell", bundle: Bundle(for: HorizontalCalendarView.self)), forCellWithReuseIdentifier: cellReuseIdentifier) setupCollectionView() setupYears() } /** Create a instance of HorizontalCalendarView with rect, the cellWidth and a custom nib. - Parameter frame: CGRect for frame. - Parameter cellWidth: Width of your custom cell. - Parameter cellNib: Nib of your custom cell. */ public init(frame: CGRect, cellWidth: Float, cellNib: UINib) { super.init(frame: frame) self.cellWidth = CGFloat(cellWidth) collectionView = UICollectionView(frame: CGRect(origin: CGPoint.zero, size: frame.size), collectionViewLayout: CalendarFlowLayout(cellWidth: self.cellWidth)) collectionView!.register(cellNib, forCellWithReuseIdentifier: cellReuseIdentifier) setupCollectionView() setupYears() } /** Create a instance of HorizontalCalendarView with rect, the cellWidth and a custom class. - Parameter frame: CGRect for frame. - Parameter cellWidth: Width of your custom cell. - Parameter cellClass: Class of your custom cell. */ public init(frame: CGRect, cellWidth: Float, cellClass: AnyClass) { super.init(frame: frame) self.cellWidth = CGFloat(cellWidth) collectionView = UICollectionView(frame: CGRect(origin: CGPoint.zero, size: frame.size), collectionViewLayout: CalendarFlowLayout(cellWidth: self.cellWidth)) collectionView!.register(cellClass, forCellWithReuseIdentifier: cellReuseIdentifier) setupCollectionView() setupYears() } /** Create a instance of HorizontalCalendarView with coder. - Parameter aDecoder: A coder. */ required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) collectionView = UICollectionView(coder: aDecoder)! collectionView!.collectionViewLayout = CalendarFlowLayout(cellWidth: CGFloat(cellWidth)) collectionView!.register(UINib(nibName: "CalendarCollectionViewCell", bundle: Bundle(for: HorizontalCalendarView.self)), forCellWithReuseIdentifier: cellReuseIdentifier) setupCollectionView() setupYears() } func setupCollectionView() { if let collectionView = collectionView { collectionView.backgroundColor = UIColor.clear collectionView.delegate = self collectionView.dataSource = self collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.showsHorizontalScrollIndicator = false addSubview(collectionView) collectionViewTopConstraint = NSLayoutConstraint(item: collectionView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1.0, constant: 0) collectionViewBottomConstraint = NSLayoutConstraint(item: collectionView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0) collectionViewLeadingConstraint = NSLayoutConstraint(item: collectionView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1.0, constant: 0) collectionViewTrailingConstraint = NSLayoutConstraint(item: collectionView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1.0, constant: 0) addConstraints([collectionViewTopConstraint!, collectionViewBottomConstraint!, collectionViewLeadingConstraint!, collectionViewTrailingConstraint!]) } } func setupYears() { startingYear = horizontalCalendar.currentYear() if let year = startingYear { dates = horizontalCalendar.datesForYear(year) displayedYears.append(year) } } func addDatesFromYear(_ year: Int) { if displayedYears.contains(year) { return } if let indexPath = activeIndexPath { let currentDate = dates[(indexPath as NSIndexPath).row] if year > startingYear { let datesOfNextYear = horizontalCalendar.datesForYear(year) dates.append(contentsOf: datesOfNextYear) } else if (year < startingYear) { let newDates = horizontalCalendar.datesForYear(year) dates.insert(contentsOf: newDates, at: 0) } displayedYears.append(year) collectionView?.reloadData() moveToDate(currentDate, animated: false) } } func updateActiveIndexPath(_ indexPath : IndexPath) { if activeIndexPath != indexPath { activeIndexPath = indexPath collectionView?.reloadData() delegate?.horizontalCalendarViewDidUpdate(self, date: dates[(indexPath as NSIndexPath).row]) } } open func moveToDate(_ date : Date, animated : Bool) { let indexOfDate = dates.index(of: horizontalCalendar.truncateDateToYearMonthDay(date)) let indexPath = IndexPath.init(item: indexOfDate!, section: 0) collectionView?.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: animated) } open func checkForEndOfDates(_ scrollView: UIScrollView) { if scrollView.contentOffset.x < 60 * cellWidth { let minYearDisplayed = displayedYears.min(); if let lastYear = minYearDisplayed { addDatesFromYear(lastYear - 1) return; } } let maxLinespacing = (self.mininumLineSpacing * CGFloat(dates.count - 1)) let maxDateSize = cellWidth * CGFloat(dates.count) + maxLinespacing let maxScrollviewOffset = maxDateSize - collectionView!.bounds.size.width let offsetToLoadMore = maxScrollviewOffset - 60 * cellWidth if scrollView.contentOffset.x > offsetToLoadMore { let minYearDisplayed = displayedYears.max(); if let lastYear = minYearDisplayed { addDatesFromYear(lastYear + 1) } } } } extension HorizontalCalendarView : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return mininumLineSpacing; } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return minimumInterItemSpacing; } } extension HorizontalCalendarView : UICollectionViewDataSource { public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dates.count } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) cell.configureCalendarCell(cell, date: dates[(indexPath as NSIndexPath).row], active: (indexPath == activeIndexPath)) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { return CGSize(width: cellWidth, height: collectionView.bounds.height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } } extension HorizontalCalendarView : UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { if let indexPath = collectionView?.indexPathForItem(at: CGPoint(x: collectionView!.center.x + scrollView.contentOffset.x, y: collectionView!.center.y)) { updateActiveIndexPath(indexPath) } } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { checkForEndOfDates(scrollView) } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { checkForEndOfDates(scrollView) } }
mit
13b9592bf24b90ab5d75d33f062c62a5
37.258964
188
0.733729
5.080952
false
false
false
false
yulingtianxia/Spiral
Spiral/GameOverIcon.swift
1
1136
// // GameOverIcon.swift // Spiral // // Created by 杨萧玉 on 15/6/4. // Copyright (c) 2015年 杨萧玉. All rights reserved. // import SpriteKit class GameOverIcon: SKSpriteNode { init(size:CGSize) { let imageString:String switch Data.sharedData.currentMode { case .ordinary: imageString = "gameover_ordinary" case .zen: imageString = "gameover_zen" case .maze: imageString = "gameover_maze" } super.init(texture: SKTexture(imageNamed: imageString), color: UIColor.clear, size: size) isUserInteractionEnabled = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { Data.sharedData.display = nil Data.sharedData.reset() let scene = MainScene(size: self.scene!.size) let flip = SKTransition.flipHorizontal(withDuration: 1) flip.pausesIncomingScene = false self.scene?.view?.presentScene(scene, transition: flip) } }
apache-2.0
f46582c3fe4944a455ec0e4f7eadbba3
28.526316
97
0.630125
4.25
false
false
false
false
ntwf/TheTaleClient
TheTale/Controllers/TabBar/MapScreen/MapViewController.swift
1
5152
// // MapViewController.swift // the-tale // // Created by Mikhail Vospennikov on 03/06/2017. // Copyright © 2017 Mikhail Vospennikov. All rights reserved. // import UIKit class MapViewController: UIViewController { // MARK: - Internal constants enum Constants { static let cellMap = "Cell" } // MARK: - Outlets @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var mapActivityIndicator: UIActivityIndicatorView! @IBOutlet weak var compassButton: UIButton! // MARK: - Internal variables var statusBarView: UIView? var map = Map() // MARK: - Load controller override func viewDidLoad() { super.viewDidLoad() setupCompassButton() setupBackgroundStatusBar() } func setupBackgroundStatusBar() { statusBarView = UIView(frame: UIApplication.shared.statusBarFrame) statusBarView?.backgroundColor = UIColor(red: 255, green: 255, blue: 255, transparency: 0.8) view.addSubview(statusBarView!) } func setupCompassButton() { compassButton.layer.cornerRadius = 8 compassButton.layer.masksToBounds = true compassButton.layer.opacity = 0.7 } // MARK: - View lifecycle override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let currentMapVersion = TaleAPI.shared.playerInformationManager.playerInformation?.mapVersion else { return } if map?.mapVersion != currentMapVersion { mapActivityIndicator.startAnimating() fetchMap() } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { switch UIDevice.current.orientation { case UIDeviceOrientation.portrait, UIDeviceOrientation.portraitUpsideDown: statusBarView?.isHidden = false case UIDeviceOrientation.landscapeLeft, UIDeviceOrientation.landscapeRight: statusBarView?.isHidden = true default: break } } // MARK: - Work with interface func reloadMap() { DispatchQueue.main.async { [weak self] in guard let strongSelf = self else { return } strongSelf.collectionView.reloadData() strongSelf.mapActivityIndicator.stopAnimating() strongSelf.scrollingToHero() } } func scrollingToHero() { guard let xCoordinate = TaleAPI.shared.playerInformationManager.heroPosition?.xCoordinate, let yCoordinate = TaleAPI.shared.playerInformationManager.heroPosition?.yCoordinate, let widthMap = map?.width, let heighMap = map?.height else { return } if xCoordinate <= widthMap && yCoordinate <= heighMap { collectionView.scrollToItem(at: IndexPath(item: xCoordinate, section: yCoordinate), at: .centeredVertically, animated: false) collectionView.scrollToItem(at: IndexPath(item: xCoordinate, section: yCoordinate), at: .centeredHorizontally, animated: false) } } // MARK: - Request to API func fetchMap() { // Blanket. Used to get old maps. let turn = "" TaleAPI.shared.getMap(turn: turn) { (result) in switch result { case .success(let data): let queue = DispatchQueue(label: "ru.the-tale.mapgenerate", qos: .userInitiated) queue.async { [weak self] in guard let strongSelf = self else { return } strongSelf.map = Map(jsonObject: data) strongSelf.reloadMap() } case .failure(let error as NSError): debugPrint("fetchMap \(error)") default: break } } } // MARK: - Outlets action @IBAction func compassButtonTapped(_ sender: UIButton) { scrollingToHero() } } // MARK: - UICollectionViewDataSource extension MapViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return map?.width ?? 1 } func numberOfSections(in collectionView: UICollectionView) -> Int { return map?.height ?? 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // swiftlint:disable:next force_cast let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Constants.cellMap, for: indexPath) as! MapCollectionViewCell if let image = map?.image[indexPath.section][indexPath.item] { cell.configuredCell() cell.setBackground(with: image) } if let place = map?.places.filter({ $0.posY == indexPath.section - 1 && $0.posX == indexPath.item }).first { cell.setAnnotation(with: place.nameRepresentation) } if let hero = TaleAPI.shared.playerInformationManager.hero, TaleAPI.shared.playerInformationManager.heroPosition?.yCoordinate == indexPath.section, TaleAPI.shared.playerInformationManager.heroPosition?.xCoordinate == indexPath.item { cell.setHero(with: hero.image) } return cell } } // MARK: - UICollectionViewDelegate extension MapViewController: UICollectionViewDelegate { }
mit
d185e802e7220b4f38fc7ae236b26eb4
29.660714
131
0.678703
4.765032
false
false
false
false