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
craftsmanship-toledo/katangapp-ios
Katanga/AppDelegate.swift
1
1434
/** * Copyright 2016-today Software Craftmanship Toledo * * 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. */ /*! @author Víctor Galán */ import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UINavigationBar.appearance().barTintColor = .black UINavigationBar.appearance().isTranslucent = false UINavigationBar.appearance().tintColor = .katangaYellow UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.katangaYellow] UITabBar.appearance().tintColor = .katangaYellow UITabBarItem.appearance().setTitleTextAttributes( [NSForegroundColorAttributeName: UIColor.white], for: .normal) return true } }
apache-2.0
e1d7ef832c5c692ce1a0a609499455d5
30.130435
85
0.738827
4.789298
false
false
false
false
J-Mendes/Bliss-Assignement
Bliss-Assignement/Bliss-Assignement/Views/ShareView.swift
1
2810
// // ShareView.swift // Bliss-Assignement // // Created by Jorge Mendes on 13/10/16. // Copyright © 2016 Jorge Mendes. All rights reserved. // import UIKit class ShareView: UIView, UITextFieldDelegate { internal var shareUrl: String! @IBOutlet weak var backgroundView: UIView! @IBOutlet weak var sharePopupView: UIView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var cancelButton: UIButton! @IBOutlet weak var shareButton: UIButton! private var email: String = "" override func awakeFromNib() { super.awakeFromNib() self.frame = UIScreen.mainScreen().bounds self.sharePopupView.layer.cornerRadius = 4.0 self.sharePopupView.layer.masksToBounds = true self.titleLabel.text = "Share this screen" self.emailLabel.text = "Email" self.emailTextField.delegate = self self.emailTextField.placeholder = "Insert email" self.cancelButton.setTitle("Cancel", forState: .Normal) self.shareButton.setTitle("Share", forState: .Normal) self.shareButton.enabled = false } internal func show() { self.alpha = 0.0 UIApplication.sharedApplication().keyWindow!.addSubview(self) self.emailTextField.becomeFirstResponder() UIView.animateWithDuration(0.3) { self.alpha = 1.0 } } internal func dismiss() { self.endEditing(true) UIView.animateWithDuration(0.3, animations: { self.alpha = 0.0 }) { (success: Bool) in self.removeFromSuperview() } } // MARK: - UITextField delegate func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } @IBAction func textDidChange(sender: AnyObject) { self.email = (sender as! UITextField).text! self.shareButton.enabled = NSPredicate(format: "SELF MATCHES %@", "^[a-zA-Z+-._0-9]+@[a-z0-9-.]+\\.[a-z]+$").evaluateWithObject(self.email) } // MARK: - UIButton actions @IBAction func cancelAction(sender: AnyObject) { self.dismiss() } @IBAction func shareAction(sender: AnyObject) { self.endEditing(true) ProgressHUD.showProgressHUD(self) NetworkClient.sharedManager().shareViaEmail(self.email, url: self.shareUrl) { (response, error) in if error == nil { ProgressHUD.dismissAllHuds(self) self.dismiss() } else { ProgressHUD.showErrorHUD(self, text: "An error was occurred\nwhile sharing.") } } } }
lgpl-3.0
d1acf72d25c532f5203a1a727d9eaee2
29.204301
147
0.614454
4.658375
false
false
false
false
xivol/MCS-V3-Mobile
examples/swift/SwiftBasics.playground/Pages/Optionals.xcplaygroundpage/Contents.swift
1
1688
/*: ## Optionals [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next) **** */ import Foundation var helloString: String? = nil type(of: helloString) helloString = "Hello, Optional!" //: ### Optional Initialisation //: - `nil` //: - Wrapped value //: //: Values can be wrapped into an opional type var optInt = Int?(4) // Int?(4) var optInt2: Int? = 4 optInt = nil if optInt == nil { "empty" } else { optInt } //: Some methods return optionals in case of a failure: let stringPi = "3.1415926535897932" let pi = Double(stringPi) type(of: pi) //: ### Conditional Unwrapping let conditionalThree = pi?.rounded() type(of: conditionalThree) helloString = nil let conditionalLowerString = helloString?.lowercased() type(of: conditionalLowerString) //: ### Optional Binding if let boundPi = Double(stringPi) { type(of: boundPi) "rounded pi is \(boundPi.rounded())" } if let str = helloString { str.lowercased() } else { "empty string" } //: Guarded optional guard let guardedPi = Double(stringPi) else { fatalError("pi is nil") } type(of: guardedPi) //: ### Forced Unwrapping let forcedThree = pi!.rounded() type(of: forcedThree) //let forcedLowerString = helloString!.lowercased() //type(of: forcedLowerString) //: Forcedly Unwrapped Optional var forcedPi: Double! = nil forcedPi = Double(stringPi) let threeFromForcedPi = forcedPi.rounded() //: Optional Chaining helloString = "Hello, Playground" let chainedIndexOfSubstr = helloString?.range(of: "Hello")?.lowerBound let chainedBase64 = helloString?.data(using: .utf8)?.base64EncodedString() //: [Table of Contents](TableOfContents) · [Previous](@previous) · [Next](@next)
mit
13c3f353d134f72ae02184f8ff73037f
22.388889
80
0.699525
3.479339
false
false
false
false
TalkingBibles/TBMultiAppearanceButton
TBMultiAppearanceButton/TBMultiAppearanceButton.swift
1
16859
// // The MIT License (MIT) // // TBMultiAppearanceButton // Copyright (c) 2015 Talking Bibles International and Stephen Clay Smith // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit /// Generic subclass of UIButton that provides methods to configure and switch between multiple appearances, /// which are specified during initialization by an enum conforming to TBControlAppearanceType. public class TBMultiAppearanceButton<TBControlAppearance: TBControlAppearanceType>: UIButton { private var titlesForAppearance = [TBControlAppearance: [UIControlState: String]]() private var attributedTitlesForAppearance = [TBControlAppearance: [UIControlState: NSAttributedString]]() private var titleColorsForAppearance = [TBControlAppearance: [UIControlState: UIColor]]() private var titleShadowColorsForAppearance = [TBControlAppearance: [UIControlState: UIColor]]() private var backgroundImagesForAppearance = [TBControlAppearance: [UIControlState: UIImage]]() private var imagesForAppearance = [TBControlAppearance: [UIControlState: UIImage]]() private var enabledForAppearance = [TBControlAppearance: [UIControlState: Bool]]() public override init(frame: CGRect) { super.init(frame: frame) } /// Holds the currently active TBControlAppearance; otherwise nil. /// Setting this property conforms the button to the current /// appearance. private var _appearance: TBControlAppearance? { didSet { guard let appearance = _appearance else { return } updateAppearance(appearance) } } override public var highlighted: Bool { didSet { guard let appearance = _appearance else { return } updateAppearance(appearance) } } override public var selected: Bool { didSet { guard let appearance = _appearance else { return } updateAppearance(appearance) } } override public var enabled: Bool { didSet { guard let appearance = _appearance else { return } updateAppearance(appearance) } } /// Update the visible properties of the button as specified for the current state and appearance /// /// - parameter appearance: The TBControlAppearance to apply to the button. private func updateAppearance(appearance: TBControlAppearance) { // Cycle through states and update each setAttributedTitle(attributedTitleForAppearance(appearance, andState: state), forState: state) setTitle(titleForAppearance(appearance, andState: state) ?? "", forState: state) let titleColor = titleColorForAppearance(appearance, andState: state) ?? TBSystemDefaults.titleColorForState(state) setTitleColor(titleColor, forState: state) let shadowColor = titleShadowColorForAppearance(appearance, andState: state) ?? TBSystemDefaults.titleShadowColorForState(state) setTitleShadowColor(shadowColor, forState: state) let bgImage = backgroundImageForAppearance(appearance, andState: state) ?? TBSystemDefaults.backgroundImageForState(state) setBackgroundImage(bgImage, forState: state) let image = imageForAppearance(appearance, andState: state) ?? TBSystemDefaults.imageForState(state) setImage(image, forState: state) } /// Updates appearance for specified appearance if the specified state matches the current state /// /// - parameter appearance: The TBControlAppearance that has been updated. /// - parameter state: The UIControlState that has been updated. private func shouldUpdateAppearance(appearance: TBControlAppearance, andState state: UIControlState) { if _appearance == appearance && self.state == state { updateAppearance(appearance) } } } public extension TBMultiAppearanceButton { // MARK: - Configuring the Button Title /// Returns the title associated with the specified appearance. /// /// - parameter appearance: The TBControlAppearance that uses the title. /// - parameter andState: The UIControlState that receives the title. /// /// - returns: The title for the specified appearance. If no title /// has been set, return nil. func titleForAppearance(appearance: TBControlAppearance, andState state: UIControlState) -> String? { return titlesForAppearance[appearance]?[state] } /// Sets the title to use for the specified appearance and multiple states. /// /// - parameter title: The text string to use for the specified appearance. /// - parameter forAppearance: The TBControlAppearance that uses the specified title. /// - parameter andStates: The UIControlStates that receive the title. func setTitle(title: String?, forAppearance appearance: TBControlAppearance, andStates states: [UIControlState]) { for state in states { setTitle(title, forAppearance: appearance, andState: state) } } /// Sets the title to use for the specified appearance. /// /// - parameter title: The text string to use for the specified appearance. /// - parameter forAppearance: The TBControlAppearance that uses the specified title. /// - parameter andState: The UIControlState that receives the title. func setTitle(title: String?, forAppearance appearance: TBControlAppearance, andState state: UIControlState) { defer { shouldUpdateAppearance(appearance, andState: state) } guard let title = title else { titlesForAppearance.removeValueForKey(appearance) return } if titlesForAppearance[appearance] == nil { titlesForAppearance[appearance] = [:] } titlesForAppearance[appearance]?[state] = title } /// Returns the attributed title associated with the specified appearance. /// /// - parameter appearance: The TBControlAppearance that uses the attributed title. /// - parameter andState: The UIControlState that receives the attributed title. /// /// - returns: The attributed title for the specified appearance. If no /// attributed title has been set, return nil. func attributedTitleForAppearance(appearance: TBControlAppearance, andState state: UIControlState) -> NSAttributedString? { return attributedTitlesForAppearance[appearance]?[state] } /// Sets the attributed title to use for the specified appearance and multiple states. /// /// - parameter title: The styled text string to use for the specified appearance. /// - parameter forAppearance: The TBControlAppearance that uses the specified attributed title. /// - parameter andStates: The UIControlStates that receive the attributed title. func setAttributedTitle(title: NSAttributedString?, forAppearance appearance: TBControlAppearance, andStates states: [UIControlState]) { for state in states { setAttributedTitle(title, forAppearance: appearance, andState: state) } } /// Sets the attributed title to use for the specified appearance. /// /// - parameter title: The styled text string to use for the specified appearance. /// - parameter forAppearance: The TBControlAppearance that uses the specified attributed title. /// - parameter andState: The UIControlState that receives the attributed title. func setAttributedTitle(title: NSAttributedString?, forAppearance appearance: TBControlAppearance, andState state: UIControlState) { defer { shouldUpdateAppearance(appearance, andState: state) } guard let title = title else { attributedTitlesForAppearance.removeValueForKey(appearance) return } if attributedTitlesForAppearance[appearance] == nil { attributedTitlesForAppearance[appearance] = [:] } attributedTitlesForAppearance[appearance]?[state] = title } /// Returns the title color associated with the specified appearance. /// /// - parameter appearance: The TBControlAppearance that uses the title color. /// - parameter andState: The UIControlState that receives the title. /// /// - returns: The color of the title for the specified appearance. func titleColorForAppearance(appearance: TBControlAppearance, andState state: UIControlState) -> UIColor? { return titleColorsForAppearance[appearance]?[state] } /// Sets the title color to use for the specified appearance and multiple states. /// /// - parameter color: The color of the title to use for the specified appearance. /// - parameter forAppearance: The TBControlAppearance that uses the specified title color. /// - parameter andState: The UIControlStates that receive the title color. func setTitleColor(color: UIColor?, forAppearance appearance: TBControlAppearance, andStates states: [UIControlState]) { for state in states { setTitleColor(color, forAppearance: appearance, andState: state) } } /// Sets the title color to use for the specified appearance. /// /// - parameter color: The color of the title to use for the specified appearance. /// - parameter forAppearance: The TBControlAppearance that uses the specified title color. /// - parameter andState: The UIControlState that receives the title color. func setTitleColor(color: UIColor?, forAppearance appearance: TBControlAppearance, andState state: UIControlState) { defer { shouldUpdateAppearance(appearance, andState: state) } guard let color = color else { titleColorsForAppearance.removeValueForKey(appearance) return } if titleColorsForAppearance[appearance] == nil { titleColorsForAppearance[appearance] = [:] } titleColorsForAppearance[appearance]?[state] = color } /// Returns the shadow color of the title used for a appearance. /// /// - parameter appearance: The TBControlAppearance that uses the title shadow color. /// - parameter andState: The UIControlState that receives the title shadow color. /// /// - returns: The color of the title’s shadow for the specified appearance. func titleShadowColorForAppearance(appearance: TBControlAppearance, andState state: UIControlState) -> UIColor? { return titleShadowColorsForAppearance[appearance]?[state] } /// Sets the shadow color of the title to use for the specified appearance and multiple states. /// /// - parameter color: The shadow color of the title to use for the specified appearance. /// - parameter forAppearance: The TBControlAppearance that uses the specified title shadow color. /// - parameter andStates: The UIControlStates that receive the title shadow color. func setTitleShadowColor(color: UIColor?, forAppearance appearance: TBControlAppearance, andStates states: [UIControlState]) { for state in states { setTitleShadowColor(color, forAppearance: appearance, andState: state) } } /// Sets the shadow color of the title to use for the specified appearance. /// /// - parameter color: The shadow color of the title to use for the specified appearance. /// - parameter forAppearance: The TBControlAppearance that uses the specified title shadow color. /// - parameter andState: The UIControlState that receives the title shadow color. func setTitleShadowColor(color: UIColor?, forAppearance appearance: TBControlAppearance, andState state: UIControlState) { defer { shouldUpdateAppearance(appearance, andState: state) } guard let color = color else { titleShadowColorsForAppearance.removeValueForKey(appearance) return } if titleShadowColorsForAppearance[appearance] == nil { titleShadowColorsForAppearance[appearance] = [:] } titleShadowColorsForAppearance[appearance]?[state] = color } // MARK: - Configuring the Button Presentation /// Returns the background image used for a button appearance. /// /// - parameter appearance: The TBControlAppearance that uses the background image. /// - parameter andState: The UIControlState that receives the background image. /// /// - returns: The background image used for the specified appearance. func backgroundImageForAppearance(appearance: TBControlAppearance, andState state: UIControlState) -> UIImage? { return backgroundImagesForAppearance[appearance]?[state] } /// Sets the background image to use for the specified button appearance and multiple states. /// /// - parameter color: The background image to use for the specified appearance. /// - parameter forAppearance: The TBControlAppearance that uses the specified background image. /// - parameter andStates: The UIControlStates that receive the background image. func setBackgroundImage(image: UIImage?, forAppearance appearance: TBControlAppearance, andStates states: [UIControlState]) { for state in states { setBackgroundImage(image, forAppearance: appearance, andState: state) } } /// Sets the background image to use for the specified button appearance. /// /// - parameter color: The background image to use for the specified appearance. /// - parameter forAppearance: The TBControlAppearance that uses the specified background image. /// - parameter andState: The UIControlState that receives the background image. func setBackgroundImage(image: UIImage?, forAppearance appearance: TBControlAppearance, andState state: UIControlState) { defer { shouldUpdateAppearance(appearance, andState: state) } guard let backgroundImage = image else { backgroundImagesForAppearance.removeValueForKey(appearance) return } if backgroundImagesForAppearance[appearance] == nil { backgroundImagesForAppearance[appearance] = [:] } backgroundImagesForAppearance[appearance]?[state] = backgroundImage } /// Returns the image used for a button appearance. /// /// - parameter appearance: The TBControlAppearance that uses the background image. /// - parameter andState: The UIControlState that receives the image. /// /// - returns: The image used for the specified appearance. func imageForAppearance(appearance: TBControlAppearance, andState state: UIControlState) -> UIImage? { return imagesForAppearance[appearance]?[state] } /// Sets the image to use for the specified button appearance and multiple states. /// /// - parameter color: The image to use for the specified appearance. /// - parameter forAppearance: The TBControlAppearance that uses the specified image. /// - parameter andStates: The UIControlStates that receive the image. func setImage(image: UIImage?, forAppearance appearance: TBControlAppearance, andStates states: [UIControlState]) { for state in states { setImage(image, forAppearance: appearance, andState: state) } } /// Sets the image to use for the specified button appearance. /// /// - parameter color: The image to use for the specified appearance. /// - parameter forAppearance: The TBControlAppearance that uses the specified image. /// - parameter andState: The UIControlState that receives the image. func setImage(image: UIImage?, forAppearance appearance: TBControlAppearance, andState state: UIControlState) { defer { shouldUpdateAppearance(appearance, andState: state) } guard let image = image else { imagesForAppearance.removeValueForKey(appearance) return } if imagesForAppearance[appearance] == nil { imagesForAppearance[appearance] = [:] } imagesForAppearance[appearance]?[state] = image } // MARK: Setting and Getting Control Appearance /// Select a TBControlAppearance, conforming the button to the specified settings. /// /// - parameter appearance: The TBControlAppearance to display. public func activateAppearance(appearance: TBControlAppearance) { _appearance = appearance } /// The currently active TBControlAppearance var appearance: TBControlAppearance? { guard let appearance = _appearance else { return nil } return appearance } }
mit
dd8a2ec41a47cb713f0fe07cdc7a29d6
42.223077
138
0.739455
5.169273
false
false
false
false
proxpero/Endgame
Sources/Position+Castle.swift
1
7193
// // Position+Castle.swift // Endgame // // Created by Todd Olsen on 3/26/17. // // extension Position { /// The castling rights of a chess game. public struct Castle { /// The rights. fileprivate var rights: Set<Right> } } extension Position.Castle { /// Creates empty rights. public init() { self.rights = Set() } /// Creates a `Castle` from a `String`. /// /// - returns: `nil` if `string` is empty or invalid. public init?(string: String) { guard !string.isEmpty else { return nil } if string == "-" { self.rights = Set() } else { var rights = Set<Right>() for char in string.characters { guard let right = Right(character: char) else { return nil } rights.insert(right) } self.rights = rights } } /// Creates castling rights for `color`. public init(color: Color) { self = color.isWhite ? .white : .black } /// Creates castling rights for `side`. public init(side: Board.Side) { self = side.isKingside ? .kingside : .queenside } /// Creates a set of rights from a sequence. public init<S: Sequence>(_ sequence: S) where S.Iterator.Element == Right { if let set = sequence as? Set<Right> { self.rights = set } else { self.rights = Set(sequence) } } } extension Position.Castle { /// Returns `true` if `self` can castle for `color`. public func canCastle(for color: Color) -> Bool { return !self.intersection(Position.Castle(color: color)).isEmpty } /// Returns `true` if `self` can castle for `side`. public func canCastle(for side: Board.Side) -> Bool { return !self.intersection(Position.Castle(side: side)).isEmpty } } extension Position.Castle { /// All castling rights. public static let all = Position.Castle(Right.all) /// White castling rights. public static let white = Position.Castle(Right.white) /// Black castling rights. public static let black = Position.Castle(Right.black) /// Kingside castling rights. public static let kingside = Position.Castle(Right.kingside) /// Queenside castling rights. public static let queenside = Position.Castle(Right.queenside) } extension Position.Castle: CustomStringConvertible { /// A textual representation of `self`. public var description: String { if !rights.isEmpty { return String(rights.map({ $0.character }).sorted()) } else { return "-" } } } extension Position.Castle: Hashable { /// The hash value. public var hashValue: Int { return rights.reduce(0) { $0 | $1.hashValue } } } extension Position.Castle: Equatable { /// Returns `true` if both have the same rights. public static func == (lhs: Position.Castle, rhs: Position.Castle) -> Bool { return lhs.rights == rhs.rights } } extension Position.Castle: Sequence { /// An iterator over the members of `Position.Castle`. public struct Iterator: IteratorProtocol { internal var rightsSet: SetIterator<Right> /// Advance to the next element and return it, or `nil` if no next element exists. public mutating func next() -> Right? { return rightsSet.next() } } /// Returns an iterator over the members. public func makeIterator() -> Iterator { return Iterator(rightsSet: rights.makeIterator()) } } extension Position.Castle: SetAlgebra { /// A Boolean value that indicates whether the set has no elements. public var isEmpty: Bool { return rights.isEmpty } /// Returns a Boolean value that indicates whether the given element exists /// in the set. public func contains(_ member: Right) -> Bool { return rights.contains(member) } /// Returns a new set with the elements of both this and the given set. public func union(_ other: Position.Castle) -> Position.Castle { return Position.Castle(rights.union(other.rights)) } /// Returns a new set with the elements that are common to both this set and /// the given set. public func intersection(_ other: Position.Castle) -> Position.Castle { return Position.Castle(rights.intersection(other.rights)) } /// Returns a new set with the elements that are either in this set or in the /// given set, but not in both. public func symmetricDifference(_ other: Position.Castle) -> Position.Castle { return Position.Castle(rights.symmetricDifference(other.rights)) } /// Inserts the given element in the set if it is not already present. @discardableResult public mutating func insert(_ newMember: Right) -> (inserted: Bool, memberAfterInsert: Right) { return rights.insert(newMember) } /// Removes the given element and any elements subsumed by the given element. @discardableResult public mutating func remove(_ member: Right) -> Right? { return rights.remove(member) } /// Inserts the given element into the set unconditionally. @discardableResult public mutating func update(with newMember: Right) -> Right? { return rights.update(with: newMember) } /// Adds the elements of the given set to the set. public mutating func formUnion(_ other: Position.Castle) { rights.formUnion(other.rights) } /// Removes the elements of this set that aren't also in the given set. public mutating func formIntersection(_ other: Position.Castle) { rights.formIntersection(other.rights) } /// Removes the elements of the set that are also in the given set and /// adds the members of the given set that are not already in the set. public mutating func formSymmetricDifference(_ other: Position.Castle) { rights.formSymmetricDifference(other.rights) } /// Returns a new set containing the elements of this set that do not occur /// in the given set. public func subtracting(_ other: Position.Castle) -> Position.Castle { return Position.Castle(rights.subtracting(other.rights)) } /// Returns a Boolean value that indicates whether the set is a subset of /// another set. public func isSubset(of other: Position.Castle) -> Bool { return rights.isSubset(of: other.rights) } /// Returns a Boolean value that indicates whether the set has no members in /// common with the given set. public func isDisjoint(with other: Position.Castle) -> Bool { return rights.isDisjoint(with: other.rights) } /// Returns a Boolean value that indicates whether the set is a superset of /// the given set. public func isSuperset(of other: Position.Castle) -> Bool { return rights.isSuperset(of: other.rights) } /// Removes the elements of the given set from this set. public mutating func subtract(_ other: Position.Castle) { rights.subtract(other) } }
mit
a5fedf62705d3032b0edf37893058fdc
28.239837
99
0.634228
4.418305
false
false
false
false
CrazyZhangSanFeng/BanTang
BanTang/BanTang/Classes/Home/View/BTTopicDesView.swift
1
1810
// // BTTopicDesView.swift // BanTang // // Created by 张灿 on 16/6/9. // Copyright © 2016年 张灿. All rights reserved. // import UIKit import SnapKit class BTTopicDesView: UIView { //模型 var productModel: BTProductModel? //边距 var margin: CGFloat = 10 //顶部图片的高度 let topImageH: CGFloat = 0.55 * BTscreenW //标题 var titleLabel: UILabel? //内容 var desLabel: UILabel? //根据传入的模型获得高度 func viewHeight(productModel: BTProductModel) -> CGFloat { titleLabel?.text = productModel.title desLabel?.text = productModel.desc self.layoutIfNeeded() return CGRectGetMaxY(desLabel!.frame) } override init(frame: CGRect) { super.init(frame: frame) titleLabel = UILabel() titleLabel?.font = UIFont.systemFontOfSize(18) titleLabel?.textColor = UIColor.darkGrayColor() desLabel = UILabel() desLabel?.font = UIFont.systemFontOfSize(15) desLabel?.preferredMaxLayoutWidth = BTscreenW - 2 * margin desLabel?.numberOfLines = 0 self.addSubview(titleLabel!) self.addSubview(desLabel!) titleLabel?.snp_makeConstraints(closure: { (make) in make.leading.equalTo(10) make.top.equalTo(10) make.trailing.equalTo(-10) make.height.equalTo(30) }) desLabel?.snp_makeConstraints(closure: { (make) in make.top.equalTo((titleLabel?.snp_bottom)!).offset(10) make.leading.equalTo(10) make.trailing.equalTo(-10) }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
c015d723810c168280dbd85382757d70
24.691176
66
0.592444
4.345771
false
false
false
false
WickedColdfront/Slide-iOS
Pods/ImageViewer/ImageViewer/Source/UtilityFunctions.swift
1
5264
// // UtilityFunctions.swift // ImageViewer // // Created by Kristian Angyal on 29/02/2016. // Copyright © 2016 MailOnline. All rights reserved. // import UIKit import AVFoundation /// returns a size that aspect-fits into the bounding size. Example -> We have some view of /// certain size and the question is, what would have to be its size, so that it would fit /// it into some rect of some size ..given we would want to keep the content rects aspect ratio. func aspectFitSize(forContentOfSize contentSize: CGSize, inBounds bounds: CGSize) -> CGSize { return AVMakeRect(aspectRatio: contentSize, insideRect: CGRect(origin: CGPoint.zero, size: bounds)).size } func aspectFitContentSize(forBoundingSize boundingSize: CGSize, contentSize: CGSize) -> CGSize { return AVMakeRect(aspectRatio: contentSize, insideRect: CGRect(origin: CGPoint.zero, size: boundingSize)).size } func aspectFillZoomScale(forBoundingSize boundingSize: CGSize, contentSize: CGSize) -> CGFloat { let aspectFitSize = aspectFitContentSize(forBoundingSize: boundingSize, contentSize: contentSize) return (floor(boundingSize.width) == floor(aspectFitSize.width)) ? (boundingSize.height / aspectFitSize.height): (boundingSize.width / aspectFitSize.width) } func contentCenter(forBoundingSize boundingSize: CGSize, contentSize: CGSize) -> CGPoint { /// When the zoom scale changes i.e. the image is zoomed in or out, the hypothetical center /// of content view changes too. But the default Apple implementation is keeping the last center /// value which doesn't make much sense. If the image ratio is not matching the screen /// ratio, there will be some empty space horizontally or vertically. This needs to be calculated /// so that we can get the correct new center value. When these are added, edges of contentView /// are aligned in realtime and always aligned with corners of scrollView. let horizontalOffset = (boundingSize.width > contentSize.width) ? ((boundingSize.width - contentSize.width) * 0.5): 0.0 let verticalOffset = (boundingSize.height > contentSize.height) ? ((boundingSize.height - contentSize.height) * 0.5): 0.0 return CGPoint(x: contentSize.width * 0.5 + horizontalOffset, y: contentSize.height * 0.5 + verticalOffset) } func zoomRect(ForScrollView scrollView: UIScrollView, scale: CGFloat, center: CGPoint) -> CGRect { let width = scrollView.frame.size.width / scale let height = scrollView.frame.size.height / scale let originX = center.x - (width / 2.0) let originY = center.y - (height / 2.0) return CGRect(x: originX, y: originY, width: width, height: height) } func screenshotFromView(_ view: UIView) -> UIImage { let image: UIImage UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale) view.drawHierarchy(in: view.bounds, afterScreenUpdates: false) image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } // the transform needed to rotate a view that matches device screen orientation to match window orientation. func windowRotationTransform() -> CGAffineTransform { let angleInDegrees = rotationAngleToMatchDeviceOrientation(UIDevice.current.orientation) let angleInRadians = degreesToRadians(angleInDegrees) return CGAffineTransform(rotationAngle: angleInRadians) } // the transform needed to rotate a view that matches window orientation to match devices screen orientation. func deviceRotationTransform() -> CGAffineTransform { let angleInDegrees = rotationAngleToMatchDeviceOrientation(UIDevice.current.orientation) let angleInRadians = degreesToRadians(angleInDegrees) return CGAffineTransform(rotationAngle: -angleInRadians) } func degreesToRadians(_ degree: CGFloat) -> CGFloat { return CGFloat(M_PI) * degree / 180 } private func rotationAngleToMatchDeviceOrientation(_ orientation: UIDeviceOrientation) -> CGFloat { var desiredRotationAngle: CGFloat = 0 switch orientation { case .landscapeLeft: desiredRotationAngle = 90 case .landscapeRight: desiredRotationAngle = -90 case .portraitUpsideDown: desiredRotationAngle = 180 default: desiredRotationAngle = 0 } return desiredRotationAngle } func rotationAdjustedBounds() -> CGRect { let applicationWindow = UIApplication.shared.delegate?.window?.flatMap { $0 } guard let window = applicationWindow else { return UIScreen.main.bounds } if UIApplication.isPortraitOnly { return (UIDevice.current.orientation.isLandscape) ? CGRect(origin: CGPoint.zero, size: window.bounds.size.inverted()): window.bounds } return window.bounds } func maximumZoomScale(forBoundingSize boundingSize: CGSize, contentSize: CGSize) -> CGFloat { /// we want to allow the image to always cover 4x the area of screen return min(boundingSize.width, boundingSize.height) / min(contentSize.width, contentSize.height) * 4 } func rotationAdjustedCenter(_ view: UIView) -> CGPoint { guard UIApplication.isPortraitOnly else { return view.center } return (UIDevice.current.orientation.isLandscape) ? view.center.inverted() : view.center }
apache-2.0
44bf4a57d1a4aecc2daff86841b20ece
39.79845
159
0.742922
4.745717
false
false
false
false
otanistudio/NaiveHTTP
NaiveHTTP/Utility.swift
1
1691
// // Utility.swift // NaiveHTTP // // Created by Robert Otani on 9/7/15. // Copyright © 2015 otanistudio.com. All rights reserved. // import Foundation internal extension URL { /// Returns an NSURL with alphabetized query paramters. /// /// This covers the use case where `http://example.com?a=1&b=2` is always returned /// even if the string given was `http://example.com?b=2&a=1` /// /// - parameter string: The string to use to create the URL, e.g.: http://example.com or file://something /// /// - parameter params: a `Dictionary<String, String>` that contains the name/value pairs for the parameters /// /// - returns: An NSURL that guarantees query parameters sorted in ascending alphabetic order. init(string: String, params: [String : String]?) { // Deal with any query params already in the URI String var urlComponents = URLComponents(string: string) var queryItems: [URLQueryItem]? = urlComponents?.queryItems if queryItems == nil { queryItems = [] } // Now, incorporate items in queryParams to generate the fully-formed NSURL if let p = params { for (key, val) in p { let qItem = URLQueryItem(name: key, value: val) queryItems?.append(qItem) } } if queryItems!.count > 0 { queryItems?.sort(by: { (qItem1: URLQueryItem, qItem2: URLQueryItem) -> Bool in return qItem1.name < qItem2.name }) urlComponents?.queryItems = queryItems } self.init(string: (urlComponents?.string)!)! } }
mit
675a1ee3a33d09651fb26074269db9ce
34.208333
112
0.593491
4.333333
false
false
false
false
yrchen/edx-app-ios
Source/UserProfileViewController.swift
1
9948
// // UserProfileViewController.swift // edX // // Created by Michael Katz on 9/22/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit public class UserProfileViewController: UIViewController { public struct Environment { public var networkManager : NetworkManager public weak var router : OEXRouter? public init(networkManager : NetworkManager, router : OEXRouter?) { self.networkManager = networkManager self.router = router } } private let environment : Environment private let profileFeed: Feed<UserProfile> private let scrollView = UIScrollView() private let margin = 4 private var avatarImage: ProfileImageView! private var usernameLabel: UILabel = UILabel() private var messageLabel: UILabel = UILabel() private var countryLabel: UILabel = UILabel() private var languageLabel: UILabel = UILabel() private let bioText: UITextView = UITextView() private var header: ProfileBanner! private var spinner = SpinnerView(size: SpinnerView.Size.Large, color: SpinnerView.Color.Primary) private let editable:Bool public init(environment : Environment, feed: Feed<UserProfile>, editable:Bool = true) { self.editable = editable self.environment = environment self.profileFeed = feed super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func addListener() { profileFeed.output.listen(self, success: { [weak self] profile in self?.spinner.removeFromSuperview() self?.populateFields(profile) }, failure : { [weak self] _ in self?.spinner.removeFromSuperview() self?.setMessage(Strings.Profile.unableToGet) self?.bioText.text = "" }) } override public func viewDidLoad() { super.viewDidLoad() view.addSubview(scrollView) scrollView.backgroundColor = OEXStyles.sharedStyles().primaryBaseColor() scrollView.delegate = self scrollView.snp_makeConstraints { (make) -> Void in make.edges.equalTo(view) } if editable { let editButton = UIBarButtonItem(barButtonSystemItem: .Edit, target: nil, action: nil) editButton.oex_setAction() { [weak self] in self?.environment.router?.showProfileEditorFromController(self!) } editButton.accessibilityLabel = Strings.Profile.editAccessibility navigationItem.rightBarButtonItem = editButton } navigationController?.navigationBar.tintColor = OEXStyles.sharedStyles().neutralWhite() navigationController?.navigationBar.barTintColor = OEXStyles.sharedStyles().primaryBaseColor() avatarImage = ProfileImageView() avatarImage.borderWidth = 3.0 scrollView.addSubview(avatarImage) usernameLabel.setContentHuggingPriority(1000, forAxis: .Vertical) scrollView.addSubview(usernameLabel) messageLabel.hidden = true messageLabel.numberOfLines = 0 messageLabel.setContentHuggingPriority(1000, forAxis: .Vertical) scrollView.addSubview(messageLabel) languageLabel.accessibilityHint = Strings.Profile.languageAccessibilityHint languageLabel.setContentHuggingPriority(1000, forAxis: .Vertical) scrollView.addSubview(languageLabel) countryLabel.accessibilityHint = Strings.Profile.countryAccessibilityHint countryLabel.setContentHuggingPriority(1000, forAxis: .Vertical) scrollView.addSubview(countryLabel) bioText.backgroundColor = OEXStyles.sharedStyles().neutralWhiteT() bioText.textAlignment = .Natural bioText.scrollEnabled = false bioText.editable = false scrollView.addSubview(bioText) let whiteSpace = UIView() whiteSpace.backgroundColor = bioText.backgroundColor scrollView.insertSubview(whiteSpace, belowSubview: bioText) avatarImage.snp_makeConstraints { (make) -> Void in make.width.equalTo(avatarImage.snp_height) make.width.equalTo(166) make.centerX.equalTo(scrollView) make.top.equalTo(scrollView.snp_topMargin).offset(20) } usernameLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(avatarImage.snp_bottom).offset(margin) make.centerX.equalTo(scrollView) } messageLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(usernameLabel.snp_bottom).offset(margin).priorityHigh() make.centerX.equalTo(scrollView) } languageLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(messageLabel.snp_bottom).offset(margin) make.centerX.equalTo(scrollView) } countryLabel.snp_makeConstraints { (make) -> Void in make.top.equalTo(languageLabel.snp_bottom).offset(margin) make.centerX.equalTo(scrollView) } bioText.snp_makeConstraints { (make) -> Void in make.top.equalTo(countryLabel.snp_bottom).offset(margin + 6).priorityHigh() make.bottom.equalTo(scrollView) make.leading.equalTo(scrollView) make.trailing.equalTo(scrollView) make.width.equalTo(scrollView) } whiteSpace.snp_makeConstraints { (make) -> Void in make.top.equalTo(bioText) make.bottom.greaterThanOrEqualTo(view) make.leading.equalTo(bioText) make.trailing.equalTo(bioText) make.width.equalTo(bioText) } header = ProfileBanner(frame: CGRectZero) header.backgroundColor = scrollView.backgroundColor header.hidden = true view.addSubview(header) header.snp_makeConstraints { (make) -> Void in make.top.equalTo(scrollView) make.leading.equalTo(scrollView) make.trailing.equalTo(scrollView) make.height.equalTo(56) } addListener() } private func setMessage(message: String?) { if let message = message { let messageStyle = OEXTextStyle(weight: .Light, size: .XSmall, color: OEXStyles.sharedStyles().primaryXLightColor()) messageLabel.hidden = false messageLabel.snp_remakeConstraints { (make) -> Void in make.top.equalTo(usernameLabel.snp_bottom).offset(margin).priorityHigh() make.centerX.equalTo(scrollView) } countryLabel.hidden = true languageLabel.hidden = true messageLabel.attributedText = messageStyle.attributedStringWithText(message) } else { messageLabel.hidden = true messageLabel.snp_updateConstraints(closure: { (make) -> Void in make.height.equalTo(0) }) countryLabel.hidden = false languageLabel.hidden = false } } private func populateFields(profile: UserProfile) { let usernameStyle = OEXTextStyle(weight : .Normal, size: .XXLarge, color: OEXStyles.sharedStyles().neutralWhiteT()) let infoStyle = OEXTextStyle(weight: .Light, size: .XSmall, color: OEXStyles.sharedStyles().primaryXLightColor()) let bioStyle = OEXStyles.sharedStyles().textAreaBodyStyle usernameLabel.attributedText = usernameStyle.attributedStringWithText(profile.username) if profile.sharingLimitedProfile { avatarImage.image = UIImage(named: "avatarPlaceholder") setMessage(editable ? Strings.Profile.showingLimited : Strings.Profile.learnerHasLimitedProfile(platformName: OEXConfig.sharedConfig().platformName())) if (profile.parentalConsent ?? false) && editable { let newStyle = OEXMutableTextStyle(textStyle: bioStyle) newStyle.alignment = .Center newStyle.color = OEXStyles.sharedStyles().neutralBlackT() bioText.attributedText = newStyle.attributedStringWithText(Strings.Profile.under13) } else { bioText.text = "" } } else { setMessage(nil) avatarImage.remoteImage = profile.image(environment.networkManager) if let language = profile.language { let icon = Icon.Comment.attributedTextWithStyle(infoStyle) let langText = infoStyle.attributedStringWithText(language) languageLabel.attributedText = NSAttributedString.joinInNaturalLayout([icon, langText]) } if let country = profile.country { let icon = Icon.Country.attributedTextWithStyle(infoStyle) let countryText = infoStyle.attributedStringWithText(country) countryLabel.attributedText = NSAttributedString.joinInNaturalLayout([icon, countryText]) } let bio = profile.bio ?? Strings.Profile.noBio bioText.attributedText = bioStyle.attributedStringWithText(bio) } header.showProfile(profile, networkManager: environment.networkManager) } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) profileFeed.refresh() } } extension UserProfileViewController : UIScrollViewDelegate { public func scrollViewDidScroll(scrollView: UIScrollView) { UIView.animateWithDuration(0.25) { self.header.hidden = scrollView.contentOffset.y < CGRectGetMaxY(self.avatarImage.frame) } } }
apache-2.0
d940e909ce60823fd33e8d7025d3c06a
37.708171
163
0.640732
5.394794
false
false
false
false
karstengresch/layout_studies
countidon/countidon/CountidonDataModel.swift
1
3630
// // CountidonDataModel.swift // countidon // // Created by Karsten Gresch on 09.01.16. // Copyright © 2016 Closure One. All rights reserved. // import UIKit import Foundation class CountidonDataModel { var countidonGroups = [CountidonGroup]() var countidonSettings = CountidonSettings() init() { print("Data file path for groups is \(dataFilePathGroups())") print("Data file path for settings is \(dataFilePathSettings())") loadCountidonSettings() loadCountidonGroups() registerUserDefaults() handleFirstTimeAppStart() } // MARK: File related func documentsDirectory() -> String { let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) return paths[0] } func dataFilePathGroups() -> String { return (documentsDirectory() as NSString).appendingPathComponent("CountidonGroups.plist") } func dataFilePathSettings() -> String { return (documentsDirectory() as NSString).appendingPathComponent("CountidonSettings.plist") } // MARK: Groups func saveCountidonGroups() { let data = NSMutableData() let archiver = NSKeyedArchiver(forWritingWith: data) archiver.encode(countidonGroups, forKey: COUNTIDON_PERSISTENCE_GROUPS) archiver.finishEncoding() data.write(toFile: dataFilePathGroups(), atomically: true) } func loadCountidonGroups() { let path = dataFilePathGroups() if FileManager.default.fileExists(atPath: path) { print("CountidonGroups.plist found at \(path)") if let data = NSData(contentsOfFile: path) { let unarchiver = NSKeyedUnarchiver(forReadingWith: data as Data) countidonGroups = unarchiver.decodeObject(forKey: COUNTIDON_PERSISTENCE_GROUPS) as! [CountidonGroup] unarchiver.finishDecoding() } } } // MARK: Settings func saveCountidonSettings() { let data = NSMutableData() let archiver = NSKeyedArchiver(forWritingWith: data) archiver.encode(countidonSettings, forKey: COUNTIDON_PERSISTENCE_SETTINGS) archiver.finishEncoding() data.write(toFile: dataFilePathSettings(), atomically: true) } func loadCountidonSettings() { let path = dataFilePathSettings() if FileManager.default.fileExists(atPath: path) { print("CountidonSettings.plist found at \(path)") if let data = NSData(contentsOfFile: path) { let unarchiver = NSKeyedUnarchiver(forReadingWith: data as Data) countidonSettings = unarchiver.decodeObject(forKey: COUNTIDON_PERSISTENCE_SETTINGS) as! CountidonSettings unarchiver.finishDecoding() } } } // MARK: Defaults and first start func registerUserDefaults() { let defaultsDictionary = ["AppRunsFirstTime": true] UserDefaults.standard.register(defaults: defaultsDictionary) } func handleFirstTimeAppStart() { let userDefaults = UserDefaults.standard let firstTime = userDefaults.bool(forKey: "AppRunsFirstTime") if firstTime { // TODO initialise default settings let firstTimeCountidonGroup = CountidonGroup(name: COUNTIDON_DATA_MODEL_FIRST_TIME_GROUP_NAME) let countidonItem = CountidonItem() countidonItem.name = COUNTIDON_ITEM_FIRST_ITEM_NAME // TODO move value to default setting countidonItem.timeToCountdown = 15 // scary! firstTimeCountidonGroup.countidonItems.append(countidonItem) countidonGroups.append(firstTimeCountidonGroup) saveCountidonGroups() saveCountidonSettings() userDefaults.set(false, forKey: "AppRunsFirstTime") userDefaults.synchronize() } } }
unlicense
8db4503d60c16cab181968fe6d7265ea
30.833333
113
0.711766
4.372289
false
false
false
false
flovouin/AsyncDisplayKit
examples_extra/ASDKgram-Swift/ASDKgram-Swift/Webservice.swift
5
2807
// // Webservice.swift // ASDKgram-Swift // // Created by Calum Harris on 06/01/2017. // // Copyright (c) 2014-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // swiftlint:disable force_cast import UIKit final class WebService { func load<A>(resource: Resource<A>, completion: @escaping (Result<A>) -> ()) { URLSession.shared.dataTask(with: resource.url) { data, response, error in // Check for errors in responses. let result = self.checkForNetworkErrors(data, response, error) switch result { case .success(let data): completion(resource.parse(data)) case .failure(let error): completion(.failure(error)) } }.resume() } } extension WebService { fileprivate func checkForNetworkErrors(_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Result<Data> { // Check for errors in responses. guard error == nil else { if (error as! NSError).domain == NSURLErrorDomain && ((error as! NSError).code == NSURLErrorNotConnectedToInternet || (error as! NSError).code == NSURLErrorTimedOut) { return .failure(.noInternetConnection) } else { return .failure(.returnedError(error!)) } } guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else { return .failure((.invalidStatusCode("Request returned status code other than 2xx \(response)"))) } guard let data = data else { return .failure(.dataReturnedNil) } return .success(data) } } struct Resource<A> { let url: URL let parse: (Data) -> Result<A> } extension Resource { init(url: URL, parseJSON: @escaping (Any) -> Result<A>) { self.url = url self.parse = { data in do { let jsonData = try JSONSerialization.jsonObject(with: data, options: []) return parseJSON(jsonData) } catch { fatalError("Error parsing data") } } } } enum Result<T> { case success(T) case failure(NetworkingErrors) } enum NetworkingErrors: Error { case errorParsingJSON case noInternetConnection case dataReturnedNil case returnedError(Error) case invalidStatusCode(String) case customError(String) }
bsd-3-clause
aea84d3e09c5ca1bd561dfb633b27e92
29.182796
170
0.706092
3.772849
false
false
false
false
huangboju/Moots
Examples/Lumia/Lumia/ViewController.swift
1
6151
// // ViewController.swift // Lumia // // Created by xiAo_Ju on 2019/12/31. // Copyright © 2019 黄伯驹. All rights reserved. // import UIKit class ViewController: UIViewController { var rows: [RowType] = [ Row<TitleCell>(viewData: TitleCellItem(title: "动画", segue: .segue(AnimationListVC.self))), Row<TitleCell>(viewData: TitleCellItem(title: "隐藏属性查看", segue: .segue(ClassCopyIvarListVC.self))), Row<TitleCell>(viewData: TitleCellItem(title: "StateMachine", segue: .segue(StateMachineVC.self))), Row<TitleCell>(viewData: TitleCellItem(title: "转场", segue: .segue(TransitionListVC.self))), Row<TitleCell>(viewData: TitleCellItem(title: "SafeArea", segue: .segue(MainViewController.self))), Row<TitleCell>(viewData: TitleCellItem(title: "CustomPaging", segue: .segue(CustomPagingVC.self))), Row<TitleCell>(viewData: TitleCellItem(title: "ScrollExample", segue: .segue(ScrollExample.self))), Row<TitleCell>(viewData: TitleCellItem(title: "PictureInPicture", segue: .segue(PictureInPicture.self))), Row<TitleCell>(viewData: TitleCellItem(title: "ParallaxImageViewController", segue: .segue(ParallaxImageViewController.self))), Row<TitleCell>(viewData: TitleCellItem(title: "UltraDrawerView", segue: .modal(ShapeViewController.self))), Row<TitleCell>(viewData: TitleCellItem(title: "QuartzDemoVC", segue: .storyboard("QuartzDemoVC"))), ] private lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() let inset: CGFloat = 20 layout.sectionInset = UIEdgeInsets(top: inset, left: inset, bottom: 0, right: inset) layout.minimumLineSpacing = inset layout.minimumInteritemSpacing = inset layout.itemSize = CGSize(width: (self.view.frame.width - inset * 3) / 2, height: 100) let collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) collectionView.backgroundColor = UIColor(white: 0.05, alpha: 1) collectionView.dataSource = self collectionView.delegate = self collectionView.register(TitleCell.self, forCellWithReuseIdentifier: "cellId") collectionView.translatesAutoresizingMaskIntoConstraints = false return collectionView }() override func viewDidLoad() { super.viewDidLoad() title = "Lumia" view.backgroundColor = UIColor(white: 0.05, alpha: 1) view.addSubview(collectionView) collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true collectionView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true collectionView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true collectionView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let selectedItems = collectionView.indexPathsForSelectedItems else { return } for selectedRow in selectedItems { transitionCoordinator?.animate(alongsideTransition: { context in self.collectionView.deselectItem(at: selectedRow, animated: true) }, completion: { context in if context.isCancelled { self.collectionView.selectItem(at: selectedRow, animated: false, scrollPosition: []) } }) } } } extension ViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let item: TitleCellItem = rows[indexPath.row].cellItem() show(item.segue) { vc in vc.title = item.title } } } extension ViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return rows.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) rows[indexPath.row].update(cell: cell) return cell } } struct TitleCellItem { let title: String let segue: Segue } class TitleCell: UICollectionViewCell { private lazy var textLabel: UILabel = { let textLabel = UILabel() textLabel.adjustsFontSizeToFitWidth = true textLabel.textColor = UIColor.white textLabel.font = UIFont.boldSystemFont(ofSize: 25) textLabel.textAlignment = .center textLabel.translatesAutoresizingMaskIntoConstraints = false return textLabel }() override init(frame: CGRect) { super.init(frame: frame) selectedBackgroundView = UIView() selectedBackgroundView?.backgroundColor = UIColor.white.withAlphaComponent(0.2) selectedBackgroundView?.layer.cornerRadius = 8 selectedBackgroundView?.clipsToBounds = true contentView.backgroundColor = UIColor.white.withAlphaComponent(0.1) contentView.layer.cornerRadius = 8 contentView.clipsToBounds = true contentView.addSubview(textLabel) textLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor).isActive = true textLabel.topAnchor.constraint(equalTo: contentView.topAnchor).isActive = true textLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor).isActive = true textLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor).isActive = true } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension TitleCell: Updatable { func update(viewData: TitleCellItem) { textLabel.text = viewData.title } } extension ViewController: CBCCatalogExample { @objc class var catalogMetadata: [String : Any]? { return [CBCBreadcrumbs: ["Case studies", "Carousel"]] } }
mit
267ef6383e79a392419465886c936de7
40.659864
135
0.693501
5.111853
false
false
false
false
djz-code/EMPageViewController
Examples/Greetings/Greetings/RootViewController.swift
1
8237
// // RootViewController.swift // EMPageViewController // // Created by Erik Malyak on 3/16/15. // Copyright (c) 2015 Erik Malyak. All rights reserved. // import UIKit class RootViewController: UIViewController, EMPageViewControllerDataSource, EMPageViewControllerDelegate { @IBOutlet weak var reverseButton: UIButton! @IBOutlet weak var scrollToButton: UIButton! @IBOutlet weak var forwardButton: UIButton! var pageViewController: EMPageViewController? var greetings: [String] = ["Hello!", "¡Hola!", "Salut!", "Hallo!", "Ciao!"] var greetingColors: [UIColor] = [ UIColor(red: 108.0/255.0, green: 122.0/255.0, blue: 137.0/255.0, alpha: 1.0), UIColor(red: 135.0/255.0, green: 211.0/255.0, blue: 124.0/255.0, alpha: 1.0), UIColor(red: 34.0/255.0, green: 167.0/255.0, blue: 240.0/255.0, alpha: 1.0), UIColor(red: 245.0/255.0, green: 171.0/255.0, blue: 53.0/255.0, alpha: 1.0), UIColor(red: 214.0/255.0, green: 69.0/255.0, blue: 65.0/255.0, alpha: 1.0) ] override func viewDidLoad() { super.viewDidLoad() // Instantiate EMPageViewController and set the data source and delegate to 'self' let pageViewController = EMPageViewController() pageViewController.dataSource = self pageViewController.delegate = self // Set the initially selected view controller let currentViewController = self.viewControllerAtIndex(0)! pageViewController.selectViewController(currentViewController, direction: .Forward, animated: false, completion: nil) // Add EMPageViewController to the root view controller self.addChildViewController(pageViewController) self.view.insertSubview(pageViewController.view, atIndex: 0) // Insert the page controller view below the navigation buttons pageViewController.didMoveToParentViewController(self) self.pageViewController = pageViewController } // MARK: - Convienient EMPageViewController scroll / transition methods @IBAction func forward(sender: AnyObject) { self.pageViewController!.scrollForwardAnimated(true, completion: nil) } @IBAction func reverse(sender: AnyObject) { self.pageViewController!.scrollReverseAnimated(true, completion: nil) } @IBAction func scrollTo(sender: AnyObject) { let choiceViewController = UIAlertController(title: "Scroll To...", message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) let selectedIndex = self.indexOfViewController(self.pageViewController!.selectedViewController as! GreetingViewController) for (index, viewControllerGreeting) in enumerate(greetings) { if (index != selectedIndex) { let action = UIAlertAction(title: viewControllerGreeting, style: UIAlertActionStyle.Default, handler: { (alertAction) in let viewController = self.viewControllerAtIndex(index)! let direction:EMPageViewControllerNavigationDirection = index > selectedIndex ? .Forward : .Reverse self.pageViewController!.selectViewController(viewController, direction: direction, animated: true, completion: nil) }) choiceViewController.addAction(action) } } let action = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil) choiceViewController.addAction(action) self.presentViewController(choiceViewController, animated: true, completion: nil) } // MARK: - EMPageViewController Data Source func em_pageViewController(pageViewController: EMPageViewController, viewControllerLeftOfViewController viewController: UIViewController) -> UIViewController? { if let viewControllerIndex = self.indexOfViewController(viewController as! GreetingViewController) { let leftViewController = self.viewControllerAtIndex(viewControllerIndex - 1) return leftViewController } else { return nil } } func em_pageViewController(pageViewController: EMPageViewController, viewControllerRightOfViewController viewController: UIViewController) -> UIViewController? { if let viewControllerIndex = self.indexOfViewController(viewController as! GreetingViewController) { let rightViewController = self.viewControllerAtIndex(viewControllerIndex + 1) return rightViewController } else { return nil } } func viewControllerAtIndex(index: Int) -> GreetingViewController? { if (self.greetings.count == 0) || (index < 0) || (index >= self.greetings.count) { return nil } let viewController = self.storyboard!.instantiateViewControllerWithIdentifier("GreetingViewController") as! GreetingViewController viewController.greeting = self.greetings[index] viewController.color = self.greetingColors[index] return viewController } func indexOfViewController(viewController: GreetingViewController) -> Int? { if let greeting: String = viewController.greeting { return find(self.greetings, greeting) } else { return nil } } // MARK: - EMPageViewController Delegate func em_pageViewController(pageViewController: EMPageViewController, willStartScrollingFrom startViewController: UIViewController, destinationViewController: UIViewController) { let startGreetingViewController = startViewController as! GreetingViewController let destinationGreetingViewController = destinationViewController as! GreetingViewController println("Will start scrolling from \(startGreetingViewController.greeting) to \(destinationGreetingViewController.greeting).") } func em_pageViewController(pageViewController: EMPageViewController, isScrollingFrom startViewController: UIViewController, destinationViewController: UIViewController, progress: CGFloat) { let startGreetingViewController = startViewController as! GreetingViewController let destinationGreetingViewController = destinationViewController as! GreetingViewController // Ease the labels' alphas in and out let absoluteProgress = fabs(progress) startGreetingViewController.label.alpha = pow(1 - absoluteProgress, 2) destinationGreetingViewController.label.alpha = pow(absoluteProgress, 2) println("Is scrolling from \(startGreetingViewController.greeting) to \(destinationGreetingViewController.greeting) with progress '\(progress)'.") } func em_pageViewController(pageViewController: EMPageViewController, didFinishScrollingFrom startViewController: UIViewController?, destinationViewController: UIViewController, transitionSuccessful: Bool) { let startViewController = startViewController as! GreetingViewController? let destinationViewController = destinationViewController as! GreetingViewController // If the transition is successful, the new selected view controller is the destination view controller. // If it wasn't successful, the selected view controller is the start view controller if transitionSuccessful { if (self.indexOfViewController(destinationViewController) == 0) { self.reverseButton.enabled = false } else { self.reverseButton.enabled = true } if (self.indexOfViewController(destinationViewController) == self.greetings.count - 1) { self.forwardButton.enabled = false } else { self.forwardButton.enabled = true } } println("Finished scrolling from \(startViewController?.greeting) to \(destinationViewController.greeting). Transition successful? \(transitionSuccessful)") } }
mit
5d33fe1004eaef7d22858280be641982
45.531073
210
0.681277
5.759441
false
false
false
false
debugsquad/nubecero
nubecero/View/PhotosAlbumPhotoSettings/VPhotosAlbumPhotoSettingsCellSize.swift
1
2959
import UIKit class VPhotosAlbumPhotoSettingsCellSize:VPhotosAlbumPhotoSettingsCell { private weak var labelSize:UILabel! private let numberFormatter:NumberFormatter override init(frame:CGRect) { numberFormatter = NumberFormatter() numberFormatter.numberStyle = NumberFormatter.Style.decimal super.init(frame:frame) backgroundColor = UIColor.white isUserInteractionEnabled = false let labelTitle:UILabel = UILabel() labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.isUserInteractionEnabled = false labelTitle.backgroundColor = UIColor.clear labelTitle.font = UIFont.medium(size:14) labelTitle.textColor = UIColor.complement labelTitle.text = NSLocalizedString("VPhotosAlbumPhotoSettingsCellSize_labelTitle", comment:"") let labelSize:UILabel = UILabel() labelSize.translatesAutoresizingMaskIntoConstraints = false labelSize.isUserInteractionEnabled = false labelSize.backgroundColor = UIColor.clear labelSize.font = UIFont.regular(size:17) labelSize.textColor = UIColor.black self.labelSize = labelSize addSubview(labelTitle) addSubview(labelSize) let views:[String:UIView] = [ "labelTitle":labelTitle, "labelSize":labelSize] let metrics:[String:CGFloat] = [:] addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"H:|-10-[labelTitle(65)]-0-[labelSize(250)]", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[labelTitle]-0-|", options:[], metrics:metrics, views:views)) addConstraints(NSLayoutConstraint.constraints( withVisualFormat:"V:|-0-[labelSize]-0-|", options:[], metrics:metrics, views:views)) } required init?(coder:NSCoder) { fatalError() } override func config(controller:CPhotosAlbumPhotoSettings, model:MPhotosAlbumPhotoSettingsItem) { super.config(controller:controller, model:model) guard let photo:MPhotosItemPhoto = controller.photo else { return } let size:Int = photo.size let sizeNumber:NSNumber = size as NSNumber guard let kilosString:String = numberFormatter.string(from:sizeNumber) else { return } let sizeString:String = String( format:NSLocalizedString("VPhotosAlbumPhotoSettingsCellSize_labelSize", comment:""), kilosString) labelSize.text = sizeString } }
mit
5ab149156aa43cf88dd835cb6582822f
30.147368
103
0.604934
6.014228
false
false
false
false
vnu/vTweetz
Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel+Fall.swift
2
5680
// // LTMorphingLabel+Fall.swift // https://github.com/lexrus/LTMorphingLabel // // The MIT License (MIT) // Copyright (c) 2015 Lex Tang, http://lexrus.com // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files // (the “Software”), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit extension LTMorphingLabel { func FallLoad() { progressClosures["Fall\(phaseProgress)"] = { (index: Int, progress: Float, isNewChar: Bool) in if isNewChar { return min( 1.0, max( 0.0, progress - self.morphingCharacterDelay * Float(index) / 1.7 ) ) } let j: Float = Float(sin(Double(index))) * 1.7 return min(1.0, max(0.0001, progress + self.morphingCharacterDelay * Float(j))) } effectClosures["Fall\(phaseDisappear)"] = { char, index, progress in return LTCharacterLimbo( char: char, rect: self.previousRects[index], alpha: CGFloat(1.0 - progress), size: self.font.pointSize, drawingProgress: CGFloat(progress)) } effectClosures["Fall\(phaseAppear)"] = { char, index, progress in let currentFontSize = CGFloat( LTEasing.easeOutQuint(progress, 0.0, Float(self.font.pointSize)) ) let yOffset = CGFloat(self.font.pointSize - currentFontSize) return LTCharacterLimbo( char: char, rect: CGRectOffset(self.newRects[index], 0.0, yOffset), alpha: CGFloat(self.morphingProgress), size: currentFontSize, drawingProgress: 0.0 ) } drawingClosures["Fall\(phaseDraw)"] = { limbo in if limbo.drawingProgress > 0.0 { let context = UIGraphicsGetCurrentContext() var charRect = limbo.rect CGContextSaveGState(context) let charCenterX = charRect.origin.x + (charRect.size.width / 2.0) var charBottomY = charRect.origin.y + charRect.size.height - self.font.pointSize / 6 var charColor = self.textColor // Fall down if drawingProgress is more than 50% if limbo.drawingProgress > 0.5 { let ease = CGFloat( LTEasing.easeInQuint( Float(limbo.drawingProgress - 0.4), 0.0, 1.0, 0.5 ) ) charBottomY = charBottomY + ease * 10.0 let fadeOutAlpha = min( 1.0, max( 0.0, limbo.drawingProgress * -2.0 + 2.0 + 0.01 ) ) charColor = self.textColor.colorWithAlphaComponent(fadeOutAlpha) } charRect = CGRect( x: charRect.size.width / -2.0, y: charRect.size.height * -1.0 + self.font.pointSize / 6, width: charRect.size.width, height: charRect.size.height) CGContextTranslateCTM(context, charCenterX, charBottomY) let angle = Float(sin(Double(limbo.rect.origin.x)) > 0.5 ? 168 : -168) let rotation = CGFloat( LTEasing.easeOutBack( min( 1.0, Float(limbo.drawingProgress) ), 0.0, 1.0 ) * angle ) CGContextRotateCTM(context, rotation * CGFloat(M_PI) / 180.0) let s = String(limbo.char) s.drawInRect(charRect, withAttributes: [ NSFontAttributeName: self.font.fontWithSize(limbo.size), NSForegroundColorAttributeName: charColor ]) CGContextRestoreGState(context) return true } return false } } }
apache-2.0
9556a6dfbdfb05c047b6f8867b822fcd
36.813333
100
0.489951
5.401905
false
false
false
false
vulgur/WeeklyFoodPlan
WeeklyFoodPlan/WeeklyFoodPlan/Views/FoodList/FoodListViewController.swift
1
5079
// // FoodListViewController.swift // WeeklyFoodPlan // // Created by vulgur on 2017/2/4. // Copyright © 2017年 MAD. All rights reserved. // import UIKit class FoodListViewController: UIViewController { let cellIdentifier = "FoodItemCell" let segueIdentifier = "ShowFood" @IBOutlet var tableView: UITableView! var foods = [Food]() override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = false self.navigationController?.view.backgroundColor = UIColor.white tableView.dataSource = self tableView.delegate = self tableView.rowHeight = 80 tableView.tableFooterView = UIView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.tabBarController?.tabBar.isHidden = false foods = BaseManager.shared.queryAllFoods() tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == segueIdentifier { if let cell = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: cell) { let food = foods[indexPath.row] let destinationVC = segue.destination as! FoodViewController destinationVC.food = food } } } @IBAction func showFoodTypeOptions(_ sender: UIBarButtonItem) { let blurEffect = UIBlurEffect(style: .regular) let blurView = UIVisualEffectView(effect: blurEffect) blurView.frame = self.view.frame let alertController = UIAlertController(title: "Choose food type", message: nil, preferredStyle: .alert) let homeCookAction = UIAlertAction(title: "HomeCook", style: .default) { [unowned self] (action) in let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "FoodViewController") as! FoodViewController vc.foodType = .homeCook blurView.removeFromSuperview() self.navigationController?.pushViewController(vc, animated: true) } let takeOutAction = UIAlertAction(title: "TakeOut", style: .default) { [unowned self] (action) in let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "FoodViewController") as! FoodViewController vc.foodType = .takeOut blurView.removeFromSuperview() self.navigationController?.pushViewController(vc, animated: true) } let eatingOutAction = UIAlertAction(title: "EatingOut", style: .default) { [unowned self] (action) in let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "FoodViewController") as! FoodViewController vc.foodType = .eatingOut blurView.removeFromSuperview() self.navigationController?.pushViewController(vc, animated: true) } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in blurView.removeFromSuperview() } alertController.addAction(homeCookAction) alertController.addAction(takeOutAction) alertController.addAction(eatingOutAction) alertController.addAction(cancelAction) self.view.addSubview(blurView) self.present(alertController, animated: true, completion: nil) } } extension FoodListViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return foods.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! FoodItemCell let food = foods[indexPath.row] cell.foodNameLabel.text = food.name let whenString = food.whenObjects.reduce("") { (string, when) -> String in string + " " + when.value } cell.foodWhenLabel.text = whenString cell.foodTypeLabel.text = food.typeRawValue if food.isFavored { cell.foodFavorImageView.isHidden = false cell.foodFavorImageView.image = #imageLiteral(resourceName: "heart") } else { cell.foodFavorImageView.isHidden = true } return cell } } extension FoodListViewController: UITableViewDelegate { // func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // let food = foods[indexPath.row] // performSegue(withIdentifier: segueIdentifier, sender: food) // } }
mit
16d678f98552925d6f0eb35850c6ed48
40.268293
147
0.664894
5.184883
false
false
false
false
crewshin/GasLog
Pods/RealmSwift/RealmSwift/RealmCollectionType.swift
3
24525
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm /** Encapsulates iteration state and interface for iteration over a `RealmCollectionType`. */ public final class RLMGenerator<T: Object>: GeneratorType { private let generatorBase: NSFastGenerator internal init(collection: RLMCollection) { generatorBase = NSFastGenerator(collection) } // swiftlint:disable valid_docs /// Advance to the next element and return it, or `nil` if no next element /// exists. public func next() -> T? { let accessor = generatorBase.next() as! T? if let accessor = accessor { RLMInitializeSwiftAccessorGenerics(accessor) } return accessor } // swiftlint:enable valid_docs } /** A homogenous collection of `Object`s which can be retrieved, filtered, sorted, and operated upon. */ public protocol RealmCollectionType: CollectionType, CustomStringConvertible { /// Element type contained in this collection. typealias Element: Object // MARK: Properties /// The Realm the objects in this collection belong to, or `nil` if the /// collection's owning object does not belong to a realm (the collection is /// standalone). var realm: Realm? { get } /// Returns the number of objects in this collection. var count: Int { get } /// Returns a human-readable description of the objects contained in this collection. var description: String { get } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the collection. - parameter object: The object whose index is being queried. - returns: The index of the given object, or `nil` if the object is not in the collection. */ func indexOf(object: Element) -> Int? /** Returns the index of the first object matching the given predicate, or `nil` no objects match. - parameter predicate: The `NSPredicate` used to filter the objects. - returns: The index of the first matching object, or `nil` if no objects match. */ func indexOf(predicate: NSPredicate) -> Int? /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: The predicate format string, optionally followed by a variable number of arguments. - returns: The index of the first matching object, or `nil` if no objects match. */ func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? // MARK: Filtering /** Returns `Results` containing collection elements that match the given predicate. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: `Results` containing collection elements that match the given predicate. */ func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> /** Returns `Results` containing collection elements that match the given predicate. - parameter predicate: The predicate to filter the objects. - returns: `Results` containing collection elements that match the given predicate. */ func filter(predicate: NSPredicate) -> Results<Element> // MARK: Sorting /** Returns `Results` containing collection elements sorted by the given property. - parameter property: The property name to sort by. - parameter ascending: The direction to sort by. - returns: `Results` containing collection elements sorted by the given property. */ func sorted(property: String, ascending: Bool) -> Results<Element> /** Returns `Results` with elements sorted by the given sort descriptors. - parameter sortDescriptors: `SortDescriptor`s to sort by. - returns: `Results` with elements sorted by the given sort descriptors. */ func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element> // MARK: Aggregate Operations /** Returns the minimum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on. - returns: The minimum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ func min<U: MinMaxType>(property: String) -> U? /** Returns the maximum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on. - returns: The maximum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ func max<U: MinMaxType>(property: String) -> U? /** Returns the sum of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate sum on. - returns: The sum of the given property over all objects in the collection. */ func sum<U: AddableType>(property: String) -> U /** Returns the average of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate average on. - returns: The average of the given property over all objects in the collection, or `nil` if the collection is empty. */ func average<U: AddableType>(property: String) -> U? // MARK: Key-Value Coding /** Returns an Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. - parameter key: The name of the property. - returns: Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. */ func valueForKey(key: String) -> AnyObject? /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified value and key. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property. */ func setValue(value: AnyObject?, forKey key: String) } private class _AnyRealmCollectionBase<T: Object>: RealmCollectionType { typealias Element = T var realm: Realm? { fatalError() } var count: Int { fatalError() } var description: String { fatalError() } func indexOf(object: Element) -> Int? { fatalError() } func indexOf(predicate: NSPredicate) -> Int? { fatalError() } func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { fatalError() } func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> { fatalError() } func filter(predicate: NSPredicate) -> Results<Element> { fatalError() } func sorted(property: String, ascending: Bool) -> Results<Element> { fatalError() } func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element> { fatalError() } func min<U: MinMaxType>(property: String) -> U? { fatalError() } func max<U: MinMaxType>(property: String) -> U? { fatalError() } func sum<U: AddableType>(property: String) -> U { fatalError() } func average<U: AddableType>(property: String) -> U? { fatalError() } subscript(index: Int) -> Element { fatalError() } func generate() -> RLMGenerator<T> { fatalError() } var startIndex: Int { fatalError() } var endIndex: Int { fatalError() } func valueForKey(key: String) -> AnyObject? { fatalError() } func setValue(value: AnyObject?, forKey key: String) { fatalError() } } private final class _AnyRealmCollection<C: RealmCollectionType>: _AnyRealmCollectionBase<C.Element> { let base: C init(base: C) { self.base = base } // MARK: Properties /// The Realm the objects in this collection belong to, or `nil` if the /// collection's owning object does not belong to a realm (the collection is /// standalone). override var realm: Realm? { return base.realm } /// Returns the number of objects in this collection. override var count: Int { return base.count } /// Returns a human-readable description of the objects contained in this collection. override var description: String { return base.description } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the collection. - parameter object: The object whose index is being queried. - returns: The index of the given object, or `nil` if the object is not in the collection. */ override func indexOf(object: C.Element) -> Int? { return base.indexOf(object) } /** Returns the index of the first object matching the given predicate, or `nil` no objects match. - parameter predicate: The `NSPredicate` used to filter the objects. - returns: The index of the first matching object, or `nil` if no objects match. */ override func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: The predicate format string, optionally followed by a variable number of arguments. - returns: The index of the first matching object, or `nil` if no objects match. */ override func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return base.indexOf(NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Filtering /** Returns `Results` containing collection elements that match the given predicate. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: `Results` containing collection elements that match the given predicate. */ override func filter(predicateFormat: String, _ args: AnyObject...) -> Results<C.Element> { return base.filter(NSPredicate(format: predicateFormat, argumentArray: args)) } /** Returns `Results` containing collection elements that match the given predicate. - parameter predicate: The predicate to filter the objects. - returns: `Results` containing collection elements that match the given predicate. */ override func filter(predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) } // MARK: Sorting /** Returns `Results` containing collection elements sorted by the given property. - parameter property: The property name to sort by. - parameter ascending: The direction to sort by. - returns: `Results` containing collection elements sorted by the given property. */ override func sorted(property: String, ascending: Bool) -> Results<C.Element> { return base.sorted(property, ascending: ascending) } /** Returns `Results` with elements sorted by the given sort descriptors. - parameter sortDescriptors: `SortDescriptor`s to sort by. - returns: `Results` with elements sorted by the given sort descriptors. */ override func sorted<S: SequenceType where S.Generator.Element == SortDescriptor> (sortDescriptors: S) -> Results<C.Element> { return base.sorted(sortDescriptors) } // MARK: Aggregate Operations /** Returns the minimum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on. - returns: The minimum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ override func min<U: MinMaxType>(property: String) -> U? { return base.min(property) } /** Returns the maximum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on. - returns: The maximum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ override func max<U: MinMaxType>(property: String) -> U? { return base.max(property) } /** Returns the sum of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate sum on. - returns: The sum of the given property over all objects in the collection. */ override func sum<U: AddableType>(property: String) -> U { return base.sum(property) } /** Returns the average of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate average on. - returns: The average of the given property over all objects in the collection, or `nil` if the collection is empty. */ override func average<U: AddableType>(property: String) -> U? { return base.average(property) } // MARK: Sequence Support /** Returns the object at the given `index`. - parameter index: The index. - returns: The object at the given `index`. */ override subscript(index: Int) -> C.Element { // FIXME: it should be possible to avoid this force-casting return unsafeBitCast(base[index as! C.Index], C.Element.self) } /// Returns a `GeneratorOf<Element>` that yields successive elements in the collection. override func generate() -> RLMGenerator<Element> { // FIXME: it should be possible to avoid this force-casting return base.generate() as! RLMGenerator<Element> } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. override var startIndex: Int { // FIXME: it should be possible to avoid this force-casting return base.startIndex as! Int } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). override var endIndex: Int { // FIXME: it should be possible to avoid this force-casting return base.endIndex as! Int } // MARK: Key-Value Coding /** Returns an Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. - parameter key: The name of the property. - returns: Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. */ override func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified value and key. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property. */ override func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) } } /** A type-erased `RealmCollectionType`. Forwards operations to an arbitrary underlying collection having the same Element type, hiding the specifics of the underlying `RealmCollectionType`. */ public final class AnyRealmCollection<T: Object>: RealmCollectionType { /// Element type contained in this collection. public typealias Element = T private let base: _AnyRealmCollectionBase<T> /// Creates an AnyRealmCollection wrapping `base`. public init<C: RealmCollectionType where C.Element == T>(_ base: C) { self.base = _AnyRealmCollection(base: base) } // MARK: Properties /// The Realm the objects in this collection belong to, or `nil` if the /// collection's owning object does not belong to a realm (the collection is /// standalone). public var realm: Realm? { return base.realm } /// Returns the number of objects in this collection. public var count: Int { return base.count } /// Returns a human-readable description of the objects contained in this collection. public var description: String { return base.description } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the collection. - parameter object: The object whose index is being queried. - returns: The index of the given object, or `nil` if the object is not in the collection. */ public func indexOf(object: Element) -> Int? { return base.indexOf(object) } /** Returns the index of the first object matching the given predicate, or `nil` no objects match. - parameter predicate: The `NSPredicate` used to filter the objects. - returns: The index of the first matching object, or `nil` if no objects match. */ public func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: The predicate format string, optionally followed by a variable number of arguments. - returns: The index of the first matching object, or `nil` if no objects match. */ public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return base.indexOf(NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Filtering /** Returns `Results` containing collection elements that match the given predicate. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: `Results` containing collection elements that match the given predicate. */ public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> { return base.filter(NSPredicate(format: predicateFormat, argumentArray: args)) } /** Returns `Results` containing collection elements that match the given predicate. - parameter predicate: The predicate to filter the objects. - returns: `Results` containing collection elements that match the given predicate. */ public func filter(predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) } // MARK: Sorting /** Returns `Results` containing collection elements sorted by the given property. - parameter property: The property name to sort by. - parameter ascending: The direction to sort by. - returns: `Results` containing collection elements sorted by the given property. */ public func sorted(property: String, ascending: Bool) -> Results<Element> { return base.sorted(property, ascending: ascending) } /** Returns `Results` with elements sorted by the given sort descriptors. - parameter sortDescriptors: `SortDescriptor`s to sort by. - returns: `Results` with elements sorted by the given sort descriptors. */ public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor> (sortDescriptors: S) -> Results<Element> { return base.sorted(sortDescriptors) } // MARK: Aggregate Operations /** Returns the minimum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on. - returns: The minimum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ public func min<U: MinMaxType>(property: String) -> U? { return base.min(property) } /** Returns the maximum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on. - returns: The maximum value for the property amongst objects in the collection, or `nil` if the collection is empty. */ public func max<U: MinMaxType>(property: String) -> U? { return base.max(property) } /** Returns the sum of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate sum on. - returns: The sum of the given property over all objects in the collection. */ public func sum<U: AddableType>(property: String) -> U { return base.sum(property) } /** Returns the average of the given property for objects in the collection. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate average on. - returns: The average of the given property over all objects in the collection, or `nil` if the collection is empty. */ public func average<U: AddableType>(property: String) -> U? { return base.average(property) } // MARK: Sequence Support /** Returns the object at the given `index`. - parameter index: The index. - returns: The object at the given `index`. */ public subscript(index: Int) -> T { return base[index] } /// Returns a `GeneratorOf<T>` that yields successive elements in the collection. public func generate() -> RLMGenerator<T> { return base.generate() } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return base.startIndex } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return base.endIndex } // MARK: Key-Value Coding /** Returns an Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. - parameter key: The name of the property. - returns: Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. */ public func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified value and key. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property. */ public func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) } }
mit
fb9254b3de2c3cf12989835e9efb0fb3
35.441308
120
0.686361
4.728167
false
false
false
false
CodeEagle/SSImageBrowser
Source/SSZoomingScrollView.swift
1
10079
// // SSZoomingScrollView.swift // Pods // // Created by LawLincoln on 15/7/11. // // import UIKit open class SSZoomingScrollView: UIScrollView { open var photo: SSPhoto? open var captionView: SSCaptionView? open var photoImageView: SSTapDetectingImageView? open var tapView: SSTapDetectingView? fileprivate var progressView: ProgressView? fileprivate weak var photoBrowser: SSImageBrowser? convenience init(aPhotoBrowser: SSImageBrowser) { self.init(frame: CGRect.zero) photoBrowser = aPhotoBrowser // Tap view for background let _tapView = SSTapDetectingView(frame: self.bounds) _tapView.tapDelegate = self _tapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] _tapView.backgroundColor = UIColor.clear addSubview(_tapView) tapView = _tapView // Image view let _photoImageView = SSTapDetectingImageView(frame: CGRect.zero) _photoImageView.tapDelegate = self _photoImageView.backgroundColor = UIColor.clear addSubview(_photoImageView) photoImageView = _photoImageView let screenBound = UIScreen.main.bounds var screenWidth = screenBound.size.width var screenHeight = screenBound.size.height let orientation = UIDevice.current.orientation if orientation == UIDeviceOrientation.landscapeLeft || orientation == UIDeviceOrientation.landscapeRight { screenWidth = screenBound.size.height screenHeight = screenBound.size.width } // Progress view let color = aPhotoBrowser.progressTintColor != nil ? aPhotoBrowser.progressTintColor : UIColor(white: 1.0, alpha: 1) progressView = ProgressView(color: color!, frame: CGRect(x: (screenWidth - 35) / 2, y: (screenHeight - 35) / 2, width: 35.0, height: 35.0)) progressView?.progress = 0 progressView?.tag = 101 if let v = progressView { addSubview(v) } // Setup backgroundColor = UIColor.clear delegate = self showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false decelerationRate = UIScrollViewDecelerationRateFast autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } open func prepareForReuse() { photo = nil captionView?.removeFromSuperview() captionView = nil tag = 0 } open func setAPhoto(_ aPhoto: SSPhoto) { photoImageView?.image = nil // Release image if aPhoto != photo { photo = aPhoto } displayImage() } open func setProgress(_ progress: CGFloat, forPhoto aPhoto: SSPhoto!) { guard let progressView = progressView else { return } if let url = photo?.photoURL?.absoluteString { if aPhoto.photoURL?.absoluteString == url { if progressView.progress < progress { progressView.progress = progress } } } else if aPhoto.asset?.identifier == photo?.asset?.identifier { if progressView.progress < progress { progressView.progress = progress } } } open func displayImage() { if let p = photo { // Reset self.maximumZoomScale = 1 self.minimumZoomScale = 1 self.zoomScale = 1 self.contentSize = CGSize(width: 0, height: 0) // Get image from browser as it handles ordering of fetching if let img = photoBrowser?.imageForPhoto(p) { // Hide ProgressView // progressView.alpha = 0.0f progressView?.removeFromSuperview() // Set image photoImageView?.image = img photoImageView?.isHidden = false // Setup photo frame var photoImageViewFrame = CGRect.zero photoImageViewFrame.origin = CGPoint.zero photoImageViewFrame.size = img.size photoImageView?.frame = photoImageViewFrame self.contentSize = photoImageViewFrame.size // Set zoom to minimum zoom setMaxMinZoomScalesForCurrentBounds() } else { // Hide image view photoImageView?.isHidden = true progressView?.alpha = 1.0 } self.setNeedsLayout() } } open func displayImageFailure() { progressView?.removeFromSuperview() } open func setMaxMinZoomScalesForCurrentBounds() { // Reset self.maximumZoomScale = 1 self.minimumZoomScale = 1 self.zoomScale = 1 // fail if photoImageView?.image == nil { return } // Sizes let boundsSize = bounds.size let imageSize = photoImageView?.frame.size ?? .zero // Calculate Min let xScale = boundsSize.width / imageSize.width // the scale needed to perfectly fit the image width-wise let yScale = boundsSize.height / imageSize.height // the scale needed to perfectly fit the image height-wise let minScale = min(xScale, yScale) // use minimum of these to allow the image to become fully visible // If image is smaller than the screen then ensure we show it at // min scale of 1 if xScale > 1 && yScale > 1 { // minScale = 1.0 } // Calculate Max var maxScale: CGFloat = 4.0 // Allow double scale // on high resolution screens we have double the pixel density, so we will be seeing every pixel if we limit the // maximum zoom scale to 0.5. maxScale = maxScale / UIScreen.main.scale if (maxScale < minScale) { maxScale = minScale * 2 } // Set self.maximumZoomScale = maxScale self.minimumZoomScale = minScale self.zoomScale = minScale // Reset position photoImageView?.frame = CGRect(x: 0, y: 0, width: photoImageView?.frame.size.width ?? 0, height: photoImageView?.frame.size.height ?? 0) self.setNeedsLayout() } open override func layoutSubviews() { // Update tap view frame tapView?.frame = bounds // Super super.layoutSubviews() // Center the image as it becomes smaller than the size of the screen let boundsSize = self.bounds.size var frameToCenter = photoImageView?.frame ?? .zero // Horizontally if frameToCenter.size.width < boundsSize.width { frameToCenter.origin.x = floor((boundsSize.width - frameToCenter.size.width) / 2.0) } else { frameToCenter.origin.x = 0 } // Vertically if frameToCenter.size.height < boundsSize.height { frameToCenter.origin.y = floor((boundsSize.height - frameToCenter.size.height) / 2.0) } else { frameToCenter.origin.y = 0 } // Center if photoImageView?.frame.equalTo(frameToCenter) == false { photoImageView?.frame = frameToCenter } } } // MARK: - UIScrollViewDelegate extension SSZoomingScrollView: UIScrollViewDelegate { public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return photoImageView } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { photoBrowser?.cancelControlHiding() } public func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) { photoBrowser?.cancelControlHiding() } public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { photoBrowser?.hideControlsAfterDelay() } public func scrollViewDidZoom(_ scrollView: UIScrollView) { setNeedsLayout() layoutIfNeeded() } } extension SSZoomingScrollView: SSTapDetectingViewDelegate, SSTapDetectingImageViewDelegate { fileprivate func handleSingleTap(_ touchPoint: CGPoint) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { () -> Void in self.photoBrowser?.toggleControls() } } fileprivate func handleDoubleTap(_ touchPoint: CGPoint) { // Cancel any single tap handling if let p = photoBrowser { NSObject.cancelPreviousPerformRequests(withTarget: p) } // Zoom if zoomScale == maximumZoomScale { setZoomScale(minimumZoomScale, animated: true) } else { zoom(to: CGRect(x: touchPoint.x, y: touchPoint.y, width: 1, height: 1), animated: true) } // Delay controls photoBrowser?.hideControlsAfterDelay() } public func imageView(_ imageView: UIImageView, singleTapDetected touch: UITouch) { handleSingleTap(touch.location(in: imageView)) } public func imageView(_ imageView: UIImageView, doubleTapDetected touch: UITouch) { handleDoubleTap(touch.location(in: imageView)) } public func imageView(_ imageView: UIImageView, tripleTapDetected touch: UITouch) { } public func view(_ view: UIView, singleTapDetected touch: UITouch) { handleSingleTap(touch.location(in: view)) } public func view(_ view: UIView, doubleTapDetected touch: UITouch) { handleDoubleTap(touch.location(in: view)) } public func view(_ view: UIView, tripleTapDetected touch: UITouch) { } } private class ProgressView: UIView { var progress: CGFloat = 0 { didSet { var p = progress if p > 1 { p = 1 } if p < 0 { p = 0 } progressLayer.strokeEnd = p } } fileprivate let progressLayer = CAShapeLayer() convenience init(color: UIColor, frame: CGRect) { self.init(frame: frame) createProgressLayer(color) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) createProgressLayer() } override init(frame: CGRect) { super.init(frame: frame) } fileprivate func createProgressLayer(_ color: UIColor = UIColor.white) { let startAngle = CGFloat(M_PI_2) let endAngle = CGFloat(M_PI * 2 + M_PI_2) let centerPoint = CGPoint(x: frame.width / 2, y: frame.height / 2) let gradientMaskLayer = gradientMask(color) progressLayer.path = UIBezierPath(arcCenter: centerPoint, radius: frame.width / 2 - 30.0, startAngle: startAngle, endAngle: endAngle, clockwise: true).cgPath progressLayer.backgroundColor = UIColor.clear.cgColor progressLayer.fillColor = nil progressLayer.strokeColor = UIColor.black.cgColor progressLayer.lineWidth = 4.0 progressLayer.strokeStart = 0.0 progressLayer.strokeEnd = 0.0 gradientMaskLayer.mask = progressLayer layer.addSublayer(gradientMaskLayer) } fileprivate func gradientMask(_ color: UIColor) -> CAGradientLayer { let gradientLayer = CAGradientLayer() gradientLayer.frame = bounds gradientLayer.locations = [0.0, 1.0] let colorTop: AnyObject = color.cgColor let colorBottom: AnyObject = color.cgColor let arrayOfColors: [AnyObject] = [colorTop, colorBottom] gradientLayer.colors = arrayOfColors return gradientLayer } func hideProgressView() { progressLayer.opacity = 0 progressLayer.strokeEnd = 0.0 } }
mit
ca4e23d1a856526364637b2f51009dfe
27.311798
159
0.725469
4.020343
false
false
false
false
BenziAhamed/Tracery
Playgrounds/Tracery.playground/Sources/Helpers.swift
1
1478
import Foundation import Tracery // scan is similar to reduce, but accumulates the intermediate results public extension Sequence { @discardableResult func scan<T>(_ initial: T, _ combine: (T, Iterator.Element) throws -> T) rethrows -> [T] { var accu = initial return try map { e in accu = try combine(accu, e) return accu } } } // This class implements two protocols // RuleCandidateSelector - which as we have seen before is used to // to select content in a custom way // RuleCandidatesProvider - the protocol which needs to be // adhered to to provide customised content public class WeightedCandidateSet : RuleCandidatesProvider, RuleCandidateSelector { public let candidates: [String] let weights: [Int] public init(_ distribution:[String:Int]) { distribution.values.map { $0 }.forEach { assert($0 > 0, "weights must be positive") } candidates = distribution.map { $0.key } weights = distribution.map { $0.value } } public func pick(count: Int) -> Int { let sum = UInt32(weights.reduce(0, +)) var choice = Int(arc4random_uniform(sum)) var index = 0 for weight in weights { choice = choice - weight if choice < 0 { return index } index += 1 } fatalError() } }
mit
aec792e0d2ff8ca88b4909ba72145215
28.56
94
0.577808
4.547692
false
false
false
false
CRAnimation/CRAnimation
Example/CRAnimation/Demo/WidgetDemo/S0004_WCLLoadingView/WCLLoadingViewDemoVC.swift
1
5175
// // WCLLoadingViewDemoVC.swift // CRAnimation // // ************************************************** // * _____ * // * __ _ __ ___ \ / * // * \ \/ \/ / / __\ / / * // * \ _ / | (__ / / * // * \/ \/ \___/ / /__ * // * /_____/ * // * * // ************************************************** // Github :https://github.com/631106979 // HomePage:https://imwcl.com // CSDN :http://blog.csdn.net/wang631106979 // // Created by 王崇磊 on 16/9/14. // Copyright © 2016年 王崇磊. All rights reserved. // // @class WCLLoadingViewDemoVC // @abstract WCLLoadingView的DemoVC // @discussion WCLLoadingView的DemoVC // import UIKit public let SWIFT_WIDTH = UIScreen.main.bounds.size.width public let SWIFT_HEIGHT = UIScreen.main.bounds.size.height public let color_0a090e = UIColor.init(rgba: "#0a090e") class WCLLoadingViewDemoVC: CRProductionBaseVC { @IBOutlet weak var loadingView: WCLLoadingView! let controlViewHeight = 40 let offY: CGFloat = 30 let gapX: CGFloat = 10 //MARK: Public Methods //MARK: Override override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. loadingView.startAnimation() view.backgroundColor = color_0a090e addTopBar(withTitle: "WCLLoadingView") createSizeControlView() createDurationControlView() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: Target Methods @IBAction func tapLoadingView(_ sender: UITapGestureRecognizer) { switch loadingView.status { case .animating: loadingView.pauseAnimation() case .pause: loadingView.resumeAnimation() case .normal: loadingView.startAnimation() } } @IBAction func sizeSliderValueChange(_ sender: UISlider) { loadingView.transform = CGAffineTransform.identity.scaledBy(x: CGFloat(sender.value) , y: CGFloat(sender.value)) } @IBAction func durationSliderValueChange(_ sender: UISlider) { loadingView.duration = Double(sender.value) } func createControlView() -> Void { createSizeControlView() createDurationControlView() } func createSizeControlView() { let sizeControlView = UIView.init(frame: CGRect.init(x: Int(CR_OFF_STARTX), y: 0, width: Int(SWIFT_WIDTH) - Int(CR_OFF_STARTX + CR_OFF_ENDX), height: controlViewHeight)) view.addSubview(sizeControlView) let sizeLabel = UILabel.init() sizeLabel.text = "Size" sizeLabel.textColor = UIColor.white sizeLabel.sizeToFit() sizeControlView.addSubview(sizeLabel) sizeLabel.bearSetRelativeLayout(with: .DIR_LEFT, destinationView: nil, parentRelation: true, distance: 0, center: true) let sizeControlSlider = CRSlider.init(frame: CGRect.init(x: sizeLabel.maxX() + gapX, y: 0, width: sizeControlView.width() - sizeLabel.maxX() - gapX, height: sizeControlView.height())) sizeControlSlider.sliderType = kCRSliderType_Normal sizeControlSlider.minimumValue = 1 sizeControlSlider.maximumValue = 2 sizeControlSlider.value = 1 sizeControlSlider.addTarget(self, action: #selector(WCLLoadingViewDemoVC.sizeSliderValueChange(_:)), for: UIControlEvents.valueChanged) sizeControlView.addSubview(sizeControlSlider) sizeControlView.setMaxY(SWIFT_HEIGHT - CGFloat(controlViewHeight) - offY) } func createDurationControlView() { let durationControlView = UIView.init(frame: CGRect.init(x: Int(CR_OFF_STARTX), y: 0, width: Int(SWIFT_WIDTH) - Int(CR_OFF_STARTX + CR_OFF_ENDX), height: controlViewHeight)) view.addSubview(durationControlView) let durationLabel = UILabel.init() durationLabel.text = "Duration" durationLabel.textColor = UIColor.white durationLabel.sizeToFit() durationControlView.addSubview(durationLabel) durationLabel.bearSetRelativeLayout(with: .DIR_LEFT, destinationView: nil, parentRelation: true, distance: 0, center: true) let durationControlSlider = CRSlider.init(frame: CGRect.init(x: durationLabel.maxX() + gapX, y: 0, width: durationControlView.width() - durationLabel.maxX() - gapX, height: durationControlView.height())) durationControlSlider.sliderType = kCRSliderType_Normal durationControlSlider.minimumValue = 1 durationControlSlider.maximumValue = 2 durationControlSlider.value = 1 durationControlSlider.addTarget(self, action: #selector(WCLLoadingViewDemoVC.durationSliderValueChange(_:)), for: UIControlEvents.valueChanged) durationControlView.addSubview(durationControlSlider) durationControlView.setMaxY(SWIFT_HEIGHT - offY) } }
mit
b6c01f36eaf828716dda7b7c086fabb7
39.920635
211
0.623157
4.406838
false
false
false
false
Dhvl-Golakiya/DGSwiftExtension
Pod/Classes/ArrayExtension.swift
1
1543
// // Created by Dhvl Golakiya on 02/04/16. // Copyright (c) 2016 Dhvl Golakiya. All rights reserved. // import Foundation extension Array { // Make Comma separated String from array public var toCommaString: String! { let stringArray = self as? NSArray if let stringArray = stringArray { return stringArray.componentsJoined(by: ",") } return "" } // Remove Specific object from Array public mutating func removeObject<U: Equatable>(_ object: U) { var index: Int? for (idx, objectToCompare) in self.enumerated() { if let to = objectToCompare as? U { if object == to { index = idx } } } if(index != nil) { self.remove(at: index!) } } // Chack Array contain specific object public func containsObject<T:AnyObject>(_ item:T) -> Bool { for element in self { if item === element as? T { return true } } return false } // Get Index of specific object public func indexOfObject<T : Equatable>(_ x:T) -> Int? { for i in 0...self.count { if self[i] as! T == x { return i } } return nil } // Gets the object at the specified index, if it exists. public func get(_ index: Int) -> Element? { return index >= 0 && index < count ? self[index] : nil } }
mit
2f7165bf22d1a18b1542cb50d064ee5c
23.887097
66
0.510693
4.371105
false
false
false
false
wbaumann/SmartReceiptsiOS
SmartReceipts/Extensions/AppDelegate+Extensions.swift
2
4458
// // AppDelegate+Extensions.swift // SmartReceipts // // Created by Bogdan Evsenev on 24/12/2018. // Copyright © 2018 Will Baumann. All rights reserved. // import Foundation import RxSwift import RxOptional //MARK: - Import extension AppDelegate { func handlePDForImage(url: URL) { var path = url.path path = path.hasSuffix("/") ? String(path[..<path.index(before: path.endIndex)]) : path filePathToAttach = path if isFileImage { // String(format: LocalizedString("dialog_attachment_text"), LocalizedString("image")) let alert = UIAlertController(title: LocalizedString("receipt_attach_file"), message: String(format: LocalizedString("dialog_attachment_text"), LocalizedString("image")), preferredStyle: .alert) alert.addAction(UIAlertAction(title: LocalizedString("generic_button_title_ok"), style: .cancel, handler: nil)) AdNavigationEntryPoint.navigationController?.visibleViewController?.present(alert, animated: true) } else { let alert = UIAlertController(title: LocalizedString("receipt_attach_file"), message: String(format: LocalizedString("dialog_attachment_text"), LocalizedString("pdf")), preferredStyle: .alert) alert.addAction(UIAlertAction(title: LocalizedString("generic_button_title_ok"), style: .cancel, handler: nil)) AdNavigationEntryPoint.navigationController?.visibleViewController?.present(alert, animated: true) } } func handleSMR(url: URL) { let alert = UIAlertController(title: LocalizedString("manual_backup_import"), message: LocalizedString("dialog_import_text"), preferredStyle: .alert) alert.addAction(UIAlertAction(title: LocalizedString("DIALOG_CANCEL"), style: .cancel, handler: { _ in FileManager.deleteIfExists(filepath: url.path) })) alert.addAction(UIAlertAction(title: LocalizedString("yes"), style: .default, handler: { _ in self.importZip(from: url, overwrite: true) })) alert.addAction(UIAlertAction(title: LocalizedString("no"), style: .default, handler: { _ in self.importZip(from: url, overwrite: false) })) AdNavigationEntryPoint.navigationController?.visibleViewController?.present(alert, animated: true) } func importZip(from: URL, overwrite: Bool) { guard let viewController = AdNavigationEntryPoint.navigationController?.visibleViewController else { return } let hud = PendingHUDView.showFullScreen() dataQueue.async { self.dataImport = DataImport(inputFile: from.path, output: FileManager.documentsPath) _ = self.dataImport.execute(overwrite: overwrite) .subscribeOn(MainScheduler.instance) .subscribe(onNext: { SyncService.shared.trySyncData() hud.hide() NotificationCenter.default.post(name: .SmartReceiptsImport, object: nil) let text = LocalizedString("toast_import_complete") _ = UIAlertController.showInfo(text: text, on: viewController).subscribe() Logger.debug("Successfully imported all reciepts") }, onError: { error in hud.hide() let text = LocalizedString("IMPORT_ERROR") _ = UIAlertController.showInfo(text: text, on: viewController).subscribe() Logger.error("Failed to import this backup: \(error.localizedDescription)") }) } } } // MARK: - Services initialize extension AppDelegate { func initializeServices() { let purchaseService = ServiceFactory.shared.purchaseService purchaseService.cacheSubscriptionValidation() purchaseService.logPurchases() purchaseService.completeTransactions() RateApplication.sharedInstance().markAppLaunch() PushNotificationService.shared.initialize() ScansPurchaseTracker.shared.initialize() GoogleDriveService.shared.initialize() SyncService.shared.initialize() MigrationService().migrate() ServiceFactory.shared.organizationService.startSync() } }
agpl-3.0
142a1d5d4c14b7f9203358660fff4c2a
44.479592
159
0.630918
5.274556
false
false
false
false
GlobusLTD/components-ios
Demo/Sources/ViewControllers/Button/ButtonViewController.swift
1
4416
// // Globus // import Globus class ButtonViewController: GLBViewController { // MARK - Outlet property @IBOutlet fileprivate weak var fillButton: GLBButton! @IBOutlet fileprivate weak var strokeButton: GLBButton! @IBOutlet fileprivate weak var tintFillButton: GLBButton! @IBOutlet fileprivate weak var tintStrokeButton: GLBButton! fileprivate lazy var fillNormalStyle: GLBTextStyle = { let style = GLBTextStyle() style.font = UIFont.boldSystemFont(ofSize: 16) style.color = UIColor.darkGray return style }() fileprivate lazy var fillHighlightedStyle: GLBTextStyle = { let style = GLBTextStyle() style.font = UIFont.boldSystemFont(ofSize: 16) style.color = UIColor.black return style }() fileprivate lazy var strokeNormalStyle: GLBTextStyle = { let style = GLBTextStyle() style.font = UIFont.italicSystemFont(ofSize: 16) style.color = UIColor.lightGray return style }() fileprivate lazy var strokeHighlightedStyle: GLBTextStyle = { let style = GLBTextStyle() style.font = UIFont.italicSystemFont(ofSize: 16) style.color = UIColor.darkGray return style }() // MARK - UIViewController override func viewDidLoad() { super.viewDidLoad() self.fillButton.contentEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) self.fillButton.normalTitleStyle = self.fillNormalStyle self.fillButton.normalBackgroundColor = UIColor.lightGray self.fillButton.normalCornerRadius = 4.0 self.fillButton.highlightedTitleStyle = self.fillHighlightedStyle self.fillButton.highlightedBackgroundColor = UIColor.darkGray self.fillButton.highlightedCornerRadius = 8.0 self.strokeButton.contentEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) self.strokeButton.normalTitleStyle = self.strokeNormalStyle self.strokeButton.normalBorderWidth = 1.0 self.strokeButton.normalBorderColor = UIColor.lightGray self.strokeButton.normalCornerRadius = 4.0 self.strokeButton.highlightedTitleStyle = self.strokeHighlightedStyle self.strokeButton.highlightedBorderColor = UIColor.darkGray self.strokeButton.highlightedBorderWidth = 2.0 self.strokeButton.highlightedCornerRadius = 8.0 self.tintFillButton.contentEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) self.tintFillButton.glb_normalImage = UIImage.glb_imageNamed("ButtonIcon", renderingMode: .alwaysTemplate) self.tintFillButton.normalTitleStyle = self.fillNormalStyle self.tintFillButton.normalBackgroundColor = UIColor.lightGray self.tintFillButton.normalCornerRadius = 4.0 self.tintFillButton.normalTintColor = UIColor.darkGray self.tintFillButton.highlightedTitleStyle = self.fillHighlightedStyle self.tintFillButton.highlightedBackgroundColor = UIColor.darkGray self.tintFillButton.highlightedCornerRadius = 8.0 self.tintFillButton.highlightedTintColor = UIColor.black self.tintStrokeButton.contentEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4) self.tintStrokeButton.glb_normalImage = UIImage.glb_imageNamed("ButtonIcon", renderingMode: .alwaysTemplate) self.tintStrokeButton.normalTitleStyle = self.strokeNormalStyle self.tintStrokeButton.normalBorderWidth = 1.0 self.tintStrokeButton.normalBorderColor = UIColor.lightGray self.tintStrokeButton.normalCornerRadius = 4.0 self.tintStrokeButton.normalTintColor = UIColor.lightGray self.tintStrokeButton.highlightedTitleStyle = self.strokeHighlightedStyle; self.tintStrokeButton.highlightedBorderColor = UIColor.darkGray self.tintStrokeButton.highlightedBorderWidth = 2.0 self.tintStrokeButton.highlightedCornerRadius = 8.0 self.tintStrokeButton.highlightedTintColor = UIColor.darkGray } // MARK - Action @IBAction internal func pressedMenu(_ sender: Any) { self.glb_slideViewController?.showLeftViewController(animated: true, complete: nil) } // MARK: - GLBNibExtension public override static func nibName() -> String { return "ButtonViewController-Swift" } }
mit
d9c57906eade8ed69ce306924503644c
42.722772
116
0.709013
4.728051
false
false
false
false
See-Ku/SK4Toolkit
SK4Toolkit/core/SK4StopWatch.swift
1
1952
// // SK4StopWatch.swift // SK4Toolkit // // Created by See.Ku on 2016/03/24. // Copyright (c) 2016 AxeRoad. All rights reserved. // import Foundation private let g_timebase: mach_timebase_info_data_t = { var base = mach_timebase_info_data_t() mach_timebase_info(&base) return base }() /// ナノ秒単位で時間を計測するためのクラス public class SK4StopWatch { var start: UInt64 = 0 var prev: UInt64 = 0 /// 初期化 public init() { reset() } /// 開始時刻をリセット public func reset() { start = mach_absolute_time() prev = start } /// 経過時間を秒単位で取得 public func totalSecond() -> NSTimeInterval { let now = mach_absolute_time() let dif = absTimeDiff(now: now, old: start) return nanoToSec(dif) } /// インターバルを秒単位で取得 public func intervalSecond() -> NSTimeInterval { let now = mach_absolute_time() let dif = absTimeDiff(now: now, old: prev) prev = now return nanoToSec(dif) } /// インターバルの平均を秒単位で取得 public func averageSecond(count: Int) -> NSTimeInterval { let dif = absTimeDiff(now: prev, old: start) let ave = dif / UInt64(count) return nanoToSec(ave) } // ///////////////////////////////////////////////////////////// /// 絶対時間の時間差をナノ秒で求める func absTimeDiff(now now: UInt64, old: UInt64) -> UInt64 { return (now - old) * UInt64(g_timebase.numer) / UInt64(g_timebase.denom) } /// ナノ秒を秒に変換 func nanoToSec(nano: UInt64) -> NSTimeInterval { return NSTimeInterval(nano) / NSTimeInterval(NSEC_PER_SEC) } // ///////////////////////////////////////////////////////////// /// 経過時間を表示 ※デバッグ用 public func printTotal() { print("-- Total: \(totalSecond()) sec") } /// インターバルを表示 ※デバッグ用 public func printInterval() { print("-- Interval: \(intervalSecond()) sec") } } // eof
mit
445e221eb000c4e19bcade8c3ddc5d14
20.012346
74
0.617509
2.758509
false
false
false
false
mattgallagher/CwlCatchException
Tests/CwlCatchExceptionTests/CwlCatchExceptionTests.swift
1
3101
// // CwlCatchExceptionTests.swift // CwlPreconditionTesting // // Created by Matt Gallagher on 11/2/16. // Copyright © 2016 Matt Gallagher ( https://www.cocoawithlove.com ). All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY // SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR // IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // import XCTest import CwlCatchException #if SWIFT_PACKAGE || COCOAPODS import CwlCatchExceptionSupport #endif class TestException: NSException { static var name: String = "com.cocoawithlove.TestException" init(userInfo: [AnyHashable: Any]? = nil) { super.init(name: NSExceptionName(rawValue: TestException.name), reason: nil, userInfo: userInfo) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } } class CatchExceptionTests: XCTestCase { func test_when_exception_raised_then_catchexception_returns_exception() { let exception = TestException.catchException { TestException(userInfo: [NSLocalizedFailureReasonErrorKey: "Reason"]).raise() } XCTAssertEqual(exception?.name, NSExceptionName(rawValue: TestException.name)) } func test_when_exception_raised_of_other_type_then_catchexception_returns_nil() { var inner: TestException? let outer = NSException.catchException { inner = TestException.catchException { NSException(name: NSExceptionName.rangeException, reason: nil, userInfo: nil).raise() } } XCTAssertNil(inner) XCTAssertNotNil(outer) } func test_when_no_exception_raised_then_catchexception_returns_nil() { let exception = TestException.catchException { } XCTAssertNil(exception) } func test_when_exception_raised_then_catchexceptionaserror_throws_exceptionerror() throws { let exception = TestException(userInfo: [NSLocalizedFailureReasonErrorKey: "Reason"]) do { try catchExceptionAsError { exception.raise() } } catch let error as ExceptionError { XCTAssertEqual(error.exception, exception) XCTAssertEqual(error.errorUserInfo[NSLocalizedFailureReasonErrorKey] as? String, "Reason") } } func test_when_error_thrown_then_catchexceptionaserror_rethrows() throws { let urlError = URLError(.badURL) do { try catchExceptionAsError { throw urlError } } catch let error as URLError { XCTAssertEqual(error, urlError) } } func test_when_neither_error_nor_exception_thrown_then_catchexceptionaserror_returns_result() throws { let value = try catchExceptionAsError { return 42 } XCTAssertEqual(value, 42) } }
isc
36da65bb315aac69fb65e590faf4fef1
33.065934
103
0.756774
3.831891
false
true
false
false
tjw/swift
stdlib/public/core/CollectionAlgorithms.swift
1
19571
//===--- CollectionAlgorithms.swift.gyb -----------------------*- 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // last //===----------------------------------------------------------------------===// extension BidirectionalCollection { /// The last element of the collection. /// /// If the collection is empty, the value of this property is `nil`. /// /// let numbers = [10, 20, 30, 40, 50] /// if let lastNumber = numbers.last { /// print(lastNumber) /// } /// // Prints "50" @inlinable public var last: Element? { return isEmpty ? nil : self[index(before: endIndex)] } } //===----------------------------------------------------------------------===// // index(of:)/index(where:) //===----------------------------------------------------------------------===// extension Collection where Element : Equatable { /// Returns the first index where the specified value appears in the /// collection. /// /// After using `index(of:)` to find the position of a particular element in /// a collection, you can use it to access the element by subscripting. This /// example shows how you can modify one of the names in an array of /// students. /// /// var students = ["Ben", "Ivy", "Jordell", "Maxime"] /// if let i = students.index(of: "Maxime") { /// students[i] = "Max" /// } /// print(students) /// // Prints "["Ben", "Ivy", "Jordell", "Max"]" /// /// - Parameter element: An element to search for in the collection. /// - Returns: The first index where `element` is found. If `element` is not /// found in the collection, returns `nil`. @inlinable public func index(of element: Element) -> Index? { if let result = _customIndexOfEquatableElement(element) { return result } var i = self.startIndex while i != self.endIndex { if self[i] == element { return i } self.formIndex(after: &i) } return nil } } extension Collection { /// Returns the first index in which an element of the collection satisfies /// the given predicate. /// /// You can use the predicate to find an element of a type that doesn't /// conform to the `Equatable` protocol or to find an element that matches /// particular criteria. Here's an example that finds a student name that /// begins with the letter "A": /// /// let students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] /// if let i = students.index(where: { $0.hasPrefix("A") }) { /// print("\(students[i]) starts with 'A'!") /// } /// // Prints "Abena starts with 'A'!" /// /// - Parameter predicate: A closure that takes an element as its argument /// and returns a Boolean value that indicates whether the passed element /// represents a match. /// - Returns: The index of the first element for which `predicate` returns /// `true`. If no elements in the collection satisfy the given predicate, /// returns `nil`. @inlinable public func index( where predicate: (Element) throws -> Bool ) rethrows -> Index? { var i = self.startIndex while i != self.endIndex { if try predicate(self[i]) { return i } self.formIndex(after: &i) } return nil } } //===----------------------------------------------------------------------===// // partition(by:) //===----------------------------------------------------------------------===// extension MutableCollection { /// Reorders the elements of the collection such that all the elements /// that match the given predicate are after all the elements that don't /// match. /// /// After partitioning a collection, there is a pivot index `p` where /// no element before `p` satisfies the `belongsInSecondPartition` /// predicate and every element at or after `p` satisfies /// `belongsInSecondPartition`. /// /// In the following example, an array of numbers is partitioned by a /// predicate that matches elements greater than 30. /// /// var numbers = [30, 40, 20, 30, 30, 60, 10] /// let p = numbers.partition(by: { $0 > 30 }) /// // p == 5 /// // numbers == [30, 10, 20, 30, 30, 60, 40] /// /// The `numbers` array is now arranged in two partitions. The first /// partition, `numbers[..<p]`, is made up of the elements that /// are not greater than 30. The second partition, `numbers[p...]`, /// is made up of the elements that *are* greater than 30. /// /// let first = numbers[..<p] /// // first == [30, 10, 20, 30, 30] /// let second = numbers[p...] /// // second == [60, 40] /// /// - Parameter belongsInSecondPartition: A predicate used to partition /// the collection. All elements satisfying this predicate are ordered /// after all elements not satisfying it. /// - Returns: The index of the first element in the reordered collection /// that matches `belongsInSecondPartition`. If no elements in the /// collection match `belongsInSecondPartition`, the returned index is /// equal to the collection's `endIndex`. /// /// - Complexity: O(*n*) @inlinable public mutating func partition( by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Index { var pivot = startIndex while true { if pivot == endIndex { return pivot } if try belongsInSecondPartition(self[pivot]) { break } formIndex(after: &pivot) } var i = index(after: pivot) while i < endIndex { if try !belongsInSecondPartition(self[i]) { swapAt(i, pivot) formIndex(after: &pivot) } formIndex(after: &i) } return pivot } } extension MutableCollection where Self : BidirectionalCollection { /// Reorders the elements of the collection such that all the elements /// that match the given predicate are after all the elements that don't /// match. /// /// After partitioning a collection, there is a pivot index `p` where /// no element before `p` satisfies the `belongsInSecondPartition` /// predicate and every element at or after `p` satisfies /// `belongsInSecondPartition`. /// /// In the following example, an array of numbers is partitioned by a /// predicate that matches elements greater than 30. /// /// var numbers = [30, 40, 20, 30, 30, 60, 10] /// let p = numbers.partition(by: { $0 > 30 }) /// // p == 5 /// // numbers == [30, 10, 20, 30, 30, 60, 40] /// /// The `numbers` array is now arranged in two partitions. The first /// partition, `numbers[..<p]`, is made up of the elements that /// are not greater than 30. The second partition, `numbers[p...]`, /// is made up of the elements that *are* greater than 30. /// /// let first = numbers[..<p] /// // first == [30, 10, 20, 30, 30] /// let second = numbers[p...] /// // second == [60, 40] /// /// - Parameter belongsInSecondPartition: A predicate used to partition /// the collection. All elements satisfying this predicate are ordered /// after all elements not satisfying it. /// - Returns: The index of the first element in the reordered collection /// that matches `belongsInSecondPartition`. If no elements in the /// collection match `belongsInSecondPartition`, the returned index is /// equal to the collection's `endIndex`. /// /// - Complexity: O(*n*) @inlinable public mutating func partition( by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Index { let maybeOffset = try _withUnsafeMutableBufferPointerIfSupported { (bufferPointer) -> Int in let unsafeBufferPivot = try bufferPointer.partition( by: belongsInSecondPartition) return unsafeBufferPivot - bufferPointer.startIndex } if let offset = maybeOffset { return index(startIndex, offsetBy: numericCast(offset)) } var lo = startIndex var hi = endIndex // 'Loop' invariants (at start of Loop, all are true): // * lo < hi // * predicate(self[i]) == false, for i in startIndex ..< lo // * predicate(self[i]) == true, for i in hi ..< endIndex Loop: while true { FindLo: repeat { while lo < hi { if try belongsInSecondPartition(self[lo]) { break FindLo } formIndex(after: &lo) } break Loop } while false FindHi: repeat { formIndex(before: &hi) while lo < hi { if try !belongsInSecondPartition(self[hi]) { break FindHi } formIndex(before: &hi) } break Loop } while false swapAt(lo, hi) formIndex(after: &lo) } return lo } } //===----------------------------------------------------------------------===// // sorted()/sort() //===----------------------------------------------------------------------===// extension Sequence where Element : Comparable { /// Returns the elements of the sequence, sorted. /// /// You can sort any sequence of elements that conform to the `Comparable` /// protocol by calling this method. Elements are sorted in ascending order. /// /// The sorting algorithm is not stable. A nonstable sort may change the /// relative order of elements that compare equal. /// /// Here's an example of sorting a list of students' names. Strings in Swift /// conform to the `Comparable` protocol, so the names are sorted in /// ascending order according to the less-than operator (`<`). /// /// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] /// let sortedStudents = students.sorted() /// print(sortedStudents) /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]" /// /// To sort the elements of your sequence in descending order, pass the /// greater-than operator (`>`) to the `sorted(by:)` method. /// /// let descendingStudents = students.sorted(by: >) /// print(descendingStudents) /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]" /// /// - Returns: A sorted array of the sequence's elements. @inlinable public func sorted() -> [Element] { var result = ContiguousArray(self) result.sort() return Array(result) } } extension Sequence { /// Returns the elements of the sequence, sorted using the given predicate as /// the comparison between elements. /// /// When you want to sort a sequence of elements that don't conform to the /// `Comparable` protocol, pass a predicate to this method that returns /// `true` when the first element passed should be ordered before the /// second. The elements of the resulting array are ordered according to the /// given predicate. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also `true`. /// (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// The sorting algorithm is not stable. A nonstable sort may change the /// relative order of elements for which `areInIncreasingOrder` does not /// establish an order. /// /// In the following example, the predicate provides an ordering for an array /// of a custom `HTTPResponse` type. The predicate orders errors before /// successes and sorts the error responses by their error code. /// /// enum HTTPResponse { /// case ok /// case error(Int) /// } /// /// let responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)] /// let sortedResponses = responses.sorted { /// switch ($0, $1) { /// // Order errors by code /// case let (.error(aCode), .error(bCode)): /// return aCode < bCode /// /// // All successes are equivalent, so none is before any other /// case (.ok, .ok): return false /// /// // Order errors before successes /// case (.error, .ok): return true /// case (.ok, .error): return false /// } /// } /// print(sortedResponses) /// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]" /// /// You also use this method to sort elements that conform to the /// `Comparable` protocol in descending order. To sort your sequence in /// descending order, pass the greater-than operator (`>`) as the /// `areInIncreasingOrder` parameter. /// /// let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] /// let descendingStudents = students.sorted(by: >) /// print(descendingStudents) /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]" /// /// Calling the related `sorted()` method is equivalent to calling this /// method and passing the less-than operator (`<`) as the predicate. /// /// print(students.sorted()) /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]" /// print(students.sorted(by: <)) /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; /// otherwise, `false`. /// - Returns: A sorted array of the sequence's elements. @inlinable public func sorted( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows -> [Element] { var result = ContiguousArray(self) try result.sort(by: areInIncreasingOrder) return Array(result) } } extension MutableCollection where Self : RandomAccessCollection, Element : Comparable { /// Sorts the collection in place. /// /// You can sort any mutable collection of elements that conform to the /// `Comparable` protocol by calling this method. Elements are sorted in /// ascending order. /// /// The sorting algorithm is not stable. A nonstable sort may change the /// relative order of elements that compare equal. /// /// Here's an example of sorting a list of students' names. Strings in Swift /// conform to the `Comparable` protocol, so the names are sorted in /// ascending order according to the less-than operator (`<`). /// /// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] /// students.sort() /// print(students) /// // Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]" /// /// To sort the elements of your collection in descending order, pass the /// greater-than operator (`>`) to the `sort(by:)` method. /// /// students.sort(by: >) /// print(students) /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]" @inlinable public mutating func sort() { let didSortUnsafeBuffer: Void? = _withUnsafeMutableBufferPointerIfSupported { (bufferPointer) -> Void in bufferPointer.sort() return () } if didSortUnsafeBuffer == nil { _introSort(&self, subRange: startIndex..<endIndex) } } } extension MutableCollection where Self : RandomAccessCollection { /// Sorts the collection in place, using the given predicate as the /// comparison between elements. /// /// When you want to sort a collection of elements that doesn't conform to /// the `Comparable` protocol, pass a closure to this method that returns /// `true` when the first element passed should be ordered before the /// second. /// /// The predicate must be a *strict weak ordering* over the elements. That /// is, for any elements `a`, `b`, and `c`, the following conditions must /// hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also `true`. /// (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// The sorting algorithm is not stable. A nonstable sort may change the /// relative order of elements for which `areInIncreasingOrder` does not /// establish an order. /// /// In the following example, the closure provides an ordering for an array /// of a custom enumeration that describes an HTTP response. The predicate /// orders errors before successes and sorts the error responses by their /// error code. /// /// enum HTTPResponse { /// case ok /// case error(Int) /// } /// /// var responses: [HTTPResponse] = [.error(500), .ok, .ok, .error(404), .error(403)] /// responses.sort { /// switch ($0, $1) { /// // Order errors by code /// case let (.error(aCode), .error(bCode)): /// return aCode < bCode /// /// // All successes are equivalent, so none is before any other /// case (.ok, .ok): return false /// /// // Order errors before successes /// case (.error, .ok): return true /// case (.ok, .error): return false /// } /// } /// print(responses) /// // Prints "[.error(403), .error(404), .error(500), .ok, .ok]" /// /// Alternatively, use this method to sort a collection of elements that do /// conform to `Comparable` when you want the sort to be descending instead /// of ascending. Pass the greater-than operator (`>`) operator as the /// predicate. /// /// var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"] /// students.sort(by: >) /// print(students) /// // Prints "["Peter", "Kweku", "Kofi", "Akosua", "Abena"]" /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; /// otherwise, `false`. If `areInIncreasingOrder` throws an error during /// the sort, the elements may be in a different order, but none will be /// lost. @inlinable public mutating func sort( by areInIncreasingOrder: (Element, Element) throws -> Bool ) rethrows { let didSortUnsafeBuffer: Void? = try _withUnsafeMutableBufferPointerIfSupported { (bufferPointer) -> Void in try bufferPointer.sort(by: areInIncreasingOrder) return () } if didSortUnsafeBuffer == nil { try _introSort( &self, subRange: startIndex..<endIndex, by: areInIncreasingOrder) } } }
apache-2.0
5cd06979d3c71e097cbef332b6d45fac
36.781853
91
0.597874
4.249946
false
false
false
false
jdbateman/Lendivine
Lendivine/UIApplication+Extension.swift
1
940
// // UIApplication+Extension.swift // Lendivine // // Created by john bateman on 5/7/16. // Copyright © 2016 John Bateman. All rights reserved. // // Acknowledgement: Thanks to Diaz on stack overflow for this extension allowing acquisition of the top controller anywhere in the app. import UIKit extension UIApplication { class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(nav.visibleViewController) } if let tab = base as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(selected) } } if let presented = base?.presentedViewController { return topViewController(presented) } return base } }
mit
f783f7c84c1df67516f0151d796c8f35
32.571429
146
0.674121
5.216667
false
false
false
false
acn001/SwiftJSONModel
SwiftJSONModel/SwiftJSONModel.swift
1
14930
// // SwiftJSONModel.swift // SWiftJSONModel // // @version 0.1.1 // @author Zhu Yue([email protected]) // // The MIT License (MIT) // // Copyright (c) 2016 Zhu Yue // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. import Foundation private var propertyTypeCheckedClasses: [String] = [String]() private var ignoredPropertiesRegisteredClasses: [String : [String]] = [String : [String]]() class SwiftJSONModel: NSObject { required override init() { super.init() if !propertyTypeCheckedClasses.contains(NSStringFromClass(self.dynamicType)) { if checkPropertyType() { propertyTypeCheckedClasses.append(NSStringFromClass(self.dynamicType)) } } } convenience init(dictionary: [String : AnyObject]) { self.init() updateWithDictionary(dictionary) } final private func checkPropertyType() -> Bool { let (properties, _) = SwiftJSONModelObjcReflection.propertiesOfClass(self.dynamicType) if properties != nil { for (propertyName, propertyType) in properties! { if !ignoredProperties().contains(propertyName) && propertyType != "Int8" && propertyType != "Int" && propertyType != "Float" && propertyType != "Double" && propertyType != "String" && propertyType != "NSString" && propertyType != "NSNumber" && propertyType != "NSArray" && !SwiftJSONModelObjcReflection.isClassWithName(propertyType, kindOfClass: SwiftJSONModel.self) && !SwiftJSONModelObjcReflection.isClassWithName(propertyType, kindOfClass: SwiftJSONModelIgnored.self) { fatalError("\(NSStringFromClass(self.dynamicType)) has invalid property type, property name: \(propertyName), property type: \(propertyType). Only Bool, Int, Float, Double, String / NSString, NSNumber, NSArray, SwiftJSONModel or its subclass, SwiftJSONModelIgnored or its subclass can be used.") } if propertyType == "NSArray" { let genericType = getGenericTypeForArrayProperty(propertyName) if genericType != "Bool" && genericType != "Int" && genericType != "Float" && genericType != "Double" && genericType != "String" && genericType != "NSString" && genericType != "NSNumber" && !SwiftJSONModelObjcReflection.isClassWithName(genericType, kindOfClass: SwiftJSONModel.self) { fatalError("\(NSStringFromClass(self.dynamicType)) has invalid generic type with its array property, array name: \(propertyName), generic type: \(genericType). Only Bool, Int, Float, Double, String / NSString, NSNumber, SwiftJSONModel or its subclass can be the valid generic type.") } } } } return true } func ignoredProperties() -> [String] { return [String]() } func genericTypes() -> [String : String] { return [String : String]() } final private func getGenericTypeForArrayProperty(propertyName: String) -> String { if let genericType = genericTypes()[propertyName] { return genericType } fatalError("Array property's generic type must be specified, class: \(NSStringFromClass(self.dynamicType)), property name: \(propertyName).") } final func updateWithDictionary(dictionary: [String : AnyObject]) { let (properties, _) = SwiftJSONModelObjcReflection.propertiesOfClass(self.dynamicType) if properties != nil { for (propertyName, propertyType) in properties! { if !ignoredProperties().contains(propertyName) { switch propertyType { case "Int8": if let propertyValue = dictionary[propertyName] as? Bool { setValue(propertyValue, forKey: propertyName) } case "Int": if let propertyValue = dictionary[propertyName] as? Int { setValue(propertyValue, forKey: propertyName) } case "Float": if let propertyValue = dictionary[propertyName] as? Float { setValue(propertyValue, forKey: propertyName) } case "Double": if let propertyValue = dictionary[propertyName] as? Double { setValue(propertyValue, forKey: propertyName) } case "String": if let propertyValue = dictionary[propertyName] as? String { setValue(propertyValue, forKey: propertyName) } case "NSString": if let propertyValue = dictionary[propertyName] as? String { setValue(propertyValue, forKey: propertyName) } case "NSNumber": if let propertyValue = dictionary[propertyName] as? NSNumber { setValue(propertyValue, forKey: propertyName) } case "NSArray": let genericType = getGenericTypeForArrayProperty(propertyName) switch genericType { case "Bool": if let propertyValue = dictionary[propertyName] as? [Bool] { setValue(propertyValue, forKey: propertyName) } case "Int": if let propertyValue = dictionary[propertyName] as? [Int] { setValue(propertyValue, forKey: propertyName) } case "Float": if let propertyValue = dictionary[propertyName] as? [Float] { setValue(propertyValue, forKey: propertyName) } case "Double": if let propertyValue = dictionary[propertyName] as? [Double] { setValue(propertyValue, forKey: propertyName) } case "String": if let propertyValue = dictionary[propertyName] as? [String] { setValue(propertyValue, forKey: propertyName) } case "NSString": if let propertyValue = dictionary[propertyName] as? [String] { setValue(propertyValue, forKey: propertyName) } case "NSNumber": if let propertyValue = dictionary[propertyName] as? [NSNumber] { setValue(propertyValue, forKey: propertyName) } default: if SwiftJSONModelObjcReflection.isClassWithName(genericType, kindOfClass: SwiftJSONModel.self) { if let arrayToParse = dictionary[propertyName] as? [[String : AnyObject]] { var propertyValue = [AnyObject]() for dictionaryToParse in arrayToParse { if let aClass = (NSClassFromString(genericType) != nil ? NSClassFromString(genericType) : NSClassFromString(SwiftJSONModelObjcReflection.getProjectNamespace() + "." + genericType)) as? SwiftJSONModel.Type { let item = aClass.init() item.updateWithDictionary(dictionaryToParse) propertyValue.append(item) } } setValue(propertyValue, forKey: propertyName) } } } default: if SwiftJSONModelObjcReflection.isClassWithName(propertyType, kindOfClass: SwiftJSONModel.self) { if let aClass = (NSClassFromString(propertyType) != nil ? NSClassFromString(propertyType) : NSClassFromString(SwiftJSONModelObjcReflection.getProjectNamespace() + "." + propertyType)) as? SwiftJSONModel.Type { if let subDictionary = dictionary[propertyName] as? [String : AnyObject] { let propertyValue = aClass.init() propertyValue.updateWithDictionary(subDictionary) setValue(propertyValue, forKey: propertyName) } } } } } } } } final func toDictionary() -> [String : AnyObject] { var dictionary = [String : AnyObject]() let (properties, _) = SwiftJSONModelObjcReflection.propertiesOfClass(self.dynamicType) if properties != nil { for (propertyName, propertyType) in properties! { if !ignoredProperties().contains(propertyName) { switch propertyType { case "Int8": if let propertyValue = valueForKey(propertyName) as? Bool { dictionary[propertyName] = propertyValue } case "Int": if let propertyValue = valueForKey(propertyName) as? Int { dictionary[propertyName] = propertyValue } case "Float": if let propertyValue = valueForKey(propertyName) as? Float { dictionary[propertyName] = propertyValue } case "Double": if let propertyValue = valueForKey(propertyName) as? Double { dictionary[propertyName] = propertyValue } case "String": if let propertyValue = valueForKey(propertyName) as? String { dictionary[propertyName] = propertyValue } case "NSString": if let propertyValue = valueForKey(propertyName) as? String { dictionary[propertyName] = propertyValue } case "NSNumber": if let propertyValue = valueForKey(propertyName) as? NSNumber { dictionary[propertyName] = propertyValue } case "NSArray": let genericType = getGenericTypeForArrayProperty(propertyName) switch genericType { case "Bool": if let propertyValue = valueForKey(propertyName) as? [Bool] { dictionary[propertyName] = propertyValue } case "Int": if let propertyValue = valueForKey(propertyName) as? [Int] { dictionary[propertyName] = propertyValue } case "Float": if let propertyValue = valueForKey(propertyName) as? [Float] { dictionary[propertyName] = propertyValue } case "Double": if let propertyValue = valueForKey(propertyName) as? [Double] { dictionary[propertyName] = propertyValue } case "String": if let propertyValue = valueForKey(propertyName) as? [String] { dictionary[propertyName] = propertyValue } case "NSString": if let propertyValue = valueForKey(propertyName) as? [String] { dictionary[propertyName] = propertyValue } case "NSNumber": if let propertyValue = valueForKey(propertyName) as? [NSNumber] { dictionary[propertyName] = propertyValue } default: if SwiftJSONModelObjcReflection.isClassWithName(genericType, kindOfClass: SwiftJSONModel.self) { if let arrayToParse = valueForKey(propertyName) as? [SwiftJSONModel] { var propertyValue = [[String : AnyObject]]() for item in arrayToParse { propertyValue.append(item.toDictionary()) } dictionary[propertyName] = propertyValue } } } default: if SwiftJSONModelObjcReflection.isClassWithName(propertyType, kindOfClass: SwiftJSONModel.self) { if let propertyValue = valueForKey(propertyName) as? SwiftJSONModel.Type { dictionary[propertyName] = propertyValue } } } } } } return dictionary } }
mit
44becda5fc0d51335916366550783c71
56.868217
488
0.511386
6.463203
false
false
false
false
Weebly/Cereal
Example/EditEmployeeViewController.swift
2
1572
// // EditEmployeeViewController.swift // Cereal // // Created by James Richard on 9/29/15. // Copyright © 2015 Weebly. All rights reserved. // import UIKit protocol EditEmployeeViewControllerDelegate: class { func editEmployeeViewController(_ editEmployeeViewController: EditEmployeeViewController, didSaveEmployee employee: Employee) } class EditEmployeeViewController: UIViewController { var employee: Employee! weak var delegate: EditEmployeeViewControllerDelegate? @IBOutlet var ageLabel: UILabel! @IBOutlet var nameTextField: UITextField! @IBOutlet var stepperView: UIStepper! @IBOutlet var genderControl: UISegmentedControl! override func viewDidLoad() { super.viewDidLoad() nameTextField.text = employee.name ageLabel.text = String(employee.age) stepperView.value = Double(employee.age) genderControl.selectedSegmentIndex = employee.gender.rawValue } @IBAction func savePressed() { delegate?.editEmployeeViewController(self, didSaveEmployee: employee) performSegue(withIdentifier: "UnwindToEmployeeList", sender: self) } @IBAction func nameValueChanged(_ textField: UITextField) { employee.name = textField.text ?? "" } @IBAction func ageStepperChanged(_ stepper: UIStepper) { let age = Int(stepper.value) employee.age = age ageLabel.text = String(age) } @IBAction func genderChanged(_ control: UISegmentedControl) { employee.gender = Gender(rawValue: control.selectedSegmentIndex)! } }
bsd-3-clause
a80b35f3e69bc7663d041cdf2a57ea88
31.061224
129
0.716104
4.775076
false
false
false
false
wenjunos/DYZB
斗鱼/斗鱼/Classes/Main/View/DYPageContentView.swift
1
5935
// // DYPageContentView.swift // 斗鱼 // // Created by pba on 2017/1/13. // Copyright © 2017年 wenjun. All rights reserved. // import UIKit // MARK: - 定义的常量 private let itemID : String = "DYPageContentViewItemID" // MARK: - 协议 protocol DYPageContentViewDelegate : class { func pageContentView(contentView : DYPageContentView,progress : CGFloat, sourceIndex : Int, targetIndex : Int) } class DYPageContentView: UIView { // MARK: - 定义属性 var chlidsVC : [UIViewController] weak var parentVC : UIViewController? //滑动的偏移量 var startOffsetX : CGFloat = 0 weak var delegate : DYPageContentViewDelegate? //禁止执行滚动的代理(点击titleView) var isforbidDelegate : Bool = false // MARK: - 懒加载的属性 lazy var collectionView : UICollectionView = {[weak self] in //1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal //2.创建collectionView let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.bounces = false collectionView.isPagingEnabled = true collectionView.dataSource = self collectionView.delegate = self //注册item collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: itemID) return collectionView }() // MARK: - 构造方法 init(frame: CGRect, chlidsVC : [UIViewController], parentVC : UIViewController?) { self.chlidsVC = chlidsVC self.parentVC = parentVC super.init(frame: frame) //设置UI setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - 设置UI extension DYPageContentView { //设置UI func setupUI() { //1.将子控制器添加到父控制器中 for childVC in self.chlidsVC { parentVC?.addChildViewController(childVC) } //2.添加collectionView,用collectionView存放控制器的view addSubview(collectionView) collectionView.frame = bounds } } // MARK: - 数据源 UICollectionViewDataSource extension DYPageContentView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return chlidsVC.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let item = collectionView.dequeueReusableCell(withReuseIdentifier: itemID, for: indexPath) //防止循环引用导致重复,先将之前的子控制器删除 for view in item.contentView.subviews { view.removeFromSuperview() } //取出子控制器,给item设置内容 let childVC = chlidsVC[indexPath.item] childVC.view.frame = item.contentView.bounds item.contentView.addSubview(childVC.view) return item } } // MARK: - UICollectionViewDelegate extension DYPageContentView : UICollectionViewDelegate { //获得开始拖拽的偏移量 func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isforbidDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { //判断是否是点击事件 if isforbidDelegate == true { return } //获取滑动的比例 var progress : CGFloat = 0 //获取当前索引 var sourceIndex : Int = 0 //获取目标索引 var targetIndex : Int = 0 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.frame.width let ratio = currentOffsetX / scrollViewW //对比偏移量,确定是左滑,还是右滑 if currentOffsetX > startOffsetX { //左滑 //1.获取滑动的比例:偏移量/宽度 progress = ratio - floor(ratio) //2.获取当前索引 sourceIndex = Int(ratio) //3.获取目标索引 targetIndex = sourceIndex + 1 if targetIndex >= chlidsVC.count { targetIndex = chlidsVC.count - 1 } //4.如果完全滑过去 if currentOffsetX - startOffsetX == scrollViewW { progress = 1.0 targetIndex = sourceIndex } }else{ //右滑 //1.获取滑动的比例:偏移量/宽度 progress = 1 - (ratio - floor(ratio)) //2.获取目标索引 targetIndex = Int(ratio) //3.获取当前索引 sourceIndex = targetIndex + 1 if sourceIndex >= chlidsVC.count { sourceIndex = chlidsVC.count - 1 } } //通知代理 delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } // MARK: - Private methold extension DYPageContentView { //设置当前的ContentView func setCurrentContentView(index : Int) { //禁止执行滑动的代理方法 isforbidDelegate = true //设置collectionView的偏移量 let offset = CGFloat(index) * frame.width collectionView.setContentOffset(CGPoint(x: offset, y: 0), animated: false) } }
mit
fa888791c87ba8e725cab4a2a2dbb7ba
27.229167
124
0.603321
5.009242
false
false
false
false
smittytone/FightingFantasy
FightingFantasy/Constants.swift
1
901
// FightingFantasy // Created by Tony Smith on 02/11/2017. // Software © 2017 Tony Smith. All rights reserved. // Software ONLY issued under MIT Licence // Fighting Fantasy © 2016 Steve Jackson and Ian Livingstone import Foundation // MARK: Constants // Game types let kGameNone = -1 let kGameWarlock = 0 let kGameCitadel = 1 let kGameForestDoom = 2 let kGameDeathtrap = 3 let kGameCityThieves = 4 let kGameHouseHell = 5 let kGameCavernsSnow = 6 let kGameIslandLizard = 7 let kGameTempleTerror = 8 let kGameTrialChampions = 9 let kGameCreatureHavoc = 10 let kGameReturnFiretop = 11 let kGameEyeDragon = 12 let kGamePortPeril = 13 let kGameSorceryWizard = 20 let kGameSorceryFighter = 21 // Colours for text let kTextColourBlack = 0 let kTextColourRed = 1 let kTextColourGrey = 2 // Potions let kPotionNone = -1 let kPotionDexterity = 0 let kPotionStrength = 1 let kPotionFortune = 2
mit
05b69aadb106b82932ae069e714d3b38
18.977778
61
0.76307
3.233813
false
false
false
false
austinzmchen/guildOfWarWorldBosses
GoWWorldBosses/Models/APIs/Remote/WBCharacterRemote.swift
1
2823
// // WBCharacterRemote.swift // GoWWorldBosses // // Created by Austin Chen on 2016-11-27. // Copyright © 2016 Austin Chen. All rights reserved. // import Foundation import Alamofire protocol WBCharacterRemoteType { } class WBCharacterRemote: WBRemote, WBCharacterRemoteType { func fetchCharacterNames(completion: @escaping (_ result: WBRemoteResult<[String]?>) -> ()) { // pass empty dict to trigger custom encoding routines let domain: String = self.remoteSession?.domain ?? "" let request = self.alamoFireManager.request(domain + "/characters", headers: self.remoteSession?.headers) request.responseJSON { (response: DataResponse<Any>) in if response.result.isSuccess { var names = response.result.value as? [String] names?.uniqueInPlace() completion(WBRemoteResult.success(names)) } else if response.response?.statusCode == 403 { completion(WBRemoteResult.failure(WBRemoteError.scopePermissionDenied)) } else { completion(WBRemoteResult.failure(response.result.error ?? WBRemoteError.unknown)) } } } func fetchCharacters(byNames names: [String], completion: @escaping (_ result: WBRemoteResult<[WBJsonCharacter]?>) -> ()) { let idsString = names.map{ $0 }.joined(separator: ",") let parameters = "?ids=\(idsString)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)! // pass empty dict to trigger custom encoding routines let domain: String = self.remoteSession?.domain ?? "" let request = self.alamoFireManager.request(domain + "/characters" + parameters, headers: self.remoteSession?.headers) request.responseJSON { (response: DataResponse<Any>) in if response.result.isSuccess, let elements = response.result.value as? [AnyObject] { var resultElements: [WBJsonCharacter] = [] for e in elements { if !(e is NSNull), let ej = e as? [String : Any], let bankElement = WBJsonCharacter(JSON: ej) { resultElements.append(bankElement) } } resultElements.uniqueInPlace() completion(WBRemoteResult.success(.some(resultElements))) } else { if response.response?.statusCode == 403 { completion(WBRemoteResult.failure(WBRemoteError.scopePermissionDenied)) } else { completion(WBRemoteResult.failure(response.result.error ?? WBRemoteError.unknown)) } } } } }
mit
9c41a705f62107468801bdc84ef2fd7e
40.5
127
0.589653
4.924956
false
false
false
false
biboran/dao
Example/Tests/RealmTests.swift
1
2365
import UIKit import XCTest import DAO import RealmSwift class RealmTests: XCTestCase { var dao: AnyDAO<Item>! let inmemoryIdentifier = "Realm.Test" var sampleItem: Item! var sampleItems: [Item]! let firstObjectKey = "sampleName" let secondObjectKey = "sampleName1" let thirdObjectKey = "sampleName2" let nonExistantKey = "HOMELESS IS NOT IN CHARGE" override func setUp() { guard let testableRealm = try? Realm(configuration: .init(inMemoryIdentifier: inmemoryIdentifier)) else { XCTFail() fatalError() } dao = AnyDAO(base: CascadeRealmDAO<RealmItem>(operationalRealm: testableRealm)) sampleItem = Item(name: firstObjectKey) sampleItems = [Item(name: firstObjectKey), Item(name: secondObjectKey), Item(name: thirdObjectKey)] } override func tearDown() { dao = nil sampleItem = nil sampleItems = nil } func testPersistingItem() { try! dao.persist(entity: sampleItem) XCTAssert(dao.getAll().contains(sampleItem)) } func testPersistingMultipleItems() { try! dao.persist(entities: sampleItems) for item in sampleItems { XCTAssert(dao.getAll().contains(item)) } } func testPersistingAnDeletingItem() { try! dao.persist(entity: sampleItem) XCTAssert(dao.getAll().contains(sampleItem)) try! dao.remove(entity: sampleItem) XCTAssert(dao.getAll().isEmpty) } func testPersistingAndDeletingMultipleItems() { try! dao.persist(entities: sampleItems) for item in sampleItems { XCTAssert(dao.getAll().contains(item)) } try! dao.remove(entities: sampleItems) XCTAssert(dao.getAll().isEmpty) } func testGetByKey() { try! dao.persist(entities: sampleItems) for item in sampleItems { XCTAssert(dao.getAll().contains(item)) } //true XCTAssert(dao.get(for: firstObjectKey) == sampleItems[0]) XCTAssert(dao.get(for: secondObjectKey) == sampleItems[1]) XCTAssert(dao.get(for: thirdObjectKey) == sampleItems[2]) //false XCTAssert(dao.get(for: nonExistantKey) == nil) } func testPurge() { try! dao.persist(entities: sampleItems) for item in sampleItems { XCTAssert(dao.getAll().contains(item)) } try! dao.purge() XCTAssert(dao.getAll().isEmpty) } //TODO: Testing for cascade objects }
mit
4d439c2a990e6721417479e5a6dcc0e6
24.159574
109
0.671882
3.858075
false
true
false
false
movabletype/smartphone-app
MT_iOS/MT_iOS/Classes/Model/UploadItem.swift
1
1644
// // UploadItem.swift // MT_iOS // // Created by CHEEBOW on 2016/02/08. // Copyright © 2016年 Six Apart, Ltd. All rights reserved. // import UIKit import SwiftyJSON class UploadItem: NSObject { internal(set) var data: NSData! = nil var blogID = "" var uploadPath = "" var uploaded = false var progress: Float = 0.0 internal(set) var _filename: String = "" var filename: String { get { if self._filename.isEmpty { return self.makeFilename() } return _filename } } func setup(completion: (() -> Void)) { completion() } func clear() { self.data = nil } internal func makeFilename()->String { return self._filename } func upload(progress progress: ((Int64!, Int64!, Int64!) -> Void)? = nil, success: (JSON! -> Void)!, failure: (JSON! -> Void)!) { let api = DataAPI.sharedInstance let app = UIApplication.sharedApplication().delegate as! AppDelegate let authInfo = app.authInfo api.authenticationV2(authInfo.username, password: authInfo.password, remember: true, success:{_ in let filename = self.makeFilename() api.uploadAssetForSite(self.blogID, assetData: self.data, fileName: filename, options: ["path":self.uploadPath, "autoRenameIfExists":"true"], progress: progress, success: success, failure: failure) }, failure: failure ) } func thumbnail(size: CGSize, completion: (UIImage->Void)) { completion(UIImage()) } }
mit
95a5cc9683789cfc441a8cd6779bb7d1
27.293103
214
0.577697
4.34127
false
false
false
false
brentsimmons/Evergreen
iOS/ShareExtension/ShareFolderPickerController.swift
1
2448
// // ShareFolderPickerController.swift // NetNewsWire iOS Share Extension // // Created by Maurice Parker on 9/12/19. // Copyright © 2019 Ranchero Software. All rights reserved. // import UIKit import Account import RSCore protocol ShareFolderPickerControllerDelegate: AnyObject { func shareFolderPickerDidSelect(_ container: ExtensionContainer) } class ShareFolderPickerController: UITableViewController { var containers: [ExtensionContainer]? var selectedContainerID: ContainerIdentifier? weak var delegate: ShareFolderPickerControllerDelegate? override func viewDidLoad() { tableView.register(UINib(nibName: "ShareFolderPickerAccountCell", bundle: Bundle.main), forCellReuseIdentifier: "AccountCell") tableView.register(UINib(nibName: "ShareFolderPickerFolderCell", bundle: Bundle.main), forCellReuseIdentifier: "FolderCell") } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return containers?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let container = containers?[indexPath.row] let cell: ShareFolderPickerCell = { if container is ExtensionAccount { return tableView.dequeueReusableCell(withIdentifier: "AccountCell", for: indexPath) as! ShareFolderPickerCell } else { return tableView.dequeueReusableCell(withIdentifier: "FolderCell", for: indexPath) as! ShareFolderPickerCell } }() if let account = container as? ExtensionAccount { cell.icon.image = AppAssets.image(for: account.type) } else { cell.icon.image = AppAssets.masterFolderImage.image } cell.label?.text = container?.name ?? "" if let containerID = container?.containerID, containerID == selectedContainerID { cell.accessoryType = .checkmark } else { cell.accessoryType = .none } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let container = containers?[indexPath.row] else { return } if let account = container as? ExtensionAccount, account.disallowFeedInRootFolder { tableView.selectRow(at: nil, animated: false, scrollPosition: .none) } else { let cell = tableView.cellForRow(at: indexPath) cell?.accessoryType = .checkmark delegate?.shareFolderPickerDidSelect(container) } } }
mit
de4588f3eda24c1394c5df2b2d0ca469
30.779221
128
0.756028
4.270506
false
false
false
false
CodaFi/swift-compiler-crashes
fixed/24629-swift-nominaltypedecl-getdeclaredtypeincontext.swift
9
2452
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing } struct B: struct b{ struct B : Int = A{ let f=(i struct A<T where h:A{ } struct c<T {typealias f: p let , i { struct b<T where h: d where g.c {enum a {struct A { struct A{ class B: let c {{ protocol A { }}struct A { class B<T where h: d class A {return" enum a {typealias f: e : p e :AnyObject.c {return"" e = b }struct c {struct c<T where T }}} struct B<h{class A{ enum A struct S<T where h:A{ }enum a {class B var = A{ class B<T { class d } }enum S<T where H:BooleanType} if true { e :A{ var _=a{} struct Q{ let enum A{init(i class b<f: {" func g: AnyObject.Element class b{class B<b let a { struct S<T where k:AnyObject.c { struct d class b struct c struct B : P { enum b{ var = A{let v: e .e = A<T where g: e extension String {struct A{ {{ struct c { } struct B typealias e:A<T where h:d<T where h: AnyObject.c {struct A{ let : let start = true { let start = Swift.c {struct Q{ {{ enum b{func b<T where h: e where B? = true { struct b{ let f=[]deinit{ class B<f=e: func b{{struct B : d func b<T where T: e .c {return"[enum b<I : e:A{class A{ let struct S<T where h:d<T where h:d struct B<T where h{class B : d where h: }} struct c class d struct b{struct A {struct Q{return" let a { } func b<T where H : b{ struct Q{ } enum a {return" let , i {init() { d{{ let d if true { struct Q{var b{ { class B<T where B:B{return" protocol A { } struct c<T where h:A{ struct b<I : {enum B:c:A{ {class b{return" let , i { } enum b class b<I : "class n{return" "" var f class A{var = b{ struct Q<T where h: struct B<I : { let f: C {println(i let : class B { struct Q{ class B<T struct c<I :c:d{return"" func b{ }} } struct c<T where h{ class b<T where T class C } struct S<f: e :d<T where B<H:a<T where g: {} var _=e:e { e = "[]deinit{class b<T where h: { let start = A struct A { protocol A:BooleanType} struct d<d = " struct S<T where B<T where k:BooleanType} struct c<T where g:BooleanType} } import Foundation var f: p } var _=B class d{let start = b{{ let v: B<T where g: {struct Q{ struct Q<T where h:c<T where H:A{{enum A{ class B{ struct B<T where T: Int = " class A:a{ protocol A {return"[enum B<T { let start = Swift.c { let f: e :A:d{ } struct S<T where h: A {return"" struct S<f=[enum b<T where h:d struct c:A{ class B<T where T: c<T where h:a<T where h:A{typealias f{ struct b<
mit
5d715cb5f676e1cf29e1f7e801a28e00
15.567568
87
0.649674
2.437376
false
false
false
false
MichaelCampbell/DateTime
src/Timespan.swift
1
3939
/* Copyright (c) 2015 Christopher Jones <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * A span of elapsed time. */ public struct TimeSpan { private static let secondsPerMinute = 60 private static let secondsPerHour = 60 * secondsPerMinute private static let secondsPerDay = 24 * secondsPerHour /// The raw time interval for the timespan, in seconds. public var timeInterval: NSTimeInterval { get { var totalSeconds = self.seconds totalSeconds += self.minutes * TimeSpan.secondsPerMinute totalSeconds += self.hours * TimeSpan.secondsPerHour totalSeconds += self.days * TimeSpan.secondsPerDay return Double(totalSeconds) } } /// The number of days. public let days: Int /// The number of hours. public let hours: Int /// The number of minutes. public let minutes: Int /// The number of seconds public let seconds: Int /** Initializes a new TimeSpan with the specified number of seconds in the time interval. :param: timeInterval The time interval of the timespan, in seconds. :returns: A new TimeSpan. */ public init(timeInterval: NSTimeInterval) { var totalSecondsInterval = Int(timeInterval) let days = (totalSecondsInterval / TimeSpan.secondsPerDay) totalSecondsInterval -= (days * TimeSpan.secondsPerDay) let hours = (totalSecondsInterval / TimeSpan.secondsPerHour) totalSecondsInterval -= (hours * TimeSpan.secondsPerHour) let minutes = (totalSecondsInterval / TimeSpan.secondsPerMinute) totalSecondsInterval -= (hours * TimeSpan.secondsPerMinute) self.days = days self.hours = hours self.minutes = minutes self.seconds = (totalSecondsInterval % 60) } /** Initializes a new TimeSpan with the specified values. :param: days The number of days in the timespan. :param: hours The number of hours in the timespan. :param: minutes The number of minutes in the timespan. :param: seconds The number of seconds in the timespan. :returns: A new TimeSpan. */ public init(days: Int, hours: Int, minutes: Int, seconds: Int) { self.days = days self.hours = hours self.minutes = minutes self.seconds = seconds } } // RawRepresentable implementation. extension TimeSpan: RawRepresentable { /// The RawValue of TimeSpan. public typealias RawValue = NSTimeInterval /** Initializes a new instance of TimeSpan by its raw value. :param: rawValue The time in seconds. :returns: A new TimeSpan. This can be safely force-unwrapped. */ public init?(rawValue: RawValue) { self.init(timeInterval: rawValue) } /// The raw value of the TimeSpan. public var rawValue: RawValue { get { return self.timeInterval } } }
mit
f229034559b6b54d5d1c4c8ba5ff336b
30.261905
89
0.692562
4.762999
false
false
false
false
mrkev/eatery
Eatery/Eatery/ProfileViewController.swift
1
5113
// // ProfileViewController.swift // Eatery // // Created by Eric Appel on 11/5/14. // Copyright (c) 2014 CUAppDev. All rights reserved. // import UIKit class ProfileViewController: UIViewController { @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var bodyTextView: UITextView! @IBOutlet weak var fbLoginButton: facebookLoginButton! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(animated: Bool) { if isLoggedIn() { fbLoginButton.setLoginState(.LoggedIn) getFacebookInfo({ (result) -> Void in self.updateUIWithFacebookProfile(result) }) } } func isLoggedIn() -> Bool { // if PFFacebookUtils.session().state == FBSessionState.CreatedTokenLoaded { // return true // } if let user = PFUser.currentUser() { return true } return false } func updateUIWithFacebookProfile(profile: JSON) { let path = profile["id"].stringValue + "/picture?type=large" let pictureURL: NSURL = NSURL(string: path, relativeToURL: NSURL(string: "https://graph.facebook.com"))! profileImageView.image = UIImage(data: NSData(contentsOfURL: pictureURL)!) nameLabel.text = profile["name"].stringValue title = nameLabel.text getMyFriendsList(profile["id"].stringValue, completion: { (result) -> Void in if let friends = result { self.bodyTextView.text = "My Friends:\n\(friends)\n\nUser Info:\n\(profile)" } else { self.bodyTextView.text = "User Info:\n\(profile)" } }) } @IBAction func fbButtonPressed(sender: facebookLoginButton) { let permissions = [ "public_profile", "email", "user_friends" ] if sender.loginState == .LoggedOut { activityIndicator.startAnimating() PFFacebookUtils.logInWithPermissions(permissions, { (user: PFUser!, error: NSError!) -> Void in self.activityIndicator.stopAnimating() println() if user == nil { println(">>>>>>>>Uh oh. The user cancelled the Facebook login.") error.handleFacebookError() sender.setLoginState(.LoggedOut) } else if user.isNew { println(">>>>>>>>User signed up and logged in through Facebook!") sender.setLoginState(.LoggedIn) self.getFacebookInfo({ (result) -> Void in self.updateUIWithFacebookProfile(result) }) } else { sender.setLoginState(.LoggedIn) println(">>>>>>>>User logged in through Facebook!") self.getFacebookInfo({ (result) -> Void in self.updateUIWithFacebookProfile(result) }) } }) } else { PFUser.logOut() updateUIWithFacebookProfile(nil) sender.setLoginState(.LoggedOut) } } func getFacebookInfo(completion:(result: JSON) -> Void) { activityIndicator.startAnimating() FBRequestConnection.startForMeWithCompletionHandler { (connection: FBRequestConnection!, result: AnyObject!, error: NSError!) -> Void in self.activityIndicator.stopAnimating() if error != nil { error.handleFacebookError() } else { if let swiftyJSON = JSON(rawValue: result) { completion(result: swiftyJSON) } } } } func getMyFriendsList(facebookID: String, completion:(result: JSON?) -> Void) { // This will only print friends who have given our app fb access. The new api does not allow access to a person's entire friends list. FBRequestConnection.startForMyFriendsWithCompletionHandler { (connection: FBRequestConnection!, result: AnyObject!, error: NSError!) -> Void in if error != nil { error.handleFacebookError() completion(result: nil) } else { if let swiftyJSON = JSON(rawValue: result) { let friendObjects: Array = swiftyJSON["data"].arrayValue var friendIDs: [String] = [] friendIDs.reserveCapacity(friendObjects.count) for fo in friendObjects { friendIDs.append(fo.stringValue) } completion(result: swiftyJSON) } else { completion(result: nil) } } } } }
mit
579402c4ce018d9854e88eeca41be533
35.521429
151
0.547037
5.348326
false
false
false
false
Hukuma23/CS193p
Assignment_4/Twitter/Twitter/Tweet.swift
1
8317
// // Tweet.swift // Twitter // // Created by CS193p Instructor. // Copyright (c) 2015 Stanford University. All rights reserved. // import Foundation // a simple container class which just holds the data in a Tweet // a Mention is a substring of the Tweet's text // for example, a hashtag or other user or url that is mentioned in the Tweet // note carefully the comments on the range property in a Mention // Tweet instances are created by fetching from Twitter using a Twitter.Request public class Tweet : NSObject { public let text: String public let user: User public let created: Date public let id: String public let media: [MediaItem] public let hashtags: [Mention] public let urls: [Mention] public let userMentions: [Mention] public override var description: String { return "\(user) - \(created)\n\(text)\nhashtags: \(hashtags)\nurls: \(urls)\nuser_mentions: \(userMentions)" + "\nid: \(id)" } // MARK: - Internal Implementation init?(data: NSDictionary?) { guard let user = User(data: data?.value(forKeyPath: TwitterKey.User) as? NSDictionary), let text = data?.value(forKeyPath: TwitterKey.Text) as? String, let created = (data?.value(forKeyPath: TwitterKey.Created) as? String)?.asTwitterDate, let id = data?.value(forKeyPath: TwitterKey.ID) as? String else { return nil } self.user = user self.text = text self.created = created self.id = id self.media = Tweet.mediaItemsFromTwitterData(data?.value(forKeyPath: TwitterKey.Media) as? NSArray) self.hashtags = Tweet.mentionsFromTwitterData(data?.arrayForKeyPath(TwitterKey.Entities.Hashtags), inText: text, withPrefix: "#") self.urls = Tweet.mentionsFromTwitterData(data?.arrayForKeyPath(TwitterKey.Entities.URLs), inText: text, withPrefix: "http") self.userMentions = Tweet.mentionsFromTwitterData(data?.arrayForKeyPath(TwitterKey.Entities.UserMentions), inText: text, withPrefix: "@") } private static func mediaItemsFromTwitterData(_ twitterData: NSArray?) -> [MediaItem] { var mediaItems = [MediaItem]() for mediaItemData in twitterData ?? [] { if let mediaItem = MediaItem(data: mediaItemData as? NSDictionary) { mediaItems.append(mediaItem) } } return mediaItems } private static func mentionsFromTwitterData(_ twitterData: NSArray?, inText text: String, withPrefix prefix: String) -> [Mention] { var mentions = [Mention]() for mentionData in twitterData ?? [] { if let mention = Mention(fromTwitterData: mentionData as? NSDictionary, inText: text as NSString, withPrefix: prefix) { mentions.append(mention) } } return mentions } struct TwitterKey { static let User = "user" static let Text = "text" static let Created = "created_at" static let ID = "id_str" static let Media = "entities.media" struct Entities { static let Hashtags = "entities.hashtags" static let URLs = "entities.urls" static let UserMentions = "entities.user_mentions" static let Indices = "indices" static let Text = "text" } } } public class Mention: NSObject { public let keyword: String // will include # or @ or http prefix public let nsrange: NSRange // index into an NS[Attributed]String made from the Tweet's text public override var description: String { return "\(keyword) (\(nsrange.location), \(nsrange.location+nsrange.length-1))" } init?(fromTwitterData data: NSDictionary?, inText text: NSString, withPrefix prefix: String) { guard let indices = data?.value(forKeyPath: Tweet.TwitterKey.Entities.Indices) as? NSArray, let start = (indices.firstObject as? NSNumber)?.intValue , start >= 0, let end = (indices.lastObject as? NSNumber)?.intValue , end > start else { return nil } var prefixAloneOrPrefixedMention = prefix if let mention = data?.value(forKeyPath: Tweet.TwitterKey.Entities.Text) as? String { prefixAloneOrPrefixedMention = mention.prependPrefixIfAbsent(prefix) } let expectedRange = NSRange(location: start, length: end - start) guard let nsrange = text.rangeOfSubstringWithPrefix(prefixAloneOrPrefixedMention, expectedRange: expectedRange) else { return nil } self.keyword = text.substring(with: nsrange) self.nsrange = nsrange } } private let twitterDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy" formatter.locale = Locale(identifier: "en_US_POSIX") return formatter }() private extension String { var asTwitterDate: Date? { return twitterDateFormatter.date(from: self) } } private extension NSDictionary { func arrayForKeyPath(_ keypath: String) -> NSArray? { return self.value(forKeyPath: keypath) as? NSArray } } private extension String { func prependPrefixIfAbsent(_ prefix: String) -> String { if hasPrefix(prefix) { return self } else { return prefix + self } } } private extension NSString { func rangeOfSubstringWithPrefix(_ prefix: String, expectedRange: NSRange) -> NSRange? { var offset = 0 var substringRange = expectedRange while range.contains(substringRange) && substringRange.intersects(expectedRange) { if substring(with: substringRange).hasPrefix(prefix) { return substringRange } offset = offset > 0 ? -(offset+1) : -(offset-1) substringRange.location += offset } // the prefix does not intersect the expectedRange // let's search for it elsewhere and if we find it, // pick the one closest to expectedRange var searchRange = range var bestMatchRange = NSRange.NotFound var bestMatchDistance = Int.max repeat { substringRange = self.range(of: prefix, options: [], range: searchRange) let distance = substringRange.distanceFrom(expectedRange) if distance < bestMatchDistance { bestMatchRange = substringRange bestMatchDistance = distance } searchRange.length -= substringRange.end - searchRange.start searchRange.start = substringRange.end } while searchRange.length > 0 if bestMatchRange.location != NSNotFound { bestMatchRange.length = expectedRange.length if range.contains(bestMatchRange) { return bestMatchRange } } print("NSString.rangeOfKeywordWithPrefix(expectedRange:) couldn't find a keyword with the prefix \(prefix) near the range \(expectedRange) in \(self)") return nil } var range: NSRange { return NSRange(location:0, length: length) } } private extension NSRange { func contains(_ range: NSRange) -> Bool { return range.location >= location && range.location+range.length <= location+length } func intersects(_ range: NSRange) -> Bool { if range.location == NSNotFound || location == NSNotFound { return false } else { return (range.start >= start && range.start < end) || (range.end >= start && range.end < end) } } func distanceFrom(_ range: NSRange) -> Int { if range.location == NSNotFound || location == NSNotFound { return Int.max } else if intersects(range) { return 0 } else { return (end < range.start) ? range.start - end : start - range.end } } static let NotFound = NSRange(location: NSNotFound, length: 0) var start: Int { get { return location } set { location = newValue } } var end: Int { return location+length } }
apache-2.0
6234366c473f838bfce4c908636e2416
35.004329
172
0.620777
4.685634
false
false
false
false
stepanhruda/ios-simulator-app-installer
src/Packaging.swift
1
2943
enum PackagingError: ErrorType { case RequiredXcodeUnavailable(String) case InvalidAppPath(String) case XcodebuildFailed case FileWriteFailed(NSError) var message: String { switch self { case .RequiredXcodeUnavailable(let requiredVersion): return "You need to have \(requiredVersion) installed and selected via xcode-select." case .InvalidAppPath(let path): return "Provided .app not found at \(path)" case .XcodebuildFailed: return "Error in xcodebuild when packaging app" case .FileWriteFailed(let error): return "Writing output bundle failed: \(error.localizedDescription)" } } } class Packaging { static func packageAppAtPath( appPath: String, deviceIdentifier: String?, outputPath outputPathMaybe: String?, packageLauncherPath packageLauncherPathMaybe: String?, shouldUninstall: Bool, fileManager: NSFileManager) throws { let packageLauncherPath = packageLauncherPathMaybe ?? "/usr/local/share/app-package-launcher" guard Xcode.isRequiredVersionInstalled() else { throw PackagingError.RequiredXcodeUnavailable(Xcode.requiredVersion) } guard fileManager.fileExistsAtPath(appPath) else { throw PackagingError.InvalidAppPath(appPath) } let fullAppPath = NSURL(fileURLWithPath: appPath).path! let outputPath = outputPathMaybe ?? defaultOutputPathForAppPath(appPath) let productFolder = "\(packageLauncherPath)/build" let productPath = "\(productFolder)/Release/app-package-launcher.app" let packagedAppFlag = "\"PACKAGED_APP=\(fullAppPath)\"" let targetDeviceFlag = deviceIdentifier != nil ? "\"TARGET_DEVICE=\(deviceIdentifier!)\"" : "" let uninstallFlag = shouldUninstall ? "UNINSTALL=1" : "" let xcodebuildExitCode = system("xcodebuild -project \(packageLauncherPath)/app-package-launcher.xcodeproj \(packagedAppFlag) \(targetDeviceFlag) \(uninstallFlag) > /dev/null") guard xcodebuildExitCode == 0 else { throw PackagingError.XcodebuildFailed } do { if fileManager.fileExistsAtPath(outputPath) { try fileManager.removeItemAtPath(outputPath) } try fileManager.moveItemAtPath(productPath, toPath: outputPath) try fileManager.removeItemAtPath(productFolder) } catch let error as NSError { throw PackagingError.FileWriteFailed(error) } print("\(appPath) successfully packaged to \(outputPath)") } static func defaultOutputPathForAppPath(appPath: String) -> String { let url = NSURL(fileURLWithPath: appPath) let appName = url.URLByDeletingPathExtension?.lastPathComponent ?? "App" return "\(appName) Installer.app" } }
mit
c5385c0f0a35c3099697a0bbafe685a5
42.925373
163
0.66123
5.136126
false
false
false
false
moozzyk/SignalR-Client-Swift
Sources/SignalRClient/HttpConnection.swift
1
13824
// // Connection.swift // SignalRClient // // Created by Pawel Kadluczka on 2/26/17. // Copyright © 2017 Pawel Kadluczka. All rights reserved. // import Foundation public class HttpConnection: Connection { private let connectionQueue: DispatchQueue private let startDispatchGroup: DispatchGroup private var url: URL private let options: HttpConnectionOptions private let transportFactory: TransportFactory private let logger: Logger private var transportDelegate: TransportDelegate? private var state: State private var transport: Transport? private var stopError: Error? public weak var delegate: ConnectionDelegate? public private(set) var connectionId: String? public var inherentKeepAlive: Bool { return transport?.inherentKeepAlive ?? true } private enum State: String { case initial = "initial" case connecting = "connecting" case connected = "connected" case stopped = "stopped" } public convenience init(url: URL, options: HttpConnectionOptions = HttpConnectionOptions(), logger: Logger = NullLogger()) { self.init(url: url, options: options, transportFactory: DefaultTransportFactory(logger: logger), logger: logger) } init(url: URL, options: HttpConnectionOptions, transportFactory: TransportFactory, logger: Logger) { logger.log(logLevel: .debug, message: "HttpConnection init") connectionQueue = DispatchQueue(label: "SignalR.connection.queue") startDispatchGroup = DispatchGroup() self.url = url self.options = options self.transportFactory = transportFactory self.logger = logger self.state = .initial } deinit { logger.log(logLevel: .debug, message: "HttpConnection deinit") } public func start() { logger.log(logLevel: .info, message: "Starting connection") if changeState(from: .initial, to: .connecting) == nil { logger.log(logLevel: .error, message: "Starting connection failed - invalid state") // the connection is already in use so the startDispatchGroup should not be touched to not affect it failOpenWithError(error: SignalRError.invalidState, changeState: false, leaveStartDispatchGroup: false) return } startDispatchGroup.enter() if options.skipNegotiation { transport = try! self.transportFactory.createTransport(availableTransports: [TransportDescription(transportType: TransportType.webSockets, transferFormats: [TransferFormat.text, TransferFormat.binary])]) startTransport(connectionId: nil) } else { negotiate(negotiateUrl: createNegotiateUrl(), accessToken: nil) { negotiationResponse in do { self.transport = try self.transportFactory.createTransport(availableTransports: negotiationResponse.availableTransports) } catch { self.logger.log(logLevel: .error, message: "Creating transport failed: \(error)") self.failOpenWithError(error: error, changeState: true) return } self.startTransport(connectionId: negotiationResponse.connectionToken ?? negotiationResponse.connectionId) } } } private func negotiate(negotiateUrl: URL, accessToken: String?, negotiateDidComplete: @escaping (NegotiationResponse) -> Void) { if let accessToken = accessToken { logger.log(logLevel: .debug, message: "Overriding accessToken") options.accessTokenProvider = { accessToken } } let httpClient = options.httpClientFactory(options) httpClient.post(url: negotiateUrl, body: nil) {httpResponse, error in if let e = error { self.logger.log(logLevel: .error, message: "Negotiate failed due to: \(e))") self.failOpenWithError(error: e, changeState: true) return } guard let httpResponse = httpResponse else { self.logger.log(logLevel: .error, message: "Negotiate returned (nil) httpResponse") self.failOpenWithError(error: SignalRError.invalidNegotiationResponse(message: "negotiate returned nil httpResponse."), changeState: true) return } if httpResponse.statusCode == 200 { self.logger.log(logLevel: .debug, message: "Negotiate completed with OK status code") do { let payload = httpResponse.contents self.logger.log(logLevel: .debug, message: "Negotiate response: \(payload != nil ? String(data: payload!, encoding: .utf8) ?? "(nil)" : "(nil)")") switch try NegotiationPayloadParser.parse(payload: payload) { case let redirection as Redirection: self.logger.log(logLevel: .debug, message: "Negotiate redirects to \(redirection.url)") self.url = redirection.url var negotiateUrl = self.url negotiateUrl.appendPathComponent("negotiate") self.negotiate(negotiateUrl: negotiateUrl, accessToken: redirection.accessToken, negotiateDidComplete: negotiateDidComplete) case let negotiationResponse as NegotiationResponse: self.logger.log(logLevel: .debug, message: "Negotiation response received") negotiateDidComplete(negotiationResponse) default: throw SignalRError.invalidNegotiationResponse(message: "internal error - unexpected negotiation payload") } } catch { self.logger.log(logLevel: .error, message: "Parsing negotiate response failed: \(error)") self.failOpenWithError(error: error, changeState: true) } } else { self.logger.log(logLevel: .error, message: "HTTP request error. statusCode: \(httpResponse.statusCode)\ndescription:\(httpResponse.contents != nil ? String(data: httpResponse.contents!, encoding: .utf8) ?? "(nil)" : "(nil)")") self.failOpenWithError(error: SignalRError.webError(statusCode: httpResponse.statusCode), changeState: true) } } } private func startTransport(connectionId: String?) { // connection is being stopped even though start has not finished yet if (self.state != .connecting) { self.logger.log(logLevel: .info, message: "Connection closed during negotiate") self.failOpenWithError(error: SignalRError.connectionIsBeingClosed, changeState: false) return } let startUrl = self.createStartUrl(connectionId: connectionId) self.transportDelegate = ConnectionTransportDelegate(connection: self, connectionId: connectionId) self.transport!.delegate = self.transportDelegate self.transport!.start(url: startUrl, options: self.options) } private func createNegotiateUrl() -> URL { var urlComponents = URLComponents(url: self.url, resolvingAgainstBaseURL: false)! var queryItems = (urlComponents.queryItems ?? []) as [URLQueryItem] queryItems.append(URLQueryItem(name: "negotiateVersion", value: "1")) urlComponents.queryItems = queryItems var negotiateUrl = urlComponents.url! negotiateUrl.appendPathComponent("negotiate") return negotiateUrl } private func createStartUrl(connectionId: String?) -> URL { if connectionId == nil { return self.url } var urlComponents = URLComponents(url: self.url, resolvingAgainstBaseURL: false)! var queryItems = (urlComponents.queryItems ?? []) as [URLQueryItem] queryItems.append(URLQueryItem(name: "id", value: connectionId)) urlComponents.queryItems = queryItems return urlComponents.url! } private func failOpenWithError(error: Error, changeState: Bool, leaveStartDispatchGroup: Bool = true) { if changeState { _ = self.changeState(from: nil, to: .stopped) } if leaveStartDispatchGroup { logger.log(logLevel: .debug, message: "Leaving startDispatchGroup (\(#function): \(#line))") startDispatchGroup.leave() } logger.log(logLevel: .debug, message: "Invoking connectionDidFailToOpen") options.callbackQueue.async { self.delegate?.connectionDidFailToOpen(error: error) } } public func send(data: Data, sendDidComplete: @escaping (_ error: Error?) -> Void) { logger.log(logLevel: .debug, message: "Sending data") guard state == .connected else { logger.log(logLevel: .error, message: "Sending data failed - connection not in the 'connected' state") // Never synchronously respond to avoid upstream deadlocks based on async assumptions options.callbackQueue.async { sendDidComplete(SignalRError.invalidState) } return } transport!.send(data: data, sendDidComplete: sendDidComplete) } public func stop(stopError: Error? = nil) { logger.log(logLevel: .info, message: "Stopping connection") let previousState = self.changeState(from: nil, to: .stopped) if previousState == .stopped { logger.log(logLevel: .info, message: "Connection already stopped") return } if previousState == .initial { logger.log(logLevel: .warning, message: "Connection not yet started") return } self.startDispatchGroup.wait() // The transport can be nil if connection was stopped immediately after starting // or failed to start. In this case we need to call connectionDidClose ourselves. if let t = transport { self.stopError = stopError t.close() } else { logger.log(logLevel: .debug, message: "Connection being stopped before transport initialized") logger.log(logLevel: .debug, message: "Invoking connectionDidClose (\(#function): \(#line))") options.callbackQueue.async { self.delegate?.connectionDidClose(error: stopError) } } } fileprivate func transportDidOpen(connectionId: String?) { logger.log(logLevel: .info, message: "Transport started") let previousState = changeState(from: .connecting, to: .connected) logger.log(logLevel: .debug, message: "Leaving startDispatchGroup (\(#function): \(#line))") startDispatchGroup.leave() if previousState != nil { logger.log(logLevel: .debug, message: "Invoking connectionDidOpen") self.connectionId = connectionId options.callbackQueue.async { self.delegate?.connectionDidOpen(connection: self) } } else { logger.log(logLevel: .debug, message: "Connection is being stopped while the transport is starting") } } fileprivate func transportDidReceiveData(_ data: Data) { logger.log(logLevel: .debug, message: "Received data from transport") options.callbackQueue.async { self.delegate?.connectionDidReceiveData(connection: self, data: data) } } fileprivate func transportDidClose(_ error: Error?) { logger.log(logLevel: .info, message: "Transport closed") let previousState = changeState(from: nil, to: .stopped) logger.log(logLevel: .debug, message: "Previous state \(previousState!)") if previousState == .connecting { logger.log(logLevel: .debug, message: "Leaving startDispatchGroup (\(#function): \(#line))") // unblock the dispatch group if transport closed when starting (likely due to an error) startDispatchGroup.leave() logger.log(logLevel: .debug, message: "Invoking connectionDidFailToOpen") options.callbackQueue.async { self.delegate?.connectionDidFailToOpen(error: self.stopError ?? error!) } } else { logger.log(logLevel: .debug, message: "Invoking connectionDidClose (\(#function): \(#line))") self.connectionId = nil options.callbackQueue.async { self.delegate?.connectionDidClose(error: self.stopError ?? error) } } } private func changeState(from: State?, to: State) -> State? { var previousState: State? = nil logger.log(logLevel: .debug, message: "Attempting to change state from: '\(from?.rawValue ?? "(nil)")' to: '\(to)'") connectionQueue.sync { if from == nil || from == state { previousState = state state = to } } logger.log(logLevel: .debug, message: "Changing state to: '\(to)' \(previousState == nil ? "failed" : "succeeded")") return previousState } } public class ConnectionTransportDelegate: TransportDelegate { private weak var connection: HttpConnection? private let connectionId: String? fileprivate init(connection: HttpConnection!, connectionId: String?) { self.connection = connection self.connectionId = connectionId } public func transportDidOpen() { connection?.transportDidOpen(connectionId: connectionId) } public func transportDidReceiveData(_ data: Data) { connection?.transportDidReceiveData(data) } public func transportDidClose(_ error: Error?) { connection?.transportDidClose(error) } }
mit
43458fe2be80c56e1b97e9017bfc6ffc
41.928571
242
0.635752
5.024718
false
false
false
false
tiagomartinho/webhose-cocoa
webhose-cocoa/WebhoseTests/WebhoseReponseSpec.swift
1
2333
@testable import Webhose import Quick import Nimble class WebhoseReponseSpec: QuickSpec { let aKey = "aKey" let aQuery = "aQuery" override func spec() { describe("the Webhose Client") { let client = WebhoseClient(key: self.aKey) context("when the response is incorrect") { beforeEach { WebhoseStub.stubIncorrectResponse() } it("does not have totalResults") { var totalResults: Int? client.search(self.aQuery) { response in totalResults = response.totalResults } expect(totalResults).toEventually(equal(0)) } } context("when the response is correct") { beforeEach { WebhoseStub.stubCorrectResponse() } it("has total results") { var totalResults: Int? client.search(self.aQuery) { response in totalResults = response.totalResults } expect(totalResults).toEventually(equal(2)) } it("has next search url") { var next: String? client.search(self.aQuery) { response in next = response.next } let expectedNext = "/search?token=1&format=json&ts=1458339113634&q=ipod" expect(next).toEventually(equal(expectedNext)) } it("has number of requests left") { var requestsLeft: Int? client.search(self.aQuery) { response in requestsLeft = response.requestsLeft } expect(requestsLeft).toEventually(equal(998)) } it("has number of more results available") { var moreResultsAvailable: Int? client.search(self.aQuery) { response in moreResultsAvailable = response.moreResultsAvailable } expect(moreResultsAvailable).toEventually(equal(5113)) } } } } }
mit
c851191469727f073ac606ac1e776310
36.031746
92
0.473639
5.594724
false
false
false
false
wjk930726/weibo
weiBo/weiBo/iPhone/Utilities/Category/UIImage+WJKAddition.swift
1
920
// // UIImage+WJKAddition.swift // weiBo // // Created by 王靖凯 on 2016/11/30. // Copyright © 2016年 王靖凯. All rights reserved. // import UIKit extension UIImage { public func createCornerImage(size: CGSize = CGSize.zero, backgroundColor: UIColor = UIColor.clear, callBack: @escaping (_ cornerImage: UIImage) -> Void) { OperationQueue().addOperation { let rect = CGRect(origin: CGPoint.zero, size: size) UIGraphicsBeginImageContext(size) backgroundColor.setFill() UIRectFill(rect) UIBezierPath(ovalIn: rect).addClip() self.draw(in: rect) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() OperationQueue.main.addOperation { if let image = image { callBack(image) } } } } }
mit
60a8f0be5eba3d5a7b6a1c9c95c1bed6
29.166667
159
0.592265
4.918478
false
false
false
false
aronse/Hero
Sources/Transition/HeroTransition+UINavigationControllerDelegate.swift
2
2023
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit extension HeroTransition: UINavigationControllerDelegate { public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { guard !isTransitioning else { return nil } self.state = .notified self.isPresenting = operation == .push self.fromViewController = fromViewController ?? fromVC self.toViewController = toViewController ?? toVC self.inNavigationController = true return self } public func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactiveTransitioning } }
mit
ad88d198c80e001d5d5d91c8d3b54261
50.871795
251
0.78349
5.423592
false
false
false
false
ahenqs/AHQSLibrary
AHQSLibrary/UIViewExtension.swift
1
3749
// // UIViewExtension.swift // AHQSLibrary // // Created by André Henrique da Silva on 28/10/2016. // Copyright © 2016 André Henrique da Silva. All rights reserved. // import UIKit extension UIView { public func setupConstraints( topAnchor: NSLayoutYAxisAnchor?, topConstant: CGFloat, leftAnchor: NSLayoutXAxisAnchor?, leftConstant: CGFloat, bottomAnchor: NSLayoutYAxisAnchor?, bottomConstant: CGFloat, rightAnchor: NSLayoutXAxisAnchor?, rightConstant: CGFloat, width: CGFloat = 0.0, height: CGFloat = 0.0 ) -> [String: NSLayoutConstraint?] { self.translatesAutoresizingMaskIntoConstraints = false var constraints = [String: NSLayoutConstraint?]() if let top = topAnchor { let topConstraint = self.topAnchor.constraint(equalTo: top, constant: topConstant) topConstraint.isActive = true constraints.updateValue(topConstraint, forKey: "top") } else { constraints.updateValue(nil, forKey: "top") } if let left = leftAnchor { let leftConstraint = self.leadingAnchor.constraint(equalTo: left, constant: leftConstant) leftConstraint.isActive = true constraints.updateValue(leftConstraint, forKey: "left") } else { constraints.updateValue(nil, forKey: "left") } if let bottom = bottomAnchor { let bottomConstraint = self.bottomAnchor.constraint(equalTo: bottom, constant: bottomConstant) bottomConstraint.isActive = true constraints.updateValue(bottomConstraint, forKey: "bottom") } else { constraints.updateValue(nil, forKey: "bottom") } if let right = rightAnchor { let rightConstraint = self.trailingAnchor.constraint(equalTo: right, constant: rightConstant) rightConstraint.isActive = true constraints.updateValue(rightConstraint, forKey: "right") } else { constraints.updateValue(nil, forKey: "right") } if width > 0.0 { let widthConstraint = self.widthAnchor.constraint(equalToConstant: width) widthConstraint.isActive = true constraints.updateValue(widthConstraint, forKey: "width") } else { constraints.updateValue(nil, forKey: "width") } if height > 0.0 { let heightConstraint = self.heightAnchor.constraint(equalToConstant: height) heightConstraint.isActive = true constraints.updateValue(heightConstraint, forKey: "height") } else { constraints.updateValue(nil, forKey: "height") } return constraints } public func setHeightRelativeTo(_ view: UIView, multiplier: CGFloat) -> NSLayoutConstraint { self.translatesAutoresizingMaskIntoConstraints = false let heightConstraint = self.heightAnchor.constraint(equalTo: view.heightAnchor, multiplier: multiplier) heightConstraint.isActive = true return heightConstraint } public func setWidthRelativeTo(_ view: UIView, multiplier: CGFloat) -> NSLayoutConstraint { self.translatesAutoresizingMaskIntoConstraints = false let widthConstraint = self.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: multiplier) widthConstraint.isActive = true return widthConstraint } }
mit
327dad54d960a450bd29c37ad373c41a
33.685185
111
0.60331
6.071313
false
false
false
false
cbatch/fruit-ninja-ios
FruitNinjaiOS/FruitNinjaiOS/PineappleEntity.swift
1
1096
// // PineappleEntity.swift // FruitNinjaiOS // // Created by Connor Batch on 11/13/16. // Copyright © 2016 Connor Batch. All rights reserved. // import SpriteKit class PineappleEntity : SwitchEntity { var isRecovered : Bool = false var isRecoveredOnce : Bool = false init() { super.init(imageNamed: "pineapple") self.physicsBody = SKPhysicsBody(rectangleOf: size) self.physicsBody?.categoryBitMask = PhysicsCategory.Pineapple self.physicsBody?.contactTestBitMask = PhysicsCategory.Ninja self.physicsBody?.collisionBitMask = PhysicsCategory.Pineapple } override func update() { if (isRecovered && !isRecoveredOnce) { levelManager.switchCounter -= 1 if (levelManager.switchCounter == 0) { levelManager.switchAction() } isRecoveredOnce = true } } required init?(coder aDecoder: NSCoder) { // Decoding length here would be nice... super.init(coder: aDecoder) } }
mit
f0b2bee21652c9dda4c0b0f79d13e7f0
23.886364
70
0.604566
4.620253
false
false
false
false
lesspass/lesspass
mobile/ios/LessPassModule.swift
2
4719
import Foundation enum HMACAlgorithm { case MD5, SHA1, SHA224, SHA256, SHA384, SHA512 func toCCHmacAlgorithm() -> CCHmacAlgorithm { var result: Int = 0 switch self { case .MD5: result = kCCHmacAlgMD5 case .SHA1: result = kCCHmacAlgSHA1 case .SHA224: result = kCCHmacAlgSHA224 case .SHA256: result = kCCHmacAlgSHA256 case .SHA384: result = kCCHmacAlgSHA384 case .SHA512: result = kCCHmacAlgSHA512 } return CCHmacAlgorithm(result) } func digestLength() -> Int { var result: CInt = 0 switch self { case .MD5: result = CC_MD5_DIGEST_LENGTH case .SHA1: result = CC_SHA1_DIGEST_LENGTH case .SHA224: result = CC_SHA224_DIGEST_LENGTH case .SHA256: result = CC_SHA256_DIGEST_LENGTH case .SHA384: result = CC_SHA384_DIGEST_LENGTH case .SHA512: result = CC_SHA512_DIGEST_LENGTH } return Int(result) } } extension String { func hmac(algorithm: HMACAlgorithm, key: String) -> String { let cKey = key.cString(using: String.Encoding.utf8) let cData = self.cString(using: String.Encoding.utf8) var result = [CUnsignedChar](repeating: 0, count: Int(algorithm.digestLength())) CCHmac(algorithm.toCCHmacAlgorithm(), cKey!, Int(strlen(cKey!)), cData!, Int(strlen(cData!)), &result) let hmacData:NSData = NSData(bytes: result, length: (Int(algorithm.digestLength()))) var bytes = [UInt8](repeating:0, count: hmacData.length) hmacData.getBytes(&bytes, length: hmacData.length) var hexString = "" for byte in bytes { hexString += String(format:"%02hhx", UInt8(byte)) } return hexString } } extension Data { struct HexEncodingOptions: OptionSet { let rawValue: Int static let upperCase = HexEncodingOptions(rawValue: 1 << 0) } func hexEncodedString(options: HexEncodingOptions = []) -> String { let hexDigits = Array((options.contains(.upperCase) ? "0123456789ABCDEF" : "0123456789abcdef").utf16) var chars: [unichar] = [] chars.reserveCapacity(2 * count) for byte in self { chars.append(hexDigits[Int(byte / 16)]) chars.append(hexDigits[Int(byte % 16)]) } return String(utf16CodeUnits: chars, count: chars.count) } } func pbkdf2(hash: CCPBKDFAlgorithm, password: String, salt: String, keyByteCount: Int, rounds: Int) -> String? { guard let passwordData = password.data(using: .utf8), let saltData = salt.data(using: .utf8) else { return nil } var derivedKeyData = Data(repeating: 0, count: keyByteCount) let derivedCount = derivedKeyData.count let derivationStatus: Int32 = derivedKeyData.withUnsafeMutableBytes { derivedKeyBytes in let keyBuffer: UnsafeMutablePointer<UInt8> = derivedKeyBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) return saltData.withUnsafeBytes { saltBytes -> Int32 in let saltBuffer: UnsafePointer<UInt8> = saltBytes.baseAddress!.assumingMemoryBound(to: UInt8.self) return CCKeyDerivationPBKDF( CCPBKDFAlgorithm(kCCPBKDF2), password, passwordData.count, saltBuffer, saltData.count, hash, UInt32(rounds), keyBuffer, derivedCount) } } return derivationStatus == kCCSuccess ? derivedKeyData.hexEncodedString() : nil } @objc(LessPassModule) class LessPassModule: NSObject { @objc(createFingerprint:resolver:rejecter:) func createFingerprint(_ masterPassword: String, resolver resolve: RCTPromiseResolveBlock, rejecter reject:RCTPromiseRejectBlock) -> Void { resolve("".hmac(algorithm: HMACAlgorithm.SHA256, key: masterPassword)) } @objc(calcEntropy:withLogin:withMasterPassword:withCounter:resolver:rejecter:) func calcEntropy(_ site: String, withLogin login: String, withMasterPassword masterPassword: String, withCounter counter: String, resolver resolve: RCTPromiseResolveBlock, rejecter reject:RCTPromiseRejectBlock) -> Void { let salt = site + login + counter let r = pbkdf2(hash: CCPBKDFAlgorithm(kCCPRFHmacAlgSHA256), password: masterPassword, salt: salt, keyByteCount: 32, rounds: 100000) resolve(r) } @objc static func requiresMainQueueSetup() -> Bool { return false } }
gpl-3.0
6ffe5e3f36a05c0701dd11c44ae62925
35.022901
135
0.621318
4.381616
false
false
false
false
Jackysonglanlan/Scripts
swift/xunyou_accelerator/Sources/srcLibs/SwifterSwift/Foundation/FileManagerExtensions.swift
1
2161
// // FileManagerExtensions.swift // SwifterSwift // // Created by Jason Jon E. Carreos on 05/02/2018. // Copyright © 2018 SwifterSwift // #if canImport(Foundation) import Foundation public extension FileManager { /// SwifterSwift: Read from a JSON file at a given path. /// /// - Parameters: /// - path: JSON file path. /// - options: JSONSerialization reading options. /// - Returns: Optional dictionary. /// - Throws: Throws any errors thrown by Data creation or JSON serialization. public func jsonFromFile( atPath path: String, readingOptions: JSONSerialization.ReadingOptions = .allowFragments) throws -> [String: Any]? { let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) let json = try JSONSerialization.jsonObject(with: data, options: readingOptions) return json as? [String: Any] } /// SwifterSwift: Read from a JSON file with a given filename. /// /// - Parameters: /// - filename: File to read. /// - bundleClass: Bundle where the file is associated. /// - readingOptions: JSONSerialization reading options. /// - Returns: Optional dictionary. /// - Throws: Throws any errors thrown by Data creation or JSON serialization. public func jsonFromFile( withFilename filename: String, at bundleClass: AnyClass? = nil, readingOptions: JSONSerialization.ReadingOptions = .allowFragments) throws -> [String: Any]? { // https://stackoverflow.com/questions/24410881/reading-in-a-json-file-using-swift // To handle cases that provided filename has an extension let name = filename.components(separatedBy: ".")[0] let bundle = bundleClass != nil ? Bundle(for: bundleClass!) : Bundle.main if let path = bundle.path(forResource: name, ofType: "json") { let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) let json = try JSONSerialization.jsonObject(with: data, options: readingOptions) return json as? [String: Any] } return nil } } #endif
unlicense
4b493b6ce5c44d8ea71ab5485885ebb9
35
102
0.657407
4.547368
false
false
false
false
CoderQHao/Live
LiveSwift/LiveSwift/Classes/Live/Controller/RoomViewController.swift
1
1524
// // RoomViewController.swift // LiveSwift // // Created by 郝庆 on 2017/5/25. // Copyright © 2017年 Enroute. All rights reserved. // import UIKit class RoomViewController: UIViewController { @IBOutlet weak var bgImageView: UIImageView! var anchor: AnchorModel? override func viewDidLoad() { super.viewDidLoad() setupBlurView() } } // MARK:- 设置UI extension RoomViewController { fileprivate func setupBlurView() { let blur = UIBlurEffect(style: .dark) let blurView = UIVisualEffectView(effect: blur) blurView.autoresizingMask = [.flexibleHeight, .flexibleWidth] blurView.frame = bgImageView.bounds bgImageView.addSubview(blurView) } } // MARK:- 事件监听 extension RoomViewController: Emitterable { @IBAction func bottomMenuClick(_ sender: UIButton) { switch sender.tag { case 0: print("点击了聊天") case 1: print("点击了分享") case 2: print("点击了礼物") case 3: print("点击了更多") case 4: sender.isSelected = !sender.isSelected let point = CGPoint(x: sender.center.x, y: view.bounds.height - sender.bounds.height * 0.5) sender.isSelected ? startEmittering(point) : stopEmittering() default: fatalError("未处理按钮") } } @IBAction func dismiss() { dismiss(animated: true, completion: nil) } }
mit
6ad83b1369cf28176bba3d9abba4232c
23.25
103
0.602749
4.369369
false
false
false
false
CorlaOnline/AlamofireUIManager
Example/AlamofireUIManager/ViewController.swift
1
2764
// // ViewController.swift // AlamofireUIManager // // Created by Alex Corlatti on 06/03/2016. // Copyright (c) 2016 Alex Corlatti. All rights reserved. // import UIKit import AlamofireUIManager import SwiftyJSON import Alamofire class ViewController: UIViewController { @IBOutlet weak var resultLabel: UILabel! let netManager = AlamofireUIManager.sharedInstance override func viewDidLoad() { super.viewDidLoad() netManager.delegate = self let URL = Foundation.URL(string: "http://jsonplaceholder.typicode.com/posts/1")! var mutableURLRequest = URLRequest(url: URL) mutableURLRequest.httpMethod = HTTPMethod.get.rawValue netManager.request(mutableURLRequest, showError: false, completionHandler: { json in print(json) self.resultLabel.text = json["body"].stringValue }, errorHandler: { error in print("Error: \(String(describing: error))") self.manageAlertError(error, completition: { }) }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: AlamofireUIManagerDelegate { func createSpinner() -> UIView { let act = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 50, height: 50)) act.center = self.view.center act.style = .gray self.view.addSubview(act) act.startAnimating() return act } func closeSpinner(_ spinner: UIView?) { guard spinner != nil else { return } if let act = spinner as? UIActivityIndicatorView { act.stopAnimating() act.removeFromSuperview() } } func checkJson(_ json: JSON, showError: Bool, completionHandler: AFRequestCompletionHandler, errorHandler: AFRequestErrorHandler) { if let errorStr = json["error"]["message"].string { // Probably authorization required let error = NSError(domain: "json", code: 401, userInfo: ["info": errorStr]) errorHandler(error) } else { completionHandler(json) } } func manageAlertError(_ error: NSError?, completition: @escaping () -> ()) { let alertController = UIAlertController(title: "Error", message: error?.description, preferredStyle: .alert) let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { _ in self.netManager.closeAlert() completition() }) alertController.addAction(defaultAction) present(alertController, animated: true, completion: nil) } }
mit
950af374fb94b5d2cc9346fb99537704
23.034783
135
0.626628
4.998192
false
false
false
false
neonichu/Clock
Sources/Clock/ISO8601Writer.swift
1
891
#if os(Linux) import Glibc #else import Darwin #endif import Foundation private let GMT_STRING_SIZE = Int(strlen("1971-02-03T09:16:06Z") + 1) private func epochToISO8601GMTString(epoch : Int) -> String? { var epoch = epoch var time: UnsafeMutablePointer<tm> time = gmtime(&epoch) let buffer = UnsafeMutablePointer<Int8>.alloc(GMT_STRING_SIZE) strftime(buffer, GMT_STRING_SIZE, "%FT%TZ", time); return String.fromCString(buffer) } extension NSDate { /// Get an ISO8601 compatible string representation public func toISO8601GMTString() -> String? { let epoch = Int(self.timeIntervalSince1970) return epochToISO8601GMTString(epoch) } } extension tm { public func toISO8601GMTString() -> String? { var tm_struct = self let epoch = Int(timegm(&tm_struct)) return epochToISO8601GMTString(epoch) } }
mit
823d8f25470b8aff1d090be3d96d158d
24.457143
69
0.680135
3.636735
false
false
false
false
kdawgwilk/vapor
Sources/Vapor/Cookie/Cookie.swift
1
944
public struct Cookie { public var name: String public var value: String public var expires: String? public var maxAge: Int? public var domain: String? public var path: String? public var secure: Bool public var HTTPOnly: Bool public init( name: String, value: String, expires: String? = nil, maxAge: Int? = nil, domain: String? = nil, path: String? = nil, secure: Bool = false, HTTPOnly: Bool = false ) { self.name = name self.value = value self.expires = expires self.maxAge = maxAge self.domain = domain self.path = path self.secure = secure self.HTTPOnly = HTTPOnly } } extension Cookie: Hashable, Equatable { public var hashValue: Int { return name.hashValue } } public func ==(lhs: Cookie, rhs: Cookie) -> Bool { return lhs.name == rhs.name }
mit
9cde812aba43473c943bad46fbeb315e
22.02439
50
0.576271
4.176991
false
false
false
false
icapps/ios-delirium
Sources/Animations/Blurred Transition/ActionPresentationController.swift
1
3092
// // ActionPresentationController.swift // Runway // // Created by Jelle Vandebeeck on 02/01/16. // Copyright © 2016 Tracio. All rights reserved. // import UIKit @available(iOS 9, *) class ActionPresentationController: UIPresentationController { // This will be the overlay view that is presented on top // of the presening controller's view fileprivate var overlayView: UIView? // MARK: - Configuration var blurEffectStyle: UIBlurEffect.Style = .light // MARK: - Presentation override func presentationTransitionWillBegin() { let effect = UIBlurEffect(style: blurEffectStyle) overlayView = UIVisualEffectView(effect: effect) overlayView?.alpha = 0.0 overlayView?.translatesAutoresizingMaskIntoConstraints = false containerView?.addSubview(overlayView!) overlayView?.topAnchor.constraint(equalTo: (containerView?.topAnchor)!).isActive = true overlayView?.trailingAnchor.constraint(equalTo: (containerView?.trailingAnchor)!).isActive = true overlayView?.bottomAnchor.constraint(equalTo: (containerView?.bottomAnchor)!).isActive = true overlayView?.leadingAnchor.constraint(equalTo: (containerView?.leadingAnchor)!).isActive = true // Add a dismiss gesture tot the overlay view. let gesture = UITapGestureRecognizer(target: self, action: #selector(ActionPresentationController.dismiss(_:))) overlayView?.addGestureRecognizer(gesture) // Add the presented view to the heirarchy containerView?.addSubview(presentedViewController.view) let transitionCoordinator = self.presentingViewController.transitionCoordinator transitionCoordinator?.animate(alongsideTransition: {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.overlayView?.alpha = 0.7 }, completion:nil) } override var frameOfPresentedViewInContainerView : CGRect { let size = presentedViewController.view.intrinsicContentSize return CGRect(x: 0, y: 0, width: size.width, height: size.height) } override func presentationTransitionDidEnd(_ completed: Bool) { if !completed { overlayView?.removeFromSuperview() } } override func dismissalTransitionWillBegin() { // Fade out the overlay view alongside the transition let transitionCoordinator = self.presentingViewController.transitionCoordinator transitionCoordinator?.animate(alongsideTransition: {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.overlayView?.alpha = 0.0 }, completion:nil) } override func dismissalTransitionDidEnd(_ completed: Bool) { if completed { overlayView?.removeFromSuperview() } } // MARK: - Gestures @objc func dismiss(_ sender: AnyObject) { if !presentedViewController.resignFirstResponder() { presentingViewController.dismiss(animated: true, completion: nil) } } }
mit
93cdec74c72d4ffdf1b95a0ef91d1099
38.126582
128
0.692656
5.932821
false
false
false
false
vikingosegundo/TaCoPopulator
TaCoPopulator/Classes/SectionCellsFactory.swift
1
2583
// // Populator.swift // Populator // // Created by Manuel Meyer on 03.12.16. // Copyright © 2016 Manuel Meyer. All rights reserved. // import UIKit public protocol SectionCellsFactoryType { var provider: SectionDataProviderType { set get } func cellModels() -> [CellModelType] var sectionIndex:Int { get set } var elementsDidReload: (() -> Void)? { set get } static func == (left: SectionCellsFactoryType, right: SectionCellsFactoryType) -> Bool } extension SectionCellsFactoryType { public static func == (lhs: SectionCellsFactoryType, rhs: SectionCellsFactoryType) -> Bool { return lhs.sectionIndex == rhs.sectionIndex } } public struct CellConfigurationDescriptor<Element:Any, Cell: PopulatorViewCell> { public let element: Element public let cell: Cell public let indexPath: IndexPath } open class SectionCellsFactory<Element:Any, Cell: PopulatorViewCell>: SectionCellsFactoryType { public init(populatorView: PopulatorView, provider: SectionDataProvider<Element>, elementsDidReload:(() -> Void)? = nil ,cellConfigurator: @escaping ((CellConfigurationDescriptor<Element, Cell>) -> Cell)){ self.provider = provider self.populatorView = populatorView self.cellConfigurator = cellConfigurator if let elementsDidReload = elementsDidReload { self.elementsDidReload = elementsDidReload } else { self.elementsDidReload = { populatorView.reloadData() } } self.provider.elementsDidReload = { [weak self] in guard let `self` = self else { return } self.elementsDidReload?() } } open var provider: SectionDataProviderType open let cellConfigurator: ((CellConfigurationDescriptor<Element, Cell>) -> Cell) open var sectionIndex: Int = -1 fileprivate weak var populatorView: PopulatorView? open var elementsDidReload: (() -> Void)? open func cellModels() -> [CellModelType] { guard let realProvider = provider as? SectionDataProvider<Element> else { fatalError() } guard let _ = populatorView else { return [] } let models: [CellModel] = realProvider.elements().enumerated().map { offset, element in return CellModel(element: element, reuseIdentifier: realProvider.reuseIdentifer(element, IndexPath(row: offset, section: sectionIndex)), cellConfigurator: cellConfigurator) } return models } }
mit
166068c412b48beb1e2e085ba8f3934a
32.973684
202
0.658404
4.635548
false
true
false
false
e78l/swift-corelibs-foundation
Foundation/NotificationQueue.swift
2
7364
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // import CoreFoundation extension NotificationQueue { public enum PostingStyle : UInt { case whenIdle = 1 case asap = 2 case now = 3 } public struct NotificationCoalescing : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let none = NotificationCoalescing(rawValue: 0) public static let onName = NotificationCoalescing(rawValue: 1 << 0) public static let onSender = NotificationCoalescing(rawValue: 1 << 1) } } open class NotificationQueue: NSObject { internal typealias NotificationQueueList = NSMutableArray internal typealias NSNotificationListEntry = (Notification, [RunLoop.Mode]) // Notification ans list of modes the notification may be posted in. internal typealias NSNotificationList = [NSNotificationListEntry] // The list of notifications to post internal let notificationCenter: NotificationCenter internal var asapList = NSNotificationList() internal var idleList = NSNotificationList() internal lazy var idleRunloopObserver: CFRunLoopObserver = { return CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, CFOptionFlags(kCFRunLoopBeforeTimers), true, 0) {[weak self] observer, activity in self!.notifyQueues(.whenIdle) } }() internal lazy var asapRunloopObserver: CFRunLoopObserver = { return CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, CFOptionFlags(kCFRunLoopBeforeWaiting | kCFRunLoopExit), true, 0) {[weak self] observer, activity in self!.notifyQueues(.asap) } }() // The NSNotificationQueue instance is associated with current thread. // The _notificationQueueList represents a list of notification queues related to the current thread. private static var _notificationQueueList = NSThreadSpecific<NSMutableArray>() internal static var notificationQueueList: NotificationQueueList { return _notificationQueueList.get() { return NSMutableArray() } } // The default notification queue for the current thread. private static var _defaultQueue = NSThreadSpecific<NotificationQueue>() open class var `default`: NotificationQueue { return _defaultQueue.get() { return NotificationQueue(notificationCenter: NotificationCenter.default) } } public init(notificationCenter: NotificationCenter) { self.notificationCenter = notificationCenter super.init() NotificationQueue.registerQueue(self) } deinit { NotificationQueue.unregisterQueue(self) removeRunloopObserver(self.idleRunloopObserver) removeRunloopObserver(self.asapRunloopObserver) } open func enqueue(_ notification: Notification, postingStyle: PostingStyle) { enqueue(notification, postingStyle: postingStyle, coalesceMask: [.onName, .onSender], forModes: nil) } open func enqueue(_ notification: Notification, postingStyle: PostingStyle, coalesceMask: NotificationCoalescing, forModes modes: [RunLoop.Mode]?) { var runloopModes: [RunLoop.Mode] = [.default] if let modes = modes { runloopModes = modes } if !coalesceMask.isEmpty { self.dequeueNotifications(matching: notification, coalesceMask: coalesceMask) } switch postingStyle { case .now: let currentMode = RunLoop.current.currentMode if currentMode == nil || runloopModes.contains(currentMode!) { self.notificationCenter.post(notification) } case .asap: // post at the end of the current notification callout or timer addRunloopObserver(self.asapRunloopObserver) self.asapList.append((notification, runloopModes)) case .whenIdle: // wait until the runloop is idle, then post the notification addRunloopObserver(self.idleRunloopObserver) self.idleList.append((notification, runloopModes)) } } open func dequeueNotifications(matching notification: Notification, coalesceMask: NotificationCoalescing) { var predicate: (NSNotificationListEntry) -> Bool switch coalesceMask { case [.onName, .onSender]: predicate = { entry in return __SwiftValue.store(notification.object) !== __SwiftValue.store(entry.0.object) || notification.name != entry.0.name } case [.onName]: predicate = { entry in return notification.name != entry.0.name } case [.onSender]: predicate = { entry in return __SwiftValue.store(notification.object) !== __SwiftValue.store(entry.0.object) } default: return } self.asapList = self.asapList.filter(predicate) self.idleList = self.idleList.filter(predicate) } // MARK: Private private func addRunloopObserver(_ observer: CFRunLoopObserver) { CFRunLoopAddObserver(RunLoop.current._cfRunLoop, observer, kCFRunLoopDefaultMode) CFRunLoopAddObserver(RunLoop.current._cfRunLoop, observer, kCFRunLoopCommonModes) } private func removeRunloopObserver(_ observer: CFRunLoopObserver) { CFRunLoopRemoveObserver(RunLoop.current._cfRunLoop, observer, kCFRunLoopDefaultMode) CFRunLoopRemoveObserver(RunLoop.current._cfRunLoop, observer, kCFRunLoopCommonModes) } private func notify(_ currentMode: RunLoop.Mode?, notificationList: inout NSNotificationList) { for (idx, (notification, modes)) in notificationList.enumerated().reversed() { if currentMode == nil || modes.contains(currentMode!) { self.notificationCenter.post(notification) notificationList.remove(at: idx) } } } /** Gets queues from the notificationQueueList and posts all notification from the list related to the postingStyle parameter. */ private func notifyQueues(_ postingStyle: PostingStyle) { let currentMode = RunLoop.current.currentMode for queue in NotificationQueue.notificationQueueList { let notificationQueue = queue as! NotificationQueue if postingStyle == .whenIdle { notificationQueue.notify(currentMode, notificationList: &notificationQueue.idleList) } else { notificationQueue.notify(currentMode, notificationList: &notificationQueue.asapList) } } } private static func registerQueue(_ notificationQueue: NotificationQueue) { self.notificationQueueList.add(notificationQueue) } private static func unregisterQueue(_ notificationQueue: NotificationQueue) { guard self.notificationQueueList.index(of: notificationQueue) != NSNotFound else { return } self.notificationQueueList.remove(notificationQueue) } }
apache-2.0
e84c570d2ac144d3682d6303b8e9b5b5
40.370787
171
0.684954
5.454815
false
false
false
false
heitorgcosta/Quiver
Quiver/Validating/Default Validators/RangeValidator.swift
1
1806
// // RangeValidator.swift // Quiver // // Created by Heitor Costa on 19/09/17. // Copyright © 2017 Heitor Costa. All rights reserved. // class BetweenComparator<T>: Validator where T: Comparable { private var value1: T private var value2: T init(value1: T, value2: T) { self.value1 = value1 self.value2 = value2 } override func validate(with object: Any?) throws -> Bool { if object == nil { return true } guard let value = object! as? T else { throw ValidationErrorType.typeMismatch(expected: T.self, actual: type(of: object!)) } return value > self.value1 && value < self.value2 } } class RangeComparator<T>: Validator where T: Comparable { private var value1: T private var value2: T init(value1: T, value2: T) { self.value1 = value1 self.value2 = value2 } override func validate(with object: Any?) throws -> Bool { if object == nil { return true } guard let value = object! as? T else { throw ValidationErrorType.typeMismatch(expected: T.self, actual: type(of: object!)) } return value >= self.value1 && value <= self.value2 } } class RangeTypeValidator<R>: Validator where R: RangeExpression { var range: R init(range: R) { self.range = range } override func validate(with object: Any?) throws -> Bool { if object == nil { return true } guard let value = object! as? R.Bound else { throw ValidationErrorType.typeMismatch(expected: R.Bound.self, actual: type(of: object!)) } return range~=value } }
mit
690910ed822724993cb3bc78211dc44b
23.726027
101
0.560665
4.178241
false
false
false
false
ben-ng/swift
test/SILGen/dynamic.swift
2
23442
// RUN: rm -rf %t && mkdir -p %t // RUN: %build-silgen-test-overlays // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-silgen | %FileCheck %s // RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -emit-sil -verify // REQUIRES: objc_interop import Foundation import gizmo class Foo: Proto { // Not objc or dynamic, so only a vtable entry init(native: Int) {} func nativeMethod() {} var nativeProp: Int = 0 subscript(native native: Int) -> Int { get { return native } set {} } // @objc, so it has an ObjC entry point but can also be dispatched // by vtable @objc init(objc: Int) {} @objc func objcMethod() {} @objc var objcProp: Int = 0 @objc subscript(objc objc: AnyObject) -> Int { get { return 0 } set {} } // dynamic, so it has only an ObjC entry point dynamic init(dynamic: Int) {} dynamic func dynamicMethod() {} dynamic var dynamicProp: Int = 0 dynamic subscript(dynamic dynamic: Int) -> Int { get { return dynamic } set {} } func overriddenByDynamic() {} @NSManaged var managedProp: Int } protocol Proto { func nativeMethod() var nativeProp: Int { get set } subscript(native native: Int) -> Int { get set } func objcMethod() var objcProp: Int { get set } subscript(objc objc: AnyObject) -> Int { get set } func dynamicMethod() var dynamicProp: Int { get set } subscript(dynamic dynamic: Int) -> Int { get set } } // ObjC entry points for @objc and dynamic entry points // normal and @objc initializing ctors can be statically dispatched // CHECK-LABEL: sil hidden @_TFC7dynamic3FooC // CHECK: function_ref @_TFC7dynamic3Fooc // CHECK-LABEL: sil hidden @_TFC7dynamic3FooC // CHECK: function_ref @_TFC7dynamic3Fooc // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Fooc // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foo10objcMethod // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foog8objcPropSi // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foos8objcPropSi // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si // TODO: dynamic initializing ctor must be objc dispatched // CHECK-LABEL: sil hidden @_TFC7dynamic3FooC // CHECK: function_ref @_TTDFC7dynamic3Fooc // CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Fooc // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.init!initializer.1.foreign : // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Fooc // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foo13dynamicMethod // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foog11dynamicPropSi // CHECK-LABEL: sil hidden [transparent] [thunk] @_TToFC7dynamic3Foos11dynamicPropSi // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foog9subscriptFT7dynamicSi_Si // CHECK-LABEL: sil hidden [thunk] @_TToFC7dynamic3Foos9subscriptFT7dynamicSi_Si // Protocol witnesses use best appropriate dispatch // Native witnesses use vtable dispatch: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_12nativeMethod // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g10nativePropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s10nativePropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT6nativeSi_Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT6nativeSi_Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : // @objc witnesses use vtable dispatch: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_10objcMethod // CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g8objcPropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s8objcPropSi // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT4objcPs9AnyObject__Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT4objcPs9AnyObject__Si // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : // Dynamic witnesses use objc dispatch: // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_13dynamicMethod // CHECK: function_ref @_TTDFC7dynamic3Foo13dynamicMethod // CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foo13dynamicMethod // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g11dynamicPropSi // CHECK: function_ref @_TTDFC7dynamic3Foog11dynamicPropSi // CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foog11dynamicPropSi // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s11dynamicPropSi // CHECK: function_ref @_TTDFC7dynamic3Foos11dynamicPropSi // CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foos11dynamicPropSi // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_g9subscriptFT7dynamicSi_Si // CHECK: function_ref @_TTDFC7dynamic3Foog9subscriptFT7dynamicSi_Si // CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foog9subscriptFT7dynamicSi_Si // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign : // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC7dynamic3FooS_5ProtoS_FS1_s9subscriptFT7dynamicSi_Si // CHECK: function_ref @_TTDFC7dynamic3Foos9subscriptFT7dynamicSi_Si // CHECK-LABEL: sil shared [transparent] [thunk] @_TTDFC7dynamic3Foos9subscriptFT7dynamicSi_Si // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign : // Superclass dispatch class Subclass: Foo { // Native and objc methods can directly reference super members override init(native: Int) { super.init(native: native) } // CHECK-LABEL: sil hidden @_TFC7dynamic8SubclassC // CHECK: function_ref @_TFC7dynamic8Subclassc override func nativeMethod() { super.nativeMethod() } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass12nativeMethod // CHECK: function_ref @_TFC7dynamic3Foo12nativeMethodfT_T_ : $@convention(method) (@guaranteed Foo) -> () override var nativeProp: Int { get { return super.nativeProp } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg10nativePropSi // CHECK: function_ref @_TFC7dynamic3Foog10nativePropSi : $@convention(method) (@guaranteed Foo) -> Int set { super.nativeProp = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss10nativePropSi // CHECK: function_ref @_TFC7dynamic3Foos10nativePropSi : $@convention(method) (Int, @guaranteed Foo) -> () } override subscript(native native: Int) -> Int { get { return super[native: native] } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT6nativeSi_Si // CHECK: function_ref @_TFC7dynamic3Foog9subscriptFT6nativeSi_Si : $@convention(method) (Int, @guaranteed Foo) -> Int set { super[native: native] = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT6nativeSi_Si // CHECK: function_ref @_TFC7dynamic3Foos9subscriptFT6nativeSi_Si : $@convention(method) (Int, Int, @guaranteed Foo) -> () } override init(objc: Int) { super.init(objc: objc) } // CHECK-LABEL: sil hidden @_TFC7dynamic8SubclasscfT4objcSi_S0_ // CHECK: function_ref @_TFC7dynamic3FoocfT4objcSi_S0_ : $@convention(method) (Int, @owned Foo) -> @owned Foo override func objcMethod() { super.objcMethod() } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass10objcMethod // CHECK: function_ref @_TFC7dynamic3Foo10objcMethodfT_T_ : $@convention(method) (@guaranteed Foo) -> () override var objcProp: Int { get { return super.objcProp } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg8objcPropSi // CHECK: function_ref @_TFC7dynamic3Foog8objcPropSi : $@convention(method) (@guaranteed Foo) -> Int set { super.objcProp = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss8objcPropSi // CHECK: function_ref @_TFC7dynamic3Foos8objcPropSi : $@convention(method) (Int, @guaranteed Foo) -> () } override subscript(objc objc: AnyObject) -> Int { get { return super[objc: objc] } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT4objcPs9AnyObject__Si // CHECK: function_ref @_TFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si : $@convention(method) (@owned AnyObject, @guaranteed Foo) -> Int set { super[objc: objc] = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT4objcPs9AnyObject__Si // CHECK: function_ref @_TFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si : $@convention(method) (Int, @owned AnyObject, @guaranteed Foo) -> () } // Dynamic methods are super-dispatched by objc_msgSend override init(dynamic: Int) { super.init(dynamic: dynamic) } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassc // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.init!initializer.1.foreign : override func dynamicMethod() { super.dynamicMethod() } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclass13dynamicMethod // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicMethod!1.foreign : override var dynamicProp: Int { get { return super.dynamicProp } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg11dynamicPropSi // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!getter.1.foreign : set { super.dynamicProp = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss11dynamicPropSi // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.dynamicProp!setter.1.foreign : } override subscript(dynamic dynamic: Int) -> Int { get { return super[dynamic: dynamic] } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclassg9subscriptFT7dynamicSi_Si // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!getter.1.foreign : set { super[dynamic: dynamic] = newValue } // CHECK-LABEL: sil hidden @_TFC7dynamic8Subclasss9subscriptFT7dynamicSi_Si // CHECK: super_method [volatile] {{%.*}} : $Subclass, #Foo.subscript!setter.1.foreign : } dynamic override func overriddenByDynamic() {} } // CHECK-LABEL: sil hidden @_TF7dynamic20nativeMethodDispatchFT_T_ : $@convention(thin) () -> () func nativeMethodDispatch() { // CHECK: function_ref @_TFC7dynamic3FooC let c = Foo(native: 0) // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 : c.nativeMethod() // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 : let x = c.nativeProp // CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 : c.nativeProp = x // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : let y = c[native: 0] // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : c[native: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic18objcMethodDispatchFT_T_ : $@convention(thin) () -> () func objcMethodDispatch() { // CHECK: function_ref @_TFC7dynamic3FooC let c = Foo(objc: 0) // CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 : c.objcMethod() // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 : let x = c.objcProp // CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 : c.objcProp = x // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 : let y = c[objc: 0 as NSNumber] // CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 : c[objc: 0 as NSNumber] = y } // CHECK-LABEL: sil hidden @_TF7dynamic21dynamicMethodDispatchFT_T_ : $@convention(thin) () -> () func dynamicMethodDispatch() { // CHECK: function_ref @_TFC7dynamic3FooC let c = Foo(dynamic: 0) // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign c.dynamicMethod() // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign let x = c.dynamicProp // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign c.dynamicProp = x // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign let y = c[dynamic: 0] // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign c[dynamic: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic15managedDispatchFCS_3FooT_ func managedDispatch(_ c: Foo) { // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!getter.1.foreign let x = c.managedProp // CHECK: class_method [volatile] {{%.*}} : $Foo, #Foo.managedProp!setter.1.foreign c.managedProp = x } // CHECK-LABEL: sil hidden @_TF7dynamic21foreignMethodDispatchFT_T_ func foreignMethodDispatch() { // CHECK: function_ref @_TFCSo9GuisemeauC let g = Guisemeau()! // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.frob!1.foreign g.frob() // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!getter.1.foreign let x = g.count // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.count!setter.1.foreign g.count = x // CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!getter.1.foreign let y: Any! = g[0] // CHECK: class_method [volatile] {{%.*}} : $Guisemeau, #Guisemeau.subscript!setter.1.foreign g[0] = y // CHECK: class_method [volatile] {{%.*}} : $NSObject, #NSObject.description!getter.1.foreign _ = g.description } extension Gizmo { // CHECK-LABEL: sil hidden @_TFE7dynamicCSo5Gizmoc // CHECK: class_method [volatile] {{%.*}} : $Gizmo, #Gizmo.init!initializer.1.foreign convenience init(convenienceInExtension: Int) { self.init(bellsOn: convenienceInExtension) } // CHECK-LABEL: sil hidden @_TFE7dynamicCSo5GizmoC // CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign convenience init(foreignClassFactory x: Int) { self.init(stuff: x) } // CHECK-LABEL: sil hidden @_TFE7dynamicCSo5GizmoC // CHECK: class_method [volatile] {{%.*}} : $@thick Gizmo.Type, #Gizmo.init!allocator.1.foreign convenience init(foreignClassExactFactory x: Int) { self.init(exactlyStuff: x) } @objc func foreignObjCExtension() { } dynamic func foreignDynamicExtension() { } } // CHECK-LABEL: sil hidden @_TF7dynamic24foreignExtensionDispatchFCSo5GizmoT_ func foreignExtensionDispatch(_ g: Gizmo) { // CHECK: class_method [volatile] %0 : $Gizmo, #Gizmo.foreignObjCExtension!1.foreign : (Gizmo) g.foreignObjCExtension() // CHECK: class_method [volatile] %0 : $Gizmo, #Gizmo.foreignDynamicExtension!1.foreign g.foreignDynamicExtension() } // CHECK-LABEL: sil hidden @_TF7dynamic33nativeMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> () func nativeMethodDispatchFromOtherFile() { // CHECK: function_ref @_TFC7dynamic13FromOtherFileC let c = FromOtherFile(native: 0) // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeMethod!1 : c.nativeMethod() // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!getter.1 : let x = c.nativeProp // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!setter.1 : c.nativeProp = x // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 : let y = c[native: 0] // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 : c[native: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic31objcMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> () func objcMethodDispatchFromOtherFile() { // CHECK: function_ref @_TFC7dynamic13FromOtherFileC let c = FromOtherFile(objc: 0) // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcMethod!1 : c.objcMethod() // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!getter.1 : let x = c.objcProp // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!setter.1 : c.objcProp = x // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 : let y = c[objc: 0] // CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 : c[objc: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic34dynamicMethodDispatchFromOtherFileFT_T_ : $@convention(thin) () -> () func dynamicMethodDispatchFromOtherFile() { // CHECK: function_ref @_TFC7dynamic13FromOtherFileC let c = FromOtherFile(dynamic: 0) // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicMethod!1.foreign c.dynamicMethod() // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!getter.1.foreign let x = c.dynamicProp // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!setter.1.foreign c.dynamicProp = x // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1.foreign let y = c[dynamic: 0] // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1.foreign c[dynamic: 0] = y } // CHECK-LABEL: sil hidden @_TF7dynamic28managedDispatchFromOtherFileFCS_13FromOtherFileT_ func managedDispatchFromOtherFile(_ c: FromOtherFile) { // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!getter.1.foreign let x = c.managedProp // CHECK: class_method [volatile] {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!setter.1.foreign c.managedProp = x } // CHECK-LABEL: sil hidden @_TF7dynamic23dynamicExtensionMethodsFCS_13ObjCOtherFileT_ func dynamicExtensionMethods(_ obj: ObjCOtherFile) { // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionMethod!1.foreign obj.extensionMethod() // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionProp!getter.1.foreign _ = obj.extensionProp // CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.extensionClassProp!getter.1.foreign // CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type _ = type(of: obj).extensionClassProp // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionMethod!1.foreign obj.dynExtensionMethod() // CHECK: class_method [volatile] {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionProp!getter.1.foreign _ = obj.dynExtensionProp // CHECK: class_method [volatile] {{%.*}} : $@thick ObjCOtherFile.Type, #ObjCOtherFile.dynExtensionClassProp!getter.1.foreign // CHECK-NEXT: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type _ = type(of: obj).dynExtensionClassProp } public class Base { dynamic var x: Bool { return false } } public class Sub : Base { // CHECK-LABEL: sil hidden @_TFC7dynamic3Subg1xSb : $@convention(method) (@guaranteed Sub) -> Bool { // CHECK: bb0([[SELF:%.*]] : $Sub): // CHECK: [[AUTOCLOSURE:%.*]] = function_ref @_TFFC7dynamic3Subg1xSbu_KzT_Sb : $@convention(thin) (@owned Sub) -> (Bool, @error Error) // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: = partial_apply [[AUTOCLOSURE]]([[SELF_COPY]]) // CHECK: return {{%.*}} : $Bool // CHECK: } // end sil function '_TFC7dynamic3Subg1xSb' // CHECK-LABEL: sil shared [transparent] @_TFFC7dynamic3Subg1xSbu_KzT_Sb : $@convention(thin) (@owned Sub) -> (Bool, @error Error) { // CHECK: bb0([[VALUE:%.*]] : $Sub): // CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]] // CHECK: [[CASTED_VALUE_COPY:%.*]] = upcast [[VALUE_COPY]] // CHECK: [[SUPER:%.*]] = super_method [volatile] [[VALUE_COPY]] : $Sub, #Base.x!getter.1.foreign : (Base) -> () -> Bool , $@convention(objc_method) (Base) -> ObjCBool // CHECK: = apply [[SUPER]]([[CASTED_VALUE_COPY]]) // CHECK: destroy_value [[VALUE_COPY]] // CHECK: destroy_value [[VALUE]] // CHECK: } // end sil function '_TFFC7dynamic3Subg1xSbu_KzT_Sb' override var x: Bool { return false || super.x } } // Vtable contains entries for native and @objc methods, but not dynamic ones // CHECK-LABEL: sil_vtable Foo { // CHECK-LABEL: #Foo.init!initializer.1: _TFC7dynamic3Fooc // CHECK-LABEL: #Foo.nativeMethod!1: _TFC7dynamic3Foo12nativeMethod // CHECK-LABEL: #Foo.subscript!getter.1: _TFC7dynamic3Foog9subscriptFT6nativeSi_Si // dynamic.Foo.subscript.getter : (native : Swift.Int) -> Swift.Int // CHECK-LABEL: #Foo.subscript!setter.1: _TFC7dynamic3Foos9subscriptFT6nativeSi_Si // dynamic.Foo.subscript.setter : (native : Swift.Int) -> Swift.Int // CHECK-LABEL: #Foo.init!initializer.1: _TFC7dynamic3Fooc // CHECK-LABEL: #Foo.objcMethod!1: _TFC7dynamic3Foo10objcMethod // CHECK-LABEL: #Foo.subscript!getter.1: _TFC7dynamic3Foog9subscriptFT4objcPs9AnyObject__Si // dynamic.Foo.subscript.getter : (objc : Swift.AnyObject) -> Swift.Int // CHECK-LABEL: #Foo.subscript!setter.1: _TFC7dynamic3Foos9subscriptFT4objcPs9AnyObject__Si // dynamic.Foo.subscript.setter : (objc : Swift.AnyObject) -> Swift.Int // CHECK-NOT: dynamic.Foo.init (dynamic.Foo.Type)(dynamic : Swift.Int) -> dynamic.Foo // CHECK-NOT: dynamic.Foo.dynamicMethod // CHECK-NOT: dynamic.Foo.subscript.getter (dynamic : Swift.Int) -> Swift.Int // CHECK-NOT: dynamic.Foo.subscript.setter (dynamic : Swift.Int) -> Swift.Int // CHECK-LABEL: #Foo.overriddenByDynamic!1: _TFC7dynamic3Foo19overriddenByDynamic // CHECK-LABEL: #Foo.nativeProp!getter.1: _TFC7dynamic3Foog10nativePropSi // dynamic.Foo.nativeProp.getter : Swift.Int // CHECK-LABEL: #Foo.nativeProp!setter.1: _TFC7dynamic3Foos10nativePropSi // dynamic.Foo.nativeProp.setter : Swift.Int // CHECK-LABEL: #Foo.objcProp!getter.1: _TFC7dynamic3Foog8objcPropSi // dynamic.Foo.objcProp.getter : Swift.Int // CHECK-LABEL: #Foo.objcProp!setter.1: _TFC7dynamic3Foos8objcPropSi // dynamic.Foo.objcProp.setter : Swift.Int // CHECK-NOT: dynamic.Foo.dynamicProp.getter // CHECK-NOT: dynamic.Foo.dynamicProp.setter // Vtable uses a dynamic thunk for dynamic overrides // CHECK-LABEL: sil_vtable Subclass { // CHECK-LABEL: #Foo.overriddenByDynamic!1: _TTDFC7dynamic8Subclass19overriddenByDynamic
apache-2.0
5cd65019c08ec6a91074d81c8e07b656
48.560254
173
0.68983
3.603689
false
false
false
false
anasmeister/nRF-Coventry-University
Pods/iOSDFULibrary/iOSDFULibrary/Classes/Implementation/DFUServiceInitiator.swift
1
12686
/* * Copyright (c) 2016, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder 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 CoreBluetooth /** The DFUServiceInitiator object should be used to send a firmware update to a remote BLE target compatible with the Nordic Semiconductor's DFU (Device Firmware Update). A `delegate`, `progressDelegate` and `logger` may be specified in order to receive status information. */ @objc public class DFUServiceInitiator : NSObject { //MARK: - Internal variables internal let centralManager : CBCentralManager internal let target : CBPeripheral internal var file : DFUFirmware? //MARK: - Public variables /** The service delegate is an object that will be notified about state changes of the DFU Service. Setting it is optional but recommended. */ public weak var delegate: DFUServiceDelegate? /** An optional progress delegate will be called only during upload. It notifies about current upload percentage and speed. */ public weak var progressDelegate: DFUProgressDelegate? /** The logger is an object that should print given messages to the user. It is optional. */ public weak var logger: LoggerDelegate? /** The selector object is used when the device needs to disconnect and start advertising with a different address to avodi caching problems, for example after switching to the Bootloader mode, or during sending a firmware containing a Softdevice (or Softdevice and Bootloader) and the Application. After flashing the first part (containing the Softdevice), the device restarts in the DFU Bootloader mode and may (since SDK 8.0.0) start advertising with an address incremented by 1. The peripheral specified in the `init` may no longer be used as there is no device advertising with its address. The DFU Service will scan for a new device and connect to the first device returned by the selector. The default selecter returns the first device with the required DFU Service UUID in the advertising packet (Secure or Legacy DFU Service UUID). Ignore this property if not updating Softdevice and Application from one ZIP file or your */ public var peripheralSelector: DFUPeripheralSelectorDelegate /** The number of packets of firmware data to be received by the DFU target before sending a new Packet Receipt Notification. If this value is 0, the packet receipt notification will be disabled by the DFU target. Default value is 12. Higher values (~20+), or disabling it, may speed up the upload process, but also cause a buffer overflow and hang the Bluetooth adapter. Maximum verified values were 29 for iPhone 6 Plus or 22 for iPhone 7, both iOS 10.1. */ public var packetReceiptNotificationParameter: UInt16 = 12 /** **Legacy DFU only.** Setting this property to true will prevent from jumping to the DFU Bootloader mode in case there is no DFU Version characteristic. Use it if the DFU operation can be handled by your device running in the application mode. If the DFU Version characteristic exists, the information whether to begin DFU operation, or jump to bootloader, is taken from the characteristic's value. The value returned equal to 0x0100 (read as: minor=1, major=0, or version 0.1) means that the device is in the application mode and buttonless jump to DFU Bootloader is supported. Currently, the following values of the DFU Version characteristic are supported: **No DFU Version characteristic** - one of the first implementations of DFU Service. The device may support only Application update (version from SDK 4.3.0), may support Soft Device, Bootloader and Application update but without buttonless jump to bootloader (SDK 6.0.0) or with buttonless jump (SDK 6.1.0). The DFU Library determines whether the device is in application mode or in DFU Bootloader mode by counting number of services: if no DFU Service found - device is in app mode and does not support buttonless jump, if the DFU Service is the only service found (except General Access and General Attribute services) - it assumes it is in DFU Bootloader mode and may start DFU immediately, if there is at least one service except DFU Service - the device is in application mode and supports buttonless jump. In the lase case, you want to perform DFU operation without jumping - call the setForceDfu(force:Bool) method with parameter equal to true. **0.1** - Device is in a mode that supports buttonless jump to the DFU Bootloader **0.5** - Device can handle DFU operation. Extended Init packet is required. Bond information is lost in the bootloader mode and after updating an app. Released in SDK 7.0.0. **0.6** - Bond information is kept in bootloader mode and may be kept after updating application (DFU Bootloader must be configured to preserve the bond information). **0.7** - The SHA-256 firmware hash is used in the Extended Init Packet instead of CRC-16. This feature is transparent for the DFU Service. **0.8** - The Extended Init Packet is signed using the private key. The bootloader, using the public key, is able to verify the content. Released in SDK 9.0.0 as experimental feature. Caution! The firmware type (Application, Bootloader, SoftDevice or SoftDevice+Bootloader) is not encrypted as it is not a part of the Extended Init Packet. A change in the protocol will be required to fix this issue. By default the DFU Library will try to switch the device to the DFU Bootloader mode if it finds more services then one (DFU Service). It assumes it is already in the bootloader mode if the only service found is the DFU Service. Setting the forceDfu to true (YES) will prevent from jumping in these both cases. */ public var forceDfu = false /** Set this flag to true to enable experimental buttonless feature in Secure DFU. When the experimental Buttonless DFU Service is found on a device, the service will use it to switch the device to the bootloader mode, connect to it in that mode and proceed with DFU. **Please, read the information below before setting it to true.** In the SDK 12.x the Buttonless DFU feature for Secure DFU was experimental. It is NOT recommended to use it: it was not properly tested, had implementation bugs (e.g. https://devzone.nordicsemi.com/question/100609/sdk-12-bootloader-erased-after-programming/) and does not required encryption and therefore may lead to DOS attack (anyone can use it to switch the device to bootloader mode). However, as there is no other way to trigger bootloader mode on devices without a button, this DFU Library supports this service, but the feature must be explicitly enabled here. Be aware, that setting this flag to false will no protect your devices from this kind of attacks, as an attacker may use another app for that purpose. To be sure your device is secure remove this experimental service from your device. Spec: Buttonless DFU Service UUID: 8E400001-F315-4F60-9FB8-838830DAEA50 Buttonless DFU characteristic UUID: 8E400001-F315-4F60-9FB8-838830DAEA50 (the same) Enter Bootloader Op Code: 0x01 Correct return value: 0x20-01-01 , where: 0x20 - Response Op Code 0x01 - Request Code 0x01 - Success The device should disconnect and restart in DFU mode after sending the notification. In SDK 13 this issue will be fixed by a proper implementation (bonding required, passing bond information to the bootloader, encryption, well tested). It is recommended to use this new service when SDK 13 (or later) is out. TODO: fix the docs when SDK 13 is out. */ public var enableUnsafeExperimentalButtonlessServiceInSecureDfu = false //MARK: - Public API /** Creates the DFUServiceInitializer that will allow to send an update to the given peripheral. The peripheral should be disconnected prior to calling start() method. The DFU service will automatically connect to the device, check if it has required DFU service (return a delegate callback if does not have such), jump to the DFU Bootloader mode if necessary and perform the DFU. Proper delegate methods will be called during the process. - parameter central manager that will be used to connect to the peripheral - parameter target: the DFU target peripheral - returns: the initiator instance - seeAlso: peripheralSelector property - a selector used when scanning for a device in DFU Bootloader mode in case you want to update a Softdevice and Application from a single ZIP Distribution Packet. */ public init(centralManager: CBCentralManager, target: CBPeripheral) { self.centralManager = centralManager // Just to be sure that manager is not scanning self.centralManager.stopScan() self.target = target // Default peripheral selector will choose the service UUID as a filter self.peripheralSelector = DFUPeripheralSelector() super.init() } /** Sets the file with the firmware. The file must be specified before calling `start()` method, and must not be nil. - parameter file: The firmware wrapper object - returns: the initiator instance to allow chain use */ public func with(firmware file: DFUFirmware) -> DFUServiceInitiator { self.file = file return self } /** Starts sending the specified firmware to the DFU target. When started, the service will automatically connect to the target, switch to DFU Bootloader mode (if necessary), and send all the content of the specified firmware file in one or two connections. Two connections will be used if a ZIP file contains a Soft Device and/or Bootloader and an Application. First the Soft Device and/or Bootloader will be transferred, then the service will disconnect, reconnect to the (new) Bootloader again and send the Application (unless the target supports receiving all files in a single connection). The current version of the DFU Bootloader, due to memory limitations, may receive together only a Softdevice and Bootloader. - returns: A DFUServiceController object that can be used to control the DFU operation. */ public func start() -> DFUServiceController? { // The firmware file must be specified before calling `start()` if file == nil { delegate?.dfuError(.fileNotSpecified, didOccurWithMessage: "Firmare not specified") return nil } let controller = DFUServiceController() let selector = DFUServiceSelector(initiator: self, controller: controller) controller.executor = selector selector.start() return controller } }
bsd-3-clause
d0bfb455ce8b464d5119f03ea42473f5
52.754237
145
0.724972
5.082532
false
false
false
false
katsumeshi/PhotoInfo
PhotoInfo/Review.swift
1
2162
// // Review.swift // photoinfo // // Created by Yuki Matsushita on 12/20/15. // Copyright © 2015 Yuki Matsushita. All rights reserved. // import Foundation import UIKit class Review { static let reviewUrl = NSURL(string: "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=998243965&mt=8&type=Purple+Software")! private static let showCount = 5 private static let reviewKey = "reviewed" private static var visitCount:Int { get { let count = NSUserDefaults.standardUserDefaults().valueForKey(Review.reviewKey) if count != nil { return (count as! NSNumber).integerValue } else { return 1 } } } static func showAfterInterval() { if Review.visitCount >= 0 { if (Review.visitCount % Review.showCount) == 0 { Review.show() } NSUserDefaults.standardUserDefaults().setValue(NSNumber(integer:Review.visitCount + 1), forKey: Review.reviewKey) } } private static func show() { let optionMenu = UIAlertController(title: "Review the app, please".toGrobal(), message: "Thank you for using the app:) Review tha app for updating the next feature".toGrobal(), preferredStyle: .Alert) let reviewAction = UIAlertAction(title: "Review due to satisfied".toGrobal(), style: .Default) { _ in NSUserDefaults.standardUserDefaults().setValue(NSNumber(integer: -1), forKey: Review.reviewKey) UIApplication.sharedApplication().openURL(Review.reviewUrl) } let noAction = UIAlertAction(title: "Don't review due to unsatisfied".toGrobal(), style: .Default) { _ in NSUserDefaults.standardUserDefaults().setValue(NSNumber(integer: -1), forKey: Review.reviewKey) } let laterAction = UIAlertAction(title: "Review later".toGrobal(), style: .Default, handler: nil) optionMenu.addAction(reviewAction) optionMenu.addAction(noAction) optionMenu.addAction(laterAction) let rootViewController = UIApplication.sharedApplication().windows.first?.rootViewController rootViewController!.presentViewController(optionMenu, animated: true, completion: nil) } }
mit
ed850e4eade23dcbcb06b8e70a56921c
33.854839
204
0.697825
4.262327
false
false
false
false
ithree1113/Note_DEMO
Note_DEMO/AppDelegate.swift
1
4595
// // AppDelegate.swift // Note_DEMO // // Created by 鄭宇翔 on 2016/11/18. // Copyright © 2016年 鄭宇翔. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Note_DEMO") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
75e9a9135d24b2532e537950d8dbd091
48.247312
285
0.684934
5.761006
false
false
false
false
adrfer/swift
test/Constraints/assignment.swift
2
1279
// RUN: %target-parse-verify-swift struct X { } struct Y { } struct WithOverloadedSubscript { subscript(i: Int) -> X { get {} set {} } subscript(i: Int) -> Y { get {} set {} } } func test_assign() { var a = WithOverloadedSubscript() a[0] = X() a[0] = Y() } var i: X var j: X var f: Y func getXY() -> (X, Y) {} var ift : (X, Y) var ovl = WithOverloadedSubscript() var slice: [X] i = j (i, f) = getXY() (i, f) = ift (i, f) = (i, f) (ovl[0], ovl[0]) = ift (ovl[0], ovl[0]) = (i, f) (_, ovl[0]) = (i, f) (ovl[0], _) = (i, f) _ = (i, f) slice[7] = i slice[7] = f // expected-error{{cannot assign value of type 'Y' to type 'X'}} slice[7] = _ // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} func value(x: Int) {} func value2(inout x: Int) {} value2(&_) // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} value(_) // expected-error{{'_' can only appear in a pattern or on the left side of an assignment}} // <rdar://problem/23798944> = vs. == in Swift if string character count statement causes segmentation fault func f23798944() { let s = "" if s.characters.count = 0 { // expected-error {{cannot assign to property: 'count' is a get-only property}} } }
apache-2.0
62813f53913633531ef68400678bffb2
20.677966
109
0.592651
2.810989
false
false
false
false
authme-org/authme
authme-iphone/AuthMeTests/CryptoTests.swift
1
4348
/* * * Copyright 2015 Berin Lautenbach * * 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. * */ // // CryptoTests.swift // AuthMe // // Created by Berin Lautenbach on 25/02/2015. // Copyright (c) 2015 Berin Lautenbach. All rights reserved. // import Foundation import UIKit import XCTest class CryptoTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testBase64() { // Base64 test vectors let inputTest1 = "foob" let outputTest1 = "Zm9vYg==" let inputTest2 = "fooba" let outputTest2 = "Zm9vYmE=" let inputTest3 = "foobar" let outputTest3 = "Zm9vYmFy" let b64 = Base64() // Encode tests let resultTest1 = b64.base64encode(inputTest1.data(using: String.Encoding.utf8, allowLossyConversion: false), length: Int32(inputTest1.lengthOfBytes(using: String.Encoding.utf8))) XCTAssertEqual(resultTest1! as String, outputTest1, "Test one in Base64 failed"); let resultTest2 = b64.base64encode(inputTest2.data(using: String.Encoding.utf8, allowLossyConversion: false), length: Int32(inputTest2.lengthOfBytes(using: String.Encoding.utf8))) XCTAssertEqual(resultTest2! as String, outputTest2, "Test two in Base64 failed"); let resultTest3 = b64.base64encode(inputTest3.data(using: String.Encoding.utf8, allowLossyConversion: false), length: Int32(inputTest3.lengthOfBytes(using: String.Encoding.utf8))) XCTAssertEqual(resultTest3! as String, outputTest3, "Test three in Base64 failed"); // decode tests let resultTest11 = b64.base64decode(outputTest1, length: Int32(outputTest1.lengthOfBytes(using: String.Encoding.utf8))) XCTAssertEqual(resultTest11! as Data, inputTest1.data(using: String.Encoding.utf8, allowLossyConversion: false)!, "Decode test 1 failed") let resultTest12 = b64.base64decode(outputTest2, length: Int32(outputTest2.lengthOfBytes(using: String.Encoding.utf8))) XCTAssertEqual(resultTest12! as Data, inputTest2.data(using: String.Encoding.utf8, allowLossyConversion: false)!, "Decode test 2 failed") let resultTest13 = b64.base64decode(outputTest3, length: Int32(outputTest3.lengthOfBytes(using: String.Encoding.utf8))) XCTAssertEqual(resultTest13! as Data, inputTest3.data(using: String.Encoding.utf8, allowLossyConversion: false)!, "Decode test 3 failed") } func testAES() { let raw = "The quick brown fox" let rawData = raw.data(using: String.Encoding.utf8, allowLossyConversion: true) XCTAssertNotNil(rawData, "rawData is nil") let rawLength = UInt(rawData!.count) let aes = AESKey() XCTAssertTrue(aes.generateKey(), "Error generating key") let b64 = Base64() let encrypted = aes.encrypt(rawData!, plainLength: size_t(rawLength)) let rawEncrypted = b64.base64decode(encrypted, length: Int32((encrypted?.lengthOfBytes(using: String.Encoding.utf8))!)) XCTAssertEqual(rawEncrypted?.length, 48, "Incorrect length of encrypted data") // Decrypt let decrypt = aes.decrypt(encrypted, cipherLength: size_t((encrypted?.lengthOfBytes(using: String.Encoding.utf8))!)) let decryptString = NSString(data: decrypt! as Data, encoding: String.Encoding.utf8.rawValue)! as String XCTAssertEqual(decryptString as String, raw, "Decrypt / Encrypt mismatch for AES") } func testPerformanceExample() { // This is an example of a performance test case. self.measure() { // Put the code you want to measure the time of here. } } }
apache-2.0
4d5f95a8be9fc8e9e54f3ca4e07c10a0
39.635514
187
0.672723
4.098021
false
true
false
false
nathantannar4/NTComponents
NTComponents/UI Kit/Alerts/NTPing.swift
1
4804
// // NTPing.swift // NTComponents // // Copyright © 2017 Nathan Tannar. // // 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. // // Created by Nathan Tannar on 5/17/17. // open class NTPing: NTView { fileprivate var statusBar: UIView? { get { return UIApplication.shared.value(forKey: "statusBar") as? UIView } } open var titleLabel: NTLabel = { let label = NTLabel(style: .title) label.font = Font.Default.Caption.withSize(12) label.textAlignment = .center label.adjustsFontSizeToFitWidth = true return label }() fileprivate var currentState: NTViewState = .hidden // MARK: - Initialization public convenience init(type: NTAlertType = NTAlertType.isInfo, title: String? = nil) { var bounds = UIScreen.main.bounds bounds.origin.y = bounds.height - 20 bounds.size.height = 20 self.init(frame: bounds) titleLabel.text = title switch type { case .isInfo: backgroundColor = Color.Default.Status.Info case .isSuccess: backgroundColor = Color.Default.Status.Success case .isWarning: backgroundColor = Color.Default.Status.Warning case .isDanger: backgroundColor = Color.Default.Status.Danger } if backgroundColor!.isDark { titleLabel.textColor = .white } } public convenience init(title: String? = nil, color: UIColor = Color.Default.Status.Info) { var bounds = UIScreen.main.bounds bounds.origin.y = bounds.height - 20 bounds.size.height = 20 self.init(frame: bounds) backgroundColor = color titleLabel.text = title if color.isDark { titleLabel.textColor = .white } } public override init(frame: CGRect) { super.init(frame: frame) addSubview(titleLabel) titleLabel.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 12, bottomConstant: 0, rightConstant: 12, widthConstant: 0, heightConstant: 0) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Presentation Methods open func show(duration: TimeInterval = 2) { guard let view = statusBar else { return } view.addSubview(self) frame = CGRect(x: 0, y: -view.frame.height, width: view.frame.width, height: self.frame.height) currentState = .transitioning UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveLinear, animations: { self.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: self.frame.height) }) { (finished) in self.currentState = .visible self.fillSuperview() DispatchQueue.executeAfter(duration, closure: { self.dismiss() }) } } open func dismiss() { if currentState != .visible { return } currentState = .transitioning UIView.transition(with: self, duration: 0.2, options: .curveLinear, animations: {() -> Void in self.frame.origin = CGPoint(x: 0, y: -self.frame.height) }, completion: { finished in self.currentState = .hidden self.removeFromSuperview() }) } open class func genericErrorMessage() { let ping = NTPing(type: .isDanger, title: "Sorry, an error occurred") ping.show() } }
mit
b2f1f115717300ede1d154e3df10638f
34.316176
205
0.623985
4.596172
false
false
false
false
KrishMunot/swift
stdlib/private/SwiftPrivatePthreadExtras/PthreadBarriers.swift
1
3622
//===--- PthreadBarriers.swift --------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) import Glibc #endif // // Implement pthread barriers. // // (OS X does not implement them.) // public struct _stdlib_pthread_barrierattr_t { public init() {} } public func _stdlib_pthread_barrierattr_init( _ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t> ) -> CInt { return 0 } public func _stdlib_pthread_barrierattr_destroy( _ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t> ) -> CInt { return 0 } public var _stdlib_PTHREAD_BARRIER_SERIAL_THREAD: CInt { return 1 } public struct _stdlib_pthread_barrier_t { var mutex: UnsafeMutablePointer<pthread_mutex_t> = nil var cond: UnsafeMutablePointer<pthread_cond_t> = nil /// The number of threads to synchronize. var count: CUnsignedInt = 0 /// The number of threads already waiting on the barrier. /// /// This shared variable is protected by `mutex`. var numThreadsWaiting: CUnsignedInt = 0 public init() {} } public func _stdlib_pthread_barrier_init( _ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t>, _ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t>, _ count: CUnsignedInt ) -> CInt { barrier.pointee = _stdlib_pthread_barrier_t() if count == 0 { errno = EINVAL return -1 } barrier.pointee.mutex = UnsafeMutablePointer(allocatingCapacity: 1) if pthread_mutex_init(barrier.pointee.mutex, nil) != 0 { // FIXME: leaking memory. return -1 } barrier.pointee.cond = UnsafeMutablePointer(allocatingCapacity: 1) if pthread_cond_init(barrier.pointee.cond, nil) != 0 { // FIXME: leaking memory, leaking a mutex. return -1 } barrier.pointee.count = count return 0 } public func _stdlib_pthread_barrier_destroy( _ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t> ) -> CInt { if pthread_cond_destroy(barrier.pointee.cond) != 0 { // FIXME: leaking memory, leaking a mutex. return -1 } if pthread_mutex_destroy(barrier.pointee.mutex) != 0 { // FIXME: leaking memory. return -1 } barrier.pointee.cond.deinitialize() barrier.pointee.cond.deallocateCapacity(1) barrier.pointee.mutex.deinitialize() barrier.pointee.mutex.deallocateCapacity(1) return 0 } public func _stdlib_pthread_barrier_wait( _ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t> ) -> CInt { if pthread_mutex_lock(barrier.pointee.mutex) != 0 { return -1 } barrier.pointee.numThreadsWaiting += 1 if barrier.pointee.numThreadsWaiting < barrier.pointee.count { // Put the thread to sleep. if pthread_cond_wait(barrier.pointee.cond, barrier.pointee.mutex) != 0 { return -1 } if pthread_mutex_unlock(barrier.pointee.mutex) != 0 { return -1 } return 0 } else { // Reset thread count. barrier.pointee.numThreadsWaiting = 0 // Wake up all threads. if pthread_cond_broadcast(barrier.pointee.cond) != 0 { return -1 } if pthread_mutex_unlock(barrier.pointee.mutex) != 0 { return -1 } return _stdlib_PTHREAD_BARRIER_SERIAL_THREAD } }
apache-2.0
35ff4d12a46d05d10b3be290ab76b289
26.648855
80
0.670348
3.873797
false
false
false
false
clrung/WMATAFetcher
WMATAFetcher/Train.swift
1
3956
// // Train.swift // // Copyright © 2016 Christopher Rung // // 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 SwiftyJSON /// Based on WMATA's definition of [IMPredictionTrainInfo](https://developer.wmata.com/docs/services/547636a6f9182302184cda78/operations/547636a6f918230da855363f/console#AIMPredictionTrainInfo). open class Train { /// The number of cars in the train open var numCars: String = "" /// The destination. Abbreviated destination is not used, and the destinationCode and destinationName can be determined by calling destination.rawValue and destination.description, respectively. open var destination: Station = Station.A01 /// The group open var group: String = "" /// The line color open var line: Line = Line.NO /// The current location of the train. The locationCode and locationName can be determined by calling location.rawValue and location.description, respectively. open var location: Station = Station.A01 /// The number of minutes until the train arrives at the station. open var min: String = "0" /// Constructor /// /// - Parameters: /// - numCars: the number of cars /// - destination: the destination Station /// - group: the group /// - line: the Line /// - location: the location Station of the Train /// - min: the estimated number of minutes until the Train arrives at the location required public init(numCars: String, destination: Station, group: String, line: Line, location: Station, min: String) { self.numCars = numCars self.destination = destination self.group = group self.line = line self.location = location self.min = min } /// Used to easily add a Station.Space object to the train array. static func initSpace() -> Train { return Train(numCars: "", destination: Station.Space, group: "-1", line: Line.NO, location: Station.Space, min: "") } /// Returns the value of each of the fields in Train. open var debugDescription: String { return "numCars: \(numCars)\t" + "destination: \(destination.description.padding(toLength: 30, withPad: " ", startingAt: 0))" + "group: \(group.padding(toLength: 3, withPad: " ", startingAt: 0))" + "line: \(line.rawValue)\t" + "location: \(location.rawValue)\t" + "min: \(min)" } } /// Stores the Train array and an error code. public struct TrainResponse { /// The array of Trains. `nil` when the call to `getPrediction()` is unsuccessful. public var trains: [Train]? /// The HTTP status code. `nil` when `getPrediction()` is successful. Common error codes: /// /// 1. -1009: The internet connection is offline /// 2. 403: Invalid request (likely a bad WMATA key) public var errorCode: Int? /// TrainResponse constructor /// /// - Parameters: /// - trains: the Train array /// - errorCode: the errorCode public init(trains: [Train]?, errorCode: Int?) { self.trains = trains self.errorCode = errorCode } }
mit
f7dff75039c66296965034b133fd0a58
40.631579
196
0.718584
3.784689
false
false
false
false
dfsilva/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/SwiftExtensions/Images.swift
4
17706
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import Darwin import UIKit import Accelerate public extension UIImage { class func tinted(_ named: String, color: UIColor) -> UIImage { return UIImage.bundled(named)!.tintImage(color) } class func templated(_ named: String) -> UIImage { return UIImage.bundled(named)!.withRenderingMode(.alwaysTemplate) } public func tintImage(_ color:UIColor) -> UIImage{ UIGraphicsBeginImageContextWithOptions(self.size,false,UIScreen.main.scale); var rect = CGRect.zero; rect.size = self.size; // Composite tint color at its own opacity. color.set(); UIRectFill(rect); // Mask tint color-swatch to this image's opaque mask. // We want behaviour like NSCompositeDestinationIn on Mac OS X. self.draw(in: rect, blendMode: .destinationIn, alpha: 1.0) let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if (self.capInsets.bottom != 0 || self.capInsets.top != 0 || self.capInsets.left != 0 || self.capInsets.right != 0) { return image!.resizableImage(withCapInsets: capInsets, resizingMode: resizingMode) } return image!.withRenderingMode(UIImageRenderingMode.alwaysOriginal) } public func tintBgImage(_ color: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size,false,UIScreen.main.scale); var rect = CGRect.zero; rect.size = self.size; // Composite tint color at its own opacity. color.set(); UIRectFill(rect); // Mask tint color-swatch to this image's opaque mask. // We want behaviour like NSCompositeDestinationIn on Mac OS X. self.draw(in: rect, blendMode: .overlay, alpha: 1.0) let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image! } public func roundImage(_ newSize: Int) -> UIImage { let nSize = CGSize(width: newSize, height: newSize) UIGraphicsBeginImageContextWithOptions(nSize,false,UIScreen.main.scale); let context = UIGraphicsGetCurrentContext(); // Background context?.addPath(CGPath(ellipseIn: CGRect(origin: CGPoint.zero, size: nSize),transform: nil)); context?.clip(); self.draw(in: CGRect(origin: CGPoint(x: -1, y: -1), size: CGSize(width: (newSize+2), height: (newSize+2)))); // Border context?.setStrokeColor(UIColor(red: 0, green: 0, blue: 0, alpha: 0x19/255.0).cgColor); // context?.addArc(CGFloat(newSize)/2, CGFloat(newSize)/2, CGFloat(newSize)/2, CGFloat(M_PI * 0), CGFloat(M_PI * 2), 0); context?.drawPath(using: .stroke); let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image!; } public func roundCorners(_ w: CGFloat, h: CGFloat, roundSize: CGFloat) -> UIImage { let nSize = CGSize(width: w, height: h) UIGraphicsBeginImageContextWithOptions(nSize, false, UIScreen.main.scale); // Background UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: w, height: h), cornerRadius: roundSize).addClip() self.draw(in: CGRect(origin: CGPoint(x: -1, y: -1), size: CGSize(width: (w+2), height: (h+2)))); let image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return image!; } public func resizeSquare(_ maxW: CGFloat, maxH: CGFloat) -> UIImage { let realW = self.size.width / self.scale; let realH = self.size.height / self.scale; let factor = min(maxW/realW, maxH/realH) return resize(factor * realW, h: factor * realH) } func resizeOptimize(_ maxPixels: Int) -> UIImage { let realW = self.size.width / self.scale; let realH = self.size.height / self.scale; let factor = min(1.0, CGFloat(maxPixels) / (realW * realH)); return resize(factor * realW, h: factor * realH) } public func resize(_ w: CGFloat, h: CGFloat) -> UIImage { let nSize = CGSize(width: w, height: h) UIGraphicsBeginImageContextWithOptions(nSize, false, 1.0) draw(in: CGRect(origin: CGPoint(x: -1, y: -1), size: CGSize(width: (w + 2), height: (h + 2)))) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image!; } public func aa_imageWithColor(_ color1: UIColor) -> UIImage { UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) let context = UIGraphicsGetCurrentContext() context?.translateBy(x: 0, y: self.size.height) context?.scaleBy(x: 1.0, y: -1.0); context?.setBlendMode(CGBlendMode.normal) let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect context?.clip(to: rect, mask: self.cgImage!) color1.setFill() context?.fill(rect) let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage UIGraphicsEndImageContext() return newImage } } open class Imaging { open class func roundedImage(_ color: UIColor, radius: CGFloat) -> UIImage { return roundedImage(color, size: CGSize(width: radius * 2, height: radius * 2), radius: radius) } open class func roundedImage(_ color: UIColor, size: CGSize, radius: CGFloat) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: size.width, height: size.height), cornerRadius: radius) path.lineWidth = 1 color.setFill() path.fill() let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image.resizableImage(withCapInsets: UIEdgeInsetsMake(radius, radius, radius, radius)) } open class func circleImage(_ color: UIColor, radius: CGFloat) -> UIImage { return circleImage(color, size: CGSize(width: radius * 2, height: radius * 2), radius: radius) } open class func circleImage(_ color: UIColor, size: CGSize, radius: CGFloat) -> UIImage { UIGraphicsBeginImageContextWithOptions(size, false, 0) let path = UIBezierPath(roundedRect: CGRect(x: 1, y: 1, width: size.width - 2, height: size.height - 2), cornerRadius: radius) color.setStroke() path.stroke() let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image.resizableImage(withCapInsets: UIEdgeInsetsMake(radius, radius, radius, radius)) } open class func imageWithColor(_ color: UIColor, size: CGSize) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } } public extension UIImage { public func applyLightEffect() -> UIImage? { return applyBlurWithRadius(30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.8) } public func applyExtraLightEffect() -> UIImage? { return applyBlurWithRadius(20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8) } public func applyDarkEffect() -> UIImage? { return applyBlurWithRadius(20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8) } public func applyTintEffectWithColor(_ tintColor: UIColor) -> UIImage? { let effectColorAlpha: CGFloat = 0.6 var effectColor = tintColor let componentCount = tintColor.cgColor.numberOfComponents if componentCount == 2 { var b: CGFloat = 0 if tintColor.getWhite(&b, alpha: nil) { effectColor = UIColor(white: b, alpha: effectColorAlpha) } } else { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) { effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha) } } return applyBlurWithRadius(10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil) } public func applyBlur(_ blurRadius: CGFloat) -> UIImage? { return applyBlurWithRadius(blurRadius, tintColor: nil, saturationDeltaFactor: 1.0) } public func applyBlurWithRadius(_ blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? { // Check pre-conditions. if (size.width < 1 || size.height < 1) { print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)") return nil } if self.cgImage == nil { print("*** error: image must be backed by a CGImage: \(self)") return nil } if maskImage != nil && maskImage!.cgImage == nil { print("*** error: maskImage must be backed by a CGImage: \(maskImage)") return nil } let __FLT_EPSILON__ = CGFloat(FLT_EPSILON) let screenScale = UIScreen.main.scale let imageRect = CGRect(origin: CGPoint.zero, size: size) var effectImage = self let hasBlur = blurRadius > __FLT_EPSILON__ let hasSaturationChange = fabs(saturationDeltaFactor - 1.0) > __FLT_EPSILON__ if hasBlur || hasSaturationChange { func createEffectBuffer(_ context: CGContext) -> vImage_Buffer { let data = context.data let width = vImagePixelCount(context.width) let height = vImagePixelCount(context.height) let rowBytes = context.bytesPerRow return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes) } UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let effectInContext = UIGraphicsGetCurrentContext() effectInContext?.scaleBy(x: 1.0, y: -1.0) effectInContext?.translateBy(x: 0, y: -size.height) effectInContext?.draw(self.cgImage!, in: imageRect) var effectInBuffer = createEffectBuffer(effectInContext!) UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let effectOutContext = UIGraphicsGetCurrentContext() var effectOutBuffer = createEffectBuffer(effectOutContext!) if hasBlur { // A description of how to compute the box kernel width from the Gaussian // radius (aka standard deviation) appears in the SVG spec: // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // // For larger values of 's' (s >= 2.0), an approximation can be used: Three // successive box-blurs build a piece-wise quadratic convolution kernel, which // approximates the Gaussian kernel to within roughly 3%. // // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. // let inputRadius = blurRadius * screenScale let radiusPi = CGFloat(sqrt(2 * M_PI)) let radiusFl = floor(inputRadius * 3.0 * radiusPi / 4 + 0.5) var radius = UInt32(radiusFl) if radius % 2 != 1 { radius += 1 // force radius to be odd so that the three box-blur methodology works. } let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) } var effectImageBuffersAreSwapped = false if hasSaturationChange { let s: CGFloat = saturationDeltaFactor let floatingPointSaturationMatrix: [CGFloat] = [ 0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0, 0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0, 0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0, 0, 0, 0, 1 ] let divisor: CGFloat = 256 let matrixSize = floatingPointSaturationMatrix.count var saturationMatrix = [Int16](repeating: 0, count: matrixSize) for i: Int in 0 ..< matrixSize { saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor)) } if hasBlur { vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) effectImageBuffersAreSwapped = true } else { vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) } } if !effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext()! } UIGraphicsEndImageContext() if effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext()! } UIGraphicsEndImageContext() } // Set up output context. UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let outputContext = UIGraphicsGetCurrentContext() outputContext?.scaleBy(x: 1.0, y: -1.0) outputContext?.translateBy(x: 0, y: -size.height) // Draw base image. outputContext?.draw(self.cgImage!, in: imageRect) // Draw effect image. if hasBlur { outputContext?.saveGState() if let image = maskImage { outputContext?.clip(to: imageRect, mask: image.cgImage!); } outputContext?.draw(effectImage.cgImage!, in: imageRect) outputContext?.restoreGState() } // Add in color tint. if let color = tintColor { outputContext?.saveGState() outputContext?.setFillColor(color.cgColor) outputContext?.fill(imageRect) outputContext?.restoreGState() } // Output image is ready. let outputImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return outputImage } } extension UIImage { public func imageRotatedByDegrees(_ degrees: CGFloat, flip: Bool) -> UIImage { // let radiansToDegrees: (CGFloat) -> CGFloat = { // return $0 * (180.0 / CGFloat(M_PI)) // } let degreesToRadians: (CGFloat) -> CGFloat = { return $0 / 180.0 * CGFloat(M_PI) } // calculate the size of the rotated view's containing box for our drawing space let rotatedViewBox = UIView(frame: CGRect(origin: CGPoint.zero, size: size)) let t = CGAffineTransform(rotationAngle: degreesToRadians(degrees)); rotatedViewBox.transform = t let rotatedSize = rotatedViewBox.frame.size // Create the bitmap context UIGraphicsBeginImageContext(rotatedSize) let bitmap = UIGraphicsGetCurrentContext() // Move the origin to the middle of the image so we will rotate and scale around the center. bitmap?.translateBy(x: rotatedSize.width / 2.0, y: rotatedSize.height / 2.0); // // Rotate the image context bitmap?.rotate(by: degreesToRadians(degrees)); // Now, draw the rotated/scaled image into the context var yFlip: CGFloat if(flip){ yFlip = CGFloat(-1.0) } else { yFlip = CGFloat(1.0) } bitmap?.scaleBy(x: yFlip, y: -1.0) bitmap?.draw(cgImage!, in: CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } }
agpl-3.0
8839a56bb49b73ff0af2883d7d46043b
40.56338
158
0.59076
4.959664
false
false
false
false
LarsStegman/helios-for-reddit
Sources/Model/Link.swift
1
4278
// // Link.swift // Helios // // Created by Lars Stegman on 02-01-17. // Copyright © 2017 Stegman. All rights reserved. // import Foundation public struct Link/*: Thing, Created, Votable */{ public let id: String public static let kind = Kind.link // MARK: - Content data public let title: String public let contentUrl: URL public let permalink: String public let domain: URL public var selftext: String public let createdUtc: Date public let subreddit: String public let subredditId: String public let preview: Preview public var isEdited: Edited public let isSelf: Bool public let isOver18: Bool public let isSpoiler: Bool public var linkFlair: Flair? public let author: String? public let authorFlair: Flair? // MARK: - Community interaction data public var score: Int public var upvotes: Int public var downvotes: Int public var numberOfComments: Int public var distinguished: Distinguishment? public var isStickied: Bool public var isLocked: Bool // MARK: - User interaction data public var isHidden: Bool public var isRead: Bool public var liked: Vote public var isSaved: Bool public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingsKeys.self) id = try container.decode(String.self, forKey: .id) title = try container.decode(String.self, forKey: .title) contentUrl = try container.decode(URL.self, forKey: .contentUrl) permalink = try container.decode(String.self, forKey: .permalink) domain = try container.decode(URL.self, forKey: .domain) selftext = try container.decode(String.self, forKey: .selftext) createdUtc = Date(timeIntervalSince1970: try container.decode(TimeInterval.self, forKey: .createdUtc)) subreddit = try container.decode(String.self, forKey: .subreddit) subredditId = try container.decode(String.self, forKey: .subredditId) preview = try container.decode(Preview.self, forKey: .preview) isEdited = try container.decode(Edited.self, forKey: .isEdited) isSelf = try container.decode(Bool.self, forKey: .isSelf) isOver18 = try container.decode(Bool.self, forKey: .isOver18) isSpoiler = try container.decode(Bool.self, forKey: .isSpoiler) linkFlair = try LinkFlair(from: decoder) author = try container.decode(String.self, forKey: .author) authorFlair = try AuthorFlair(from: decoder) score = try container.decode(Int.self, forKey: .score) upvotes = try container.decode(Int.self, forKey: .upvotes) downvotes = try container.decode(Int.self, forKey: .downvotes) numberOfComments = try container.decode(Int.self, forKey: .numberOfComments) distinguished = try container.decode(Distinguishment.self, forKey: .distinguishment) isStickied = try container.decode(Bool.self, forKey: .isStickied) isLocked = try container.decode(Bool.self, forKey: .isLocked) isHidden = try container.decode(Bool.self, forKey: .isHidden) isRead = try container.decode(Bool.self, forKey: .isRead) liked = try container.decode(Vote.self, forKey: .liked) isSaved = try container.decode(Bool.self, forKey: .isSaved) } private enum CodingsKeys: String, CodingKey { case id case title case contentUrl = "url" case domain case score case upvotes = "ups" case downvotes = "downs" case author case isRead = "clicked" case isHidden = "hidden" case isSelf = "is_self" case liked = "likes" case isLocked = "locked" case isEdited = "edited" case numberOfComments = "num_comments" case isOver18 = "over_18" case isSpoiler = "spoiler" case permalink case isSaved = "saved" case selftext case subreddit case subredditId = "subreddit_id" case preview case isStickied = "stickied" case createdUtc = "created_utc" case distinguishment = "distinguished" } }
mit
f4cffc5a4ba0373b2f5347375ec9ef6f
36.191304
111
0.648352
4.184932
false
false
false
false
naokits/my-programming-marathon
iPhoneSensorDemo/Pods/RxCocoa/RxCocoa/Common/Observables/Implementations/KVOObservable.swift
39
4787
// // KVOObservable.swift // RxCocoa // // Created by Krunoslav Zaher on 7/5/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif class KVOObservable<Element> : ObservableType , KVOObservableProtocol { typealias E = Element? unowned var target: AnyObject var strongTarget: AnyObject? var keyPath: String var options: NSKeyValueObservingOptions var retainTarget: Bool init(object: AnyObject, keyPath: String, options: NSKeyValueObservingOptions, retainTarget: Bool) { self.target = object self.keyPath = keyPath self.options = options self.retainTarget = retainTarget if retainTarget { self.strongTarget = object } } func subscribe<O : ObserverType where O.E == Element?>(observer: O) -> Disposable { let observer = KVOObserver(parent: self) { (value) in if value as? NSNull != nil { observer.on(.Next(nil)) return } observer.on(.Next(value as? Element)) } return AnonymousDisposable { observer.dispose() } } } #if !DISABLE_SWIZZLING func observeWeaklyKeyPathFor(target: NSObject, keyPath: String, options: NSKeyValueObservingOptions) -> Observable<AnyObject?> { let components = keyPath.componentsSeparatedByString(".").filter { $0 != "self" } let observable = observeWeaklyKeyPathFor(target, keyPathSections: components, options: options) .distinctUntilChanged { $0 === $1 } .finishWithNilWhenDealloc(target) if !options.intersect(.Initial).isEmpty { return observable } else { return observable .skip(1) } } // This should work correctly // Identifiers can't contain `,`, so the only place where `,` can appear // is as a delimiter. // This means there is `W` as element in an array of property attributes. func isWeakProperty(properyRuntimeInfo: String) -> Bool { return properyRuntimeInfo.rangeOfString(",W,") != nil } extension ObservableType where E == AnyObject? { func finishWithNilWhenDealloc(target: NSObject) -> Observable<AnyObject?> { let deallocating = target.rx_deallocating return deallocating .map { _ in return Observable.just(nil) } .startWith(self.asObservable()) .switchLatest() } } func observeWeaklyKeyPathFor( target: NSObject, keyPathSections: [String], options: NSKeyValueObservingOptions ) -> Observable<AnyObject?> { weak var weakTarget: AnyObject? = target let propertyName = keyPathSections[0] let remainingPaths = Array(keyPathSections[1..<keyPathSections.count]) let property = class_getProperty(object_getClass(target), propertyName) if property == nil { return Observable.error(RxCocoaError.InvalidPropertyName(object: target, propertyName: propertyName)) } let propertyAttributes = property_getAttributes(property) // should dealloc hook be in place if week property, or just create strong reference because it doesn't matter let isWeak = isWeakProperty(String.fromCString(propertyAttributes) ?? "") let propertyObservable = KVOObservable(object: target, keyPath: propertyName, options: options.union(.Initial), retainTarget: false) as KVOObservable<AnyObject> // KVO recursion for value changes return propertyObservable .flatMapLatest { (nextTarget: AnyObject?) -> Observable<AnyObject?> in if nextTarget == nil { return Observable.just(nil) } let nextObject = nextTarget! as? NSObject let strongTarget: AnyObject? = weakTarget if nextObject == nil { return Observable.error(RxCocoaError.InvalidObjectOnKeyPath(object: nextTarget!, sourceObject: strongTarget ?? NSNull(), propertyName: propertyName)) } // if target is alive, then send change // if it's deallocated, don't send anything if strongTarget == nil { return Observable.empty() } let nextElementsObservable = keyPathSections.count == 1 ? Observable.just(nextTarget) : observeWeaklyKeyPathFor(nextObject!, keyPathSections: remainingPaths, options: options) if isWeak { return nextElementsObservable .finishWithNilWhenDealloc(nextObject!) } else { return nextElementsObservable } } } #endif
mit
1a2c42c29196ad73ce59c1f751351e5d
31.557823
165
0.627455
5.305987
false
false
false
false
LesCoureurs/Courir
Courir/Courir/GameState.swift
1
5841
// // GameState.swift // Courir // // Created by Ian Ngiaw on 3/20/16. // Copyright © 2016 NUS CS3217. All rights reserved. // import Foundation import MultipeerConnectivity class GameState: Observed { // MARK: Basic Game Properties weak var observer: Observer? var myPlayer: Player! var players = [Player]() var environmentObjects = [Environment]() var obstacles = [Obstacle]() { didSet { observer?.didChangeProperty("obstacles", from: self) } } var objects: [GameObject] { return players.map {$0 as GameObject} + obstacles.map {$0 as GameObject} } var host: Player? var hostID: MCPeerID? var peerMapping = [MCPeerID: Int]() var scoreTracking = [MCPeerID: Int]() private(set) var myEvents = [PlayerEvent]() var currentSpeed = initialGameSpeed var distance = 0 { didSet { observer?.didChangeProperty("distance", from: self) } } // Score var gameIsOver = false { didSet { observer?.didChangeProperty("gameIsOver", from: self) } } // MARK: Multiplayer & Ghost Mode Properties private (set) var mode: GameMode var isMultiplayer: Bool { return mode == .Multiplayer || mode == .SpecialMultiplayer } let seed: NSData private var allPlayersReady: Bool { return players.filter { $0.state == PlayerState.Ready }.count == players.count } private(set) var arePlayersReady = false { didSet { observer?.didChangeProperty("arePlayersReady", from: self) } } var ghostStore: GhostStore { return GhostStore(seed: seed, score: distance, eventSequence: myEvents) } init(seed: NSData, mode: GameMode = .SinglePlayer) { self.mode = mode self.seed = seed for i in 0..<numEnvironmentObjects { environmentObjects.append(Environment(identifier: i)) } } /// Initialise all `Player` models, including the current device's player func initPlayers(peers: [MCPeerID]) { var allPeerIDs = peers allPeerIDs.append(me.peerID) allPeerIDs.sortInPlace({ (this, other) in this.displayName < other.displayName }) initPlayersHelper(allPeerIDs) } /// Initialise all `Player` models, and set a host for the game. func initPlayers(peers: [MCPeerID], withHost hostID: MCPeerID) { var allPeerIDs: [MCPeerID] = Array(Set(peers)) if me.peerID.displayName != hostID.displayName { allPeerIDs = Array(Set(peers).union([me.peerID]).subtract([hostID])) } allPeerIDs.sortInPlace({ (this, other) in this.displayName < other.displayName }) initPlayersHelper(allPeerIDs) self.host = Player(playerNumber: defaultHostNumber, numPlayers: allPeerIDs.count) self.hostID = hostID if me.peerID.displayName == hostID.displayName { myPlayer = self.host } } private func initPlayersHelper(peers: [MCPeerID]) { for (playerNum, peer) in peers.enumerate() { let player = Player(playerNumber: playerNum, numPlayers: peers.count) if peer.displayName == me.peerID.displayName { myPlayer = player player.ready() } peerMapping[peer] = playerNum players.append(player) } } /// Retrieve the `Player` with the specified `peerID`. func getPlayer(withPeerID peerID: MCPeerID) -> Player? { guard peerID != hostID else { return nil } if let index = peerMapping[peerID] { return players[index] } return nil } /// Retrieve the `Player` with the specified `playerNumber`. func getPlayer(withPlayerNumber playerNumber: Int?) -> Player? { if let player = players.filter({ $0.playerNumber == playerNumber }).first { return player } else if let host = host where playerNumber == defaultHostNumber { return host } return nil } /// Updates the state of the `Player` with the given peerID to be `Ready` func playerReady(peerID: MCPeerID) { getPlayer(withPeerID: peerID)?.ready() if allPlayersReady { arePlayersReady = true } } /// - returns: `true` if all players have completed (lost) the game func everyoneFinished() -> Bool { for player in players { if player.state != .Lost { return false } } return true } /// - returns: `true` if the current device's player is still alive in the game func ownPlayerStillPlaying() -> Bool { return myPlayer.state != PlayerState.Lost } /// Update the given `Player`'s score func updatePlayerScore(player: Player, score: Int) { for (peerID, playerNumber) in peerMapping { if playerNumber == player.playerNumber { scoreTracking[peerID] = score break } } } // MARK: Player event methods func addJumpEvent(timeStep: Int) { addGameEvent(.PlayerDidJump, timeStep: timeStep) } func addDuckEvent(timeStep: Int) { addGameEvent(.PlayerDidDuck, timeStep: timeStep) } func addCollideEvent(timeStep: Int, xCoordinate: Int) { addGameEvent(.PlayerDidCollide, timeStep: timeStep, otherData: xCoordinate) } func addLostEvent(timeStep: Int, score: Int) { addGameEvent(.PlayerLost, timeStep: timeStep, otherData: score) } private func addGameEvent(event: GameEvent, timeStep: Int, otherData: AnyObject? = nil) { myEvents.append(PlayerEvent(event: event, timeStep: timeStep, otherData: otherData)) } }
mit
868df0e27f6f3124382b06202a7fe25b
28.205
93
0.606849
4.404223
false
false
false
false
koehlermichael/focus
Blockzilla/UserAgent.swift
1
2068
/* 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 class UserAgent { static var browserUserAgent: String? static func setup() { assert(Thread.current.isMainThread, "UserAgent.setup() must be called on the main thread") if let cachedUserAgent = UserAgent.cachedUserAgent() { setUserAgent(userAgent: cachedUserAgent) return } guard let userAgent = UserAgent.generateUserAgent() else { return } UserDefaults.standard.set(userAgent, forKey: "UserAgent") UserDefaults.standard.set(UIDevice.current.systemVersion, forKey: "LastSeenSystemVersion") UserDefaults.standard.synchronize() setUserAgent(userAgent: userAgent) } private static func cachedUserAgent() -> String? { guard let lastSeenSystemVersion = UserDefaults.standard.string(forKey: "LastSeenSystemVersion") else { return nil } if lastSeenSystemVersion != UIDevice.current.systemVersion { return nil } return UserDefaults.standard.string(forKey: "UserAgent") } private static func generateUserAgent() -> String? { let webView = UIWebView() guard var webViewUserAgent = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent") else { return nil } // Insert our product/version before Mobile/1234 if let range = webViewUserAgent.range(of: "Mobile/") { let productName = AppInfo.isFocus ? "Focus" : "Klar" webViewUserAgent.insert(contentsOf: "\(productName)/\(AppInfo.ShortVersion) ".characters, at: range.lowerBound) } return webViewUserAgent } private static func setUserAgent(userAgent: String) { UserDefaults.standard.register(defaults: ["UserAgent": userAgent]) UserDefaults.standard.synchronize() } }
mpl-2.0
20ecfda9dc8f445f3a894ccae6e9f02f
33.466667
123
0.660542
4.959233
false
false
false
false
hengZhuo/DouYuZhiBo
swift-DYZB/swift-DYZB/Classes/Tools/Common.swift
1
341
// // Common.swift // swift-DYZB // // Created by chenrin on 2016/11/14. // Copyright © 2016年 zhuoheng. All rights reserved. // import UIKit let kStatusBarH : CGFloat = 20 let kNavgationBarH : CGFloat = 44 let kScreenW = UIScreen.main.bounds.size.width let kScreenH = UIScreen.main.bounds.size.height let kTabBarH : CGFloat = 44
mit
91625659d6c29c33a1917b6ee46db0a7
17.777778
52
0.715976
3.38
false
false
false
false
Yalantis/PixPic
PixPic/Resources/Constants.swift
1
4597
// // Constants.swift // InstaFeedObserver // // Created by Jack Lapin on 13.11.15. // Copyright © 2015 Jack Lapin. All rights reserved. // struct Constants { struct ParseApplicationId { //add this 2 keys from 'develop'. also add fabric script to build phases, url scheme and FacebookAppID to plist static let AppID = "" static let ClientKey = "" } struct NotificationName { static let newPostIsUploaded = "newPostIsUploaded" static let newPostIsReceaved = "newPostIsReceaved" static let followersListIsUpdated = "followersListIsUpdated" static let likersListIsUpdated = "likersListIsUpdated" } struct BaseDimensions { static let toolBarHeight: CGFloat = 66 static let navBarWithStatusBarHeight: CGFloat = 64 } struct FileSize { static let maxUploadSizeBytes = 10485760 } struct Path { static let documents = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] static let tmp = NSTemporaryDirectory() } struct Storyboard { static let authorization = "Authorization" static let feed = "Feed" static let photoEditor = "PhotoEditor" static let profile = "Profile" static let launchScreen = "LaunchScreen" static let settings = "Settings" } struct UserDefaultsKeys { static let remoteNotifications = "remoteNotifications" static let followedPosts = "followedPosts" } struct UserKey { static let avatar = "avatar" static let id = "objectId" } struct Profile { static let toastActivityDuration: NSTimeInterval = 5 static let headerHeight: CGFloat = 322 static let avatarImageCornerRadius: CGFloat = 95.5 static let avatarImagePlaceholderName = "profile_placeholder.png" static let possibleInsets: CGFloat = 45 static let settingsButtonImage = "icEdit" static let navigationTitle = "Profile" } struct DataSource { static let queryLimit = 10 as Int } struct ValidationErrors { static let wrongLenght = "Length of the username must be 3-30 characters long" static let alreadyExist = "Username already exists" static let spaceInBegining = "Username can't start with spaces" static let characterSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ0123456789" + "абвгдеёжзийклмнопрстуфхцчшщъыьэюяАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ " static let spaceInEnd = "Username can't end with spaces" static let numbersAndSymbolsInUsername = "Username has to contain only letters and numbers" static let twoConsecutiveSpaces = "Username can't contain two consecutive spaces" static let minUserName = 3 static let maxUserName = 30 static let whiteSpace: Character = " " } struct PhotoEditor { static let imageViewControllerSegue = "imageViewControllerSegue" static let stickersPickerSegue = "stickersPickerSegue" } struct StickerPicker { static let stickerPickerCellIdentifier = "StickerPickerCell" } struct StickerEditor { static let userResizableViewGlobalOffset: CGFloat = 5 static let stickerViewControlSize: CGFloat = 36 } struct EditProfile { static let navigationTitle = "Edit Profile" } struct Attributes { static let postsCount = "postsCount" static let followStatusByCurrentUser = "followStatusByCurrentUser" static let likeStatusByCurrentUser = "likeStatusByCurrentUser" static let likesCount = "likesCount" static let likers = "likers" static let comments = "comments" static let followers = "followers" static let following = "following" static let followersCount = "followersCount" static let followingCount = "followingCount" } struct ActivityKey { static let fromUser = "fromUser" static let toUser = "toUser" static let toPost = "toPost" static let type = "type" } struct Feed { static let navigationTitle = "PixPic" } struct Settings { static let navigationTitle = "Settings" } struct Network { static let timeoutTimeInterval: NSTimeInterval = 5 } struct StickerCell { static let size = CGSize(width: 105, height: 105) } }
mit
6d45f324e8092660af4fbce01112da58
24.166667
119
0.660927
4.808917
false
false
false
false
WalterCreazyBear/Swifter30
AppleNews/AppleNews/NewsTableViewCell.swift
1
4092
// // NewsTableViewCell.swift // AppleNews // // Created by 熊伟 on 2017/6/27. // Copyright © 2017年 Bear. All rights reserved. // import UIKit class NewsTableViewCell: UITableViewCell { static let titleFontSize = CGFloat( 16) static let dateFontSize = CGFloat(13) static let contentFontSize = CGFloat(14) lazy var title : UILabel = { let title : UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 0)) title.textColor = UIColor.black title.numberOfLines = 0 title.font = UIFont.systemFont(ofSize: titleFontSize) title.textAlignment = .center return title }() lazy var date : UILabel = { let date : UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 0)) date.textColor = UIColor.gray date.numberOfLines = 1 date.font = UIFont.systemFont(ofSize: dateFontSize) date.textAlignment = .right return date }() lazy var content : UILabel = { let content : UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 0)) content.textColor = UIColor.black content.numberOfLines = 0 content.font = UIFont.systemFont(ofSize: contentFontSize) return content }() override func awakeFromNib() { super.awakeFromNib() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(self.title) contentView.addSubview(self.date) contentView.addSubview(self.content) } static func cellId()->String { return String(describing: self) } func bindData(model:(title: String, description: String, pubDate: String)) { self.title.text = model.title self.date.text = model.pubDate self.content.text = model.description let titleHeight = model.title.heightWithConstrainedWidth(width: UIScreen.main.bounds.width, font: UIFont.systemFont(ofSize: NewsTableViewCell.titleFontSize)) let dateHeight = model.pubDate.heightWithConstrainedWidth(width: UIScreen.main.bounds.width, font: UIFont.systemFont(ofSize: NewsTableViewCell.dateFontSize)) let contentHeight = model.description.heightWithConstrainedWidth(width: UIScreen.main.bounds.width, font: UIFont.systemFont(ofSize: NewsTableViewCell.contentFontSize)) self.title.frame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: titleHeight) self.date.frame = CGRect.init(x: 0, y: titleHeight + 10, width: UIScreen.main.bounds.width, height: dateHeight) self.content.frame = CGRect.init(x: 0, y: titleHeight+dateHeight + 20, width: UIScreen.main.bounds.width, height: contentHeight) } static func heightForCell(model:(title: String, description: String, pubDate: String)) ->CGFloat { let titleHeight = model.title.heightWithConstrainedWidth(width: UIScreen.main.bounds.width, font: UIFont.systemFont(ofSize: titleFontSize)) let dateHeight = model.pubDate.heightWithConstrainedWidth(width: UIScreen.main.bounds.width, font: UIFont.systemFont(ofSize: dateFontSize)) let contentHeight = model.description.heightWithConstrainedWidth(width: UIScreen.main.bounds.width, font: UIFont.systemFont(ofSize: contentFontSize)) return CGFloat( titleHeight + dateHeight + contentHeight + 30) } } extension String { func heightWithConstrainedWidth(width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return boundingBox.height } }
mit
c6eb3eb9473b3027a62510d8fc9811fe
40.683673
176
0.689106
4.479167
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
the-blue-alliance-ios/View Controllers/Districts/District/DistrictEventsViewController.swift
1
2260
import CoreData import Foundation import TBAData import TBAKit class DistrictEventsViewController: EventsViewController { private let district: District init(district: District, dependencies: Dependencies) { self.district = district super.init(dependencies: dependencies) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Refreshable override var refreshKey: String? { return "\(district.key)_events" } override var automaticRefreshInterval: DateComponents? { return DateComponents(day: 7) } override var automaticRefreshEndDate: Date? { // Automatically refresh event districts during the year before the selected year (when events are rolling in) // Ex: Districts for 2019 will stop automatically refreshing on January 1st, 2019 (should all be set by then) return Calendar.current.date(from: DateComponents(year: district.year)) } @objc override func refresh() { var operation: TBAKitOperation! operation = tbaKit.fetchDistrictEvents(key: district.key) { [self] (result, notModified) in guard case .success(let events) = result, !notModified else { return } let context = persistentContainer.newBackgroundContext() context.performChangesAndWait({ let district = context.object(with: self.district.objectID) as! District district.insert(events) }, saved: { [unowned self] in self.markTBARefreshSuccessful(tbaKit, operation: operation) }, errorRecorder: errorRecorder) } addRefreshOperations([operation]) } // MARK: - Stateful override var noDataText: String? { return "No events for district" } // MARK: - EventsViewControllerDataSourceConfiguration override var firstSortDescriptor: NSSortDescriptor { return Event.weekSortDescriptor() } override var sectionNameKeyPath: String { return Event.weekKeyPath() } override var fetchRequestPredicate: NSPredicate { return Event.districtPredicate(districtKey: district.key) } }
mit
6e73eda44f628f6cf69a6c39f9784cce
29.540541
118
0.664602
5.09009
false
false
false
false
glessard/swiftian-dispatch
Tests/deferredTests/DeferredSelectionTests.swift
3
12535
// // DeferredSelectionTests.swift // deferredTests // // Created by Guillaume Lessard on 2019-05-02. // Copyright © 2019-2020 Guillaume Lessard. All rights reserved. // import XCTest import Dispatch import deferred extension Deferred { convenience init() { self.init(task: { _ in }) } } class DeferredSelectionTests: XCTestCase { func testFirstValueCollection() throws { func resolution(_ c: Int) -> ([Resolver<Int, Error>], Deferred<Int, Error>?) { let q = DispatchQueue(label: #function) var r = [Resolver<Int, Error>]() var d = [Deferred<Int, Error>]() for i in 0...c { let tbd = DeallocWitness(self.expectation(description: String(i)), queue: q) { r.append($0) } d.append(tbd) } for deferred in d { deferred.beginExecution() } q.sync { XCTAssertEqual(r.count, d.count) } return (r, firstValue(d, qos: .utility)) } let count = 10 let (resolvers, first) = resolution(count) let lucky = Int.random(in: 1..<count) resolvers[count].resolve(error: TestError(count)) resolvers[lucky].resolve(value: lucky) first?.beginExecution() waitForExpectations(timeout: 1.0) XCTAssertEqual(first?.value, lucky) for r in resolvers { XCTAssertFalse(r.needsResolution) } } func testFirstValueSequence() throws { func resolution(_ c: Int) -> ([Resolver<Int, Error>], Deferred<Int, Error>?) { let q = DispatchQueue(label: #function) var r = [Resolver<Int, Error>]() var d = [Deferred<Int, Error>]() for i in 0...c { let tbd = DeallocWitness(self.expectation(description: String(i)), queue: q) { r.append($0) } d.append(tbd) } for deferred in d { deferred.beginExecution() } q.sync { XCTAssertEqual(r.count, d.count) } return (r, firstValue(AnySequence(d), qos: .utility)) } let count = 10 let (resolvers, first) = resolution(count) let lucky = Int.random(in: 1..<count) resolvers[count].resolve(error: TestError(count)) resolvers[lucky].resolve(value: lucky) first?.beginExecution() waitForExpectations(timeout: 1.0) XCTAssertEqual(first?.value, lucky) for r in resolvers { XCTAssertFalse(r.needsResolution) } } func testFirstValueEmptyCollection() throws { let empty: [Deferred<Void, Never>] = [] let zero = firstValue(empty, queue: DispatchQueue.global()) XCTAssertNil(zero) } func testFirstValueEmptySequence() throws { let empty: [Deferred<Void, Never>] = [] let zero = firstValue(AnySequence(empty), queue: DispatchQueue.global()) XCTAssertNil(zero) } func testFirstValueCollectionError() throws { func noValue(_ c: Int) -> Deferred<Int, Error> { let deferreds = (0..<c).map { i -> Deferred<Int, Error> in let e = expectation(description: String(i)) return DeallocWitness(e, task: { $0.resolve(error: TestError(i)) }) } return firstValue(deferreds, cancelOthers: true)! } let count = 10 let first = noValue(count) first.onError { XCTAssertEqual($0, TestError(count-1)) } waitForExpectations(timeout: 1.0) withExtendedLifetime(first) {} } func testFirstValueSequenceError() throws { func noValue(_ c: Int) -> Deferred<Int, Error> { let deferreds = (0..<c).map { i -> Deferred<Int, Error> in let e = expectation(description: String(i)) return DeallocWitness(e, task: { $0.resolve(error: TestError(i)) }) } return firstValue(AnySequence(deferreds), cancelOthers: true)! } let count = 10 let first = noValue(count) first.onError { XCTAssertEqual($0, TestError(count-1)) } waitForExpectations(timeout: 1.0) withExtendedLifetime(first) {} } func testFirstResolvedCollection() throws { let count = 10 let e = Int.random(in: 1..<count) func resolution() -> ([Resolver<Int, Error>], Deferred<Int, Error>) { let q = DispatchQueue(label: #function) var r: [Resolver<Int, Error>] = [] var d: [Deferred<Int, Error>] = [] for i in 0...count { let tbd = DeallocWitness(self.expectation(description: String(i)), queue: q, task: { r.append($0) }) if i == e { tbd.beginExecution() } else { tbd.notify { XCTAssertEqual($0.error?.isTimeout, true) } } d.append(tbd) } q.sync { XCTAssertEqual(r.count, d.count) } return (r, firstResolved(d, qos: .utility, cancelOthers: true)!) } let (r, f) = resolution() for resolver in r { XCTAssertEqual(resolver.needsResolution, true) } r[e].resolve(error: TestError(e)) XCTAssertEqual(f.error, TestError(e)) waitForExpectations(timeout: 1.0) } func testFirstResolvedSequence() throws { let count = 10 let e = Int.random(in: 1..<count) func resolution() -> ([Resolver<Int, Error>], Deferred<Int, Error>) { let q = DispatchQueue(label: #function) var r: [Resolver<Int, Error>] = [] var d: [Deferred<Int, Error>] = [] for i in 0...count { let tbd = DeallocWitness(self.expectation(description: String(i)), queue: q, task: { r.append($0) }) if i == e { tbd.beginExecution() } else { tbd.notify { XCTAssertEqual($0.error?.isTimeout, true) } } d.append(tbd) } q.sync { XCTAssertEqual(r.count, d.count) } return (r, firstResolved(AnySequence(d), qos: .utility, cancelOthers: true)!) } let (r, f) = resolution() for resolver in r { XCTAssertEqual(resolver.needsResolution, true) } r[e].resolve(value: e) XCTAssertEqual(try f.get(), e) waitForExpectations(timeout: 1.0) } func testFirstResolvedEmptyCollection() throws { let zero = firstResolved(Array<Deferred<Void, Never>>(), queue: DispatchQueue.global()) XCTAssertNil(zero) } func testFirstResolvedEmptySequence() throws { let zero = firstResolved(AnySequence(EmptyCollection<Deferred<Void, Never>>())) XCTAssertNil(zero) } func testSelectFirstResolvedBinary() { let e1 = expectation(description: #function + "1") let e2 = expectation(description: #function + "2") let r2 = nzRandom() let q2 = DispatchQueue(label: #function) var t2: Resolver<Int, Error>! = nil let (s1, s2) = firstResolved(DeallocWitness<Double, Cancellation>(e1), DeallocWitness<Int, Error>(e2, queue: q2, task: { t2 = $0 }).execute, cancelOthers: true) q2.sync { XCTAssertNotNil(r2) } s1.notify { XCTAssertEqual($0.error?.isTimeout, true) } s2.notify { XCTAssertEqual($0, r2) } t2.resolve(value: r2) waitForExpectations(timeout: 1.0) } func testSelectFirstResolvedTernary() { let r1 = nzRandom() let d2 = Deferred<Float, Error>() let (s1, s2, s3) = firstResolved(Deferred<Int, TestError>(error: TestError(r1)), d2, Deferred<Double, NSError>(), cancelOthers: true) XCTAssertEqual(s1.error, TestError(r1)) XCTAssertEqual(d2.error?.isTimeout, true) XCTAssertEqual(s2.error?.isTimeout, true) XCTAssertEqual(s3.error?.isTimeout, true) } func testSelectFirstResolvedQuaternary() { let r1 = nzRandom() let d2 = Deferred<String, Error>() let (s1, s2, s3, s4) = firstResolved(Deferred<Int, TestError>(error: TestError(r1)), d2, Deferred<Double, NSError>(), Deferred<Void, Cancellation>(), cancelOthers: true) XCTAssertEqual(s1.error, TestError(r1)) XCTAssertEqual(d2.error?.isTimeout, true) XCTAssertEqual(s2.error?.isTimeout, true) XCTAssertEqual(s3.error?.isTimeout, true) XCTAssertEqual(s4.error?.isTimeout, true) } func testSelectFirstValueBinary1() { let d1 = Deferred<Double, Cancellation>() let (r2, d2) = Deferred<Int, Never>.CreatePair() let (s1, s2) = firstValue(d1, d2, cancelOthers: true) XCTAssertEqual(d1.state, .waiting) XCTAssertEqual(d2.state, .waiting) XCTAssertEqual(s1.state, .waiting) XCTAssertEqual(s2.state, .waiting) let e2 = expectation(description: #function) s2.notify { _ in e2.fulfill() } r2.resolve(value: nzRandom()) waitForExpectations(timeout: 1.0) { _ in d1.cancel() } XCTAssertEqual(s2.value, d2.value) XCTAssertEqual(s1.error?.isTimeout, true) XCTAssertEqual(d1.error?.isTimeout, true) } func testSelectFirstValueBinary2() { let r1 = nzRandom() let r2 = nzRandom() let e2 = expectation(description: #function) let (s1, s2) = firstValue(Deferred<Int, TestError>(error: TestError(r1)), DeallocWitness<Void, Error>(e2, task: { $0.resolve(error: TestError(r2)) })) s1.notify { XCTAssertEqual($0, TestError(r1)) } s2.notify { XCTAssertEqual($0, TestError(r2)) } waitForExpectations(timeout: 1.0) } func testSelectFirstValueMemoryRelease() { do { let (s1, s2) = firstValue(DeallocWitness<Void, Error>(expectation(description: #function + "1")), DeallocWitness<Void, Error>(expectation(description: #function + "2"))) s1.beginExecution() s2.beginExecution() } waitForExpectations(timeout: 1.0) } func testSelectFirstValueRetainMemory() { let d1 = Deferred<Void, Never>() { _ in } let e2 = expectation(description: #function) let (s1, s2) = firstValue(d1, Deferred<Void, Error> { _ in e2.fulfill() } ) let q = DispatchQueue(label: #function) q.asyncAfter(deadline: .now() + 0.01) { s1.beginExecution() } XCTAssertEqual(s1.state, .waiting) XCTAssertEqual(s2.state, .waiting) XCTAssertEqual(d1.state, .waiting) waitForExpectations(timeout: 1.0) XCTAssertEqual(d1.state, .executing) } func testSelectFirstValueTernary1() { let r1 = nzRandom() let t3 = Deferred<Double, Error>() let (s1, s2, s3) = firstValue(Deferred<Int, Never>(value: r1), Deferred<Int, TestError>(error: TestError()), t3, cancelOthers: true) XCTAssertEqual(s1.value, r1) XCTAssertEqual(s2.error?.isTimeout, true) XCTAssertEqual(t3.error?.isTimeout, true) XCTAssertEqual(s3.error?.isTimeout, true) } func testSelectFirstValueTernary2() { let r1 = nzRandom() let r2 = nzRandom() let r3 = nzRandom() let (s1, s2, s3) = firstValue(Deferred<Float, TestError>(error: TestError(r1)), Deferred<Void, TestError>(error: TestError(r2)), Deferred<Double, Error>(error: TestError(r3))) XCTAssertEqual(s1.error, TestError(r1)) XCTAssertEqual(s2.error, TestError(r2)) XCTAssertEqual(s3.error, TestError(r3)) } func testSelectFirstValueQuaternary1() { let r = nzRandom() let t3 = Deferred<Double, Cancellation>() let (s1, s2, s3, s4) = firstValue(Deferred<Void, TestError>(error: TestError(r)), Deferred<Int, Never>(value: r), t3, Deferred<Int, Error>(), cancelOthers: true) XCTAssertEqual(s1.error?.isTimeout, true) XCTAssertEqual(s2.value, r) XCTAssertEqual(t3.error?.isTimeout, true) XCTAssertEqual(s3.error?.isTimeout, true) XCTAssertEqual(s4.error?.isTimeout, true) } func testSelectFirstValueQuaternary2() { let r1 = nzRandom() let r2 = nzRandom() let r3 = nzRandom() let r4 = nzRandom() let (s1, s2, s3, s4) = firstValue(Deferred<Float, TestError>(error: TestError(r1)), Deferred<Void, Error>(error: TestError(r2)), Deferred<Int, TestError>(error: TestError(r3)), Deferred<Double, Error>(error: TestError(r4))) XCTAssertEqual(s1.error, TestError(r1)) XCTAssertEqual(s2.error, TestError(r2)) XCTAssertEqual(s3.error, TestError(r3)) XCTAssertEqual(s4.error, TestError(r4)) } } extension Error { var isTimeout: Bool { if case .timedOut? = self as? Cancellation { return true } else { return false } } }
mit
55e93f4edfa0601286bca3abcfdd2e00
29.720588
108
0.607468
3.836547
false
true
false
false
RylynnLai/V2EX--practise
V2EX/AllTopic/TopicsTVC/topicDetail/RLTopicDetailVC.swift
1
5767
// // RLTopicDetailVC.swift // V2EX // // Created by LLZ on 16/3/24. // Copyright © 2016年 ucs. All rights reserved. // import UIKit class RLTopicDetailVC: UIViewController, UIWebViewDelegate, UITableViewDelegate, UITableViewDataSource { var topicModel:RLTopic? @IBOutlet weak var loadingAIV: UIActivityIndicatorView! @IBOutlet weak var authorLable: UILabel! @IBOutlet weak var titleLable: UILabel! @IBOutlet weak var createdTimeLable: UILabel! @IBOutlet weak var authorBtn: UIButton! @IBOutlet weak var replieNumLable: UILabel! private lazy var contentWbV:UIWebView = { let wv:UIWebView = UIWebView.init(frame: CGRectMake(0, self.authorLable.mj_h + self.authorLable.mj_y, screenW, 10)) wv.delegate = self return wv }() private var repliesListView:UITableView? private var replies:NSArray? override func viewDidLoad() { super.viewDidLoad() initUI() initData() /*这里规则是 *检查数据是否完整,完整就直接显示帖子内容,不重新请求;不完整就发起网络请求,并更新内存缓存保存新的数据 *用户可以手动下拉刷新话题列表刷新或下拉刷新帖子刷新,需要更新缓存数据 */ if topicModel?.content_rendered == nil { loadingAIV.startAnimating() RLTopicsTool.shareTopicsTool.topicWithTopicID((topicModel?.ID)!, completion: {[weak self] (topic) in if let strongSelf = self { strongSelf.topicModel = topic strongSelf.initData() } }) } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) UIView.animateWithDuration(0.1, animations: { [weak self] in if let strongSelf = self { strongSelf.navigationController?.navigationBar.mj_y = 20; } }) } //MARK: -私有方法 private func initUI() { self.view.addSubview(self.contentWbV) loadingAIV.frame = CGRectMake(self.view.mj_w * 0.5, self.view.mj_h * 0.5, 20, 20) loadingAIV.activityIndicatorViewStyle = .Gray loadingAIV.hidesWhenStopped = true } private func initData() { //导航栏标题 self.title = topicModel!.title //帖子内容 let htmlStr = String.HTMLstringWithBody(topicModel!.content_rendered ?? "") contentWbV.loadHTMLString(htmlStr, baseURL: nil) //头像 let iconURL = NSURL.init(string: "https:\(topicModel!.member.avatar_normal!)") authorBtn.sd_setImageWithURL(iconURL, forState: .Normal, placeholderImage: UIImage.init(named: "blank")) //标题 titleLable.text = topicModel!.title titleLable.adjustsFontSizeToFitWidth = true//固定lable大小,内容自适应,还有个固定字体大小,lable自适应的方法sizeToFit //作者名称 authorLable.text = "\(topicModel!.member.username!) ●" //创建时间 if topicModel!.createdTime != nil { createdTimeLable.text = "\(topicModel!.createdTime!) ●" } else { createdTimeLable.text = String.creatTimeByTimeIntervalSince1970(Double(topicModel!.created!)!) } //回复个数 replieNumLable.text = "\(topicModel!.replies!)个回复" } private func loadRepliesData() { } private func addRepliesList() { } //MARK: - UIWebViewDelegate func webViewDidStartLoad(webView: UIWebView) { loadingAIV.startAnimating() } func webViewDidFinishLoad(webView: UIWebView) { if webView.loading { return } else { loadingAIV.stopAnimating() webView.mj_h = webView.scrollView.contentSize.height + 64 webView.scrollView.scrollEnabled = false let scrollView = self.view as! UIScrollView scrollView.contentSize = CGSizeMake(webView.mj_w, webView.mj_h + 100) //MJRefresh(加载评论) let footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: Selector(loadRepliesData())) footer.refreshingTitleHidden = true footer.stateLabel.textColor = UIColor.lightGrayColor() footer.stateLabel.alpha = 0.4 footer.setTitle("点击或上拉显示评论列表", forState: .Idle) scrollView.mj_footer = footer } } //MARK: - UIScrollViewDelegate func scrollViewDidScroll(scrollView: UIScrollView) { //当前为最顶上控制器才进行下面判断是否隐藏导航条 if self.navigationController?.topViewController == self { let navBar = self.navigationController?.navigationBar if scrollView.contentOffset.y > 0 && (navBar?.mj_y == 20) { UIView.animateWithDuration(0.5, animations: { (navBar?.mj_y = -(navBar?.mj_h)!)! }) } else if scrollView.contentOffset.y < 0 && (navBar?.mj_y < 0) { UIView.animateWithDuration(0.5, animations: { navBar?.mj_y = 20.0 }) } } } //MARK: - UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (self.replies?.count)! } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("replyCell") if cell == nil { cell = UITableViewCell.init() } return cell! } }
mit
a6ab7d12e1785d2f0938ff617231b7cd
35.255034
126
0.611625
4.539496
false
false
false
false
Stitch7/mclient
mclient/PrivateMessages/_MessageKit/Extensions/UIView+Extensions.swift
1
4567
/* MIT License Copyright (c) 2017-2018 MessageKit Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit extension UIView { internal func fillSuperview() { guard let superview = self.superview else { return } translatesAutoresizingMaskIntoConstraints = false let constraints: [NSLayoutConstraint] = [ leftAnchor.constraint(equalTo: superview.leftAnchor), rightAnchor.constraint(equalTo: superview.rightAnchor), topAnchor.constraint(equalTo: superview.topAnchor), bottomAnchor.constraint(equalTo: superview.bottomAnchor) ] NSLayoutConstraint.activate(constraints) } internal func centerInSuperview() { guard let superview = self.superview else { return } translatesAutoresizingMaskIntoConstraints = false let constraints: [NSLayoutConstraint] = [ centerXAnchor.constraint(equalTo: superview.centerXAnchor), centerYAnchor.constraint(equalTo: superview.centerYAnchor) ] NSLayoutConstraint.activate(constraints) } internal func constraint(equalTo size: CGSize) { guard superview != nil else { return } translatesAutoresizingMaskIntoConstraints = false let constraints: [NSLayoutConstraint] = [ widthAnchor.constraint(equalToConstant: size.width), heightAnchor.constraint(equalToConstant: size.height) ] NSLayoutConstraint.activate(constraints) } @discardableResult internal func addConstraints(_ top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, topConstant: CGFloat = 0, leftConstant: CGFloat = 0, bottomConstant: CGFloat = 0, rightConstant: CGFloat = 0, widthConstant: CGFloat = 0, heightConstant: CGFloat = 0) -> [NSLayoutConstraint] { if self.superview == nil { return [] } translatesAutoresizingMaskIntoConstraints = false var constraints = [NSLayoutConstraint]() if let top = top { let constraint = topAnchor.constraint(equalTo: top, constant: topConstant) constraint.identifier = "top" constraints.append(constraint) } if let left = left { let constraint = leftAnchor.constraint(equalTo: left, constant: leftConstant) constraint.identifier = "left" constraints.append(constraint) } if let bottom = bottom { let constraint = bottomAnchor.constraint(equalTo: bottom, constant: -bottomConstant) constraint.identifier = "bottom" constraints.append(constraint) } if let right = right { let constraint = rightAnchor.constraint(equalTo: right, constant: -rightConstant) constraint.identifier = "right" constraints.append(constraint) } if widthConstant > 0 { let constraint = widthAnchor.constraint(equalToConstant: widthConstant) constraint.identifier = "width" constraints.append(constraint) } if heightConstant > 0 { let constraint = heightAnchor.constraint(equalToConstant: heightConstant) constraint.identifier = "height" constraints.append(constraint) } NSLayoutConstraint.activate(constraints) return constraints } }
mit
19b61d0f383e89feb37c3da56823ed4e
38.37069
365
0.668929
5.680348
false
false
false
false
TonnyTao/HowSwift
Funny Swift.playground/Pages/find type back if erased.xcplaygroundpage/Contents.swift
1
869
//: [Previous](@previous) import Foundation public struct AnyEquatable { private let value: Any private let equals: (Any) -> Bool public init<T: Equatable>(_ value: T) { self.value = value self.equals = { ($0 as? T == value) } } } extension AnyEquatable: Equatable { static public func == (lhs: AnyEquatable, rhs: AnyEquatable) -> Bool { return lhs.equals(rhs.value) } } let anyArr: [Any] = [5, 5.0] let w = AnyEquatable(5) let x = AnyEquatable(5.0) let y = AnyEquatable(6) let z = AnyEquatable("Hello") print(w == x, w == y, w == z) let arr = [AnyEquatable(55), AnyEquatable("dog")] print(arr.contains(AnyEquatable("dog")), arr.contains(AnyEquatable(10))) // -> true false // Note that two values are only equal if they are the same type print(AnyEquatable(5 as Int) == AnyEquatable(5 as Double)) // -> false
mit
5cd26887086fc65bba467e4a9a5ea115
23.138889
89
0.639816
3.291667
false
false
false
false
mindz-eye/MYTableViewIndex
MYTableViewIndex/Public/Items/TruncationItem.swift
1
1363
// // TruncationItem.swift // TableViewIndex // // Created by Makarov Yury on 06/08/16. // Copyright © 2016 Makarov Yury. All rights reserved. // import UIKit /// Default truncation symbol. Tries to match `•` symbol appearance used in UITableView. @objc (MYTruncationItem) @objcMembers open class TruncationItem : UIView { override public init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func sizeThatFits(_ size: CGSize) -> CGSize { let circleBounds = circleBoundsForSize(size) return CGSize(width: circleBounds.width, height: circleBounds.height * 1.8) } private func circleBoundsForSize(_ size: CGSize) -> CGRect { let radius = round(size.height * 0.25) return CGRect(origin: CGPoint.zero, size: CGSize(width: radius * 2, height: radius * 2)) } open override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() var circleFrame = circleBoundsForSize(rect.size) circleFrame.center = rect.center context?.addEllipse(in: circleFrame) context?.setFillColor(tintColor.cgColor) context?.fillPath() } }
mit
ddd74e7a386c779fc7736516715c66c4
29.222222
96
0.652941
4.503311
false
false
false
false
juancruzmdq/LocationRequestManager
Sources/LocationRequest.swift
1
5834
//Copyright (c) 2016 Juan Cruz Ghigliani <[email protected]> // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN //THE SOFTWARE. //////////////////////////////////////////////////////////////////////////////// // MARK: Imports import Foundation import CoreLocation //////////////////////////////////////////////////////////////////////////////// // MARK: Types public typealias CompleteRequestBlock = (_ currentLocation:CLLocation?, _ error: Error?)->Void public enum LocationRequestStatus { case Pending case Active case Timeout case Canceled case Completed } /** * Class that define a Location Request to be executed by a LocationManager */ public class LocationRequest { //////////////////////////////////////////////////////////////////////////////// // MARK: Private Properties public var status:LocationRequestStatus = .Pending public var desiredAccuracy:CLLocationAccuracy = kCLLocationAccuracyThreeKilometers public var distanceFilter:CLLocationDistance = kCLDistanceFilterNone; public var recurrent:Bool = false public var timeout:TimeInterval? public var block:CompleteRequestBlock? public var latestLocation:CLLocation? public var latestError:Error? //////////////////////////////////////////////////////////////////////////////// // MARK: Public Properties private var timer:Timer? //////////////////////////////////////////////////////////////////////////////// // MARK: Public Methods //////////////////////////////////////////////////////////////////////////////// // MARK: Setup & Teardown public init(_ block:CompleteRequestBlock?){ self.block = block } //////////////////////////////////////////////////////////////////////////////// // MARK: Private Methods //////////////////////////////////////////////////////////////////////////////// // MARK: public Methods /** Change request status to .Start, if the request have a timeout, initialize the timer */ func start(){ // Change request status to .Active self.status = .Active // If there are an old timer active, invalidate it if let timer:Timer = self.timer { timer.invalidate() } // If there are a currenti timeout defined , start a new timer if let interval:TimeInterval = self.timeout { self.timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(LocationRequest.onTimeOut), userInfo: nil, repeats: false) } } /** Update current request with an error status, and finish the request - parameter error: instance of Error - returns: true if the request was updated */ func update(error: Error) -> Bool { self.latestError = error self.complete() return true } /** Update current request with a CLLocation, if the accuracy is the one defined by the user, and is not a reccurrent request, finish it - parameter location: instance of CLLocation - returns: true if the request was updated */ func update(location:CLLocation) -> Bool { // Clean latest location and error self.latestLocation = location self.latestError = nil if !recurrent { //horizontalAccuracy represent accuracy in meters, lower value reprecent lower level of error if location.horizontalAccuracy <= self.desiredAccuracy { self.complete() } } return true } /** Change request status to .Completed and stop request */ func complete(){ self.status = .Completed self.stopAndReport() } /** Change request status to .Canceled and stop request */ func cancel(){ self.status = .Canceled self.stopAndReport() } /** Change request status to .Timeout and stop request */ func timedOut(){ self.status = .Timeout self.stopAndReport() } /** Stop current request timer, and call block that report t the user */ func stopAndReport() { if let timer:Timer = self.timer { timer.invalidate() } if let blockToCall:CompleteRequestBlock = self.block { blockToCall(self.latestLocation,self.latestError) } } /** Time out Listener */ @objc private func onTimeOut(){ self.timedOut() } }
mit
488a2890ae009dee8128f6a6906e1e0a
32.722543
137
0.552965
5.714006
false
false
false
false
material-motion/material-motion-swift
src/interactions/ChangeDirection.swift
2
3052
/* Copyright 2017-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import Foundation import UIKit /** Changes the direction of a transition when the provided pan gesture recognizer completes. Without any configuration, will set the direction to backward if the absolute velocity exceeds minimumThreshold on the y axis. **Common configurations** *Modal dialogs and sheets*: cancel a dismissal when tossing up using `whenNegative: .forward`. **Constraints** Either the x or y axis can be selected. The default axis is y. */ public final class ChangeDirection: Interaction { /** The gesture recognizer that will be observed by this interaction. */ public let gesture: UIPanGestureRecognizer? /** The minimum absolute velocity required change the transition's direction. If this velocity is not met, the direction will not be changed. */ public let minimumVelocity: CGFloat /** The transition direction to emit when the velocity is below -minimumVelocity. */ public let whenNegative: TransitionDirection /** The transition direction to emit when the velocity is above minimumVelocity. */ public let whenPositive: TransitionDirection /** - parameter minimumVelocity: The minimum absolute velocity required to change the transition's direction. */ public init(withVelocityOf gesture: UIPanGestureRecognizer?, minimumVelocity: CGFloat = 100, whenNegative: TransitionDirection = .backward, whenPositive: TransitionDirection = .backward) { self.gesture = gesture self.minimumVelocity = minimumVelocity self.whenNegative = whenNegative self.whenPositive = whenPositive } /** The velocity axis to observe. */ public enum Axis { /** Observes the velocity's x axis. */ case x /** Observes the velocity's y axis. */ case y } public func add(to direction: ReactiveProperty<TransitionDirection>, withRuntime runtime: MotionRuntime, constraints axis: Axis?) { guard let gesture = gesture else { return } let axis = axis ?? .y let chooseAxis: (MotionObservable<CGPoint>) -> MotionObservable<CGFloat> switch axis { case .x: chooseAxis = { $0.x() } case .y: chooseAxis = { $0.y() } } runtime.connect(chooseAxis(runtime.get(gesture).velocityOnReleaseStream()) .thresholdRange(min: -minimumVelocity, max: minimumVelocity) .rewrite([.below: whenNegative, .above: whenPositive]), to: direction) } }
apache-2.0
8bf8c21dac1c086e727eb61e723e2773
29.52
190
0.720839
4.688172
false
false
false
false
eggswift/pull-to-refresh
ESPullToRefreshExample/ESPullToRefreshExample/WebViewController.swift
2
1768
// // WebViewController.swift // ESPullToRefreshExample // // Created by lihao on 16/5/6. // Copyright © 2016年 egg swift. All rights reserved. // import UIKit class WebViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var networkTipsButton: UIButton! @IBOutlet weak var webViewXib: UIWebView! var webView: UIWebView! override func viewDidLoad() { super.viewDidLoad() if let _ = self.webViewXib { self.webView = self.webViewXib } else { self.webView = UIWebView() self.webView.frame = self.view.bounds self.view.addSubview(self.webView!) } self.webView!.delegate = self let url = "https://github.com/eggswift" self.title = "egg swift" let request = NSURLRequest.init(url: NSURL(string: url)! as URL) self.webView.scrollView.es.addPullToRefresh { [weak self] in self?.webView.loadRequest(request as URLRequest) } self.webView.scrollView.es.startPullToRefresh() } func webViewDidFinishLoad(_ webView: UIWebView) { self.webView.scrollView.es.stopPullToRefresh() self.webView.scrollView.bounces = true self.webView.scrollView.alwaysBounceVertical = true } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { self.webView.scrollView.es.stopPullToRefresh(ignoreDate: true) self.networkTipsButton.isHidden = false } @IBAction func networkRetryAction(_ sender: AnyObject) { self.networkTipsButton.isHidden = true UIView.performWithoutAnimation { self.webView.scrollView.es.startPullToRefresh() } } }
mit
14de148375d3415eba7ffcbe0ddc783e
29.431034
75
0.637394
4.694149
false
false
false
false
ijovi23/JvPunchIO
JvPunchIO-Recorder/JvPunchIO-Recorder/Model/PRRecordGroup.swift
1
986
// // PRRecordModel.swift // JvPunchIO-Recorder // // Created by Jovi Du on 21/10/2016. // Copyright © 2016 org.Jovistudio. All rights reserved. // import UIKit class PRRecordGroup: NSObject, NSCoding { var date : String = "2000-00-00" var records : [Date] = [] init(withDate date: String, records: [Date]) { self.date = date self.records = records } func encode(with aCoder: NSCoder) { aCoder.encode(date, forKey: "date") aCoder.encode(records, forKey: "records") } required init?(coder aDecoder: NSCoder) { self.date = aDecoder.decodeObject(forKey: "date") as! String self.records = aDecoder.decodeObject(forKey: "records") as! [Date] } func calcDuration() -> TimeInterval { var dur : TimeInterval = 0 if records.count >= 2 { dur = records.first!.timeIntervalSince(records.last!) } return dur } }
mit
5e30a59c6555c88f153d358835364508
23.02439
74
0.581726
3.971774
false
false
false
false
yangyouyong0/SwiftLearnLog
LearnBBS/LearnBBS/AEXML.swift
3
10142
// // AEXML.swift // // Copyright (c) 2014 Marko Tadić <[email protected]> http://tadija.net // // 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 public class AEXMLElement { // MARK: Properties public private(set) weak var parent: AEXMLElement? public private(set) var children: [AEXMLElement] = [AEXMLElement]() public let name: String public private(set) var attributes: [NSObject : AnyObject] public var value: String? public var stringValue: String { return value ?? String() } public var boolValue: Bool { return stringValue.lowercaseString == "true" || stringValue.toInt() == 1 ? true : false } public var intValue: Int { return stringValue.toInt() ?? 0 } public var doubleValue: Double { return (stringValue as NSString).doubleValue } // MARK: Lifecycle public init(_ name: String, value: String? = nil, attributes: [NSObject : AnyObject] = [NSObject : AnyObject]()) { self.name = name self.attributes = attributes self.value = value } // MARK: XML Read // this element name is used when unable to find element public class var errorElementName: String { return "AEXMLError" } // non-optional first element with given name (<error> element if not exists) public subscript(key: String) -> AEXMLElement { if name == AEXMLElement.errorElementName { return self } else { let filtered = children.filter { $0.name == key } return filtered.count > 0 ? filtered.first! : AEXMLElement(AEXMLElement.errorElementName, value: "element <\(key)> not found") } } public var all: [AEXMLElement]? { return parent?.children.filter { $0.name == self.name } } public var first: AEXMLElement? { return all?.first } public var last: AEXMLElement? { return all?.last } public var count: Int { return all?.count ?? 0 } public func allWithAttributes <K: NSObject, V: AnyObject where K: Equatable, V: Equatable> (attributes: [K : V]) -> [AEXMLElement]? { var found = [AEXMLElement]() if let elements = all { for element in elements { var countAttributes = 0 for (key, value) in attributes { if element.attributes[key] as? V == value { countAttributes++ } } if countAttributes == attributes.count { found.append(element) } } return found.count > 0 ? found : nil } else { return nil } } public func countWithAttributes <K: NSObject, V: AnyObject where K: Equatable, V: Equatable> (attributes: [K : V]) -> Int { return allWithAttributes(attributes)?.count ?? 0 } // MARK: XML Write public func addChild(child: AEXMLElement) -> AEXMLElement { child.parent = self children.append(child) return child } public func addChild(#name: String, value: String? = nil, attributes: [NSObject : AnyObject] = [NSObject : AnyObject]()) -> AEXMLElement { let child = AEXMLElement(name, value: value, attributes: attributes) return addChild(child) } public func addAttribute(name: NSObject, value: AnyObject) { attributes[name] = value } public func addAttributes(attributes: [NSObject : AnyObject]) { for (attributeName, attributeValue) in attributes { addAttribute(attributeName, value: attributeValue) } } private var parentsCount: Int { var count = 0 var element = self while let parent = element.parent { count++ element = parent } return count } private func indentation(count: Int) -> String { var indent = String() if count > 0 { for i in 0..<count { indent += "\t" } } return indent } public var xmlString: String { var xml = String() // open element xml += indentation(parentsCount - 1) xml += "<\(name)" if attributes.count > 0 { // insert attributes for att in attributes { xml += " \(att.0.description)=\"\(att.1.description)\"" } } if value == nil && children.count == 0 { // close element xml += " />" } else { if children.count > 0 { // add children xml += ">\n" for child in children { xml += "\(child.xmlString)\n" } // add indentation xml += indentation(parentsCount - 1) xml += "</\(name)>" } else { // insert string value and close element xml += ">\(stringValue)</\(name)>" } } return xml } public var xmlStringCompact: String { let chars = NSCharacterSet(charactersInString: "\n\t") return join("", xmlString.componentsSeparatedByCharactersInSet(chars)) } } // MARK: - public class AEXMLDocument: AEXMLElement { // MARK: Properties public let version: Double public let encoding: String public let standalone: String public var root: AEXMLElement { return children.count == 1 ? children.first! : AEXMLElement(AEXMLElement.errorElementName, value: "XML Document must have root element.") } // MARK: Lifecycle public init(version: Double = 1.0, encoding: String = "utf-8", standalone: String = "no", root: AEXMLElement? = nil) { // set document properties self.version = version self.encoding = encoding self.standalone = standalone // init super with default name super.init("AEXMLDocument") // document has no parent element parent = nil // add root element to document (if any) if let rootElement = root { addChild(rootElement) } } public convenience init?(version: Double = 1.0, encoding: String = "utf-8", standalone: String = "no", xmlData: NSData, inout error: NSError?) { self.init(version: version, encoding: encoding, standalone: standalone) if let parseError = readXMLData(xmlData) { error = parseError return nil } } // MARK: Read XML public func readXMLData(data: NSData) -> NSError? { children.removeAll(keepCapacity: false) let xmlParser = AEXMLParser(xmlDocument: self, xmlData: data) return xmlParser.tryParsing() ?? nil } // MARK: Override public override var xmlString: String { var xml = "<?xml version=\"\(version)\" encoding=\"\(encoding)\" standalone=\"\(standalone)\"?>\n" for child in children { xml += child.xmlString } return xml } } // MARK: - class AEXMLParser: NSObject, NSXMLParserDelegate { // MARK: Properties let xmlDocument: AEXMLDocument let xmlData: NSData var currentParent: AEXMLElement? var currentElement: AEXMLElement? var currentValue = String() var parseError: NSError? // MARK: Lifecycle init(xmlDocument: AEXMLDocument, xmlData: NSData) { self.xmlDocument = xmlDocument self.xmlData = xmlData currentParent = xmlDocument super.init() } // MARK: XML Parse func tryParsing() -> NSError? { var success = false let parser = NSXMLParser(data: xmlData) parser.delegate = self success = parser.parse() return success ? nil : parseError } // MARK: NSXMLParserDelegate func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [NSObject : AnyObject]) { currentValue = String() currentElement = currentParent?.addChild(name: elementName, attributes: attributeDict) currentParent = currentElement } func parser(parser: NSXMLParser, foundCharacters string: String?) { currentValue += string ?? String() let newValue = currentValue.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) currentElement?.value = newValue == String() ? nil : newValue } func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { currentParent = currentParent?.parent currentElement = nil } func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) { self.parseError = parseError } }
apache-2.0
78b3b8afdbd502bc3b138d93191e8650
30.993691
178
0.592151
5.022784
false
false
false
false
m0rb1u5/iOS_10_1
iOS_15_1 Extension/IngredientesWKController.swift
1
2920
// // IngredientesWKController.swift // iOS_10_1 // // Created by Juan Carlos Carbajal Ipenza on 18/04/16. // Copyright © 2016 Juan Carlos Carbajal Ipenza. All rights reserved. // import WatchKit import Foundation class IngredientesWKController: WKInterfaceController { var jamon: Bool = false var pepperoni: Bool = false var pavo: Bool = false var salchicha: Bool = false var aceituna: Bool = false var cebolla: Bool = false var pimiento: Bool = false var pina: Bool = false var anchoa: Bool = false var carne: Bool = false var valorContexto: Valor = Valor() override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) self.setTitle("Ingredientes") valorContexto = context as! Valor } override func willActivate() { super.willActivate() } override func didDeactivate() { super.didDeactivate() } @IBAction func continuar() { valorContexto.ingredientes.removeAll() if (jamon) { valorContexto.ingredientes.append("Jamón") } if (pepperoni) { valorContexto.ingredientes.append("Pepperoni") } if (pavo) { valorContexto.ingredientes.append("Pavo") } if (salchicha) { valorContexto.ingredientes.append("Salchicha") } if (aceituna) { valorContexto.ingredientes.append("Aceituna") } if (cebolla) { valorContexto.ingredientes.append("Cebolla") } if (pimiento) { valorContexto.ingredientes.append("Pimiento") } if (pina) { valorContexto.ingredientes.append("Piña") } if (anchoa) { valorContexto.ingredientes.append("Anchoa") } if (carne) { valorContexto.ingredientes.append("Carne") } if (valorContexto.ingredientes.count>=1&&valorContexto.ingredientes.count<=5) { pushControllerWithName("idConfirmacion", context: valorContexto) print(valorContexto.ingredientes) } } @IBAction func guardarJamon(value: Bool) { jamon = value } @IBAction func guardarPepperoni(value: Bool) { pepperoni = value } @IBAction func guardarPavo(value: Bool) { pavo = value } @IBAction func guardarSalchicha(value: Bool) { salchicha = value } @IBAction func guardarAceituna(value: Bool) { aceituna = value } @IBAction func guardarCebolla(value: Bool) { cebolla = value } @IBAction func guardarPimiento(value: Bool) { pimiento = value } @IBAction func guardarPina(value: Bool) { pina = value } @IBAction func guardarAnchoa(value: Bool) { anchoa = value } @IBAction func guardarCarne(value: Bool) { carne = value } }
gpl-3.0
7a51b4fb6a07043e0392b8c52ff8b5b3
27.048077
87
0.60096
3.899733
false
false
false
false
victorlin/ReactiveCocoa
ReactiveCocoa/Swift/Observer.swift
1
2640
// // Observer.swift // ReactiveCocoa // // Created by Andy Matuschak on 10/2/15. // Copyright © 2015 GitHub. All rights reserved. // /// A protocol for type-constrained extensions of `Observer`. public protocol ObserverProtocol { associatedtype Value associatedtype Error: Swift.Error /// Puts a `next` event into `self`. func sendNext(_ value: Value) /// Puts a failed event into `self`. func sendFailed(_ error: Error) /// Puts a `completed` event into `self`. func sendCompleted() /// Puts an `interrupted` event into `self`. func sendInterrupted() } /// An Observer is a simple wrapper around a function which can receive Events /// (typically from a Signal). public final class Observer<Value, Error: Swift.Error> { public typealias Action = @escaping (Event<Value, Error>) -> Void /// An action that will be performed upon arrival of the event. public let action: Action /// An initializer that accepts a closure accepting an event for the /// observer. /// /// - parameters: /// - action: A closure to lift over received event. public init(_ action: Action) { self.action = action } /// An initializer that accepts closures for different event types. /// /// - parameters: /// - next: Optional closure executed when a `next` event is observed. /// - failed: Optional closure that accepts an `Error` parameter when a /// failed event is observed. /// - completed: Optional closure executed when a `completed` event is /// observed. /// - interruped: Optional closure executed when an `interrupted` event is /// observed. public convenience init( next: ((Value) -> Void)? = nil, failed: ((Error) -> Void)? = nil, completed: (() -> Void)? = nil, interrupted: (() -> Void)? = nil ) { self.init { event in switch event { case let .next(value): next?(value) case let .failed(error): failed?(error) case .completed: completed?() case .interrupted: interrupted?() } } } } extension Observer: ObserverProtocol { /// Puts a `next` event into `self`. /// /// - parameters: /// - value: A value sent with the `next` event. public func sendNext(_ value: Value) { action(.next(value)) } /// Puts a failed event into `self`. /// /// - parameters: /// - error: An error object sent with failed event. public func sendFailed(_ error: Error) { action(.failed(error)) } /// Puts a `completed` event into `self`. public func sendCompleted() { action(.completed) } /// Puts an `interrupted` event into `self`. public func sendInterrupted() { action(.interrupted) } }
mit
1040afb7e4ba31fd5f45ae80f01d510e
24.375
78
0.650625
3.605191
false
false
false
false
linkedin/LayoutKit
LayoutKitSampleApp/FeedScrollViewController.swift
6
2189
// Copyright 2016 LinkedIn Corp. // 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. import UIKit import LayoutKit /// Displays a feed using a UIScrollView class FeedScrollViewController: FeedBaseViewController { private var scrollView: UIScrollView! private var cachedFeedLayout: Layout? override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.purple scrollView = UIScrollView(frame: view.bounds) scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(scrollView) self.layoutFeed(width: self.view.bounds.width) } private func layoutFeed(width: CGFloat) { let _ = CFAbsoluteTimeGetCurrent() DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { let arrangement = self.getFeedLayout().arrangement(width: width) DispatchQueue.main.async(execute: { self.scrollView.contentSize = arrangement.frame.size arrangement.makeViews(in: self.scrollView) let _ = CFAbsoluteTimeGetCurrent() // NSLog("user: \((end-start).ms)") }) } } func getFeedLayout() -> Layout { if let cachedFeedLayout = cachedFeedLayout { return cachedFeedLayout } let feedItems = getFeedItems() let feedLayout = StackLayout( axis: .vertical, distribution: .leading, sublayouts: feedItems ) cachedFeedLayout = feedLayout return feedLayout } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) layoutFeed(width: size.width) } }
apache-2.0
4408e513f5c69992f2fa140156aaefe3
34.885246
131
0.668342
4.952489
false
false
false
false
AdySan/HomeKit-Demo
BetterHomeKit/AddAccessoriesViewController.swift
4
3844
// // AddAccessoriesViewController.swift // BetterHomeKit // // Created by Khaos Tian on 6/4/14. // Copyright (c) 2014 Oltica. All rights reserved. // import UIKit import HomeKit let addAccessoryNotificationString = "DidAddHomeAccessory" class AddAccessoriesViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,HMAccessoryBrowserDelegate { @IBOutlet var accessoriesTableView : UITableView! lazy var accessories = [HMAccessory]() var accessoriesManager:HMAccessoryBrowser = HMAccessoryBrowser() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization } required init(coder aDecoder: NSCoder){ super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() accessoriesManager.delegate = self // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) accessoriesManager.startSearchingForNewAccessories() } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) accessoriesManager.stopSearchingForNewAccessories() } @IBAction func dismissAddAccessories(sender : AnyObject) { dismissViewControllerAnimated(true, completion: nil) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return accessories.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! UITableViewCell cell.textLabel?.text = accessories[indexPath.row].name return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) Core.sharedInstance.currentHome?.addAccessory(accessories[indexPath.row], completionHandler: { (error:NSError!) in if error != nil { NSLog("\(error)") }else{ NSNotificationCenter.defaultCenter().postNotificationName(addAccessoryNotificationString, object: nil) } } ) } func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) { let accessory = accessories[indexPath.row] accessory.identifyWithCompletionHandler({ (error:NSError!) in if error != nil { println("Failed to identify \(error)") } }) } func accessoryBrowser(browser: HMAccessoryBrowser, didFindNewAccessory accessory: HMAccessory!) { if !contains(accessories, accessory) { accessories.insert(accessory, atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) accessoriesTableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } } func accessoryBrowser(browser: HMAccessoryBrowser, didRemoveNewAccessory accessory: HMAccessory!) { if let index = find(accessories, accessory) { accessories.removeAtIndex(index) accessoriesTableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .Fade) } } }
mit
6e1e99258356726938e0f0e05d59c5ad
32.719298
137
0.664932
5.661267
false
false
false
false
mozilla-magnet/magnet-client
ios/RegionManager.swift
1
2908
// // RegionManager.swift // Magnet // // Created by Francisco Jordano on 09/11/2016. // Copyright © 2016 Mozilla. All rights reserved. // // This class takes care of waking up in background and // checking the current location to know if there are interesting // things around. // In order to do this we use the region functionality in iOS. // We setup circular regions centered in the current location of the user, // when the OS detect that we abandon that region, we get a callback and have // some time in the background to get a meassure of the new location, check // if there are interesting things around and setup the new region. // // This process will happen, creation of the region, detection of the region // being abandoned, checking things around, and again we start. import Foundation import CoreLocation import MagnetScannerIOS @objc(RegionManager) class RegionManager: NSObject, CLLocationManagerDelegate { let locationManager:CLLocationManager = CLLocationManager() private static let REGION_NAME = "region.magnet.mozilla.org" private static let REGION_RADIUS: Double = 50 var scanner: MagnetScanner? = nil var isEnabled = true var currentRegion: CLRegion? let locationResolver: LocationHelper = LocationHelper() @objc override init() { super.init() isEnabled = CLLocationManager.isMonitoringAvailableForClass(CLRegion.self) guard isEnabled else { Log.w("Region monitoring not enabled for this device") return; } scanner = MagnetScanner(callback: self.onItemFound) } private func onItemFound(item: Dictionary<String, AnyObject>) { Log.l("Found item on leaving region \(item)") let url = item["url"] as! String var channel: String? = nil if item["channel_id"] != nil { channel = item["channel_id"] as! String } NotificationsHelper.notifyUser(url, channel: channel) } @objc func startListeningToRegionChange() { guard isEnabled else { return } Log.l("Start listening to region changes") self.locationManager.delegate = self setupRegion() } @objc func stopListeningToRegionChange() { guard isEnabled && self.currentRegion != nil else { return } Log.l("Stoping listening to region changes") self.locationManager.stopMonitoringForRegion(self.currentRegion!) } private func setupRegion() { locationResolver.start { location in let region = CLCircularRegion(center: location.coordinate, radius: RegionManager.REGION_RADIUS, identifier: RegionManager.REGION_NAME) self.currentRegion = region Log.l("Setting up region \(region)") self.locationManager.startMonitoringForRegion(region) } } func locationManager(manager: CLLocationManager, didExitRegion region: CLRegion) { setupRegion() Log.l("Waking up case region abandoned") self.scanner!.start() } }
mpl-2.0
09b2e997ab2ad3e50c8b03a772d16662
32.413793
140
0.714826
4.371429
false
false
false
false
hulu001/AMScrollingNavbar
Demo/ScrollingNavbarDemoTests/ScrollingNavbarDemoTests.swift
2
3076
import UIKit import Quick import Nimble import Nimble_Snapshots import AMScrollingNavbar extension UIViewController { func preloadView() { let _ = self.view } } class TableController: UITableViewController, ScrollingNavigationControllerDelegate { var called = false var status = NavigationBarState.Expanded func scrollingNavigationController(controller: ScrollingNavigationController, didChangeState state: NavigationBarState) { called = true status = state } } class DataSource: NSObject, UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 100 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) cell.textLabel?.text = "Row \(indexPath.row)" if indexPath.row % 2 == 0 { cell.backgroundColor = UIColor(white: 0.8, alpha: 1) } else { cell.backgroundColor = UIColor(white: 0.9, alpha: 1) } return cell } } class ScrollingNavbarDemoTests: QuickSpec { override func spec() { var subject: ScrollingNavigationController! let dataSource = DataSource() var tableController: TableController? beforeEach { tableController = TableController(style: .Plain) tableController?.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "Cell") tableController?.tableView.dataSource = dataSource subject = ScrollingNavigationController(rootViewController: tableController!) subject.scrollingNavbarDelegate = tableController UIApplication.sharedApplication().keyWindow!.rootViewController = subject subject.preloadView() tableController?.tableView.reloadData() subject.followScrollView(tableController!.tableView, delay: 0) } describe("hideNavbar") { it("should hide the navigation bar") { subject.hideNavbar(animated: false) expect(subject.view).to(haveValidSnapshot()) } } describe("showNavbar") { it("should show the navigation bar") { subject.hideNavbar(animated: false) subject.showNavbar(animated: false) expect(subject.view).toEventually(haveValidSnapshot(), timeout: 2, pollInterval: 1) } } describe("ScrollingNavigationControllerDelegate") { it("should call the delegate with the new state of scroll") { subject.hideNavbar(animated: false) expect(tableController?.called).to(beTrue()) expect(tableController?.status).to(equal(NavigationBarState.Scrolling)) expect(tableController?.status).toEventually(equal(NavigationBarState.Collapsed), timeout: 2, pollInterval: 1) } } } }
mit
5ba4cc9030b95b6d1edbad0a8bb01f77
34.767442
126
0.656697
5.6234
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Model/Activity.swift
1
5673
//// /// Activity.swift // //import Crashlytics import SwiftyJSON let ActivityVersion = 1 @objc(Activity) public final class Activity: JSONAble { // active record public let id: String public let createdAt: NSDate // required public let kind: Kind public let subjectType: SubjectType // links public var subject: JSONAble? { return getLinkObject(identifier: "subject") } public enum Kind: String { // Posts case FriendPost = "friend_post" // main feed case OwnPost = "own_post" // main feed case WelcomePost = "welcome_post" // main feed case NoisePost = "noise_post" // main feed // Comments case FriendComment = "friend_comment" // Notifications case NewFollowerPost = "new_follower_post" // someone started following you case NewFollowedUserPost = "new_followed_user_post" // you started following someone case InvitationAcceptedPost = "invitation_accepted_post" // someone accepted your invitation case PostMentionNotification = "post_mention_notification" // you were mentioned in a post case CommentMentionNotification = "comment_mention_notification" // you were mentioned in a comment case CommentNotification = "comment_notification" // someone commented on your post case CommentOnOriginalPostNotification = "comment_on_original_post_notification" // someone commented on your repost case CommentOnRepostNotification = "comment_on_repost_notification" // someone commented on other's repost of your post case WelcomeNotification = "welcome_notification" // welcome to Ello case RepostNotification = "repost_notification" // someone reposted your post case WatchNotification = "watch_notification" // someone watched your post on ello case WatchCommentNotification = "watch_comment_notification" // someone commented on a post you're watching case WatchOnRepostNotification = "watch_on_repost_notification" // someone watched your repost case WatchOnOriginalPostNotification = "watch_on_original_post_notification" // someone watched other's repost of your post case LoveNotification = "love_notification" // someone loved your post case LoveOnRepostNotification = "love_on_repost_notification" // someone loved your repost case LoveOnOriginalPostNotification = "love_on_original_post_notification" // someone loved other's repost of your post // Deprecated posts case CommentMention = "comment_mention" // Fallback for not defined types case Unknown = "Unknown" } public enum SubjectType: String { case User = "User" case Post = "Post" case Comment = "Comment" case Unknown = "Unknown" } // MARK: Initialization public init(id: String, createdAt: NSDate, kind: Kind, subjectType: SubjectType) { self.id = id self.createdAt = createdAt self.kind = kind self.subjectType = subjectType super.init(version: ActivityVersion) } // MARK: NSCoding public required init(coder aDecoder: NSCoder) { let decoder = Coder(aDecoder) // active record self.id = decoder.decodeKey(key: "id") self.createdAt = decoder.decodeKey(key: "createdAt") // required let rawKind: String = decoder.decodeKey(key: "rawKind") self.kind = Kind(rawValue: rawKind) ?? Kind.Unknown let rawSubjectType: String = decoder.decodeKey(key: "rawSubjectType") self.subjectType = SubjectType(rawValue: rawSubjectType) ?? SubjectType.Unknown super.init(coder: decoder.coder) } public override func encode(with encoder: NSCoder) { let coder = Coder(encoder) // active record coder.encodeObject(obj: id, forKey: "id") coder.encodeObject(obj: createdAt, forKey: "createdAt") // required coder.encodeObject(obj: kind.rawValue, forKey: "rawKind") coder.encodeObject(obj: subjectType.rawValue, forKey: "rawSubjectType") super.encode(with: coder.coder) } // MARK: JSONAble override public class func fromJSON(data: [String: AnyObject], fromLinked: Bool = false) -> JSONAble { let json = JSON(data) // Crashlytics.sharedInstance().setObjectValue(json.rawString(), forKey: CrashlyticsKey.ActivityFromJSON.rawValue) // active record let id = json["created_at"].stringValue var createdAt: NSDate // if let date = id.toNSDate() { // // good to go // createdAt = date // } // else { createdAt = NSDate() // // send data to segment to try to get more data about this // Tracker.sharedTracker.createdAtCrash("Activity", json: json.rawString()) // } // create activity let activity = Activity( id: id, createdAt: createdAt, kind: Kind(rawValue: json["kind"].stringValue) ?? Kind.Unknown, subjectType: SubjectType(rawValue: json["subject_type"].stringValue) ?? SubjectType.Unknown ) // links activity.links = data["links"] as? [String: AnyObject] // store self in collection // if !fromLinked { // ElloLinkedStore.sharedInstance.setObject(activity, forKey: activity.id, inCollection: MappingType.ActivitiesType.rawValue) // } return activity } }
mit
4627d0d10cd49bb0d31e8840b3d49cae
38.950704
136
0.636524
4.807627
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/NotificationsCenterDetailViewModel+ActionExtensions.swift
1
11091
import Foundation extension NotificationsCenterDetailViewModel { var primaryAction: NotificationsCenterAction? { switch commonViewModel.notification.type { case .userTalkPageMessage: if let talkPageAction = commonViewModel.titleAction(needsConvertToOrFromTalk: false, simplified: true) { return talkPageAction } case .mentionInTalkPage: if let titleTalkPageAction = commonViewModel.titleAction(needsConvertToOrFromTalk: false, simplified: true) { return titleTalkPageAction } case .editReverted, .mentionInEditSummary: if let diffAction = commonViewModel.diffAction { return diffAction } case .successfulMention, .failedMention, .pageReviewed, .editMilestone: if let titleAction = commonViewModel.titleAction(needsConvertToOrFromTalk: false, simplified: true) { return titleAction } case .userRightsChange: if let userGroupRightsAction = commonViewModel.userGroupRightsAction { return userGroupRightsAction } case .pageLinked: if let pageLinkFromAction = commonViewModel.pageLinkFromAction { return pageLinkFromAction } case .connectionWithWikidata: if let wikidataItemAction = commonViewModel.wikidataItemAction { return wikidataItemAction } case .emailFromOtherUser: if let agentUserPageAction = commonViewModel.agentUserPageAction { return agentUserPageAction } case .thanks: if let diffAction = commonViewModel.diffAction { return diffAction } case .translationMilestone: return nil case .welcome: if let gettingStartedAction = commonViewModel.gettingStartedAction { return gettingStartedAction } case .loginFailKnownDevice, .loginFailUnknownDevice, .loginSuccessUnknownDevice: if let changePasswordAction = commonViewModel.changePasswordAction { return changePasswordAction } case .unknownAlert, .unknownSystemAlert: if let primaryLink = commonViewModel.notification.primaryLink, let primaryAction = commonViewModel.actionForGenericLink(link: primaryLink) { return primaryAction } case .unknownSystemNotice, .unknownNotice, .unknown: if let primaryLink = commonViewModel.notification.primaryLink, let primaryAction = commonViewModel.actionForGenericLink(link: primaryLink) { return primaryAction } } return nil } var secondaryActions: [NotificationsCenterAction] { var secondaryActions: [NotificationsCenterAction] = [] switch commonViewModel.notification.type { case .userTalkPageMessage: secondaryActions.append(contentsOf: userTalkPageActions) case .mentionInTalkPage: secondaryActions.append(contentsOf: mentionInTalkPageActions) case .editReverted: secondaryActions.append(contentsOf: editRevertedActions) case .mentionInEditSummary: secondaryActions.append(contentsOf: mentionInEditSummaryActions) case .successfulMention, .failedMention: secondaryActions.append(contentsOf: successfulAndFailedMentionActions) case .userRightsChange: secondaryActions.append(contentsOf: userGroupRightsActions) case .pageReviewed: secondaryActions.append(contentsOf: pageReviewedActions) case .pageLinked: secondaryActions.append(contentsOf: pageLinkActions) case .connectionWithWikidata: secondaryActions.append(contentsOf: connectionWithWikidataActions) case .emailFromOtherUser: secondaryActions.append(contentsOf: emailFromOtherUserActions) case .thanks: secondaryActions.append(contentsOf: thanksActions) case .translationMilestone, .editMilestone, .welcome: break case .loginFailKnownDevice, .loginFailUnknownDevice, .loginSuccessUnknownDevice: secondaryActions.append(contentsOf: loginActions) case .unknownAlert, .unknownSystemAlert: secondaryActions.append(contentsOf: genericAlertActions) case .unknownSystemNotice, .unknownNotice, .unknown: secondaryActions.append(contentsOf: genericActions) } return secondaryActions } /// Do not include secondary action if its destination is the same as the primary action or any other secondary action var uniqueSecondaryActions: [NotificationsCenterAction] { guard let primaryActionURL = primaryAction?.actionData?.url else { return secondaryActions } let filteredArray = secondaryActions.filter({ action in action.actionData?.url != primaryActionURL }) return NSOrderedSet(array: filteredArray).compactMap { $0 as? NotificationsCenterAction } } } // MARK: Private Helpers - Aggregate Swipe Action methods private extension NotificationsCenterDetailViewModel { var userTalkPageActions: [NotificationsCenterAction] { var actions: [NotificationsCenterAction] = [] if let agentUserPageAction = commonViewModel.agentUserPageAction { actions.append(agentUserPageAction) } if let diffAction = commonViewModel.diffAction { actions.append(diffAction) } return actions } var mentionInTalkPageActions: [NotificationsCenterAction] { var actions: [NotificationsCenterAction] = [] if let agentUserPageAction = commonViewModel.agentUserPageAction { actions.append(agentUserPageAction) } if let diffAction = commonViewModel.diffAction { actions.append(diffAction) } if let titleAction = commonViewModel.titleAction(needsConvertToOrFromTalk: true, simplified: true) { actions.append(titleAction) } return actions } var mentionInEditSummaryActions: [NotificationsCenterAction] { var actions: [NotificationsCenterAction] = [] if let agentUserPageAction = commonViewModel.agentUserPageAction { actions.append(agentUserPageAction) } if let titleAction = commonViewModel.titleAction(needsConvertToOrFromTalk: false, simplified: true) { actions.append(titleAction) } return actions } var successfulAndFailedMentionActions: [NotificationsCenterAction] { return [] } var editRevertedActions: [NotificationsCenterAction] { var actions: [NotificationsCenterAction] = [] if let agentUserPageAction = commonViewModel.agentUserPageAction { actions.append(agentUserPageAction) } if let talkTitleAction = commonViewModel.titleAction(needsConvertToOrFromTalk: true, simplified: true) { actions.append(talkTitleAction) } if let titleAction = commonViewModel.titleAction(needsConvertToOrFromTalk: false, simplified: true) { actions.append(titleAction) } return actions } var userGroupRightsActions: [NotificationsCenterAction] { var actions: [NotificationsCenterAction] = [] if let specificUserGroupRightsAction = commonViewModel.specificUserGroupRightsAction { actions.append(specificUserGroupRightsAction) } if let agentUserPageAction = commonViewModel.agentUserPageAction { actions.append(agentUserPageAction) } return actions } var pageReviewedActions: [NotificationsCenterAction] { var actions: [NotificationsCenterAction] = [] if let agentUserPageAction = commonViewModel.agentUserPageAction { actions.append(agentUserPageAction) } return actions } var pageLinkActions: [NotificationsCenterAction] { var actions: [NotificationsCenterAction] = [] if let agentUserPageAction = commonViewModel.agentUserPageAction { actions.append(agentUserPageAction) } // Article you edited if let titleAction = commonViewModel.titleAction(needsConvertToOrFromTalk: false, simplified: false) { actions.append(titleAction) } if let diffAction = commonViewModel.diffAction { actions.append(diffAction) } return actions } var connectionWithWikidataActions: [NotificationsCenterAction] { var actions: [NotificationsCenterAction] = [] if let agentUserPageAction = commonViewModel.agentUserPageAction { actions.append(agentUserPageAction) } if let titleAction = commonViewModel.titleAction(needsConvertToOrFromTalk: false, simplified: true) { actions.append(titleAction) } return actions } var emailFromOtherUserActions: [NotificationsCenterAction] { return [] } var thanksActions: [NotificationsCenterAction] { var actions: [NotificationsCenterAction] = [] if let agentUserPageAction = commonViewModel.agentUserPageAction { actions.append(agentUserPageAction) } if let titleAction = commonViewModel.titleAction(needsConvertToOrFromTalk: false, simplified: true) { actions.append(titleAction) } return actions } var loginActions: [NotificationsCenterAction] { var actions: [NotificationsCenterAction] = [] if let loginHelpAction = commonViewModel.loginNotificationsGoToAction { actions.append(loginHelpAction) } return actions } var genericAlertActions: [NotificationsCenterAction] { var actions: [NotificationsCenterAction] = [] if let secondaryLinks = commonViewModel.notification.secondaryLinks { let secondaryActions = secondaryLinks.compactMap { commonViewModel.actionForGenericLink(link:$0) } actions.append(contentsOf: secondaryActions) } if let diffAction = commonViewModel.diffAction { actions.append(diffAction) } return actions } var genericActions: [NotificationsCenterAction] { var actions: [NotificationsCenterAction] = [] if let agentUserPageAction = commonViewModel.agentUserPageAction { actions.append(agentUserPageAction) } if let diffAction = commonViewModel.diffAction { actions.append(diffAction) } return actions } }
mit
bf22ab94632bf2d9f038cbf64d5ac2b0
33.021472
122
0.652241
5.248935
false
false
false
false
NoryCao/zhuishushenqi
zhuishushenqi/NewVersion/ZSExtension/ZSExtension/Classes/NSObject+Extension.swift
2
791
// // NSObject+Extension.swift // zhuishushenqi // // Created by yung on 2018/2/6. // Copyright © 2018年 QS. All rights reserved. // import Foundation extension NSObject { public func fetchProperties() ->[String:Any] { var outCount:UInt32 = 0 let properties = class_copyPropertyList(self.classForCoder, &outCount) var dict = [String:Any]() let count = Int(outCount) for idx in 0..<count { let property = properties![idx] let ivarName = property_getName(property) let ivarKey = String(cString: ivarName) let ivarValue = value(forKey: ivarKey) if let iValue = ivarValue { dict["\(ivarKey)"] = iValue as Any } } return dict } }
mit
dbdad03bc38779d87792ae437717f711
26.172414
78
0.574873
4.169312
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceModel/Sources/EurofurenceModel/Private/Services/URL/ConcreteContentLinksService.swift
1
728
import Foundation class ConcreteContentLinksService: ContentLinksService { private let urlEntityProcessor: URLEntityProcessor init(urlEntityProcessor: URLEntityProcessor) { self.urlEntityProcessor = urlEntityProcessor } func lookupContent(for link: Link) -> LinkContentLookupResult? { guard let urlString = link.contents as? String, let url = URL(string: urlString) else { return nil } if let scheme = url.scheme, scheme == "https" || scheme == "http" { return .web(url) } return .externalURL(url) } func describeContent(in url: URL, toVisitor visitor: URLContentVisitor) { urlEntityProcessor.process(url, visitor: visitor) } }
mit
b8c7b5708b039c5b84d483703f033a85
28.12
108
0.677198
4.333333
false
false
false
false
ello/ello-ios
Sources/Controllers/Profile/Cells/ProfileHeaderLinksCell.swift
1
6788
//// /// ProfileHeaderLinksCell.swift // import SnapKit class ProfileHeaderLinksCell: ProfileHeaderCell { static let reuseIdentifier = "ProfileHeaderLinksCell" struct Size { static let margins = UIEdgeInsets(top: 12, left: 15, bottom: 15, right: 15) static let iconInsets = UIEdgeInsets(all: 15) static let iconSize = CGSize(width: 22, height: 22) static let iconMargins: CGFloat = 10 static let verticalLinkMargin: CGFloat = 3 static let horizLinkButtonMargin: CGFloat = 5 static let linkHeight: CGFloat = 26 } var externalLinks: [ExternalLink] = [] { didSet { setNeedsUpdateConstraints() rearrangeLinks() } } private var linksBox = UIView() private var iconsBox = UIView() private var linkButtons: [UIButton] = [] private var iconButtons: [UIButton] = [] private var buttonLinks: [UIButton: ExternalLink] = [:] override func style() { backgroundColor = .white iconsBox.backgroundColor = .white } override func arrange() { contentView.addSubview(linksBox) contentView.addSubview(iconsBox) linksBox.snp.makeConstraints { make in make.leading.top.bottom.equalTo(contentView).inset(Size.margins) make.trailing.equalTo(iconsBox.snp.leading).offset(-Size.horizLinkButtonMargin) } iconsBox.snp.makeConstraints { make in make.trailing.top.bottom.equalTo(contentView).inset(Size.iconInsets) make.width.equalTo(Size.iconSize.width) } } } extension ProfileHeaderLinksCell { override func prepareForReuse() { super.prepareForReuse() externalLinks = [] } } extension ProfileHeaderLinksCell { func rearrangeLinks() { guard bounds.width > 0 else { return } for view in linkButtons + iconButtons { view.removeFromSuperview() } linkButtons = [] iconButtons = [] var prevLink: UIButton? var prevIcon: UIButton? var prevRow: UIButton? var iconsCount = 0 let textLinks = externalLinks.filter { $0.iconURL == nil && !$0.text.isEmpty } let iconLinks = externalLinks.filter { $0.iconURL != nil } let (perRow, iconsBoxWidth) = ProfileHeaderLinksSizeCalculator.calculateIconsBoxWidth( externalLinks, width: bounds.width ) iconsBox.snp.updateConstraints { make in make.width.equalTo(iconsBoxWidth) } for textLink in textLinks { prevLink = addLinkButton(textLink, prevLink: prevLink) } for iconLink in iconLinks { prevIcon = addIconButton( iconLink, iconsCount: iconsCount, prevIcon: prevIcon, prevRow: prevRow, perRow: perRow, hasTextLinks: textLinks.count > 0 ) iconsCount += 1 if iconsCount % perRow == 0 { prevRow = prevIcon } } let totalHeight: CGFloat if externalLinks.count == 0 { totalHeight = 0 } else { totalHeight = ProfileHeaderLinksSizeCalculator.calculateHeight( externalLinks, width: bounds.width ) } if totalHeight != frame.size.height { heightMismatchOccurred(totalHeight) } } private func addIconButton( _ externalLink: ExternalLink, iconsCount: Int, prevIcon: UIButton?, prevRow: UIView?, perRow: Int, hasTextLinks: Bool ) -> UIButton { let button = UIButton() button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside) buttonLinks[button] = externalLink iconsBox.addSubview(button) iconButtons.append(button) button.layer.masksToBounds = true button.layer.cornerRadius = Size.iconSize.width / 2 button.backgroundColor = .greyE5 button.snp.makeConstraints { make in make.size.equalTo(Size.iconSize) let direction = hasTextLinks ? make.trailing : make.leading switch iconsCount % perRow { case 0: direction.equalTo(iconsBox) default: let prevDirection = hasTextLinks ? prevIcon!.snp.leading : prevIcon!.snp.trailing let offset = hasTextLinks ? -Size.iconMargins : Size.iconMargins direction.equalTo(prevDirection).offset(offset) } if let prevRow = prevRow { make.top.equalTo(prevRow.snp.bottom).offset(Size.iconMargins) } else { make.top.equalTo(iconsBox) } } if let iconURL = externalLink.iconURL { button.pin_setImage(from: iconURL) } return button } private func addLinkButton(_ externalLink: ExternalLink, prevLink: UIButton?) -> UIButton { let button = UIButton() button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside) buttonLinks[button] = externalLink linksBox.addSubview(button) linkButtons.append(button) button.snp.makeConstraints { make in make.leading.trailing.equalTo(linksBox) if let prevLink = prevLink { make.top.equalTo(prevLink.snp.bottom).offset(Size.verticalLinkMargin) } else { make.top.equalTo(linksBox) } } button.setAttributedTitle( NSAttributedString( string: externalLink.text, attributes: [ .font: UIFont.defaultFont(), .foregroundColor: UIColor.greyA, .underlineStyle: NSUnderlineStyle.single.rawValue, ] ), for: .normal ) button.setAttributedTitle( NSAttributedString( string: externalLink.text, attributes: [ .font: UIFont.defaultFont(), .foregroundColor: UIColor.black, .underlineStyle: NSUnderlineStyle.single.rawValue, ] ), for: .highlighted ) button.contentHorizontalAlignment = .left return button } @objc func buttonTapped(_ button: UIButton) { guard let externalLink = buttonLinks[button] else { return } let request = URLRequest(url: externalLink.url) ElloWebViewHelper.handle(request: request, origin: self) } }
mit
c8297b69e1bb6c637942f457d7a42613
28.77193
97
0.573954
4.93314
false
false
false
false
yousefhamza/openmrs-contrib-ios-client
OpenMRS-iOS/SelectVisitTypeView.swift
1
4318
// // SelectVisitTypeView.swift // // // Created by Parker Erway on 1/22/15. // // import UIKit protocol SelectVisitTypeViewDelegate { func didSelectVisitType(type: MRSVisitType) } class SelectVisitTypeView : UITableViewController, UIViewControllerRestoration { var visitTypes: [MRSVisitType]! = [] var delegate: SelectVisitTypeViewDelegate! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } override init(style: UITableViewStyle) { super.init(style: .Plain) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) MRSHelperFunctions.updateTableViewForDynamicTypeSize(self.tableView) } func updateFontSize() { MRSHelperFunctions.updateTableViewForDynamicTypeSize(self.tableView) } override func viewDidLoad() { super.viewDidLoad() self.restorationIdentifier = NSStringFromClass(self.dynamicType); self.restorationClass = self.dynamicType; let defaultCenter = NSNotificationCenter.defaultCenter() defaultCenter.addObserver(self, selector:"updateFontSize", name: UIContentSizeCategoryDidChangeNotification, object: nil) MRSHelperFunctions.updateTableViewForDynamicTypeSize(self.tableView) self.title = NSLocalizedString("Visit Type", comment: "Label -visit- -type-") self.reloadData() } func reloadData() { if self.visitTypes == nil { MBProgressExtension.showBlockWithTitle(NSLocalizedString("Loading", comment: "Label loading"), inView: self.view) OpenMRSAPIManager.getVisitTypesWithCompletion { (error:NSError!, types:[AnyObject]!) -> Void in MBProgressExtension.hideActivityIndicatorInView(self.view) if error != nil { MRSAlertHandler.alertViewForError(self, error: error).show(); NSLog("Error getting visit types: \(error)") } else { MBProgressExtension.showSucessWithTitle(NSLocalizedString("Completed", comment: "Label completed"), inView: self.view) self.visitTypes = types as! [MRSVisitType] dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } } } } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.visitTypes.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("cell") if cell == nil { cell = UITableViewCell(style: .Default, reuseIdentifier: "cell") } let visitType = self.visitTypes[indexPath.row] cell.textLabel?.text = visitType.display return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let visitType = visitTypes[indexPath.row] delegate.didSelectVisitType(visitType) self.navigationController?.popToRootViewControllerAnimated(true) } override func encodeRestorableStateWithCoder(coder: NSCoder) { coder.encodeObject(self.delegate as! StartVisitViewController, forKey: "delegate") coder.encodeObject(self.visitTypes, forKey: "visitTypes") } static func viewControllerWithRestorationIdentifierPath(identifierComponents: [AnyObject], coder: NSCoder) -> UIViewController? { let visitTypeList = SelectVisitTypeView(style: UITableViewStyle.Plain) visitTypeList.visitTypes = coder.decodeObjectForKey("visitTypes") as! [MRSVisitType] visitTypeList.delegate = coder.decodeObjectForKey("delegate") as! StartVisitViewController return visitTypeList } }
mpl-2.0
ba4856e99c5ae47daf6c5bb9734800ef
36.877193
138
0.660954
5.272283
false
false
false
false
MFaarkrog/Apply
Apply/Classes/Extensions/UICollectionViewFlowLayout+Apply.swift
1
1190
// // Created by Morten Faarkrog // import UIKit public extension UICollectionViewFlowLayout { @discardableResult public func apply<T: UICollectionViewFlowLayout>(estimatedItemSize: CGSize) -> T { self.estimatedItemSize = estimatedItemSize return self as! T } @discardableResult public func apply<T: UICollectionViewFlowLayout>(itemSize: CGSize) -> T { self.itemSize = itemSize return self as! T } @discardableResult public func apply<T: UICollectionViewFlowLayout>(minimumInteritemSpacing: CGFloat) -> T { self.minimumInteritemSpacing = minimumInteritemSpacing return self as! T } @discardableResult public func apply<T: UICollectionViewFlowLayout>(minimumLineSpacing: CGFloat) -> T { self.minimumLineSpacing = minimumLineSpacing return self as! T } @discardableResult public func apply<T: UICollectionViewFlowLayout>(sectionInset: UIEdgeInsets) -> T { self.sectionInset = sectionInset return self as! T } @discardableResult public func apply<T: UICollectionViewFlowLayout>(scrollDirection: UICollectionView.ScrollDirection) -> T { self.scrollDirection = scrollDirection return self as! T } }
mit
cc047a83b58f1a39a07350813f18e693
29.512821
127
0.743697
5.384615
false
false
false
false
mozilla-mobile/focus-ios
Blockzilla/Search/SearchEngineManager.swift
1
7333
/* 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 class SearchEngineManager { public static let prefKeyEngine = "prefKeyEngine" public static let prefKeyDisabledEngines = "prefKeyDisabledEngines" public static let prefKeyCustomEngines = "prefKeyCustomEngines" public static let prefKeyV98AndAboveResetSearchEngine = "prefKeyAboveV98ResetSearchEngine" // Ref Bug: #1653822 private let prefs: UserDefaults var engines = [SearchEngine]() init(prefs: UserDefaults) { self.prefs = prefs loadEngines() } var activeEngine: SearchEngine { get { let selectName = prefs.string(forKey: SearchEngineManager.prefKeyEngine) return engines.first { $0.name == selectName } ?? engines.first! } set { prefs.set(newValue.name, forKey: SearchEngineManager.prefKeyEngine) sortEnginesAlphabetically() setActiveEngineAsFirstElement() } } func addEngine(name: String, template: String) -> SearchEngine { let correctedTemplate = template.replacingOccurrences(of: "%s", with: "{searchTerms}") let engine = SearchEngine(name: name, image: nil, searchTemplate: correctedTemplate, suggestionsTemplate: nil, isCustom: true) // Persist var customEngines = readCustomEngines() customEngines.append(engine) saveCustomEngines(customEngines: customEngines) // Update inmemory list engines.append(engine) sortEnginesAlphabetically() // Set as default search engine activeEngine = engine return engine } func hasDisabledDefaultEngine() -> Bool { return getDisabledDefaultEngineNames().count > 0 } func restoreDisabledDefaultEngines() { prefs.removeObject(forKey: SearchEngineManager.prefKeyDisabledEngines) loadEngines() } func removeEngine(engine: SearchEngine) { // If this is a custom engine then it should be removed from the custom engine array // otherwise this is a default engine and so it should be added to the disabled engines array if activeEngine.name == engine.name { // Can not remove active engine return } let customEngines = readCustomEngines() let filteredEngines = customEngines.filter { (a: SearchEngine) -> Bool in return a.name != engine.name } if customEngines.count != filteredEngines.count { saveCustomEngines(customEngines: filteredEngines) } else { var disabledEngines = getDisabledDefaultEngineNames() disabledEngines.append(engine.name) saveDisabledDefaultEngineNames(engines: disabledEngines) } loadEngines() } func isValidSearchEngineName(_ name: String) -> Bool { if name.isEmpty { return false } var names = engines.map { (engine) -> String in return engine.name } names = names + getDisabledDefaultEngineNames() return !names.contains(where: { (n) -> Bool in return n == name }) } private func loadEngines() { // Get the directories to look for engines, from most to least specific. var components = Locale.preferredLanguages.first!.components(separatedBy: "-") if components.count == 3 { components.remove(at: 1) } let searchPaths = [components.joined(separator: "-"), components[0], "default"] let parser = OpenSearchParser(pluginMode: true) let pluginsPath = Bundle.main.url(forResource: "SearchPlugins", withExtension: nil)! let enginesPath = Bundle.main.path(forResource: "SearchEngines", ofType: "plist")! let engineMap = NSDictionary(contentsOfFile: enginesPath) as! [String: [String]] let engines = searchPaths.compactMap { engineMap[$0] }.first! // Find and parse the engines for this locale. self.engines = engines.compactMap { name in let path = searchPaths .map({ pluginsPath.appendingPathComponent($0).appendingPathComponent(name + ".xml") }) .first { FileManager.default.fileExists(atPath: $0.path) }! return parser.parse(file: path) } // Filter out disabled engines let disabledEngines = getDisabledDefaultEngineNames() self.engines = self.engines.filter { engine in return !disabledEngines.contains(engine.name) } // Add in custom engines let customEngines = readCustomEngines() self.engines.append(contentsOf: customEngines) let searchEnginePrefV98 = prefs.string(forKey: SearchEngineManager.prefKeyV98AndAboveResetSearchEngine) let hasDefaultSearchEngine = prefs.string(forKey: SearchEngineManager.prefKeyEngine) let versionNumberList = AppInfo.shortVersion.components(separatedBy: ".") let versionNum = Int(versionNumberList[0]) ?? 0 // Ref Bug: #1653822 // Set default search engine pref if hasDefaultSearchEngine == nil || (searchEnginePrefV98 == nil && versionNum >= 98) { prefs.set(self.engines.first?.name, forKey: SearchEngineManager.prefKeyEngine) prefs.set(true, forKey: SearchEngineManager.prefKeyV98AndAboveResetSearchEngine) } sortEnginesAlphabetically() setActiveEngineAsFirstElement() } private func sortEnginesAlphabetically() { engines.sort { (aEngine, bEngine) -> Bool in return aEngine.name < bEngine.name } } private func setActiveEngineAsFirstElement() { let activeEngineIndex = engines.firstIndex(of: activeEngine)! engines.insert(activeEngine, at: 0) engines.remove(at: activeEngineIndex.advanced(by: 1)) } private func readCustomEngines() -> [SearchEngine] { do { if let archiveData = prefs.value(forKey: SearchEngineManager.prefKeyCustomEngines) as? NSData { let archivedCustomEngines = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(archiveData as Data) let customEngines = archivedCustomEngines as? [SearchEngine] ?? [SearchEngine]() return customEngines.map { engine in engine.isCustom = true return engine } } } catch { print(error) } return [SearchEngine]() } private func saveCustomEngines(customEngines: [SearchEngine]) { do { try prefs.set(NSKeyedArchiver.archivedData(withRootObject: customEngines, requiringSecureCoding: false), forKey: SearchEngineManager.prefKeyCustomEngines) } catch { print(error) } } private func getDisabledDefaultEngineNames() -> [String] { return prefs.stringArray(forKey: SearchEngineManager.prefKeyDisabledEngines) ?? [String]() } private func saveDisabledDefaultEngineNames(engines: [String]) { prefs.set(engines, forKey: SearchEngineManager.prefKeyDisabledEngines) } }
mpl-2.0
f69176deb83a0e6b74215ff2158852e4
36.413265
166
0.649802
4.914879
false
false
false
false
kzin/swift-testing
swift-testing/swift-testing/MyTableViewController.swift
1
1837
// // MyTableViewController.swift // swift-testing // // Created by Rodrigo Cavalcante on 21/07/17. // Copyright © 2017 Rodrigo Cavalcante. All rights reserved. // import UIKit import Cartography class MyTableViewController: UIViewController, MyDelegateDatasourceProtocol { let tableView: UITableView let myDelegateDatasource: MyDelegateDatasource init() { self.tableView = UITableView.init() self.myDelegateDatasource = MyDelegateDatasource() super.init(nibName: nil, bundle: nil) self.myDelegateDatasource.delegate = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() build() requestExample() } func build() { buildViewHierarchy() buildConstrains() setup() } func buildViewHierarchy() { self.view.addSubview(tableView) } func buildConstrains() { constrain(self.view, tableView) { view, tableView in tableView.top == view.top + 20 tableView.right == view.right tableView.bottom == view.bottom tableView.left == view.left } } func setup() { self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") self.tableView.dataSource = self.myDelegateDatasource self.tableView.delegate = self.myDelegateDatasource self.view.backgroundColor = .white } func requestExample() { self.myDelegateDatasource.data = ["Rodrigo", "Cavalcante", "Testing", "Delegate", "Datasource"] self.tableView.reloadData() } func didSelectCell(data: String) { print("Selected \(data)") } }
mit
d88f967799fa5671ae3021a2cf000d3b
25.608696
103
0.625817
4.744186
false
false
false
false
pyconjp/pyconjp-ios
PyConJP/ViewController/More/MapViewController.swift
1
2437
// // MapViewController.swift // PyConJP // // Created by Yutaro Muta on 2016/03/10. // Copyright © 2016 PyCon JP. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController, MKMapViewDelegate, StoryboardIdentifiable { @IBOutlet weak var textView: UITextView! @IBOutlet weak var mapView: MKMapView! private var venue: Venue? static func build(venue: Venue) -> MapViewController { let mapViewController: MapViewController = UIStoryboard(storyboard: .more).instantiateViewController() mapViewController.venue = venue return mapViewController } override func viewDidLoad() { super.viewDidLoad() guard let venue = venue else { return } textView.text = venue.address mapView.setCenter(venue.location, animated: true) var region: MKCoordinateRegion = mapView.region region.center = venue.location region.span.latitudeDelta = 0.01 region.span.longitudeDelta = 0.01 mapView.setRegion(region, animated: true) let annotation = MKPointAnnotation() annotation.coordinate = venue.location annotation.title = venue.name mapView.addAnnotation(annotation) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() textView.setContentOffset(.zero, animated: false) } enum Venue { case waseda case microsoft var name: String { switch self { case .waseda: return NSLocalizedString("nameWaseda", tableName: "Map", comment: "") case .microsoft: return NSLocalizedString("nameMicrosoft", tableName: "Map", comment: "") } } var location: CLLocationCoordinate2D { switch self { case .waseda: return CLLocationCoordinate2D(latitude: 35.706069, longitude: 139.706809) case .microsoft: return CLLocationCoordinate2D(latitude: 35.626670, longitude: 139.740375) } } var address: String { switch self { case .waseda: return NSLocalizedString("addressWaseda", tableName: "Map", comment: "") case .microsoft: return NSLocalizedString("addressMicrosoft", tableName: "Map", comment: "") } } } }
mit
73a1e027eae81fb3e12cf1a73b58726e
29.835443
110
0.614532
5.205128
false
false
false
false