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
oddnetworks/odd-sample-apps
apple/tvos/tvOSTemplate/Odd tvOS Template/TVSearchViewController.swift
1
6463
// // TVSearchViewController.swift // Odd-tvOS // // Created by Patrick McConnell on 10/13/15. // Copyright © 2015 Patrick McConnell. All rights reserved. // import UIKit import OddSDKtvOS import AVFoundation // the VC for the user to enter search terms and query our API // relies on the searchResultsController to display the results class TVSearchViewController: UIViewController, UITextFieldDelegate, Dimmable, SearchResultsCollectionBrowserDelegate, SearchResultsDelegate, LibraryTableViewControllerDelegate { @IBOutlet weak var searchTextField: UITextField! @IBOutlet weak var logoImageView: UIImageView! @IBOutlet weak var collectionViewContainer: UIView! let kFadeAnimationDuration = 0.5 var searchResultsCollectionViewController : TVSearchResultsCollectionViewController? var collectionsViewController: LibraryTableViewController? var collectionsNavController: UINavigationController? var screenView: UIView? var viewToFocus: UIView? = nil { didSet { if viewToFocus != nil { self.setNeedsFocusUpdate(); self.updateFocusIfNeeded(); } } } override var preferredFocusEnvironments: [UIFocusEnvironment] { get { if viewToFocus != nil { return [viewToFocus!]; } else { return super.preferredFocusEnvironments; } } } // override weak var preferredFocusedView: UIView? { // if viewToFocus != nil { // return viewToFocus; // } else { // return super.preferredFocusedView; // } // } override func viewDidLoad() { super.viewDidLoad() configureTextFieldElements(textField: searchTextField) self.searchTextField.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func configureTextFieldElements(textField: UITextField) { let iconSize: CGFloat = 36 let container = UIView(frame: CGRect(x: 24, y: 0, width: 56, height: 36)) let magnifyView = UIImageView(frame: CGRect(x: 0, y: 0, width: iconSize, height: iconSize)) magnifyView.image = UIImage(named: "magnify") magnifyView.image = magnifyView.image!.withRenderingMode(.alwaysTemplate) magnifyView.tintColor = .lightGray container.addSubview(magnifyView) magnifyView.center.x += 8 textField.leftView = container textField.leftViewMode = .always } // MARK: - UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { if (textField.text?.characters.count)! > 0 { let query = textField.text?.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) OddLogger.info("search for: \(query)") fetchSearchResults(term: query!) } textField.resignFirstResponder() return true } func fetchSearchResults( term: String ) { fadeLogoImage(alpha: 1) OddContentStore.sharedStore.searchForTerm(term) { (videos, collections) -> Void in print("Found \(videos!.count) videos and \(collections!.count) collections") self.fadeLogoImage(alpha: 0) self.configureSearchResultsViewController(videos: videos, collections: collections) } } func configureSearchResultsViewController(videos: Array<OddVideo>?, collections: Array<OddMediaObjectCollection>?) { self.searchResultsCollectionViewController?.presentUpdatedResults(videos: videos, collections: collections ) } func fadeLogoImage(alpha : CGFloat) { UIView.animate(withDuration: 0.5) { () -> Void in self.logoImageView.alpha = 0 } } func fadeBackground() { UIView.animate(withDuration: 0.5, animations: { () -> Void in }) { (complete) -> Void in } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let id = segue.identifier else { return } switch id { case "playVideoSegue": if let vc = segue.destination as? TVOddAVPlayerViewController, let video = sender as? OddVideo, let urlString = video.urlString { print("Playing Video: \(urlString)") if let videoURL = NSURL(string: urlString) { let mediaItem = AVPlayerItem(url: videoURL as URL) let player = AVPlayer(playerItem: mediaItem) player.isMuted = UserDefaults.standard.bool(forKey: "liveStreamMuted") vc.player = player vc.player?.play() } } case "searchResultsCollectionViewEmbed": if let vc = segue.destination as? TVSearchResultsCollectionViewController { self.searchResultsCollectionViewController = vc self.searchResultsCollectionViewController?.collectionView?.alpha = 0 vc.collectionDelegate = self vc.searchResultDelegate = self } case "embedCollectionBrowser": guard let navCon = segue.destination as? UINavigationController, let vc = navCon.topViewController as? LibraryTableViewController else { return } self.collectionsViewController = vc self.collectionsViewController?.tableView.alpha = 0 self.collectionsViewController?.headerText = "Collection Content" vc.delegate = self default: break } } // Collection Browser func showBrowserForCollection(collection: OddMediaObjectCollection) { guard let collectionTableView = self.collectionsViewController?.tableView else { return } self.collectionsViewController?.mediaObjectCollection = collection self.collectionViewContainer?.isHidden = false UIView.animate(withDuration: kFadeAnimationDuration) { collectionTableView.alpha = 1 self.searchResultsCollectionViewController?.collectionView?.alpha = 0.1 } self.view.bringSubview(toFront: collectionTableView) self.viewToFocus = self.collectionsViewController?.tableView } //MARK: - LibraryTableViewControllerDelegate func didHighlightVideo(video: OddVideo) { print("didHighlightVideo") } func show(video: OddVideo) { OddLogger.debug("showVideo") self.performSegue(withIdentifier: "playVideoSegue", sender: video) } func hideTableView() { UIView.animate(withDuration: kFadeAnimationDuration, animations: { self.collectionsViewController?.tableView.alpha = 0 self.searchResultsCollectionViewController?.collectionView?.alpha = 1 }) { (complete) in self.collectionViewContainer?.isHidden = true } } }
apache-2.0
c9b5c367b4e2b8d6831f1ff6cc49961c
30.990099
178
0.701176
4.906606
false
false
false
false
DianQK/TransitionTreasury
TransitionTreasury/PresentTransition/UIViewController+TRPresent.swift
1
4191
// // UIViewController+TRPresent.swift // TransitionTreasury // // Created by DianQK on 12/20/15. // Copyright © 2016 TransitionTreasury. All rights reserved. // import UIKit /** * Enable Transition for Present. */ public protocol ViewControllerTransitionable: class, NSObjectProtocol { /// Retain transition delegate. var tr_presentTransition: TRViewControllerTransitionDelegate?{get set} } // MARK: - Transition Treasury UIViewController Extension. public extension ViewControllerTransitionable where Self: UIViewController { /** Transition treasury present viewController. */ func tr_presentViewController(_ viewControllerToPresent: UIViewController, method: TransitionAnimationable, statusBarStyle: TRStatusBarStyle = .default, completion: (() -> Void)? = nil) { let transitionDelegate = TRViewControllerTransitionDelegate(method: method) tr_presentTransition = transitionDelegate viewControllerToPresent.transitioningDelegate = transitionDelegate transitionDelegate.previousStatusBarStyle = TRStatusBarStyle.currentlyTRStatusBarStyle() let fullCompletion = { completion?() statusBarStyle.updateStatusBarStyle() } transitionDelegate.transition.completion = fullCompletion /** * http://stackoverflow.com/questions/20320591/uitableview-and-presentviewcontroller-takes-2-clicks-to-display */ /** * http://stackoverflow.com/questions/21075540/presentviewcontrolleranimatedyes-view-will-not-appear-until-user-taps-again */ DispatchQueue.main.async { if transitionDelegate.transition.completion != nil { // Choose who deal completion self.present(viewControllerToPresent, animated: true, completion: nil) } else { self.present(viewControllerToPresent, animated: true, completion: fullCompletion) } } } /** Transition treasury dismiss ViewController. */ func tr_dismissViewController(_ interactive: Bool = false, completion: (() -> Void)? = nil) { let transitionDelegate = tr_presentTransition if var interactiveTransition = transitionDelegate?.transition as? TransitionInteractiveable { interactiveTransition.interacting = interactive } presentedViewController?.transitioningDelegate = transitionDelegate let fullCompletion = { completion?() transitionDelegate?.previousStatusBarStyle?.updateStatusBarStyle() self.tr_presentTransition = nil } transitionDelegate?.transition.completion = fullCompletion if transitionDelegate?.transition.completion != nil { dismiss(animated: true, completion: nil) } else { dismiss(animated: true, completion: fullCompletion) } } } /// Modal Transition & Delegate. public typealias ModalTransitionDelegate = ViewControllerTransitionable & ModalViewControllerDelegate /** * Your `MianViewController` should conform this delegate. */ public protocol ModalViewControllerDelegate: class, NSObjectProtocol { /** Dismiss by delegate. - parameter data: callback data */ func modalViewControllerDismiss(_ interactive: Bool, callbackData data:Any?) func modalViewControllerDismiss(callbackData data:Any?) } // MARK: - Implement dismiss public extension ModalViewControllerDelegate where Self: ViewControllerTransitionable, Self: UIViewController { func modalViewControllerDismiss(_ interactive: Bool = false, callbackData data:Any? = nil) { if data != nil { debugPrint("WARNING: You set callbackData, but you forget implement this `modalViewControllerDismiss(_:_:)` to get data.") } tr_dismissViewController(interactive, completion: nil) } func modalViewControllerDismiss(callbackData data:Any? = nil) { if data != nil { debugPrint("WARNING: You set callbackData, but you forget implement this `modalViewControllerDismiss(_:)` to get data.") } tr_dismissViewController(completion: nil) } }
mit
3f060e1b0f27f9abc0c82fe5bb2d5535
39.288462
191
0.695943
5.498688
false
false
false
false
Pluto-tv/jsonjam
Example/Pods/JSONHelper/JSONHelper/Conversion.swift
1
3777
// // Copyright © 2016 Baris Sencan. All rights reserved. // import Foundation /// Operator for use in right hand side to left hand side conversion. infix operator <-- { associativity right precedence 150 } /// Thrown when a conversion operation fails. public enum ConversionError: Error { /// TODOC case unsupportedType /// TODOC case invalidValue } /// An object that can attempt to convert values of unknown types to its own type. public protocol Convertible { /// TODOC static func convertFromValue<T>(_ value: T?) throws -> Self? } // MARK: - Basic Conversion public func <-- <T, U>(lhs: inout T?, rhs: U?) -> T? { if !(lhs is NSNull) { lhs = JSONHelper.convertToNilIfNull(rhs) as? T } else { lhs = rhs as? T } return lhs } public func <-- <T, U>(lhs: inout T, rhs: U?) -> T { var newValue: T? newValue <-- rhs lhs = newValue ?? lhs return lhs } public func <-- <C: Convertible, T>(lhs: inout C?, rhs: T?) -> C? { lhs = nil do { lhs = try C.convertFromValue(JSONHelper.convertToNilIfNull(rhs)) } catch ConversionError.invalidValue { #if DEBUG print("Invalid value \(rhs.debugDescription) for supported type.") #endif } catch ConversionError.unsupportedType { #if DEBUG print("Unsupported type.") #endif } catch {} return lhs } public func <-- <C: Convertible, T>(lhs: inout C, rhs: T?) -> C { var newValue: C? newValue <-- rhs lhs = newValue ?? lhs return lhs } // MARK: - Array Conversion public func <-- <C: Convertible, T>(lhs: inout [C]?, rhs: [T]?) -> [C]? { guard let rhs = rhs else { lhs = nil return lhs } lhs = [C]() for element in rhs { var convertedElement: C? convertedElement <-- element if let convertedElement = convertedElement { lhs?.append(convertedElement) } } return lhs } public func <-- <C: Convertible, T>(lhs: inout [C], rhs: [T]?) -> [C] { var newValue: [C]? newValue <-- rhs lhs = newValue ?? lhs return lhs } public func <-- <C: Convertible, T>(lhs: inout [C]?, rhs: T?) -> [C]? { guard let rhs = rhs else { lhs = nil return lhs } if let elements = rhs as? NSArray as? [AnyObject] { return lhs <-- elements } return nil } public func <-- <C: Convertible, T>(lhs: inout [C], rhs: T?) -> [C] { var newValue: [C]? newValue <-- rhs lhs = newValue ?? lhs return lhs } // MARK: - Dictionary Conversion public func <-- <T, C: Convertible, U>(lhs: inout [T : C]?, rhs: [T : U]?) -> [T : C]? { guard let rhs = rhs else { lhs = nil return lhs } lhs = [T : C]() for (key, value) in rhs { var convertedValue: C? convertedValue <-- value if let convertedValue = convertedValue { lhs?[key] = convertedValue } } return lhs } public func <-- <T, C: Convertible, U>(lhs: inout [T : C], rhs: [T : U]?) -> [T : C] { var newValue: [T : C]? newValue <-- rhs lhs = newValue ?? lhs return lhs } public func <-- <T, C: Convertible, U>(lhs: inout [T : C]?, rhs: U?) -> [T : C]? { guard let rhs = rhs else { lhs = nil return lhs } if let elements = rhs as? NSDictionary as? [T : AnyObject] { return lhs <-- elements } return nil } public func <-- <T, C: Convertible, U>(lhs: inout [T : C], rhs: U?) -> [T : C] { var newValue: [T : C]? newValue <-- rhs lhs = newValue ?? lhs return lhs } // MARK: - Enum Conversion public func <-- <T: RawRepresentable, U>(lhs: inout T?, rhs: U?) -> T? { var newValue: T? if let rawValue = rhs as? T.RawValue, let enumValue = T(rawValue: rawValue) { newValue = enumValue } lhs = newValue return lhs } public func <-- <T: RawRepresentable, U>(lhs: inout T, rhs: U?) -> T { var newValue: T? newValue <-- rhs lhs = newValue ?? lhs return lhs }
mit
af769310c909c3b3984b600f19c6ab10
19.410811
88
0.597193
3.426497
false
false
false
false
bamzy/goQueer-iOS
GoQueer/GalleryController.swift
1
4613
import UIKit import YouTubePlayer class GalleryController: BaseViewController { @IBOutlet weak var videoPlayer: YouTubePlayerView! @IBOutlet weak var progress: UIActivityIndicatorView! @IBOutlet weak var descriptionText: UITextView! @IBOutlet weak var imageViewWidth: NSLayoutConstraint! @IBOutlet weak var imageViewHeight: NSLayoutConstraint! @IBAction func previousPressed(_ sender: UIButton) { chooseImage(media: GalleryController.myGallery.media[getPrevious(index: self.index)]) descriptionText.text = GalleryController.myGallery.media[self.index].description titleText.text = GalleryController.myGallery.media[self.index].name if (GalleryController.myGallery.media[self.index].extraLinks != "" && GalleryController.myGallery.media[self.index].extraLinks != nil && GalleryController.myGallery.media[self.index].extraLinks != "null"){ linkText.text = GalleryController.myGallery.media[self.index].extraLinks.replacingOccurrences(of: "\\/", with: "/") } else { linkText.text = "" } } @IBAction func nextPressed(_ sender: UIButton) { chooseImage(media: GalleryController.myGallery.media[getNext(index: self.index)]) descriptionText.text = GalleryController.myGallery.media[self.index].description titleText.text = GalleryController.myGallery.media[self.index].name if (GalleryController.myGallery.media[self.index].typeId == 1){ linkText.text = String(GalleryController.myGallery.media[self.index].mediaURL).replacingOccurrences(of: "\\/", with: "/", options: .literal, range: nil) } else { linkText.text = "" } } func getPrevious(index: Int) -> Int{ if index > 0 { self.index = index - 1 return self.index } else{ showToast(message: "Nothing left") } return 0 } @IBOutlet weak var linkText: UITextView! func getNext(index: Int) -> Int{ if index < GalleryController.myGallery.media.count-1 { self.index = index+1 return self.index } else{ showToast(message: "Nothing left") } return GalleryController.myGallery.media.count-1 } var index: Int = 0 public static var myGallery = QGallery() override func viewDidLoad() { super.viewDidLoad() if (self.index > -1 && self.index < GalleryController.myGallery.media.count ){ chooseImage(media: GalleryController.myGallery.media[self.index]) descriptionText.text = GalleryController.myGallery.media[index].description titleText.text = GalleryController.myGallery.media[index].name titleText.textAlignment = .center } } @IBOutlet weak var picture: UIImageView! func chooseImage(media: QMedia) { progress.startAnimating() var imageURL = URL(string: "") imageURL = URL(string: MapController.baseUrl + "client/downloadMediaById?media_id=" + String(media.id) ) if (media.typeId == 5 || media.typeId == 4) { self.videoPlayer.isHidden = true fetchImageFromURL(imageURL: imageURL!, media: media) } else if media.typeId == 1 { self.videoPlayer.isHidden = false let myVideoURL = NSURL(string: media.mediaURL.replacingOccurrences(of: "\\", with: "")) self.videoPlayer.loadVideoURL(myVideoURL! as URL) } else { self.videoPlayer.isHidden = true } } func fetchImageFromURL(imageURL: URL,media: QMedia) { DispatchQueue.global(qos: DispatchQoS.userInitiated.qosClass).async { let fetch = NSData(contentsOf: imageURL as URL) DispatchQueue.main.async { if let imageData = fetch { let imageView = UIImageView(frame: self.view.bounds) if media.typeId == 4 { self.picture.image = UIImage(data: imageData as Data) self.view.addSubview(imageView) }else if media.typeId == 5 { self.picture.image = UIImage.gif(data: imageData as Data) self.view.addSubview(imageView) } } } } } @IBOutlet weak var titleText: UILabel! }
mit
f19d3bd5db5fc2ec16516fbfeb589845
38.767241
169
0.59419
4.881481
false
false
false
false
nodekit-io/nodekit-darwin
src/nodekit/NKScripting/NKScriptInvocation.swift
1
17581
/* * nodekit.io * * Copyright (c) 2016 OffGrid Networks. All Rights Reserved. * Portions Copyright 2015 XWebView * Portions Copyright (c) 2014 Intel Corporation. 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 ObjectiveC public class NKScriptInvocation { public final let target: AnyObject private let queue: dispatch_queue_t? private let thread: NSThread? public enum Option { case None case Queue(queue: dispatch_queue_t) case Thread(thread: NSThread) } public init(target: AnyObject, option: Option = .None) { self.target = target switch option { case .None: self.queue = nil self.thread = nil case .Queue(let queue): self.queue = queue self.thread = nil case .Thread(let thread): self.thread = thread self.queue = nil } } public class func construct(`class`: AnyClass, initializer: Selector = #selector(NSObject.init), withArguments arguments: [Any!] = []) -> AnyObject? { let alloc = #selector(_SpecialSelectors.alloc) guard let obj = invoke(`class`, selector: alloc, withArguments: []) as? AnyObject else { return nil } return invoke(obj, selector: initializer, withArguments: arguments) as? AnyObject } public func call(selector: Selector, withArguments arguments: [Any!] = []) -> Any! { return invoke(target, selector: selector, withArguments: arguments, onThread: thread) } // No callback support, so return value is expected to lose. public func asyncCall(selector: Selector, withArguments arguments: [Any!] = []) { if queue == nil { invoke(target, selector: selector, withArguments: arguments, onThread: thread, waitUntilDone: false) } else { dispatch_async(queue!) { invoke(self.target, selector: selector, withArguments: arguments) } } } // Objective-C interface // These methods accept parameters in ObjC 'id' instead of Swift 'Any' type. // Meanwhile, arguments which are NSNull will be converted to nil before calling. // Return value in scalar type will be converted to object type if feasible. public func call(selector: Selector, withObjects objects: [AnyObject]?) -> AnyObject! { let args: [Any!] = objects?.map { $0 !== NSNull() ? ($0 as Any) : nil } ?? [] let result = call(selector, withArguments: args) return castToObjectFromAny(result) } public func asyncCall(selector: Selector, withObjects objects: [AnyObject]?) { let args: [Any!] = objects?.map { $0 !== NSNull() ? ($0 as Any) : nil } ?? [] asyncCall(selector, withArguments: args) } // Syntactic sugar for calling method public subscript (selector: Selector) -> (Any!...)->Any! { return { (args: Any!...)->Any! in self.call(selector, withArguments: args) } } } extension NKScriptInvocation { // Property accessor public func getProperty(name: String) -> Any! { let getter = getterOfName(name) assert(getter != Selector(), "Property '\(name)' does not exist") return getter != Selector() ? call(getter) : Void() } public func setValue(value: Any!, forProperty name: String) { let setter = setterOfName(name) assert(setter != Selector(), "Property '\(name)' " + (getterOfName(name) == nil ? "does not exist" : "is readonly")) assert(!(value is Void)) if setter != Selector() { call(setter, withArguments: [value]) } } // Syntactic sugar for accessing property public subscript (name: String) -> Any! { get { return getProperty(name) } set { setValue(newValue, forProperty: name) } } private func getterOfName(name: String) -> Selector { var getter = Selector() let property = class_getProperty(target.dynamicType, name) if property != nil { let attr = property_copyAttributeValue(property, "G") getter = Selector(attr == nil ? name : String(UTF8String: attr)!) free(attr) } return getter } private func setterOfName(name: String) -> Selector { var setter = Selector() let property = class_getProperty(target.dynamicType, name) if property != nil { var attr = property_copyAttributeValue(property, "R") if attr == nil { attr = property_copyAttributeValue(property, "S") if attr == nil { setter = Selector("set\(String(name.characters.first!).uppercaseString)\(String(name.characters.dropFirst())):") } else { setter = Selector(String(UTF8String: attr)!) } } free(attr) } return setter } } // Notice: The target method must strictly obey the Cocoa convention. // Do NOT call method with explicit family control or parameter attribute of ARC. // See: http://clang.llvm.org/docs/AutomaticReferenceCounting.html private let _NSInvocation: AnyClass = NSClassFromString("NSInvocation")! private let _NSMethodSignature: AnyClass = NSClassFromString("NSMethodSignature")! public func invoke(target: AnyObject, selector: Selector, withArguments arguments: [Any!], onThread thread: NSThread? = nil, waitUntilDone wait: Bool = true) -> Any! { let method = class_getInstanceMethod(target.dynamicType, selector) if method == nil { // TODO: supports forwordingTargetForSelector: of NSObject? (target as? NSObject)?.doesNotRecognizeSelector(selector) // Not an NSObject, mimic the behavior of NSObject let reason = "\(selector.description) unrecognized selector sent to instance \(unsafeAddressOf(target))" withVaList([reason]) { NSLogv("%@", $0) } NSException(name: NSInvalidArgumentException, reason: reason, userInfo: nil).raise() } let sig = (_NSMethodSignature as! _NSMethodSignatureFactory).signatureWithObjCTypes(method_getTypeEncoding(method)) let inv = (_NSInvocation as! _NSInvocationFactory).invocationWithMethodSignature(sig) // Setup arguments assert(arguments.count + 2 <= Int(sig.numberOfArguments), "Too many arguments for calling -[\(target.dynamicType) \(selector)]") var args = [[Int]](count: arguments.count, repeatedValue: []) for i in 0 ..< arguments.count { let type = sig.getArgumentTypeAtIndex(i + 2) let typeChar = Character(UnicodeScalar(UInt8(type[0]))) // Convert argument type to adapte requirement of method. // Firstly, convert argument to appropriate object type. var argument: Any! = castToObjectFromAny(arguments[i]) assert(argument != nil || arguments[i] == nil, "Can't convert '\(arguments[i].dynamicType)' to object type") if typeChar != "@", let obj: AnyObject = argument as? AnyObject { // Convert back to scalar type as method requires. argument = castToAnyFromObject(obj, withObjCType: type) } if typeChar == "f", let float = argument as? Float { // Float type shouldn't be promoted to double if it is not variadic. args[i] = [ Int(unsafeBitCast(float, Int32.self)) ] } else if let val = argument as? CVarArgType { // Scalar(except float), pointer and Objective-C object types args[i] = val._cVarArgEncoding } else if let obj: AnyObject = argument as? AnyObject { // Pure swift object type args[i] = [ unsafeBitCast(unsafeAddressOf(obj), Int.self) ] } else { // Nil or unsupported type assert(argument == nil, "Unsupported argument type '\(String(UTF8String: type))'") var align: Int = 0 NSGetSizeAndAlignment(sig.getArgumentTypeAtIndex(i), nil, &align) args[i] = [Int](count: align / sizeof(Int), repeatedValue: 0) } args[i].withUnsafeBufferPointer { inv.setArgument(UnsafeMutablePointer($0.baseAddress), atIndex: i + 2) } } if selector.family == .init_ { // Self should be consumed for method belongs to init famlily _ = Unmanaged.passRetained(target) } inv.selector = selector if thread == nil || (thread == NSThread.currentThread() && wait) { inv.invokeWithTarget(target) } else { let selector = #selector(_SpecialSelectors.invokeWithTarget(_:)) inv.retainArguments() inv.performSelector(selector, onThread: thread!, withObject: target, waitUntilDone: wait) guard wait else { return Void() } } if sig.methodReturnLength == 0 { return Void() } // Fetch the return value let buffer = UnsafeMutablePointer<UInt8>.alloc(sig.methodReturnLength) inv.getReturnValue(buffer) defer { if sig.methodReturnType[0] == 0x40 && selector.returnsRetained { // To balance the retained return value Unmanaged.passUnretained(UnsafePointer<AnyObject>(buffer).memory).release() } buffer.dealloc(sig.methodReturnLength) } return castToAnyFromBytes(buffer, withObjCType: sig.methodReturnType) } // Convert byte array to specified Objective-C type // See: https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html private func castToAnyFromBytes(bytes: UnsafePointer<Void>, withObjCType type: UnsafePointer<Int8>) -> Any! { switch Character(UnicodeScalar(UInt8(type[0]))) { case "c": return UnsafePointer<CChar>(bytes).memory case "i": return UnsafePointer<CInt>(bytes).memory case "s": return UnsafePointer<CShort>(bytes).memory case "l": return UnsafePointer<Int32>(bytes).memory case "q": return UnsafePointer<CLongLong>(bytes).memory case "C": return UnsafePointer<CUnsignedChar>(bytes).memory case "I": return UnsafePointer<CUnsignedInt>(bytes).memory case "S": return UnsafePointer<CUnsignedShort>(bytes).memory case "L": return UnsafePointer<UInt32>(bytes).memory case "Q": return UnsafePointer<CUnsignedLongLong>(bytes).memory case "f": return UnsafePointer<CFloat>(bytes).memory case "d": return UnsafePointer<CDouble>(bytes).memory case "B": return UnsafePointer<CBool>(bytes).memory case "v": assertionFailure("Why cast to Void type?") case "*": return UnsafePointer<CChar>(bytes) case "@": return UnsafePointer<AnyObject!>(bytes).memory case "#": return UnsafePointer<AnyClass!>(bytes).memory case ":": return UnsafePointer<Selector>(bytes).memory case "^": return UnsafePointer<COpaquePointer>(bytes).memory default: assertionFailure("Unknown Objective-C type encoding '\(String(UTF8String: type))'") } return Void() } // Convert AnyObject to specified Objective-C type private func castToAnyFromObject(object: AnyObject, withObjCType type: UnsafePointer<Int8>) -> Any! { let num = object as? NSNumber switch Character(UnicodeScalar(UInt8(type[0]))) { case "c": return num?.charValue case "i": return num?.intValue case "s": return num?.shortValue case "l": return num?.intValue case "q": return num?.longLongValue case "C": return num?.unsignedCharValue case "I": return num?.unsignedIntValue case "S": return num?.unsignedShortValue case "L": return num?.unsignedIntValue case "Q": return num?.unsignedLongLongValue case "f": return num?.floatValue case "d": return num?.doubleValue case "B": return num?.boolValue case "v": return Void() case "*": return (object as? String)?.nulTerminatedUTF8.withUnsafeBufferPointer { COpaquePointer($0.baseAddress) } case ":": return object is String ? Selector(object as! String) : Selector() case "@": return object case "#": return object as? AnyClass case "^": return (object as? NSValue)?.pointerValue default: assertionFailure("Unknown Objective-C type encoding '\(String(UTF8String: type))'") } return nil } // Convert Any value to appropriate Objective-C object public func castToObjectFromAny(value: Any!) -> AnyObject! { if value == nil || value is AnyObject { // Some scalar types (Int, UInt, Bool, Float and Double) can be converted automatically by runtime. return value as? AnyObject } if let v = value as? Int8 { return NSNumber(char: v) } else if let v = value as? Int16 { return NSNumber(short: v) } else if let v = value as? Int32 { return NSNumber(int: v) } else if let v = value as? Int64 { return NSNumber(longLong: v) } else if let v = value as? UInt8 { return NSNumber(unsignedChar: v) } else if let v = value as? UInt16 { return NSNumber(unsignedShort: v) } else if let v = value as? UInt32 { return NSNumber(unsignedInt: v) } else if let v = value as? UInt64 { return NSNumber(unsignedLongLong: v) } else if let v = value as? UnicodeScalar { return NSNumber(unsignedInt: v.value) } else if let s = value as? Selector { return s.description } else if let p = value as? COpaquePointer { return NSValue(pointer: UnsafePointer<Void>(p)) } //assertionFailure("Can't convert '\(value.dynamicType)' to AnyObject") return nil } // Additional Swift types which can be represented in C type. extension Bool: CVarArgType { public var _cVarArgEncoding: [Int] { return [ Int(self) ] } } extension UnicodeScalar: CVarArgType { public var _cVarArgEncoding: [Int] { return [ Int(self.value) ] } } extension Selector: CVarArgType { public var _cVarArgEncoding: [Int] { return [ unsafeBitCast(self, Int.self) ] } } private extension Selector { enum Family: Int8 { case none = 0 case alloc = 97 case copy = 99 case mutableCopy = 109 case init_ = 105 case new = 110 } static var prefixes: [[CChar]] = [ /* alloc */ [97, 108, 108, 111, 99], /* copy */ [99, 111, 112, 121], /* mutableCopy */ [109, 117, 116, 97, 98, 108, 101, 67, 111, 112, 121], /* init */ [105, 110, 105, 116], /* new */ [110, 101, 119] ] var family: Family { // See: http://clang.llvm.org/docs/AutomaticReferenceCounting.html#id34 var s = unsafeBitCast(self, UnsafePointer<Int8>.self) while s.memory == 0x5f { s += 1 } // skip underscore for p in Selector.prefixes { let lowercase: Range<CChar> = 97...122 let l = p.count if strncmp(s, p, l) == 0 && !lowercase.contains(s.advancedBy(l).memory) { return Family(rawValue: s.memory)! } } return .none } var returnsRetained: Bool { return family != .none } }
apache-2.0
90dc6bdea322fd6e8b67c4b4b3433caa
26.906349
167
0.564701
4.96358
false
false
false
false
CoderST/DYZB
DYZB/DYZB/Class/Home/Controller/RecommendViewController.swift
1
4021
// // RecommendViewController.swift // DYZB // // Created by xiudou on 16/9/19. // Copyright © 2016年 xiudo. All rights reserved. // 推荐 import UIKit // MARK:- 常量 /// 轮播图高度 private let sRecommendCycleHeight : CGFloat = sScreenW * 3 / 8 /// 推荐游戏高度 private let sRecommendGameHeight : CGFloat = 90 /// 颜值cell标识 private let sCellPrettyIdentifier = "cellPrettyIdentifier" class RecommendViewController: BaseAnchorViewController { // MARK:- 懒加载 // 轮播图的view fileprivate lazy var recommendCycleView : RecommendCycleView = { let recommendCycleView = RecommendCycleView.creatRecommendCycleView() // y = -recommendCycleHeight(因为设置了collectionView.contentInset) recommendCycleView.frame = CGRect(x: 0, y: -(sRecommendCycleHeight + sRecommendGameHeight), width: sScreenW, height: sRecommendCycleHeight) return recommendCycleView }() // 推荐游戏view fileprivate lazy var recommentGameView : RecommendGameView = { let recommentGameView = RecommendGameView.creatRecommendGameView() let recommentGameViewF = CGRect(x: 0, y: -sRecommendGameHeight, width: sScreenW, height: sRecommendGameHeight) recommentGameView.frame = recommentGameViewF return recommentGameView }() // MARK:- 生命周期 override func viewDidLoad() { super.viewDidLoad() // 设置UI setupUI() setupNetWork() } } // MARK:- 初始化UI extension RecommendViewController{ override func setupUI(){ super.setupUI() // 将collectionView添加到控制器的view中 view.addSubview(collectionView) collectionView.register(UINib(nibName: "CollectionViewPrettyCell", bundle: nil), forCellWithReuseIdentifier : sCellPrettyIdentifier) // 添加子控间 collectionView.addSubview(recommendCycleView) collectionView.addSubview(recommentGameView) // 设置collectionView的内边距 collectionView.contentInset = UIEdgeInsets(top: sRecommendCycleHeight + sRecommendGameHeight, left: 0, bottom: 0, right: 0) } } extension RecommendViewController{ fileprivate func setupNetWork(){ // 请求推荐数据 recommendViewModel.request { () -> () in self.collectionView.reloadData() let anchorGroups = self.recommendViewModel.anchorGroups self.recommentGameView.anchorGroups = anchorGroups self.endAnimation() } // 请求轮播图数据 recommendViewModel.requestCycleData { () -> () in self.recommendCycleView.cycleModels = self.recommendViewModel.cycleDatas } } } extension RecommendViewController{ override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 取出对应组 let anchorGroup = recommendViewModel.anchorGroups[indexPath.section] let anchorModel = anchorGroup.anchors[indexPath.item] var cell : CollectionBaseCell! if indexPath.section == 1{ cell = collectionView.dequeueReusableCell(withReuseIdentifier: sCellPrettyIdentifier, for: indexPath) as! CollectionViewPrettyCell cell.anchorModel = anchorModel return cell }else{ return super.collectionView(collectionView, cellForItemAt: indexPath) } } override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: sItemWidth, height: sItemPrettyWidth) } return CGSize(width: sItemWidth, height: sItemNormalWidth) } }
mit
ef95a618e89af0d1d638557f53db6ce3
30.333333
178
0.659574
5.33795
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/macOS/AudioKit for macOS/Playgrounds/macOSDevelopment.playground/Pages/Callback Instrument.xcplaygroundpage/Contents.swift
2
2089
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Callback Instrument //: import XCPlayground import AudioKit var sequencer = AKSequencer() // at Tempo 120, that will trigger every sixteenth note var tempo = 120.0 var division = 1 var callbacker = AKCallbackInstrument() { status, note, velocity in if status == .NoteOn { print("Start Note \(note) at \(sequencer.currentPosition.seconds)") } } let clickTrack = sequencer.newTrack() for i in 0 ..< division { clickTrack?.add(noteNumber: 80, velocity: 100, position: AKDuration(beats: Double(i) / Double(division)), duration: AKDuration(beats: Double(0.1 / Double(division)))) clickTrack?.add(noteNumber: 60, velocity: 100, position: AKDuration(beats: (Double(i) + 0.5) / Double(division)), duration: AKDuration(beats: Double(0.1 / Double(division)))) } clickTrack?.setMIDIOutput(callbacker.midiIn) clickTrack?.setLoopInfo(AKDuration(beats: 1.0), numberOfLoops: 10) sequencer.setTempo(tempo) // We must link the clock's output to AudioKit (even if we don't need the sound) //AudioKit.output = callbacker //AudioKit.start() //: Create a simple user interface class PlaygroundView: AKPlaygroundView { override func setup() { addTitle("Callback Instrument") addSubview(AKButton(title: "Play") { sequencer.play() return "" }) addSubview(AKButton(title: "Pause", color: AKColor.redColor()) { sequencer.stop() return "" }) addSubview(AKButton(title: "Rewind", color: AKColor.cyanColor()) { sequencer.rewind() return "" }) addLabel("Open the console log to show output.") } } sequencer.play() XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView() //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
mit
da83039cbbf90fd319cf2d998afb849e
30.179104
86
0.621829
4.203219
false
false
false
false
Eonil/EditorLegacy
Modules/EditorFileTreeNavigationFeature/EditorFileTreeNavigationFeature/FileNavigating/FileNode2.swift
2
8985
//// //// FileNode2.swift //// RustCodeEditor //// //// Created by Hoon H. on 11/12/14. //// Copyright (c) 2014 Eonil. All rights reserved. //// // //import Foundation // // ///// Soley owned file tree node. ///// Fully URL based. //final class FileNode2 { // // /// Notifies any error occured while processing this tree. // /// All notifications will be routed to root node. // /// After the error occurs, any processing will stop, but // /// processed operations will stay as is. // /// As a result, there's no way to recover from error, and // /// you must dispose the whole tree after an error occured. // let notifyAnyError = Notifier<NSError>() // // /// Usually direct supernode is passed for changes of its // /// subnode. // let notifyInvalidationOfNode = Notifier<FileNode2>() // // // // let supernode:FileNode2? // let absoluteURL:NSURL // // lazy var subnodes:FileNodeSet = FileNodeSet(host: self) // // // // // // private var _subnodes:[FileNode2]? // private var _validity = false // // private var _cacheReady = false // // private var _accessor:NSFileCoordinator? // private var _tracker:FileEventTracker? // // // // // // /// Makes a root node. // convenience init(absoluteURL:NSURL) { // precondition(absoluteURL.fileURL, "Only file path URL is supported.") // precondition(absoluteURL.absoluteURL == absoluteURL, "You must provide an absolute URL.") // // self.init(supernode: nil, absoluteURL: absoluteURL) // } // private init(supernode:FileNode2?, absoluteURL:NSURL) { // assert(supernode == nil || (absoluteURL.URLByDeletingLastPathComponent == supernode!.absoluteURL), "Supplied URL doesn't seem to be a direct subnode of the supernode.") // assert(absoluteURL.absoluteURL == absoluteURL, "You must provide an absolute URL.") // // self.supernode = supernode // self.absoluteURL = absoluteURL // self.subnodes = FileNodeSet(host: self) // // _validity = true // _tracker = FileEventTracker(host: self) // // let p1 = FileEventTracker(host: self) // // This routine exists to guarantee synchronised file access. // // See Cocoa manual for details. // dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0), { () -> Void in // var e1 = nil as NSError? // let c1 = NSFileCoordinator(filePresenter: nil) // c1.coordinateReadingItemAtURL(absoluteURL, options: NSFileCoordinatorReadingOptions.allZeros, error: &e1, byAccessor: { (u1:NSURL!) -> Void in // NSFileCoordinator.addFilePresenter(p1) // }) // dispatch_async(dispatch_get_main_queue(), { () -> Void in // if let e2 = e1 { // self.notifyAnyError.signal(e2) // } else { // self._tracker = p1 // } // }) // }) // } // // private func _prepareCache() { // if _cacheReady == false { // _rebuildCache() // subnodes._prepareCache() // } // } // private func _invalidateCache() { // if _cacheReady == true { // subnodes._invalidateCache() // _invalidateCache() // } // } // private func _rebuildCache() { // assert(_cacheReady == false) // _cacheReady = true // } // private func _demolishCache() { // assert(_cacheReady == true) // _cacheReady = false // } //} // ///// Stably sorted, but the algorithm is opaque. //final class FileNodeSet : SequenceType { // private unowned let _host:FileNode2 // private var _cacheItems = [] as [FileNode2] // private var _cacheReady = false // // init(host:FileNode2) { // _host = host // } // var count:Int { // get { // _prepareCache() // return _cacheItems.count // } // } // subscript(index:Int) -> FileNode2 { // get { // _prepareCache() // return _cacheItems[index] // } // } // func generate() -> GeneratorOf<FileNode2> { // _prepareCache() // return GeneratorOf(_cacheItems.generate()) // } // // private func _tuneCacheByAddingOneAtURL(absoluteURL:NSURL) { // if _cacheReady { // let n1 = FileNode2(supernode: _host, absoluteURL: absoluteURL) // _cacheItems.append(n1) // } // } // private func _tuneCacheByRemovingOne(n:FileNode2) { // if _cacheReady { // _cacheItems = _cacheItems.filter({$0 !== n}) // } // } // private func _prepareCache() { // if _cacheReady == false { // _rebuildCache() // } // } // private func _invalidateCache() { // if _cacheReady == true { // _invalidateCache() // } // } // private func _rebuildCache() { // assert(_cacheReady == false) // assert(_cacheItems.count == 0) // if NSFileManager.defaultManager().fileExistsAtPathAsDirectoryFile(_host.absolutePath) { // let u1 = _host.absoluteURL // let it1 = NSFileManager.defaultManager().enumeratorAtURL(u1, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles | NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants, errorHandler: { (url:NSURL!, error:NSError!) -> Bool in // return false // }) // let it2 = it1! // while let o1 = it2.nextObject() as? NSURL { // var e1 = nil as NSError? // let n1 = FileNode2(supernode: _host, absoluteURL: o1) // _cacheItems.append(n1) // } // } // _cacheReady = true // } // private func _demolishCache() { // assert(_cacheReady == true) // _cacheReady = false // _cacheItems.removeAll(keepCapacity: false) // } //} // // // // // // //extension FileNode2 { // // var displayName:String { // get { // return NSFileManager.defaultManager().displayNameAtPath(absolutePath) // } // } // var absolutePath:String { // get { // return absoluteURL.path! // } // } // var existing:Bool { // get { // return NSFileManager.defaultManager().fileExistsAtPath(absolutePath) // } // } // // var data:NSData? { // get { // if NSFileManager.defaultManager().fileExistsAtPathAsDataFile(absolutePath) { // return NSData(contentsOfFile: absolutePath) // } // return nil // } // } // // var root:FileNode2 { // get { // return supernode == nil ? self : supernode!.root // } // } // var directory:Bool { // get { // var f1 = false as ObjCBool // return NSFileManager.defaultManager().fileExistsAtPath(self.absolutePath, isDirectory: &f1) && f1.boolValue // } // } //} // // // // // // // // // // // ///// Provides cooperative file locking with other processes. ///// I hope the world to be full of good... //private final class FileEventTracker : NSObject, NSFilePresenter { // unowned let host:FileNode2 // // init(host:FileNode2) { // self.host = host // super.init() // } // deinit { // } // // //// MARK: Core // // var presentedItemURL:NSURL? { // get { // return host.absoluteURL // } // } // var presentedItemOperationQueue:NSOperationQueue { // get { // return NSOperationQueue.mainQueue() // } // } // // //// MARK: About Self // // private func savePresentedItemChangesWithCompletionHandler(completionHandler: (NSError!) -> Void) { // // Nothing to save. // completionHandler(nil) // } // private func accommodatePresentedItemDeletionWithCompletionHandler(completionHandler: (NSError!) -> Void) { // host.supernode?._invalidateCache() // completionHandler(nil) // } // private func presentedItemDidMoveToURL(newURL: NSURL) { // host.supernode?._invalidateCache() // } // private func presentedItemDidChange() { // host.supernode?._invalidateCache() // } // // //// MARK: About Subitems // // private func accommodatePresentedSubitemDeletionAtURL(url: NSURL, completionHandler: (NSError!) -> Void) { // host._invalidateCache() // completionHandler(nil) // } // private func presentedSubitemDidAppearAtURL(url: NSURL) { // host._invalidateCache() // } // private func presentedSubitemAtURL(oldURL: NSURL, didMoveToURL newURL: NSURL) { // host._invalidateCache() // } // private func presentedSubitemDidChangeAtURL(url: NSURL) { // host._invalidateCache() // } // // //// MARK: Versioning // // private func presentedItemDidGainVersion(version: NSFileVersion) { // host.supernode?._invalidateCache() // } // private func presentedItemDidLoseVersion(version: NSFileVersion) { // host.supernode?._invalidateCache() // } // private func presentedItemDidResolveConflictVersion(version: NSFileVersion) { // host.supernode?._invalidateCache() // } // private func presentedSubitemAtURL(url: NSURL, didGainVersion version: NSFileVersion) { // host.supernode?._invalidateCache() // } // private func presentedSubitemAtURL(url: NSURL, didLoseVersion version: NSFileVersion) { // host.supernode?._invalidateCache() // } // private func presentedSubitemAtURL(url: NSURL, didResolveConflictVersion version: NSFileVersion) { // host.supernode?._invalidateCache() // } // //} // // // // // // // // // // // //private func defaultGlobalFilePresentationEventQueue() -> NSOperationQueue { // struct Slot { // static let theSlot = Slot() // let value:NSOperationQueue // init() { // let q1 = NSOperationQueue() // q1.maxConcurrentOperationCount = 1 // value = q1 // } // } // return Slot.theSlot.value //} // //private func mainThreadFileCoordinator() -> NSFileCoordinator { // struct Slot { // static let value = NSFileCoordinator() // } // return Slot.value //} // // // //
mit
d95b3576052bb13b9f5e297de37080e1
24.744986
272
0.660211
2.963391
false
false
false
false
gbasile/Trail
Pod/Classes/TrailRequest.swift
1
828
// // TrailRequest.swift // Pods // // Created by Giuseppe Basile on 03/02/2016. // // import Foundation import Alamofire // Callback for Trail Request public typealias TrailCallback = (result: Result<AnyObject, NSError>) -> Void public class TrailRequest { public let path: String public let method: Alamofire.Method public var parameters: Dictionary<String, AnyObject>? public var callback: TrailCallback public init(path: String, method: Alamofire.Method, callback: TrailCallback) { self.path = path self.callback = callback self.method = method } public convenience init(path: String, method: Alamofire.Method, parameters: Dictionary<String, AnyObject>, callback: TrailCallback) { self.init(path: path, method: method, callback:callback) self.parameters = parameters } }
mit
8f4db9667c6bdf5df0fc4a407036521e
24.875
135
0.724638
4.119403
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/GroupDetails/Sections/RenameGroupSectionController.swift
1
5255
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireDataModel import WireSyncEngine final class RenameGroupSectionController: NSObject, CollectionViewSectionController { fileprivate var validName: String? fileprivate var conversation: GroupDetailsConversationType fileprivate var renameCell: GroupDetailsRenameCell? fileprivate var token: AnyObject? private var sizingFooter = SectionFooter(frame: .zero) var isHidden: Bool { return false } init(conversation: GroupDetailsConversationType) { self.conversation = conversation super.init() if let conversation = conversation as? ZMConversation { token = ConversationChangeInfo.add(observer: self, for: conversation) } } func focus() { guard conversation.isSelfAnActiveMember else { return } renameCell?.titleTextField.becomeFirstResponder() } func prepareForUse(in collectionView: UICollectionView?) { collectionView.flatMap(GroupDetailsRenameCell.register) collectionView?.register(SectionFooter.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "SectionFooter") } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(ofType: GroupDetailsRenameCell.self, for: indexPath) cell.configure(for: conversation, editable: SelfUser.current.canModifyTitle(in: conversation)) cell.titleTextField.textFieldDelegate = self renameCell = cell return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "SectionFooter", for: indexPath) (view as? SectionFooter)?.titleLabel.text = "participants.section.name.footer".localized(args: ZMConversation.maxParticipants) return view } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.size.width, height: 56) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize { guard SelfUser.current.hasTeam else { return .zero } sizingFooter.titleLabel.text = "participants.section.name.footer".localized(args: ZMConversation.maxParticipants) sizingFooter.size(fittingWidth: collectionView.bounds.width) return sizingFooter.bounds.size } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { focus() } } extension RenameGroupSectionController: ZMConversationObserver { func conversationDidChange(_ changeInfo: ConversationChangeInfo) { guard changeInfo.securityLevelChanged || changeInfo.nameChanged else { return } guard let conversation = conversation as? ZMConversation else { return } renameCell?.configure(for: conversation, editable: ZMUser.selfUser()?.canModifyTitle(in: conversation) ?? false) } } extension RenameGroupSectionController: SimpleTextFieldDelegate { func textFieldReturnPressed(_ textField: SimpleTextField) { guard let value = textField.value else { return } switch value { case .valid(let name): validName = name textField.endEditing(true) case .error: // TODO show error textField.endEditing(true) } } func textField(_ textField: SimpleTextField, valueChanged value: SimpleTextField.Value) { } func textFieldDidBeginEditing(_ textField: SimpleTextField) { renameCell?.accessoryIconView.isHidden = true } func textFieldDidEndEditing(_ textField: SimpleTextField) { if let newName = validName { ZMUserSession.shared()?.enqueue { self.conversation.userDefinedName = newName } } else { textField.text = conversation.displayName } renameCell?.accessoryIconView.isHidden = false } }
gpl-3.0
f6def9b2ebff9e00011b24c874ac251d
37.07971
171
0.725595
5.445596
false
false
false
false
solinor/paymenthighway-ios-framework
PaymentHighway/UI/AddCardViewController.swift
1
4967
// // AddCardViewController.swift // PaymentHighway // // Copyright © 2018 Payment Highway Oy. All rights reserved. // import UIKit public protocol AddCardDelegate: class { func cancel() func addCard(_ card: CardData) } /// View controller to manage a credit card entry. /// It renders a 'Cancel' and 'Add card' buttons so it must be presented inside a `UINavigationController`. /// /// `Presenter` helper can be used to show the View Controller. /// /// User can fill out the form and on submission card data will be provided to addCard delegate. /// User can cancel the form and proper delegate call is performed. /// public class AddCardViewController: UIViewController, ValidationDelegate { @IBOutlet var addCardView: AddCardView! var addCardButton: UIBarButtonItem! var cancelButton: UIBarButtonItem! var theme: Theme { didSet { addCardView?.theme = theme } } /// The add card delegate public weak var addCardDelegate: AddCardDelegate? /// Initializes a new `AddCardViewController` with thecprovided theme. /// public init(theme: Theme = DefaultTheme.instance) { self.theme = theme super.init(nibName: "AddCardView", bundle: Bundle(for: type(of: self))) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(AddCardViewController.cancelPressed(_:))) cancelButton.setTitleTextAttributes([.foregroundColor: theme.highlightColor], for: .normal) cancelButton.setTitleTextAttributes([.foregroundColor: theme.highlightDisableColor], for: .disabled) navigationItem.leftBarButtonItem = cancelButton handleRightBarButton(spinner: false) addCardView.validationDelegate = self addCardView?.theme = theme navigationController?.navigationBar.isTranslucent = false navigationController?.navigationBar.barTintColor = theme.barTintColor navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: theme.primaryForegroundColor, .font: theme.emphasisFont] } public func isValidDidChange(_ isValid: Bool, _ textField: TextField?) { self.addCardButton.isEnabled = isValid } public func showError(message: String) { enableUserInput(enabled: true) addCardView.showError(message: message) } @objc func cancelPressed(_ sender: UIBarButtonItem) { finish() } @objc func addCardPressed(_ sender: Any) { if let pan = addCardView.cardNumberTextField.text, let cvc = addCardView.securityCodeTextField.text, let expiryDateString = addCardView.expiryDateTextField.text, let expiryDate = ExpiryDate(expiryDate:expiryDateString) { let card = CardData(pan: pan, cvc: cvc, expiryDate: expiryDate) finish(card) } } private func enableUserInput(enabled: Bool) { handleRightBarButton(spinner: !enabled) addCardView.isUserInteractionEnabled = enabled cancelButton.isEnabled = enabled } private func finish(_ card: CardData? = nil) { if let card = card { enableUserInput(enabled: false) addCardDelegate?.addCard(card) } else { addCardDelegate?.cancel() } addCardView.endEditing(true) } private func handleRightBarButton(spinner: Bool = false) { navigationItem.rightBarButtonItem = nil if spinner == false { let addCardButtonTitle = NSLocalizedString("AddCardButtonTitle", bundle: Bundle(for: type(of: self)), comment: "The text shown on the 'add card' button") addCardButton = UIBarButtonItem(title: addCardButtonTitle, style: .plain, target: self, action: #selector(AddCardViewController.addCardPressed(_:))) addCardButton.isEnabled = addCardView.isValid addCardButton.setTitleTextAttributes([.foregroundColor: theme.highlightColor], for: .normal) addCardButton.setTitleTextAttributes([.foregroundColor: theme.highlightDisableColor], for: .disabled) } else { let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) activityIndicator.hidesWhenStopped = false activityIndicator.startAnimating() addCardButton = UIBarButtonItem(customView: activityIndicator) } navigationItem.rightBarButtonItem = addCardButton } }
mit
c41ec74adbfb3aacf0c954a44acc65af
37.496124
142
0.64559
5.511654
false
false
false
false
amberstar/State
Sources/State/Format.swift
2
4978
// // State: Format.swift // Copyright © 2016 SIMPLETOUCH LLC. All rights reserved. // import Foundation /*===----------------------------------------------------------------------===// * MARK: - FORMAT * Formatting - Support for conversion types * * Convert types to property lists. (key value data) * Converting to different formats. (binary, plist, json) * Basic read/write to files, strings, data * * TODO: make a protocol to support other types and uses //===----------------------------------------------------------------------===*/ /// A Format can convert property lists to /// some other form. Read and writes to files, strings, data. etc. /// current support for JSON, Plists, and Binary. public class Format { public static var binary: Format { return Format() } public static var json: Format { return JSONFormat() } public static var plist: Format { return PlistFormat() } /// Writes data to a file. /// - returns: true if succeeded, false if failed func write(_ object: Any, to url: URL) -> Bool { if let data = makeData(from: object, prettyPrint: true) { return ((try? data.write(to: url, options: [.atomic])) != nil) } else { return false } } /// Writes data to and returns a `Data` plist object. func makeData(from object: Any, prettyPrint: Bool) -> Data? { return NSKeyedArchiver.archivedData(withRootObject: object) } /// Writes data to String. /// - returns: a string or nil if failed func makeString(from object: Any) -> String? { if let data = makeData(from: object, prettyPrint: true) { return String(data: data, encoding: .utf8) } else { print("Could not make data") return nil } } /// Reads and returns a new `Data` plist object. func read(_ data: Data) -> Any? { return NSKeyedUnarchiver.unarchiveObject(with: data) } /// Reads file and create Data from a URL. /// - returns: a data object or nil func read(_ url: URL) -> Any? { if let data = try? Data(contentsOf: url) { return read(data) } return nil } /// Creates `Data` plist object from a string. func read(_ content: String) -> Any? { guard let data = makeData(from: content) else { return nil } return read(data) } /// Creates `Data` from a string. func makeData(from string: String) -> Data? { return string.data(using: .utf8, allowLossyConversion: true) } } final class JSONFormat: Format { /// Reads and returns a new `Data` plist object. override func read(_ data: Data) -> Any? { do { let o: Any = try JSONSerialization.jsonObject( with: data, options: JSONSerialization.ReadingOptions.allowFragments) return o } catch let error as NSError { Swift.print(error) return nil } } /// Writes data to and returns a `Data` JSON object. override func makeData(from object: Any, prettyPrint: Bool) -> Data? { guard JSONSerialization.isValidJSONObject(object) else { return nil } let options: JSONSerialization.WritingOptions = prettyPrint ? .prettyPrinted : [] let data: Data? do { data = try JSONSerialization.data(withJSONObject: object, options: options) } catch let error as NSError { Swift.print(error) data = nil } return data } } final class PlistFormat: Format { /// Reads and returns a new `Data` plist object. override func read(_ data: Data) -> Any? { do { let o: Any = try PropertyListSerialization.propertyList(from: data, options: [.mutableContainersAndLeaves], format: nil) return o } catch let error as NSError { Swift.print(error) return nil } } /// Creates `Data` plist object from a string. override func read(_ content: String) -> Any? { let s = content as NSString return s.propertyList() } /// Writes data to and returns a `Data` plist object. override func makeData(from object: Any, prettyPrint: Bool) -> Data? { guard PropertyListSerialization.propertyList( object, isValidFor: PropertyListSerialization.PropertyListFormat.xml) else { print("Object is invalid for property list serialization") return nil } do { let data: Data? = try PropertyListSerialization.data( fromPropertyList: object, format: PropertyListSerialization.PropertyListFormat.xml, options: 0) return data } catch let error as NSError { Swift.print(error) } return nil } }
mit
56f44ec68413852c3595dbb7ee5c12e4
31.109677
127
0.569419
4.717536
false
false
false
false
fakerabbit/autobot
Carthage/Checkouts/NVActivityIndicatorView/NVActivityIndicatorViewDemo/ViewController.swift
1
3705
// // ViewController.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import Foundation import NVActivityIndicatorView class ViewController: UIViewController, NVActivityIndicatorViewable { override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(red: CGFloat(237 / 255.0), green: CGFloat(85 / 255.0), blue: CGFloat(101 / 255.0), alpha: 1) let cols = 4 let rows = 8 let cellWidth = Int(self.view.frame.width / CGFloat(cols)) let cellHeight = Int(self.view.frame.height / CGFloat(rows)) (NVActivityIndicatorType.ballPulse.rawValue ... NVActivityIndicatorType.audioEqualizer.rawValue).forEach { let x = ($0 - 1) % cols * cellWidth let y = ($0 - 1) / cols * cellHeight let frame = CGRect(x: x, y: y, width: cellWidth, height: cellHeight) let activityIndicatorView = NVActivityIndicatorView(frame: frame, type: NVActivityIndicatorType(rawValue: $0)!) let animationTypeLabel = UILabel(frame: frame) animationTypeLabel.text = String($0) animationTypeLabel.sizeToFit() animationTypeLabel.textColor = UIColor.white animationTypeLabel.frame.origin.x += 5 animationTypeLabel.frame.origin.y += CGFloat(cellHeight) - animationTypeLabel.frame.size.height activityIndicatorView.padding = 20 if $0 == NVActivityIndicatorType.orbit.rawValue { activityIndicatorView.padding = 0 } self.view.addSubview(activityIndicatorView) self.view.addSubview(animationTypeLabel) activityIndicatorView.startAnimating() let button: UIButton = UIButton(frame: frame) button.tag = $0 button.addTarget(self, action: #selector(buttonTapped(_:)), for: UIControlEvents.touchUpInside) self.view.addSubview(button) } } func buttonTapped(_ sender: UIButton) { let size = CGSize(width: 30, height: 30) startAnimating(size, message: "Loading...", type: NVActivityIndicatorType(rawValue: sender.tag)!) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.5) { NVActivityIndicatorPresenter.sharedInstance.setMessage("Authenticating...") } DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) { self.stopAnimating() } } }
gpl-3.0
3bf2af0866982ff18aec7fa5e60da4db
41.102273
136
0.662078
4.959839
false
false
false
false
twostraws/SwiftGD
Sources/SwiftGD/Color.swift
1
5319
public struct Color { public var redComponent: Double public var greenComponent: Double public var blueComponent: Double public var alphaComponent: Double public init(red: Double, green: Double, blue: Double, alpha: Double) { redComponent = red greenComponent = green blueComponent = blue alphaComponent = alpha } } // MARK: Constants extension Color { public static let red = Color(red: 1, green: 0, blue: 0, alpha: 1) public static let green = Color(red: 0, green: 1, blue: 0, alpha: 1) public static let blue = Color(red: 0, green: 0, blue: 1, alpha: 1) public static let black = Color(red: 0, green: 0, blue: 0, alpha: 1) public static let white = Color(red: 1, green: 1, blue: 1, alpha: 1) } // MARK: Hexadecimal extension Color { /// The maximum representable integer for each color component. private static let maxHex: Int = 0xff /// Initializes a new `Color` instance of given hexadecimal color string. /// /// Given string will be stripped from a single leading "#", if applicable. /// Resulting string must met any of the following criteria: /// /// - Is a string with 8-characters and therefore a fully fledged hexadecimal /// color representation **including** an alpha component. Given value will remain /// untouched before conversion. Example: `ffeebbaa` /// - Is a string with 6-characters and therefore a fully fledged hexadecimal color /// representation **excluding** an alpha component. Given RGB color components will /// remain untouched and an alpha component of `0xff` (opaque) will be extended before /// conversion. Example: `ffeebb` -> `ffeebbff` /// - Is a string with 4-characters and therefore a shortened hexadecimal color /// representation **including** an alpha component. Each single character will be /// doubled before conversion. Example: `feba` -> `ffeebbaa` /// - Is a string with 3-characters and therefore a shortened hexadecimal color /// representation **excluding** an alpha component. Given RGB color character will /// be doubled and an alpha of component of `0xff` (opaque) will be extended before /// conversion. Example: `feb` -> `ffeebbff` /// /// - Parameters: /// - string: The hexadecimal color string. /// - leadingAlpha: Indicate whether given string should be treated as ARGB (`true`) or RGBA (`false`) /// - Throws: `.invalidColor` if given string does not match any of the above mentioned criteria or is not a valid hex color. public init(hex string: String, leadingAlpha: Bool = false) throws { let string = try Color.sanitize(hex: string, leadingAlpha: leadingAlpha) guard let code = Int(string, radix: 16) else { throw Error.invalidColor(reason: "0x\(string) is not a valid hex color code") } self.init(hex: code, leadingAlpha: leadingAlpha) } /// Initializes a new `Color` instance of given hexadecimal color values. /// /// - Parameters: /// - color: The hexadecimal color value, incl. red, green, blue and alpha /// - leadingAlpha: Indicate whether given code should be treated as ARGB (`true`) or RGBA (`false`) public init(hex color: Int, leadingAlpha: Bool = false) { let max = Double(Color.maxHex) let first = Double((color >> 24) & Color.maxHex) / max let secnd = Double((color >> 16) & Color.maxHex) / max let third = Double((color >> 8) & Color.maxHex) / max let forth = Double((color >> 0) & Color.maxHex) / max if leadingAlpha { self.init(red: secnd, green: third, blue: forth, alpha: first) // ARGB } else { self.init(red: first, green: secnd, blue: third, alpha: forth) // RGBA } } // MARK: Private helper /// Sanitizes given hexadecimal color string (strips # and forms proper length). /// /// - Parameters: /// - string: The hexadecimal color string to sanitize /// - leadingAlpha: Indicate whether given and returning string should be treated as ARGB (`true`) or RGBA (`false`) /// - Returns: The sanitized hexadecimal color string /// - Throws: `.invalidColor` if given string is not of proper length private static func sanitize(hex string: String, leadingAlpha: Bool) throws -> String { // Drop leading "#" if applicable var string = string.hasPrefix("#") ? String(string.dropFirst(1)) : string // Evaluate if short code w/wo alpha (e.g. `feb` or `feb4`). Double up the characters if so. if string.count == 3 || string.count == 4 { string = string.map({ "\($0)\($0)" }).joined() } // Evaluate if fully fledged code w/wo alpha (e.g. `ffaabb` or `ffaabb44`), otherwise throw error switch string.count { case 6: // Hex color code without alpha (e.g. ffeeaa) let alpha = String(Color.maxHex, radix: 16) // 0xff (opaque) return leadingAlpha ? alpha + string : string + alpha case 8: // Fully fledged hex color including alpha (e.g. eebbaa44) return string default: throw Error.invalidColor(reason: "0x\(string) has invalid hex color string length") } } }
mit
d132be9e475cc5d76f4f440b39b13db7
45.252174
129
0.641662
4.20807
false
false
false
false
liufengting/FTChatMessageDemoProject
FTChatMessage/FTChatMessageCell/FTChatMessageBubbleItem/FTChatMessageBubbleLocationItem.swift
1
2242
// // FTChatMessageBubbleLocationItem.swift // FTChatMessage // // Created by liufengting on 16/5/7. // Copyright © 2016年 liufengting <https://github.com/liufengting>. All rights reserved. // import UIKit import MapKit class FTChatMessageBubbleLocationItem: FTChatMessageBubbleItem { var mapView : MKMapView! convenience init(frame: CGRect, aMessage : FTChatMessageModel, for indexPath: IndexPath) { self.init(frame:frame) self.backgroundColor = UIColor.clear message = aMessage let mapRect = self.getMapSize(aMessage.isUserSelf) mapView = MKMapView(frame : mapRect) mapView.isScrollEnabled = false mapView.isUserInteractionEnabled = false mapView.layer.cornerRadius = FTDefaultMessageRoundCorner mapView.layer.borderColor = aMessage.messageSender.isUserSelf ? FTDefaultOutgoingColor.cgColor : FTDefaultIncomingColor.cgColor mapView.layer.borderWidth = 0.8 self.addSubview(mapView) // setRegion let coordinate = CLLocationCoordinate2DMake(31.479461477978905, 120.38549624655187); let region = MKCoordinateRegionMakeWithDistance(coordinate, Double(mapRect.size.width), Double(mapRect.size.height)) mapView.setRegion(region, animated: false) // addAnnotation let string = NSString(format: "%.1f,%.1f",coordinate.latitude,coordinate.longitude) let pin = MapPin.init(coordinate: coordinate, title: "My Location", subtitle: string as String) mapView.addAnnotation(pin as MKAnnotation) } fileprivate func getMapSize(_ isUserSelf : Bool) -> CGRect { let bubbleRect = CGRect(x: isUserSelf ? 0 : FTDefaultMessageBubbleAngleWidth, y: 0, width: self.bounds.size.width - FTDefaultMessageBubbleAngleWidth , height: self.bounds.size.height) return bubbleRect; } } class MapPin : NSObject, MKAnnotation { var coordinate: CLLocationCoordinate2D var title: String? var subtitle: String? init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String) { self.coordinate = coordinate self.title = title self.subtitle = subtitle } }
mit
3ca98d3fb706ea59c94e1e43821e4dd6
34.539683
191
0.69138
4.569388
false
false
false
false
huangboju/AsyncDisplay_Study
AsyncDisplay/Controllers/ASCollectionViewController.swift
1
2556
// // ASCollectionView.swift // AsyncDisplay // // Created by 伯驹 黄 on 2017/4/19. // Copyright © 2017年 伯驹 黄. All rights reserved. // import AsyncDisplayKit class ASCollectionViewController: UIViewController { private lazy var collectionNode: ASCollectionNode = { let layout = UICollectionViewFlowLayout() layout.headerReferenceSize = CGSize(width: 50.0, height: 50.0) layout.footerReferenceSize = CGSize(width: 50.0, height: 50.0) let collectionNode = ASCollectionNode(frame: self.view.bounds, collectionViewLayout: layout) collectionNode.registerSupplementaryNode(ofKind: UICollectionView.elementKindSectionHeader) collectionNode.registerSupplementaryNode(ofKind: UICollectionView.elementKindSectionFooter) collectionNode.dataSource = self collectionNode.delegate = self collectionNode.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionNode.backgroundColor = UIColor.white return collectionNode }() override func viewDidLoad() { super.viewDidLoad() view.addSubnode(collectionNode) collectionNode.frame = view.bounds } deinit { collectionNode.dataSource = nil collectionNode.delegate = nil } } extension ASCollectionViewController: ASCollectionDataSource { func collectionNode(_ collectionNode: ASCollectionNode, nodeBlockForItemAt indexPath: IndexPath) -> ASCellNodeBlock { let text = "[\(indexPath.section).\(indexPath.item)] says hi" return { return ItemNode(string: text) } } func collectionNode(_ collectionNode: ASCollectionNode, nodeForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> ASCellNode { let text = kind == UICollectionView.elementKindSectionHeader ? "Header" : "Footer" let node = SupplementaryNode(text: text) let isHeaderSection = kind == UICollectionView.elementKindSectionHeader node.backgroundColor = isHeaderSection ? UIColor.blue : UIColor.red return node } func collectionNode(_ collectionNode: ASCollectionNode, numberOfItemsInSection section: Int) -> Int { return 10 } func numberOfSections(in collectionNode: ASCollectionNode) -> Int { return 100 } func collectionNode(_ collectionNode: ASCollectionNode, willBeginBatchFetchWith context: ASBatchContext) { context.completeBatchFetching(true) } } extension ASCollectionViewController: ASCollectionDelegate { }
mit
055467c8746404c895ed24d29f82ed1c
32.88
148
0.712318
5.429487
false
false
false
false
ianthetechie/SwiftCGI-Demo
Carthage/Checkouts/SwiftCGI/SwiftCGI Framework/Backends/FCGI/FCGIRequest.swift
1
4486
// // Request.swift // SwiftCGI // // Copyright (c) 2014, Ian Wagner // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that thefollowing 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. // // 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. // let FCGIRecordHeaderLength: UInt = 8 let FCGITimeout: NSTimeInterval = 5 public class FCGIRequest { let record: BeginRequestRecord let keepConnection: Bool public internal(set) var params: RequestParams = [:] // Set externally and never reset to nil thereafter private var _cookies: [String: String]? public var socket: GCDAsyncSocket? // Set externally by the server public var streamData: NSMutableData? // TODO: actually set the headers public var headers: [String: String]? init(record: BeginRequestRecord) { self.record = record keepConnection = record.flags?.contains(.KeepConnection) ?? false } // FCGI-specific implementation private func finishWithProtocolStatus(protocolStatus: FCGIProtocolStatus, andApplicationStatus applicationStatus: FCGIApplicationStatus) -> Bool { guard let sock = socket else { NSLog("ERROR: No socket for request") return false } let outRecord = EndRequestRecord(version: record.version, requestID: record.requestID, paddingLength: 0, protocolStatus: protocolStatus, applicationStatus: applicationStatus) sock.writeData(outRecord.fcgiPacketData, withTimeout: 5, tag: 0) if keepConnection { sock.readDataToLength(FCGIRecordHeaderLength, withTimeout: FCGITimeout, tag: FCGISocketTag.AwaitingHeaderTag.rawValue) } else { sock.disconnectAfterWriting() } return true } } extension FCGIRequest: Request { public var path: String { guard let uri = params["REQUEST_URI"] else { fatalError("Encountered reques that was missing a path") } return uri } public func finish(status: RequestCompletionStatus) { switch status { case .Complete: finishWithProtocolStatus(.RequestComplete, andApplicationStatus: 0) } } public var cookies: [String: String]? { get { if _cookies == nil { if let cookieString = params["HTTP_COOKIE"] { var result: [String: String] = [:] let cookieDefinitions = cookieString.componentsSeparatedByString("; ") for cookie in cookieDefinitions { let cookieDef = cookie.componentsSeparatedByString("=") result[cookieDef[0]] = cookieDef[1] } _cookies = result } } return _cookies } set { _cookies = newValue } } public var method: HTTPMethod { guard let requestMethod = params["REQUEST_METHOD"] else { fatalError("No REQUEST_METHOD found in the FCGI request params.") } guard let meth = HTTPMethod(rawValue: requestMethod) else { fatalError("Invalid HTTP method specified in REQUEST_METHOD.") } return meth } }
bsd-2-clause
729807aeca70ba8450046a708634dcd3
36.07438
182
0.648685
4.935094
false
false
false
false
AnirudhDas/AniruddhaDas.github.io
RedBus/RedBus/Common/Constants.swift
1
3604
// // Constants.swift // RedBus // // Created by Anirudh Das on 8/22/18. // Copyright © 2018 Aniruddha Das. All rights reserved. // import Foundation import UIKit struct Constants { //Success and Error Messages public static let useDifferentFilter = "Use a different filter!" public static let bookingSuccessful = "Bus booking successful." public static let fetchBusesSuccess = "Showing all buses." public static let cancelSuccessful = "Booking cancelled successfully." public static let invalidRatingInput = "Please enter a valid rating between 0 to 5" public static let ratingUpdateSuccess = "Rating updated successfully." public static let filterSuccess = "Filter applied successfully." //Images public static let placeholderImage: UIImage = #imageLiteral(resourceName: "placeholder") public static let filter: UIImage = #imageLiteral(resourceName: "filter") public static let clearFilter: UIImage = #imageLiteral(resourceName: "clearFilter") public static let ratingDeselected: UIImage = #imageLiteral(resourceName: "ratingDeselected") public static let ratingSelected: UIImage = #imageLiteral(resourceName: "ratingSelected") public static let depatureDeselected: UIImage = #imageLiteral(resourceName: "departureDeselected") public static let depatureSelected: UIImage = #imageLiteral(resourceName: "departureSelected") public static let fareDeselected: UIImage = #imageLiteral(resourceName: "fareDeselected") public static let fareSelected: UIImage = #imageLiteral(resourceName: "fareSelected") public static let arrowUp: UIImage = #imageLiteral(resourceName: "arrowUp") public static let arrowDown: UIImage = #imageLiteral(resourceName: "arrowDown") public static let acDeselected: UIImage = #imageLiteral(resourceName: "acDeselected") public static let acSelected: UIImage = #imageLiteral(resourceName: "acSelected") public static let nonACDeselected: UIImage = #imageLiteral(resourceName: "nonACDeselected") public static let nonACSelected: UIImage = #imageLiteral(resourceName: "nonACSelected") public static let seaterDeselected: UIImage = #imageLiteral(resourceName: "seaterDeselected") public static let seaterSelected: UIImage = #imageLiteral(resourceName: "seaterSelected") public static let sleeperDeselected: UIImage = #imageLiteral(resourceName: "sleeperDeselected") public static let sleeperSelected: UIImage = #imageLiteral(resourceName: "sleeperSelected") //Storyboard Identifiers public static let filterVCStoryboardId = "filterVC" public static let busCell = "busCell" public static let bookingCell = "bookingCell" public static let busesListVC = "busesListVC" //Alerts public static let bookingAlertTitle = "Confirm Booking" public static let bookingAlertMessage = "Are you sure you want to book your bus" public static let bookingAlertOK = "Book" public static let bookingAlertCancel = "Dismiss" public static let cancelAlertTitle = "Confirm Cancel" public static let cancelAlertMessage = "Are you sure you want to cancel your booking?" public static let cancelAlertOK = "Proceed" public static let cancelAlertCancel = "Dismiss" public static let updateAlertPlaceholder = "Enter rating" public static let updateAlertTitle = "Confirm Update" public static let updateAlertMessage = "Are you sure you want to update rating?" public static let updateAlertOK = "Update" public static let updateAlertCancel = "Dismiss" }
apache-2.0
590bb68e2c1ddec00fc9905eaee06574
47.689189
102
0.747433
4.96281
false
false
false
false
jay18001/brickkit-ios
Example/Source/Examples/Interactive/BrickCollectionInteractiveViewController.swift
1
8168
// // BrickCollectionInteractiveViewController.swift // BrickApp // // Created by Ruben Cagnie on 5/26/16. // Copyright © 2016 Wayfair. All rights reserved. // import UIKit import BrickKit private let RepeatSection = "RepeatSection" private let Stepper = "Stepper" private let Section = "Section" private let FooterTitleLabel = "FooterTitleLabel" private let FooterSection = "FooterSection" private let RepeatTitleLabel = "RepeatTitleLabel" private let RepeatLabel1 = "RepeatLabel1" private let RepeatLabel2 = "RepeatLabel2" class BrickCollectionInteractiveViewController: BrickViewController { override class var brickTitle: String { return "CollectionBrick" } override class var subTitle: String { return "Shows how to add and remove CollectionBricks in an interactive way" } #if os(iOS) var stepperModel = StepperBrickModel(count: 1) #endif var footerModel = LabelBrickCellModel(text: "There are no values") var repeatSection: BrickSection! var dataSources: [BrickCollectionViewDataSource] = [] var even = true override func viewDidLoad() { super.viewDidLoad() let layout = self.brickCollectionView.layout layout.zIndexBehavior = .bottomUp self.registerBrickClass(LabelBrick.self) self.registerBrickClass(CollectionBrick.self) #if os(iOS) self.registerBrickClass(StepperBrick.self) #endif self.brickCollectionView.backgroundColor = .brickBackground repeatSection = BrickSection(RepeatSection, bricks: [ LabelBrick(RepeatTitleLabel, backgroundColor: .brickGray1, dataSource: self), LabelBrick(RepeatLabel1, width: .ratio(ratio: 0.5), backgroundColor: .brickGray2, dataSource: self), LabelBrick(RepeatLabel2, width: .ratio(ratio: 0.5), backgroundColor: .brickGray4, dataSource: self), ]) let footerSection = BrickSection(FooterSection, backgroundColor: UIColor.darkGray, bricks: [ LabelBrick(FooterTitleLabel, backgroundColor: .brickGray1, dataSource: footerModel), ], inset: 10, edgeInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)) let bricksTypes: [Brick.Type] = [LabelBrick.self, CollectionBrick.self] #if os(iOS) let section = BrickSection(Section, bricks: [ LabelBrick(BrickIdentifiers.titleLabel, backgroundColor: .brickGray3, dataSource: LabelBrickCellModel(text: "Tap here to change the collections".uppercased()) { cell in cell.configure() }), StepperBrick(Stepper, backgroundColor: .brickGray1, dataSource: stepperModel, delegate: self), BrickSection(RepeatSection, bricks: [ CollectionBrick(BrickIdentifiers.repeatLabel, width: .ratio(ratio: 0.5), backgroundColor: .brickGray5, dataSource: self, brickTypes: bricksTypes) ], inset: 5), footerSection ], inset: 10, edgeInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)) #else let section = BrickSection(Section, bricks: [ LabelBrick(BrickIdentifiers.titleLabel, backgroundColor: .brickGray3, dataSource: LabelBrickCellModel(text: "Tap here to change the collections".uppercased()) { cell in cell.configure() }), BrickSection(RepeatSection, bricks: [ CollectionBrick(BrickIdentifiers.repeatLabel, width: .ratio(ratio: 0.5), backgroundColor: .brickGray5, dataSource: self, brickTypes: bricksTypes) ], inset: 5), footerSection ], inset: 10, edgeInsets: UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)) #endif section.repeatCountDataSource = self let stickyBehavior = StickyFooterLayoutBehavior(dataSource: self) self.layout.behaviors.insert(stickyBehavior) updateDataSources() self.setSection(section) self.layout.hideBehaviorDataSource = self updateTitle() } var currentCount: Int { #if os(iOS) return stepperModel.count #else return 1 #endif } func updateDataSources() { dataSources = [] for _ in 0..<currentCount { let dataSource = BrickCollectionViewDataSource() dataSource.setSection(repeatSection) dataSources.append(dataSource) } } func updateTitle() { footerModel.text = "There are \(1) label(s)" reloadBricksWithIdentifiers([FooterTitleLabel]) } } extension BrickCollectionInteractiveViewController { func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: IndexPath) { let brickInfo = brickCollectionView.brickInfo(at:indexPath) if brickInfo.brick.identifier == BrickIdentifiers.titleLabel { even = !even UIView.performWithoutAnimation({ self.reloadBricksWithIdentifiers([BrickIdentifiers.repeatLabel, RepeatSection], shouldReloadCell: true) }) } collectionView.deselectItem(at: indexPath, animated: true) } } extension BrickCollectionInteractiveViewController: LabelBrickCellDataSource { func configureLabelBrickCell(_ cell: LabelBrickCell) { if cell.brick.identifier == RepeatTitleLabel { cell.label.text = "Title \(cell.collectionIndex + 1)" } cell.label.text = "Label \(cell.collectionIndex + 1)" } } extension BrickCollectionInteractiveViewController: BrickRepeatCountDataSource { func repeatCount(for identifier: String, with collectionIndex: Int, collectionIdentifier: String) -> Int { if identifier == BrickIdentifiers.repeatLabel { return currentCount } else { return 1 } } } #if os(iOS) extension BrickCollectionInteractiveViewController: StepperBrickCellDelegate { func stepperBrickCellDidUpdateStepper(cell: StepperBrickCell) { stepperModel.count = Int(cell.stepper.value) updateTitle() updateDataSources() UIView.animate(withDuration: 0.5, animations: { self.brickCollectionView.invalidateRepeatCounts() self.reloadBricksWithIdentifiers([RepeatSection, Stepper, FooterSection]) }) } } #endif extension BrickCollectionInteractiveViewController: CollectionBrickCellDataSource { func registerBricks(for cell: CollectionBrickCell) { #if os(iOS) cell.brickCollectionView.registerBrickClass(StepperBrick.self) #endif } func configure(for cell: CollectionBrickCell) { let layout = cell.brickCollectionView.layout layout.hideBehaviorDataSource = self } func dataSourceForCollectionBrickCell(cell: CollectionBrickCell) -> BrickCollectionViewDataSource { return dataSources[cell.index] } } extension BrickCollectionInteractiveViewController: HideBehaviorDataSource { func hideBehaviorDataSource(shouldHideItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> Bool { guard let brickCollectionView = collectionViewLayout.collectionView as? BrickCollectionView else { return false } let brickInfo = brickCollectionView.brickInfo(at:indexPath) if identifier == FooterTitleLabel { return true } else if identifier == RepeatTitleLabel && (brickInfo.collectionIndex % 2 == 0) == even { return true } return false } } extension BrickCollectionInteractiveViewController: StickyLayoutBehaviorDataSource { func stickyLayoutBehavior(_ stickyLayoutBehavior: StickyLayoutBehavior, shouldStickItemAtIndexPath indexPath: IndexPath, withIdentifier identifier: String, inCollectionViewLayout collectionViewLayout: UICollectionViewLayout) -> Bool { return identifier == FooterSection } }
apache-2.0
afb43e9bdc64cccab79b3fed96e9077c
35.623318
238
0.673809
5.208546
false
false
false
false
josve05a/wikipedia-ios
Wikipedia/Code/WikipediaURLTranslations.swift
2
1587
struct WikipediaURLTranslations { private static var sharedLookupTable: [String: WikipediaSiteInfoLookup] = [:] private static func lookupTable(for languageCode: String) -> WikipediaSiteInfoLookup? { var lookup = sharedLookupTable[languageCode] if lookup == nil { lookup = WikipediaSiteInfoLookup.fromFile(with: languageCode) sharedLookupTable[languageCode] = lookup } return lookup } private static func canonicalized(_ string: String) -> String { return string.uppercased().replacingOccurrences(of: "_", with: " ") } static func commonNamespace(for namespaceString: String, in languageCode: String) -> PageNamespace? { let canonicalNamespace = canonicalized(namespaceString) return lookupTable(for: languageCode)?.namespace[canonicalNamespace] } static func isMainpageTitle(_ maybeMainpage: String, in languageCode: String) -> Bool { return lookupTable(for: languageCode)?.mainpage == canonicalized(maybeMainpage) } } private struct WikipediaSiteInfoLookup: Codable { let namespace: Dictionary<String, PageNamespace> let mainpage: String static func fromFile(with languageCode: String) -> WikipediaSiteInfoLookup? { guard let url = Bundle.main.url(forResource: "wikipedia-namespaces/\(languageCode)", withExtension: "json"), let data = try? Data(contentsOf: url) else { return nil } return try? JSONDecoder().decode(WikipediaSiteInfoLookup.self, from: data) } }
mit
3898083ffb3c696db82e08c7fd451728
37.707317
114
0.681159
4.943925
false
false
false
false
ephread/Instructions
Examples/Example/Sources/Core/View Controllers/Delegate Examples/PausingCodeViewController.swift
1
4753
// Copyright (c) 2018-present Frédéric Maquin <[email protected]> and contributors. // Licensed under the terms of the MIT License. import UIKit import Instructions // A controller showcasing the ability to pause the flow, do something else on the screen // and start it again. internal class PausingCodeViewController: ProfileViewController { let text1 = "That's a beautiful navigation bar." let text2 = "We're going to pause the flow. Use this button to start it again." let text2HideNothing = """ We're going to pause the flow, without hiding anything (which means \ that the UI will be blocked). Use the skip button to get out. """ let text2HideOverlay = """ We're going to pause the flow, hiding the overlay (while \ keeping the UI blocked). Use the skip button to get out. """ let text3 = "Good job, that's all folks!" var pauseStyle: PauseStyle = .hideNothing @IBOutlet var tapMeButton: UIButton! // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() coachMarksController.dataSource = self coachMarksController.delegate = self emailLabel?.layer.cornerRadius = 4.0 postsLabel?.layer.cornerRadius = 4.0 reputationLabel?.layer.cornerRadius = 4.0 let skipView = CoachMarkSkipDefaultView() skipView.setTitle("Skip", for: .normal) coachMarksController.skipView = skipView coachMarksController.overlay.isUserInteractionEnabled = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } @IBAction func performButtonTap(_ sender: AnyObject) { // The user tapped on the button, so let's carry on! coachMarksController.flow.resume() } // MARK: - Protocol Conformance | CoachMarksControllerDelegate override func coachMarksController(_ coachMarksController: CoachMarksController, willShow coachMark: inout CoachMark, beforeChanging change: ConfigurationChange, at index: Int) { if index == 2 && change == .nothing { coachMarksController.flow.pause(and: pauseStyle) } } } // MARK: - Protocol Conformance | CoachMarksControllerDataSource extension PausingCodeViewController: CoachMarksControllerDataSource { func numberOfCoachMarks(for coachMarksController: CoachMarksController) -> Int { return 3 } func coachMarksController(_ coachMarksController: CoachMarksController, coachMarkAt index: Int) -> CoachMark { let controller = coachMarksController switch index { case 0: let navigationBar = navigationController?.navigationBar return controller.helper.makeCoachMark(for: navigationBar) { (frame) -> UIBezierPath in // This will make a cutoutPath matching the shape of // the component (no padding, no rounded corners). return UIBezierPath(rect: frame) } case 1: return controller.helper.makeCoachMark(for: tapMeButton) case 2: return controller.helper.makeCoachMark(for: postsLabel) default: return CoachMark() } } func coachMarksController( _ coachMarksController: CoachMarksController, coachMarkViewsAt index: Int, madeFrom coachMark: CoachMark ) -> (bodyView: (UIView & CoachMarkBodyView), arrowView: (UIView & CoachMarkArrowView)?) { let coachViews = coachMarksController.helper.makeDefaultCoachViews( withArrow: true, withNextText: true, arrowOrientation: coachMark.arrowOrientation ) switch index { case 0: coachViews.bodyView.hintLabel.text = text1 coachViews.bodyView.nextLabel.text = nextButtonText case 1: switch pauseStyle { case .hideInstructions: coachViews.bodyView.hintLabel.text = text2 case .hideOverlay: coachViews.bodyView.hintLabel.text = text2HideOverlay case .hideNothing: coachViews.bodyView.hintLabel.text = text2HideNothing } coachViews.bodyView.nextLabel.text = nextButtonText case 2: coachViews.bodyView.hintLabel.text = text3 coachViews.bodyView.nextLabel.text = nextButtonText default: break } return (bodyView: coachViews.bodyView, arrowView: coachViews.arrowView) } }
mit
5cf48101343bdc61c43916c9ada5c225
37.008
99
0.62892
5.479815
false
false
false
false
peterlafferty/Emojirama
Today Extension/TodayViewController.swift
1
2857
// // TodayViewController.swift // Today Extension Today Extension // // Created by Peter Lafferty on 16/11/2015. // Copyright © 2015 Peter Lafferty. All rights reserved. // import UIKit import NotificationCenter import EmojiramaKit class TodayViewController: UIViewController, NCWidgetProviding { static let numberOfMinutes = 5 @IBOutlet weak var openAppButton: UIButton! @IBOutlet weak var label: UILabel! var emojirama = Emojirama() var emoji = Emoji() var displayString: String { if emoji.value.isEmpty { return "loading..." } else { return "What does \(emoji.value) mean?" } } override func viewDidLoad() { super.viewDidLoad() emoji = loadEmoji() openAppButton.setTitle(displayString, for: UIControlState()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) { // Perform any setup necessary in order to update the view. // If an error is encountered, use NCUpdateResult.Failed // If there's no update required, use NCUpdateResult.NoData // If there's an update, use NCUpdateResult.NewData completionHandler(NCUpdateResult.noData) } func widgetMarginInsets(forProposedMarginInsets defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets { return UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0) } @IBAction func launchApplication(_ sender: AnyObject) { let emojiString = emoji.value.addingPercentEncoding( withAllowedCharacters: CharacterSet.alphanumerics)! let string = "emojirama://view/\(emojiString)/?modifier=1" if let url = URL(string: string) { extensionContext?.open(url, completionHandler: nil) } } func loadEmoji() -> Emoji { let defaults = UserDefaults.standard let emoji: Emoji //only update today extension if time has passed if let savedEmojiValue: String = defaults.string(forKey: "emoji"), let saveDate = defaults.object( forKey: "saveDate") as? Date, Int(Date().timeIntervalSince(saveDate) / 60 ) < TodayViewController.numberOfMinutes { let filteredEmoji = emojirama.filter(savedEmojiValue) if filteredEmoji.count > 0 { emoji = filteredEmoji[0] } else { emoji = emojirama.random() } } else { emoji = emojirama.random() defaults.set(emoji.value, forKey: "emoji") defaults.set(Date(), forKey: "saveDate") defaults.synchronize() } return emoji } }
mit
2c37c9deaa19da95b50cc3d56af5eb92
30.733333
104
0.627801
4.907216
false
false
false
false
li13418801337/DouyuTV
DouyuZB/DouyuZB/Classes/Main/View/PageContentView.swift
1
5402
// // PageContentView.swift // DouyuZB // // Created by work on 16/10/20. // Copyright © 2016年 xiaosi. All rights reserved. // import UIKit protocol PageContentViewDelegate : class { func pageContentView(_ contentView : PageContentView , progress : CGFloat, sourceIndex : Int, targetIndex : Int) } private let ContentCellID = "ContentwCellID" class PageContentView: UIView { //定义属性 fileprivate var childVcs : [UIViewController] fileprivate weak var parentViewController : UIViewController? fileprivate var startOffsetX : CGFloat = 0 fileprivate var isForbidScrollDelegate = false weak var delegate : PageContentViewDelegate? //懒加载属性CollectionView fileprivate lazy var collectionView : UICollectionView = {[weak self]in //创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal //创建UICollectionView let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsVerticalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID) return collectionView }() //MARK: 自定义构造函数 init(frame: CGRect, chidlVcs : [UIViewController], parentViewController : UIViewController?) { self.childVcs = chidlVcs self.parentViewController = parentViewController super.init(frame:frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK: 设置UI界面 extension PageContentView{ fileprivate func setupUI(){ //将所有字控制器添加到父控制器中 for childVc in childVcs { parentViewController?.addChildViewController(childVc) } //添加uicollectionview addSubview(collectionView) collectionView.frame = bounds } } //MARK: 遵守UICollectionView数据源 extension PageContentView : UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath) for view in cell.contentView.subviews{ view.removeFromSuperview() } let childVc = childVcs[(indexPath as NSIndexPath).item] childVc.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVc.view) return cell } } //MARK: 遵守UICollectionView代理 extension PageContentView : UICollectionViewDelegate{ func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { if isForbidScrollDelegate {return} // 获取数据 //滑动的比例 var progress : CGFloat = 0 //当前的index var sourceIndex : Int = 0 //目标的index? var targetIndex : Int = 0 // 判断左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX{ //左滑 progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) sourceIndex = Int(currentOffsetX / scrollViewW) targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } //如果完全滑过去 if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } }else{ //右滑 progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) targetIndex = Int(currentOffsetX / scrollViewW) sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } } //将3个属性传递给titleview delegate!.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } //MARK: 对外暴露的方法 extension PageContentView{ func setCurrentIndex(_ currentIndex : Int){ isForbidScrollDelegate = true let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x:offsetX,y:0), animated: false) } }
mit
58fe77f275bbf742957b59b52d57be23
27.420765
121
0.631609
5.978161
false
false
false
false
937447974/YJCocoa
Demo/Swift/AppFrameworks/UIKit/YJTableView/YJTableView/ViewController.swift
1
1042
// // ViewController.swift // YJTableView // // Created by 阳君 on 2019/5/22. // Copyright © 2019 YJCocoa. All rights reserved. // import UIKit import YJCocoa class ViewController: UIViewController { lazy var tableView: YJUITableView = { let tableView = YJUITableView.init(frame: self.view.bounds, style: .plain) tableView.delegate = tableView.manamger tableView.dataSource = tableView.manamger return tableView }() override func viewDidLoad() { super.viewDidLoad() self.edgesForExtendedLayout = UIRectEdge.init(); // self.automaticallyAdjustsScrollViewInsets = false; self.view.addSubview(self.tableView) self.testData() } func testData() { for i in 0..<50 { let cm = YJTestTVCellModel() cm.userName = "阳君-\(i)" let co = YJTestTVCell.cellObject(with: cm) self.tableView.dataSourceCellFirst.append(co) } self.tableView.reloadData() } }
mit
4c67271aaba04a18accef0e465e84f4d
24.195122
82
0.616651
4.433476
false
true
false
false
DmIvanov/DIAuth
DIAuth/DIAuth/DIFacebook.swift
1
2581
// // DIFacebook.swift // Created by Dmitry Ivanov on 26.09.15. // import FBSDKCoreKit import FBSDKLoginKit public class DIFacebook: DISocialNetwork { //MARK: Properties private var fbLoginManager: FBSDKLoginManager = FBSDKLoginManager() //MARK: Events from appDelegate override func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } override func applicationDidBecomeActive(application: UIApplication) { FBSDKAppEvents.activateApp() } //MARK: override func resetAuthData() { fbLoginManager.logOut() super.resetAuthData() } override public class func snTypeString() -> String { return "fb" } override func snCachedAuthDataIsAvailable() -> Bool { return fillDataFromFBToken() } override func openSession(appID: String, forcedWebView: Bool, vc: UIViewController? = nil) { fbLoginManager.loginBehavior = forcedWebView ? FBSDKLoginBehavior.Web : FBSDKLoginBehavior.Native FBSDKSettings.setAppID(socialAppID()) fbLoginManager.logInWithReadPermissions(permissions(), fromViewController: nil) { (result, error) -> Void in if error != nil { DIAuth.sharedInstance.snAuthorizationFailed() print("Auth error: \(error)") } else if result.isCancelled { DIAuth.sharedInstance.snAuthorizationFailed() print("Auth canceled") } else { self.fbDidFinish(result) } } } private func fbDidFinish(result: FBSDKLoginManagerLoginResult) { guard fillDataFromFBToken() else { return } DIAuth.sharedInstance.snAuthorizationDidComplete() FBSDKGraphRequest(graphPath: "me", parameters: nil).startWithCompletionHandler({ (connection, result, error) -> Void in //let id = result["id"] as? String let name = result["name"] as? String self.setAuthData(newUserName: name) }) } private func fillDataFromFBToken() -> Bool { if let fbToken = FBSDKAccessToken.currentAccessToken() { setAuthData(fbToken.userID, newToken: fbToken.tokenString, newUserName: nil) return true } else { return false } } }
mit
74e1d8a0bcc3061bb2a9c8a1e4163345
32.960526
157
0.639287
5.162
false
false
false
false
Vkt0r/AccordionMenu
Source/TableViewDataSource.swift
2
2508
// // TableViewDataSource.swift // AccordionSwift // // Created by Victor Sigler Lopez on 7/5/18. // Copyright © 2018 Victor Sigler. All rights reserved. // import UIKit typealias NumberOfSectionsClosure = () -> Int typealias NumberOfItemsInSectionClosure = (Int) -> Int typealias TableCellForRowAtIndexPathClosure = (UITableView, IndexPath) -> UITableViewCell typealias TableTitleForHeaderInSectionClosure = (Int) -> String? typealias TableTitleForFooterInSectionClosure = (Int) -> String? /// Defines the methods in the UITableViewDataSource @objc final class TableViewDataSource: NSObject { // MARK: - Properties let numberOfSections: NumberOfSectionsClosure let numberOfItemsInSection: NumberOfItemsInSectionClosure var tableCellForRowAtIndexPath: TableCellForRowAtIndexPathClosure? var tableTitleForHeaderInSection: TableTitleForHeaderInSectionClosure? var tableTitleForFooterInSection: TableTitleForFooterInSectionClosure? // MARK: - Initializer /// Construct a new TableViewDataSource /// /// - Parameters: /// - numberOfSections: The number of sections closure in data source /// - numberOfItemsInSection: The number of items in the section closure in data source init(numberOfSections: @escaping NumberOfSectionsClosure, numberOfItemsInSection: @escaping NumberOfItemsInSectionClosure) { self.numberOfSections = numberOfSections self.numberOfItemsInSection = numberOfItemsInSection } } extension TableViewDataSource: UITableViewDataSource { // MARK: - UITableViewDataSource @objc func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return numberOfItemsInSection(section) } @objc func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableCellForRowAtIndexPath!(tableView, indexPath) } @objc func numberOfSections(in tableView: UITableView) -> Int { return numberOfSections() } @objc func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { guard let closure = tableTitleForHeaderInSection else { return nil } return closure(section) } @objc func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { guard let closure = tableTitleForFooterInSection else { return nil } return closure(section) } }
mit
fd5455ab813c64a674af4b063cf3a866
35.333333
106
0.731552
5.736842
false
false
false
false
akio0911/til
20201217/20201217.playground/Pages/tryRemoveDuplicates.xcplaygroundpage/Contents.swift
1
596
//: [Previous](@previous) import Foundation import Combine // tryRemoveDuplicates(by:) | Apple Developer Documentation // https://developer.apple.com/documentation/combine/publisher/tryremoveduplicates(by:) struct BadValuesError: Error {} let numbers = [0,0,0,0,1,2,2,3,3,3,4,4,4,4] let cancellable = numbers.publisher .tryRemoveDuplicates(by: { first, second -> Bool in if first == 4 && second == 4 { throw BadValuesError() } return first == second }).sink(receiveCompletion: {print($0)}, receiveValue: {print($0)}) //: [Next](@next)
mit
6eaae4c6be6854ec193d07be4ad1acc2
27.380952
87
0.647651
3.679012
false
false
false
false
joejcon1/snapdiff
snapdiff/main.swift
1
1225
// // main.swift // snapdiff // // Created by Joe Conway on 02/10/2016. // Copyright © 2016 jc. All rights reserved. // import Foundation // add the destinations to SwiftyBeaver func main() { /* * Start reading stdin */ var parser = Parser() let imageMover = ImageCopier() let generator = HTMLGenerator() let params = ParameterParser.parseCurrentParameters() guard let configuration = Configuration(withParameters: params) else { Logger.fatal("Invalid parameters. \(params)\n\(ParameterParser.usage())") } while let line = readLine() { if let failedTest: TestCase = parser.parse(line) { imageMover.copyImages(forFailures: failedTest.snapshotTestFailures, withConfiguration: configuration) } Logger.stdout(line) } let failedTests = parser.failedSnapshotTestCases() Logger.stdout("\(failedTests.count) Failed snapshot tests found") /* * html generator takes list of failed tests, returns html */ generator.generatePage(forFailures: failedTests, withConfiguration: configuration) Logger.stdout(configuration.htmlOutputFile.absoluteString) exit(EXIT_SUCCESS) } main()
mit
03284247af51feead158297f66ba2ad6
24.5
113
0.673203
4.450909
false
true
false
false
fluidpixel/tvOS-controller
tvOS-controller/PlayersViewController.swift
1
8485
// // PlayersViewController.swift // tvOS-controller // // Created by Lauren Brown on 16/11/2015. // Copyright © 2015 Fluid Pixel Limited. All rights reserved. // import UIKit import SceneKit class PlayersViewController: UIViewController, TVCTVSessionDelegate { @IBOutlet weak var CarView1: SCNView! @IBOutlet weak var CarView2: SCNView! @IBOutlet weak var CarView3: SCNView! @IBOutlet weak var CarView4: SCNView! var players = [GameObject]() var numberOfPlayers = 0 let MAX_NUMBER_OF_PLAYERS = 4 var carScene = SCNScene() //ready confirmation @IBOutlet weak var ready1: UILabel! @IBOutlet weak var Ready2: UILabel! @IBOutlet weak var Ready3: UILabel! @IBOutlet weak var Ready4: UILabel! //lights var lightNode1 = SCNNode() var lightNode2 = SCNNode() var lightNode3 = SCNNode() var lightNode4 = SCNNode() // cameras let cameraNode1 = SCNNode() let cameraNode2 = SCNNode() let cameraNode3 = SCNNode() let cameraNode4 = SCNNode() //array to neaten things up var PlayerViews = [SCNView!]() let remote = TVCTVSession() @IBOutlet weak var Player1ColourLabel: UILabel! @IBOutlet weak var PlayerNumberLabel: UILabel! @IBOutlet weak var StatusLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() prepareScenes() self.remote.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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "StartGame" { if let vc = segue.destinationViewController as? ViewController { vc.gameObjects = players } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ func prepareScenes() { //prepare all at the start and only light them up when a player joins // CarView1.scene = SCNScene() CarView2.scene = SCNScene() CarView3.scene = SCNScene() CarView4.scene = SCNScene() PlayerViews = [CarView1, CarView2, CarView3, CarView4] //setup cameras let camera = SCNCamera() cameraNode1.camera = camera cameraNode2.camera = camera cameraNode3.camera = camera cameraNode4.camera = camera cameraNode1.position = SCNVector3(10, 5, 10) cameraNode2.position = SCNVector3(10, 5, 10) cameraNode3.position = SCNVector3(10, 5, 10) cameraNode4.position = SCNVector3(10, 5, 10) let light = SCNLight() light.type = SCNLightTypeSpot lightNode1.light = light lightNode2.light = light lightNode3.light = light lightNode4.light = light lightNode1.position = SCNVector3(0, 50, 0) lightNode2.position = SCNVector3(0, 50, 0) lightNode3.position = SCNVector3(0, 50, 0) lightNode4.position = SCNVector3(0, 50, 0) // //add camera and light to views // CarView1.scene!.rootNode.addChildNode(cameraNode1) // CarView2.scene!.rootNode.addChildNode(cameraNode2) // CarView3.scene!.rootNode.addChildNode(cameraNode3) // CarView4.scene!.rootNode.addChildNode(cameraNode4) } func addNewPlayer(device : String) { numberOfPlayers++ var newPlayer = GameObject() newPlayer.playerID = device newPlayer.ID = numberOfPlayers newPlayer.colourID = numberOfPlayers PlayerNumberLabel.text = "\(numberOfPlayers)/\(MAX_NUMBER_OF_PLAYERS)" if numberOfPlayers == MAX_NUMBER_OF_PLAYERS { StatusLabel.text = "All Players Ready!" } switch numberOfPlayers { case 1: AddPlayerToScreen(CarView1, lightNode: lightNode1, cameraNode: cameraNode1) break case 2: AddPlayerToScreen(CarView2, lightNode: lightNode2, cameraNode: cameraNode2) break case 3: AddPlayerToScreen(CarView3, lightNode: lightNode3, cameraNode: cameraNode3) break case 4: AddPlayerToScreen(CarView4, lightNode: lightNode4, cameraNode: cameraNode4) break default: break } players.append(newPlayer) } func AddPlayerToScreen(view : SCNView, lightNode : SCNNode, cameraNode : SCNNode) { if let carScene : SCNScene = SCNScene(named: "gameAssets.scnassets/rc_car.dae") { if let node = carScene.rootNode.childNodeWithName("rccarBody", recursively: false) { node.position = SCNVector3Make(0, 0, 0) node.rotation = SCNVector4Make(0, 1, 0, Float(M_PI)) node.physicsBody = SCNPhysicsBody.staticBody() node.name = "Car" let action = SCNAction.repeatActionForever(SCNAction.rotateByX(0, y: 0.5, z: 0, duration: 0.5)) node.runAction(action) let constraint = SCNLookAtConstraint(target: node) lightNode.constraints = [constraint] cameraNode.rotation = SCNVector4(0, 1, 0, 0.7) view.scene?.rootNode.addChildNode(node) view.scene?.rootNode.addChildNode(lightNode) view.scene?.rootNode.addChildNode(cameraNode) } } } func removePlayerFromScreen() { } func changePlayerColour(i : Int, playerFromDevice: String) { for var j = 0; j < numberOfPlayers; ++j { if players[j].playerID == playerFromDevice { if let node = PlayerViews[j].scene!.rootNode.childNodeWithName("Car", recursively: false) { players[j].colourID = (players[j].colourID + i) % 9 node.geometry?.materials[0].diffuse.contents = players[j].GetColour(players[j].colourID) } } } } func playerIsReady(playerFromDevice : String) { for var j = 0; j < numberOfPlayers; ++j { if players[j].playerID == playerFromDevice { switch j { case 0: ready1.hidden = !ready1.hidden break case 1: Ready2.hidden = !Ready2.hidden break case 2: Ready3.hidden = !Ready3.hidden break case 3: Ready4.hidden = !Ready4.hidden break default: break } } } } func deviceDidConnect(device: String) { print("Player joined!") addNewPlayer(device) } func deviceDidDisconnect(device: String) { print("Player left! :(") numberOfPlayers-- //remove player from list for var i = 0; i < players.count; ++i { if players[i].playerID == device { players.removeAtIndex(i) } } } func didReceiveMessage(message: [String : AnyObject], fromDevice: String) { print("received message") //join game //addNewPlayer(fromDevice) } func didReceiveMessage(message: [String : AnyObject], fromDevice: String, replyHandler: ([String : AnyObject]) -> Void) { print("received message with reply handler") if message.keys.first! == "Colour" { changePlayerColour(message.values.first as! Int, playerFromDevice: fromDevice) } else if message.keys.first == "Ready" { playerIsReady(fromDevice) } //join game //addNewPlayer(fromDevice) } }
mit
4a2d1756a3fe236b1f739c381d685d08
30.775281
125
0.571546
4.742314
false
false
false
false
kingcos/Swift-X-Algorithms
Search/01-BinarySearch-Iteratively/01-BinarySearch-Iteratively/main.swift
1
940
// // main.swift // 01-BinarySearch-Iteratively // // Created by kingcos on 05/09/2017. // Copyright © 2017 kingcos. All rights reserved. // import Foundation func binarySearchIteratively<T: Comparable>(_ target: T, in arr: [T]) -> Int? { // 下标下限 var lowerBound = 0 // 下标上限 var upperBound = arr.count - 1 while lowerBound <= upperBound { let middle = lowerBound + (upperBound - lowerBound) / 2 if arr[middle] == target { return middle } if target < arr[middle] { upperBound = middle - 1 } else { lowerBound = middle + 1 } } return nil } let numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67] print(binarySearchIteratively(67, in: numbers) ?? -1) print(binarySearchIteratively(24, in: numbers) ?? -1)
mit
bd64978a171fb8b574ba539530a3e5de
23.945946
86
0.534128
3.692
false
false
false
false
kingcos/Swift-X-Algorithms
LeetCode/066-Plus-One/066-Plus-One.playground/Contents.swift
1
1461
import UIKit class Solution_1 { // 12 ms func plusOne(_ digits: [Int]) -> [Int] { guard let last = digits.last else { fatalError("digits is empty.") } var digits = digits if last == 9 { digits[digits.count-1] = 10 for i in 1...digits.count { if digits[digits.count-i] > 9 { digits[digits.count-i] = 0 if digits.count - i - 1 >= 0 { digits[digits.count-i-1] += 1 } else { digits.insert(1, at: 0) } } else { if i == 1 { digits[digits.count-i] += 1 } break } } } else { digits[digits.count-1] += 1 } return digits } } class Solution_2 { // 8 ms func plusOne(_ digits: [Int]) -> [Int] { guard !digits.isEmpty else { return [] } var digits = digits digits[digits.count - 1] += 1 for t in digits.enumerated().reversed() { if digits[t.offset] == 10 { digits[t.offset] = 0 if t.offset == 0 { digits.insert(1, at: 0) } else { digits[t.offset - 1] += 1 } } } return digits } }
mit
11bc75f0a3b3e4fdd7ab6ceba5641c14
26.055556
76
0.372348
4.481595
false
false
false
false
cnharris10/CHRadarGraph
Pod/Classes/CHSectorDataCollection.swift
1
823
// // CHSliceCollection.swift // CHRadarGraph // // Created by Christopher Harris on 4/9/16. // Copyright © 2016 Christopher Harris. All rights reserved. // import Foundation protocol CHSectorDataCollectionProtocol { associatedtype SectorData init(_ data: [SectorData]) } public struct CHSectorDataCollection<T>: CHSectorDataCollectionProtocol { public typealias SectorData = T public var startIndex = 0 public var endIndex: Int public var currentIndex = 0 public var data: [SectorData] public var count: Int { return data.count } public init(_ data: [SectorData]) { self.data = data self.endIndex = data.count - 1 } public subscript(index: Int) -> T? { get { return index < count ? data[index] : nil } } }
mit
75ada00a695b91e72dc33791fc12e13d
20.102564
73
0.644769
3.914286
false
false
false
false
teepsllc/BuckoNetworking
BuckoNetworking/Bucko.swift
1
5421
// // Bucko.swift // Networking // // Created by Chayel Heinsen on 2/6/17. // Copyright © 2017 Teeps. All rights reserved. // import Foundation import Alamofire public protocol BuckoErrorHandler: class { func buckoRequest(request: URLRequest, error: Error) } public typealias BuckoResponseClosure = ((DataResponse<Any>) -> Void) public typealias BuckoDataResponseClosure = ((DataResponse<Data>) -> Void) public struct Bucko { /** Can be overriden to configure the session manager. e.g - Creating server trust policies ``` let manager: SessionManager = { // Create the server trust policies let serverTrustPolicies: [String: ServerTrustPolicy] = [ "0.0.0.0": .disableEvaluation // Use your server obviously. Can be a url as well, example.com ] // Create custom manager let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders let manager = SessionManager( configuration: URLSessionConfiguration.default, serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies) ) return manager }() Bucko.shared.manager = manager ``` */ public var manager: SessionManager = SessionManager() public static let shared = Bucko() public weak var delegate: BuckoErrorHandler? public init() { } /** Make API requests. Use this to handle responses with your own response closure. The example uses responseData to handle the response. If you are expecting JSON, you should use `Bucko.shared.request(endpoint:,completion:)` instead. Example: ``` let request = Bucko.shared.request(.getUser(id: "1")) request.responseData { response in if response.result.isSuccess { debugPrint(response.result.description) } else { debugPrint(response.result.error ?? "Error") } } ``` - parameter endpoint: The endpoint to use. - returns: The request that was made. */ public func request(endpoint: Endpoint) -> DataRequest { let request = manager.request( endpoint.fullURL, method: endpoint.method, parameters: endpoint.body, encoding: endpoint.encoding, headers: endpoint.headers ) print(request.description) return request } /** Make API requests with JSON response. Example: ``` let request = Bucko.shared.request(.getUser(id: "1")) { response in if let response.result.isSuccess { let json = JSON(response.result.value!) } else { let error = JSON(data: response.data) } ``` - parameter endpoint: The endpoint to use. - parameter completion: The closure that will return the response from the server. - returns: The request that was made. */ @discardableResult public func request(endpoint: Endpoint, completion: @escaping BuckoResponseClosure) -> DataRequest { let request = self.request(endpoint: endpoint).validate().responseJSON { response in if response.result.isSuccess { debugPrint(response.result.description) } else { debugPrint(response.result.error ?? "Error") // Can globably handle errors here if you want if let urlRequest = response.request, let error = response.result.error { self.delegate?.buckoRequest(request: urlRequest, error: error) } } completion(response) } print(request.description) return request } @discardableResult public func requestData(endpoint: Endpoint, completion: @escaping BuckoDataResponseClosure) -> DataRequest { let request = self.request(endpoint: endpoint).validate().responseData { response in if response.result.isSuccess { debugPrint(response.result.description) } else { debugPrint(response.result.error ?? "Error") // Can globably handle errors here if you want if let urlRequest = response.request, let error = response.result.error { self.delegate?.buckoRequest(request: urlRequest, error: error) } } completion(response) } print(request.description) return request } public func request(endpoint: Endpoint) -> Promise<DataResponse<Any>> { return Promise { seal in request(endpoint: endpoint) { response in if response.result.isSuccess { seal.fulfill(response) } else { if let responseError = response.result.value { do { let json = try JSONSerialization.data(withJSONObject: responseError, options: []) seal.reject(BuckoError(apiError: json)) } catch { seal.reject(response.result.error!) } } else { seal.reject(response.result.error!) } } } } } public func requestData(endpoint: Endpoint) -> Promise<Data> { return Promise { seal in requestData(endpoint: endpoint) { response in if response.result.isSuccess { seal.fulfill(response.result.value!) } else { if let responseError = response.result.value { seal.reject(BuckoError(apiError: responseError)) } else { seal.reject(response.result.error!) } } } } } }
mit
fb29df98b7e711cd9214dd9655f79749
28.139785
110
0.642435
4.640411
false
false
false
false
lenssss/whereAmI
Whereami/Model/UserModel.swift
1
5801
// // UserModel.swift // Whereami // // Created by ChenPengyu on 16/3/11. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit class UserModel: NSObject { var account: String? var sessionId: String? var comments: NSNumber? var commits: NSNumber? var countryCode: String? var countryName: String? var dan: NSNumber? var headPortraitUrl: String? var id: String? var lastLogin: NSDate? var level: NSNumber? var nickname: String? var points: NSNumber? var battles: NSNumber? var quits: NSNumber? var wins: NSNumber? var loss:NSNumber? var right: NSNumber? var wrong: NSNumber? var status: NSNumber? var nextPoint: NSNumber? var levelUpPersent: NSNumber? var inBattles: NSNumber? var releases: NSNumber? var backPictureUrl:String? static func modelFromDBModel(dbmodel:DBUser)->(UserModel){ let user = UserModel() user.account = dbmodel.account user.battles = dbmodel.battles user.comments = dbmodel.comments user.commits = dbmodel.commits user.countryCode = dbmodel.countryCode user.countryName = dbmodel.countryName user.dan = dbmodel.dan user.headPortraitUrl = dbmodel.headPortraitUrl user.id = dbmodel.id user.lastLogin = dbmodel.lastLogin user.level = dbmodel.level user.nickname = dbmodel.nickname user.points = dbmodel.points user.quits = dbmodel.quits user.right = dbmodel.right user.sessionId = dbmodel.sessionId user.wrong = dbmodel.wrong user.status = dbmodel.status user.wins = dbmodel.wins user.loss = dbmodel.loss user.nextPoint = dbmodel.nextPoint user.levelUpPersent = dbmodel.levelUpPersent user.inBattles = dbmodel.inBattles user.releases = dbmodel.releases user.backPictureUrl = dbmodel.backpictureId return user } class func getModelFromDictionary(dic:NSDictionary) -> UserModel{ let userModel = UserModel() userModel.account = dic["account"] as? String userModel.sessionId = dic["lastSession"] as? String userModel.comments = dic["comments"] as? NSNumber userModel.commits = dic["commits"] as? NSNumber userModel.countryCode = dic["countryCode"] as? String userModel.countryName = dic["countryName"] as? String userModel.dan = dic["dan"] as? NSNumber userModel.headPortraitUrl = dic["headPortrait"] as? String userModel.id = dic["_id"] as? String userModel.level = dic["level"] as? NSNumber userModel.nickname = dic["nickname"] as? String userModel.points = dic["points"] as? NSNumber userModel.battles = dic["battles"] as? NSNumber userModel.quits = dic["quits"] as? NSNumber userModel.wins = dic["wins"] as? NSNumber userModel.loss = dic["loss"] as? NSNumber userModel.right = dic["right"] as? NSNumber userModel.wrong = dic["wrong"] as? NSNumber userModel.status = dic["status"] as? NSNumber userModel.nextPoint = dic["nextPoint"] as? NSNumber userModel.levelUpPersent = dic["levelUpPersent"] as? NSNumber userModel.inBattles = dic["inBattles"] as? NSNumber userModel.releases = dic["releases"] as? NSNumber userModel.backPictureUrl = dic["backpictureUrl"] as? String print(dic["lastLogin"]) print(NSNull()) if ((dic["lastLogin"]!.isEqual(NSNull())) == false) { let dateStr = "\(dic["lastLogin"]!)" let lastLogin = NSDate.string2Date(dateStr) userModel.lastLogin = lastLogin } return userModel } class func getModelFromDictionaryById(dic:NSDictionary)->UserModel { let userModel = UserModel() userModel.id = dic["_id"] as? String userModel.account = dic["account"] as? String userModel.sessionId = dic["lastSession"] as? String userModel.headPortraitUrl = dic["headPortrait"] as? String userModel.countryCode = dic["countryCode"] as? String userModel.countryName = dic["countryName"] as? String userModel.comments = dic["comments"] as? NSNumber userModel.commits = dic["commits"] as? NSNumber userModel.dan = dic["dan"] as? NSNumber userModel.level = dic["level"] as? NSNumber userModel.nickname = dic["nickname"] as? String userModel.points = dic["points"] as? NSNumber userModel.battles = dic["battles"] as? NSNumber userModel.quits = dic["quits"] as? NSNumber userModel.wins = dic["wins"] as? NSNumber userModel.loss = dic["loss"] as? NSNumber userModel.right = dic["right"] as? NSNumber userModel.wrong = dic["wrong"] as? NSNumber userModel.nextPoint = dic["nextPoint"] as? NSNumber userModel.levelUpPersent = dic["levelUpPersent"] as? NSNumber userModel.inBattles = dic["inBattles"] as? NSNumber userModel.releases = dic["releases"] as? NSNumber userModel.backPictureUrl = dic["backpictureUrl"] as? String return userModel } class func getModelFromFriend(friend:FriendsModel) -> UserModel{ let userModel = UserModel() userModel.id = friend.friendId userModel.nickname = friend.nickname return userModel } class func getCurrentUser() -> UserModel?{ let sessionId = LUserDefaults().objectForKey("sessionId") as? String guard sessionId != nil else{ return nil } guard let model = CoreDataManager.sharedInstance.fetchUser(sessionId!) else{ return nil } return model } }
mit
ab8f08af759f997b457fe9eda7b2c1d3
36.895425
84
0.636426
4.463433
false
false
false
false
crarau/swift-parent-child-callback
ParentChildCallback/TimerView.swift
1
1707
// // TimerView.swift // ParentChildCallback // // Created by Ciprian Rarau on 2017-01-23. // Copyright © 2017 Ciprian Rarau. All rights reserved. // import Foundation import UIKit enum State: String { case stopped = "Stopped" case started = "Started" } class TimerView: UIView { var callback: ((Int) -> ())? = nil var counter = 0 var state: State = .stopped var timer:Timer? = Timer() @IBOutlet var stopStartButton: UIButton! override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup() { self.state = .stopped } func startTimer() { self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in if let callback = self.callback { callback(self.counter) } self.counter = self.counter + 1 } } func stopTimer() { guard let timer = self.timer else { return } timer.invalidate() } @IBAction func timeButtonTouchUpInside(_ sender: Any) { guard let callback = self.callback else { return } if (state == .stopped) { state = .started stopStartButton.setTitle("Stop timer", for: .normal) self.startTimer() } else { state = .stopped stopStartButton.setTitle("Start timer", for: .normal) self.stopTimer() } if (state == .started) { callback(counter) } } }
mit
91fb9d6e57819d3524062dde62e7de63
21.155844
90
0.528722
4.385604
false
false
false
false
octplane/Rapide
Rapide/MyPlayground.playground/section-1.swift
1
231
// Playground - noun: a place where people can play import Cocoa var str = "Hello, playground" var lines: [String] = split(str) { $0 == " " } // what's remaining to process var zL: String = lines[0] lines[0] = lineRemain + zL
mit
a9b60517c42f326ba43aeff4437de1f8
18.25
51
0.65368
3.039474
false
false
false
false
dhardiman/MVVMTools
Sources/MVVM/CollectionViewCellSource.swift
1
2472
// // CollectionViewCellSource.swift // MVVM // // Created by Stephen Anthony on 05/01/2017. // Copyright © 2017 David Hardiman. All rights reserved. // import Foundation import UIKit // MARK: - Default implementation of reuse identifier for collection view cells public extension ViewCell where Self: UICollectionViewCell { static var defaultReuseIdentifier: String { return String(describing: self) } } /** * A protocol that describes a source for MVVM compatible collection view cells */ public protocol CollectionViewCellSource: UICollectionViewDataSource { /// The type of the view model being used by the cells. Used as a type /// constraint in the extension below associatedtype CellViewModelType: ViewModel /// The collection view being supplied var collectionView: UICollectionView! { get set } } public extension CollectionViewCellSource { /** Registers a collection cell by nib name with the current collection view - parameter _: The type of the cell being registered */ func registerNib<T: UICollectionViewCell>(_: T.Type, bundle: Bundle? = nil) where T: ViewCell { let nib = UINib(nibName: (String(describing: T.self)), bundle: bundle) collectionView?.register(nib, forCellWithReuseIdentifier: T.defaultReuseIdentifier) } /** Registers a collection view cell by its class - parameter _: The type of the cell being registered */ func registerClass<T: UICollectionViewCell>(_: T.Type) where T: ViewCell { collectionView?.register(T.self, forCellWithReuseIdentifier: T.defaultReuseIdentifier) } /** Dequeues a cell from the current collection view and configures the cell's view model with the specified item - parameter item: The item for the cell to display - parameter atIndexPath: The indexPath to dequeue the cell for - returns: A configured cell */ func cell<VC: ViewCell>(forItem item: CellViewModelType.ModelType, at indexPath: IndexPath) -> VC where VC.ViewModelType == Self.CellViewModelType, VC: UICollectionViewCell { guard let cell = collectionView?.dequeueReusableCell(withReuseIdentifier: VC.defaultReuseIdentifier, for: indexPath) as? VC else { fatalError("No cell registered for \(VC.defaultReuseIdentifier)") } cell.viewModel.model = item return cell } }
mit
e68fb95542d0eb8ead34909344afef07
35.338235
142
0.694051
5.180294
false
false
false
false
IvanVorobei/RequestPermission
Example/SPPermission/SPPermission/Frameworks/SparrowKit/UI/Buttons/SPPlayCircleButton.swift
1
2489
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([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 class SPPlayCircleButton: UIButton { var audioState: AudioState = AudioState.play { didSet { switch self.audioState { case .play: self.iconView.type = .play break case .pause: self.iconView.type = .pause break case .stop: self.iconView.type = .stop break } } } var iconColor = SPNativeColors.white { didSet { self.iconView.color = self.iconColor } } let iconView = SPAudioIconView.init() init() { super.init(frame: CGRect.zero) self.addSubview(self.iconView) self.iconView.isUserInteractionEnabled = false self.setTitle("", for: .normal) self.backgroundColor = SPNativeColors.blue self.audioState = .play } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() self.iconView.setBounds(self, withWidthFactor: 0.45, withHeightFactor: 0.45, withCentering: true) self.round() } enum AudioState { case play case pause case stop } }
mit
1f35a5c323791d777d0a1cc2a9d8e315
32.173333
105
0.643891
4.703214
false
false
false
false
lucas34/SwiftQueue
Sources/SwiftQueue/Constraint+Repeat.swift
1
4880
// The MIT License (MIT) // // Copyright (c) 2022 Lucas Nelaupe // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation internal final class RepeatConstraint: SimpleConstraint, CodableConstraint { /// Number of run maximum internal let maxRun: Limit /// Time between each repetition of the job internal let interval: TimeInterval /// Executor to run job in foreground or background internal let executor: Executor /// Current number of run private var runCount: Double = 0 required init(maxRun: Limit, interval: TimeInterval, executor: Executor) { self.maxRun = maxRun self.interval = interval self.executor = executor } convenience init?(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: RepeatConstraintKey.self) if container.contains(.maxRun) && container.contains(.interval) && container.contains(.executor) { try self.init( maxRun: container.decode(Limit.self, forKey: .maxRun), interval: container.decode(TimeInterval.self, forKey: .interval), executor: container.decode(Executor.self, forKey: .executor) ) } else { return nil } } override func run(operation: SqOperation) -> Bool { switch executor { case .background: return false case .foreground: return true case.any: return true } } func completionSuccess(sqOperation: SqOperation) { if case .limited(let limit) = maxRun { // Reached run limit guard runCount + 1 < limit else { sqOperation.onTerminate() return } } guard interval > 0 else { // Run immediately runCount += 1 sqOperation.run() return } // Schedule run after interval sqOperation.nextRunSchedule = Date().addingTimeInterval(interval) sqOperation.dispatchQueue.runAfter(interval, callback: { [weak self, weak sqOperation] in self?.runCount += 1 sqOperation?.run() }) } private enum RepeatConstraintKey: String, CodingKey { case maxRun case interval case executor } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: RepeatConstraintKey.self) try container.encode(maxRun, forKey: .maxRun) try container.encode(interval, forKey: .interval) try container.encode(executor, forKey: .executor) } } /// Enum to specify background and foreground restriction public enum Executor: Int { /// Job will only run only when the app is in foreground case foreground = 0 /// Job will only run only when the app is in background case background = 1 /// Job can run in both background and foreground case any = 2 } internal extension Executor { static func fromRawValue(value: Int) -> Executor { assert(value == 0 || value == 1 || value == 2) switch value { case 1: return Executor.background case 2: return Executor.any default: return Executor.foreground } } } extension Executor: Codable { private enum CodingKeys: String, CodingKey { case value } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let value = try values.decode(Int.self, forKey: .value) self = Executor.fromRawValue(value: value) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.rawValue, forKey: .value) } }
mit
e77ba1452da42fbed3912127984eb40b
31.317881
106
0.648975
4.737864
false
false
false
false
mikaelm1/Teach-Me-Fast
Teach Me Fast/CustomView.swift
1
819
// // CustomView.swift // Teach Me Fast // // Created by Mikael Mukhsikaroyan on 6/14/16. // Copyright © 2016 MSquaredmm. All rights reserved. // import Foundation class CustomView: UIView { override init(frame: CGRect) { super.init(frame: frame) setupviews() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { setupviews() } func setupviews() { layer.cornerRadius = 2 layer.shadowColor = UIColor.rgb(157, green: 157, blue: 157, alpha: 0.5).cgColor backgroundColor = UIColor.rgb(245, green: 245, blue: 245, alpha: 1) layer.shadowOpacity = 0.8 layer.shadowRadius = 5.0 layer.shadowOffset = CGSize(width: 0, height: 2) } }
mit
e17a013266fdbf6c07485ca5b40ed9d1
22.371429
87
0.601467
3.840376
false
false
false
false
apple/swift-argument-parser
Sources/ArgumentParser/Parsable Types/AsyncParsableCommand.swift
1
2538
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2020 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 // //===----------------------------------------------------------------------===// /// A type that can be executed asynchronously, as part of a nested tree of /// commands. @available(macOS 10.15, macCatalyst 13, iOS 13, tvOS 13, watchOS 6, *) public protocol AsyncParsableCommand: ParsableCommand { /// The behavior or functionality of this command. /// /// Implement this method in your `ParsableCommand`-conforming type with the /// functionality that this command represents. /// /// This method has a default implementation that prints the help screen for /// this command. mutating func run() async throws } @available(macOS 10.15, macCatalyst 13, iOS 13, tvOS 13, watchOS 6, *) extension AsyncParsableCommand { /// Executes this command, or one of its subcommands, with the program's /// command-line arguments. /// /// Instead of calling this method directly, you can add `@main` to the root /// command for your command-line tool. public static func main() async { do { var command = try parseAsRoot() if var asyncCommand = command as? AsyncParsableCommand { try await asyncCommand.run() } else { try command.run() } } catch { exit(withError: error) } } } /// A type that can designate an `AsyncParsableCommand` as the program's /// entry point. /// /// See the ``AsyncParsableCommand`` documentation for usage information. @available( swift, deprecated: 5.6, message: "Use @main directly on your root `AsyncParsableCommand` type.") public protocol AsyncMainProtocol { associatedtype Command: ParsableCommand } @available(swift, deprecated: 5.6) @available(macOS 10.15, macCatalyst 13, iOS 13, tvOS 13, watchOS 6, *) extension AsyncMainProtocol { /// Executes the designated command type, or one of its subcommands, with /// the program's command-line arguments. public static func main() async { do { var command = try Command.parseAsRoot() if var asyncCommand = command as? AsyncParsableCommand { try await asyncCommand.run() } else { try command.run() } } catch { Command.exit(withError: error) } } }
apache-2.0
736097dff29082358cca5dad9e1d4f6e
32.84
80
0.650906
4.516014
false
false
false
false
TheAppCookbook/MiseEnPlace
Source/Pagination.swift
1
3524
// // TableViewPagination.swift // MiseEnPlace // // Created by PATRICK PERINI on 9/12/15. // Copyright © 2015 pcperini. All rights reserved. // import UIKit import ObjectiveC import UIScrollView_InfiniteScroll public protocol Pageable: NSObjectProtocol { // MARK: Data Handlers func reloadData() // MARK: Infinite Scroll Handlers func addInfiniteScrollWithHandler(handler: ((AnyObject!) -> Void)!) func finishInfiniteScroll() func removeInfiniteScroll() // MARK: View Handlers func addSubview(view: UIView) var subviews: [UIView] { get } } public protocol PageableViewController: NSObjectProtocol { // MARK: Properties var infiniteScrolls: Bool { get set } var refreshes: Bool { get set } var pageableView: Pageable? { get } // MARK: Responders func refreshControlWasTriggered(sender: UIRefreshControl!) // MARK: Data Handlers func reloadData(byMerging: Bool, completion: () -> Void) func appendNextPage(completion: () -> Void) } public extension PageableViewController { // MARK: Properties var infiniteScrolls: Bool { get { return objc_getAssociatedObject(self, "InfiniteScrolls") as? Bool ?? false } set { objc_setAssociatedObject(self, "InfiniteScrolls", newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) if newValue { self.pageableView?.addInfiniteScrollWithHandler { (_) in self.appendNextPage { self.pageableView?.finishInfiniteScroll() } } } else { self.pageableView?.removeInfiniteScroll() } } } public var refreshes: Bool { get { return objc_getAssociatedObject(self, "Refreshes") as? Bool ?? false } set { objc_setAssociatedObject(self, "Refreshes", newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN) if newValue { let refreshControl = UIRefreshControl() refreshControl.addTarget(self, action: "refreshControlWasTriggered:", forControlEvents: .ValueChanged) self.pageableView?.addSubview(refreshControl) } else { let refreshControls = self.pageableView?.subviews.filter { $0.isKindOfClass(UIRefreshControl.self) } refreshControls?.forEach { $0.removeFromSuperview() } } } } // MARK: Responders func refreshControlWasTriggered(sender: UIRefreshControl!) { self.reloadData { sender.endRefreshing() } } // MARK: Data Handlers func reloadData(byMerging: Bool = true, completion: () -> Void = {}) { self.pageableView?.reloadData() completion() } func appendNextPage(completion: () -> Void = {}) { self.pageableView?.reloadData() completion() } } // MARK: Table Views extension UITableView: Pageable {} extension UITableViewController: PageableViewController { public var pageableView: Pageable? { return self.tableView } } // MARK: Collection Views extension UICollectionView: Pageable {} extension UICollectionViewController: PageableViewController { public var pageableView: Pageable? { return self.collectionView } }
mit
dc84eb05488ad9be3c0a7b92df190233
28.613445
116
0.603179
5.329803
false
false
false
false
tom-wolters/TWLocalize
TWLocalize/Logger.swift
1
1952
// // Logger.swift // SwiftStarterProject // // Created by Tom Wolters on 31-05-17. // Copyright © 2017 9to5. All rights reserved. // import Foundation public enum LogOption { case error(String?) case warning(String?) case print(String?) case todo(String?) } public class Logger { class func log(_ option:LogOption, file:String = #file, function:StaticString = #function, line:UInt = #line) { var fileName = file.components(separatedBy: "/").last! fileName = fileName.replacingOccurrences(of: ".swift", with: "") var message:String = "" message += symbol(for: option) message += "\(dateString(from: Date())): " message += "\(fileName).\(function) logged " switch option { case .error: message += "a error " case .warning: message += "a warning " case .print: message += "a print " case .todo: message += "a TODO " } message += "at line \(line)" switch option { case .error(let error): if let error = error { message += ":: ** \(error) **" } case .warning(let warning): if let warning = warning { message += ":: \(warning)" } case .print(let print): if let print = print { message += ":: \(print)" } case .todo(let todo): if let todo = todo { message += ":: \(todo)" } } message += " \(symbol(for: option))" print(message) } fileprivate class func dateString(from date:Date) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "H:mm:ss" return dateFormatter.string(from: date) } fileprivate class func symbol(for option:LogOption) -> String { switch option { case .error: return "❌ " case .warning: return "⚠️ " case .print: return "➡ " case .todo: return "🔜 " } } }
mit
c81a86ff863a36cc353c4854c26e9fb0
29.793651
115
0.552062
4.217391
false
false
false
false
skylib/SnapImagePicker
SnapImagePicker/SnapImagePickerTransition.swift
1
3132
import Foundation import UIKit class VerticalSlideTransitionManager : NSObject, UIViewControllerAnimatedTransitioning { let animationDuration = 0.3 let action: Action enum Action { case push case pop } init(action: Action) { self.action = action } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return animationDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if action == .push { push(transitionContext) } else { pop(transitionContext) } } func push(_ transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView if let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) { containerView.addSubview(toView) let size = containerView.bounds.size let initalFrame = CGRect(x: CGFloat(0.0), y: -size.height, width: size.width, height: size.height) let finalFrame = containerView.bounds toView.frame = initalFrame UIView.animate(withDuration: animationDuration, animations: { toView.frame = finalFrame }, completion: { _ in transitionContext.completeTransition(true) }) } } func pop(_ transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView if let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from), let toView = transitionContext.view(forKey: UITransitionContextViewKey.to) { let size = containerView.bounds.size let finalFrame = CGRect(x: CGFloat(0.0), y: -size.height, width: size.width, height: size.height) toView.frame = CGRect(x: CGFloat(0.0), y: 0, width: size.width, height: size.height) containerView.addSubview(toView) containerView.sendSubview(toBack: toView) UIView.animate(withDuration: animationDuration, animations: {fromView.frame = finalFrame}, completion: { _ in transitionContext.completeTransition(true)}) } } } open class SnapImagePickerNavigationControllerDelegate: NSObject, UINavigationControllerDelegate, UIViewControllerTransitioningDelegate { public override init() { super.init() } open func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { switch operation { case .none: return nil case .push: return VerticalSlideTransitionManager(action: .push) case .pop: return VerticalSlideTransitionManager(action: .pop) } } }
bsd-3-clause
ae5147d366336f1b4766bf06f146b1e9
40.76
251
0.648787
6.046332
false
false
false
false
jmgc/swift
test/SPI/spi_client.swift
1
2904
/// Check an SPI import of an SPI library to detect correct SPI access // RUN: %empty-directory(%t) // /// Compile the SPI lib // RUN: %target-swift-frontend -enable-experimental-prespecialization -emit-module %S/Inputs/spi_helper.swift -module-name SPIHelper -emit-module-path %t/SPIHelper.swiftmodule -emit-module-interface-path %t/SPIHelper.swiftinterface -emit-private-module-interface-path %t/SPIHelper.private.swiftinterface -enable-library-evolution -swift-version 5 -parse-as-library /// Reading from swiftmodule // RUN: %target-typecheck-verify-swift -enable-experimental-prespecialization -I %t -verify-ignore-unknown /// Reading from .private.swiftinterface // RUN: rm %t/SPIHelper.swiftmodule // RUN: %target-typecheck-verify-swift -enable-experimental-prespecialization -I %t -verify-ignore-unknown //// Reading from .swiftinterface should fail as it won't find the decls // RUN: rm %t/SPIHelper.private.swiftinterface // RUN: not %target-swift-frontend -enable-experimental-prespecialization -typecheck -I %t @_spi(HelperSPI) import SPIHelper // Use as SPI publicFunc() spiFunc() internalFunc() // expected-error {{cannot find 'internalFunc' in scope}} let c = SPIClass() c.spiMethod() c.spiVar = "write" print(c.spiVar) let s = SPIStruct() s.spiMethod() s.spiInherit() s.spiDontInherit() // expected-error {{'spiDontInherit' is inaccessible due to '@_spi' protection level}} s.spiExtensionHidden() s.spiExtension() s.spiExtensionInherited() s.spiVar = "write" print(s.spiVar) SPIEnum().spiMethod() SPIEnum.A.spiMethod() var ps = PublicStruct() let _ = PublicStruct(alt_init: 1) ps.spiMethod() ps.spiVar = "write" print(ps.spiVar) otherApiFunc() // expected-error {{cannot find 'otherApiFunc' in scope}} public func publicUseOfSPI(param: SPIClass) -> SPIClass {} // expected-error 2{{cannot use class 'SPIClass' here; it is an SPI imported from 'SPIHelper'}} public func publicUseOfSPI2() -> [SPIClass] {} // expected-error {{cannot use class 'SPIClass' here; it is an SPI imported from 'SPIHelper'}} @inlinable public func inlinable1() -> SPIClass { // expected-error {{class 'SPIClass' cannot be used in an '@inlinable' function because it is an SPI imported from 'SPIHelper'}} spiFunc() // expected-error {{global function 'spiFunc()' cannot be used in an '@inlinable' function because it is an SPI imported from 'SPIHelper'}} _ = SPIClass() // expected-error {{class 'SPIClass' cannot be used in an '@inlinable' function because it is an SPI imported from 'SPIHelper'}} // expected-error@-1 {{initializer 'init()' cannot be used in an '@inlinable' function because it is an SPI imported from 'SPIHelper'}} _ = [SPIClass]() // expected-error {{class 'SPIClass' cannot be used in an '@inlinable' function because it is an SPI imported from 'SPIHelper'}} } @_spi(S) @inlinable public func inlinable2() -> SPIClass { spiFunc() _ = SPIClass() _ = [SPIClass]() }
apache-2.0
c7e27b2a8454a93519cd635a510f0d2e
41.086957
364
0.736226
3.732648
false
false
false
false
WangWenzhuang/ZKSegment
Demo/Demo/ViewController.swift
1
4057
// // ViewController.swift // Demo // // Created by 王文壮 on 2018/3/22. // Copyright © 2018年 王文壮. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.view.addSubview({ let segment = ZKSegment.segmentLine( frame: CGRect(x: 0, y: 50, width: self.view.frame.size.width, height: 45), itemColor: UIColor(red: 102.0 / 255.0, green: 102.0 / 255.0, blue: 102.0 / 255.0, alpha: 1), itemSelectedColor: UIColor(red: 202.0 / 255.0, green: 51.0 / 255.0, blue: 54.0 / 255.0, alpha: 1), itemFont: UIFont.systemFont(ofSize: 14), itemMargin: 20, items: ["菜单一", "菜单二", "菜单三", "菜单四", "菜单五", "菜单六", "菜单七", "菜单八"], change: { (index, item) in print("segmentLine change index:\(index)") }) segment.backgroundColor = UIColor(red: 238.0 / 255.0, green: 238.0 / 255.0, blue: 238.0 / 255.0, alpha: 1) return segment }()) self.view.addSubview({ let segment = ZKSegment.segmentRectangle( frame: CGRect(x: 0, y: 115, width: self.view.frame.size.width, height: 45), itemColor: UIColor(red: 102.0 / 255.0, green: 102.0 / 255.0, blue: 102.0 / 255.0, alpha: 1), itemSelectedColor: .white, itemStyleSelectedColor: UIColor(red: 202.0 / 255.0, green: 51.0 / 255.0, blue: 54.0 / 255.0, alpha: 1), itemFont: nil, itemMargin: 10, items: ["菜单一", "菜单二", "菜单三", "菜单四", "菜单五", "菜单六", "菜单七", "菜单八"], change: { (index, item) in print("segmentRectangle change index:\(index)") }) segment.backgroundColor = UIColor(red: 238.0 / 255.0, green: 238.0 / 255.0, blue: 238.0 / 255.0, alpha: 1) return segment }()) self.view.addSubview({ let segment = ZKSegment.segmentText( frame: CGRect(x: 0, y: 180, width: self.view.frame.size.width, height: 45), itemColor: UIColor(red: 102.0 / 255.0, green: 102.0 / 255.0, blue: 102.0 / 255.0, alpha: 1), itemSelectedColor: UIColor(red: 202.0 / 255.0, green: 51.0 / 255.0, blue: 54.0 / 255.0, alpha: 1), itemFont: nil, itemMargin: 20, items: ["菜单一", "菜单二", "菜单三", "菜单四", "菜单五", "菜单六", "菜单七", "菜单八"], change: { (index, item) in print("segmentText change index:\(index)") }) segment.backgroundColor = UIColor(red: 238.0 / 255.0, green: 238.0 / 255.0, blue: 238.0 / 255.0, alpha: 1) return segment }()) self.view.addSubview({ let segment = ZKSegment.segmentDot( frame: CGRect(x: 0, y: 245, width: self.view.frame.size.width, height: 45), itemColor: UIColor(red: 102.0 / 255.0, green: 102.0 / 255.0, blue: 102.0 / 255.0, alpha: 1), itemSelectedColor: UIColor(red: 202.0 / 255.0, green: 51.0 / 255.0, blue: 54.0 / 255.0, alpha: 1), itemFont: UIFont.systemFont(ofSize: 14), itemMargin: 20, items: ["菜单一", "菜单二", "菜单三", "菜单四", "菜单五", "菜单六", "菜单七", "菜单八"], change: { (index, item) in print("segmentLine change index:\(index)") }) segment.backgroundColor = UIColor(red: 238.0 / 255.0, green: 238.0 / 255.0, blue: 238.0 / 255.0, alpha: 1) return segment }()) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
93115a16c5b67d5d96dd27f0974ab661
44.294118
119
0.511688
3.571429
false
false
false
false
quadro5/swift3_L
Swift_api.playground/Pages/Singleton.xcplaygroundpage/Contents.swift
1
316
//: [Previous](@previous) import Foundation var str = "Hello, playground" //: [Next](@next) class SingletionClass { private init() { } static let shared = SingletionClass() } let hehe = SingletionClass.shared let haha = SingletionClass.shared if hehe === haha { print("Is the same instance") }
unlicense
41e7c57056ccfc3b0b44b730ccd7a493
12.73913
41
0.664557
3.397849
false
false
false
false
SwiftGen/SwiftGen
Sources/SwiftGenKit/Parsers/InterfaceBuilder/InterfaceBuilderParser.swift
1
1948
// // SwiftGenKit // Copyright © 2022 SwiftGen // MIT Licence // import Foundation import Kanna import PathKit public enum InterfaceBuilder { public enum ParserError: Error, CustomStringConvertible { case invalidFile(path: Path, reason: String) case unsupportedTargetRuntime(target: String) public var description: String { switch self { case .invalidFile(let path, let reason): return "error: Unable to parse file at \(path). \(reason)" case .unsupportedTargetRuntime(let target): return "Unsupported target runtime `\(target)`." } } } public final class Parser: SwiftGenKit.Parser { private let options: ParserOptionValues var storyboards = [Storyboard]() public var warningHandler: Parser.MessageHandler? public init(options: [String: Any] = [:], warningHandler: Parser.MessageHandler? = nil) throws { self.options = try ParserOptionValues(options: options, available: Self.allOptions) self.warningHandler = warningHandler } public static let defaultFilter = filterRegex(forExtensions: ["storyboard"]) public func parse(path: Path, relativeTo parent: Path) throws { try addStoryboard(at: path) } func addStoryboard(at path: Path) throws { do { let document = try Kanna.XML(xml: path.read(), encoding: .utf8) let name = path.lastComponentWithoutExtension let storyboard = try Storyboard(with: document, name: name) storyboards += [storyboard] } catch let error { throw ParserError.invalidFile(path: path, reason: "XML parser error: \(error).") } } var modules: Set<String> { Set<String>(storyboards.flatMap { $0.modules }) } var platform: String? { let platforms = Set<String>(storyboards.map { $0.platform.name }) if platforms.count > 1 { return nil } else { return platforms.first } } } }
mit
88de6202135914cfe670acec0c8438c5
27.632353
100
0.65999
4.475862
false
false
false
false
SwiftGen/SwiftGen
Sources/SwiftGenKit/Parsers/Strings/StringsDictEntry.swift
1
7963
// // SwiftGenKit // Copyright © 2022 SwiftGen // MIT Licence // import Foundation import PathKit /// This enum represents the types of entries a `.stringsdict` file can contain. enum StringsDict { case pluralEntry(PluralEntry) case variableWidthEntry(VariableWidthEntry) } extension StringsDict { /// Plural entries are used to define language plural rules. /// /// Reference: https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPInternational/StringsdictFileFormat/StringsdictFileFormat.html // swiftlint:disable:previous line_length struct PluralEntry: Codable { /// A format string that contains variables. /// Each variable is preceded by the %#@ characters and followed by the @ character. let formatKey: String /// An array of variables specifying the rules to use for each variable in the `formatKey`. /// Every variable that is part of the `formatKey` must be contained in this dictionary. let variables: [Variable] } /// Variable width entries are used to define width variations for a localized string. /// /// Reference: https://developer.apple.com/documentation/foundation/nsstring/1413104-variantfittingpresentationwidth /// /// Note: SwiftGen doesn't yet support parsing those VariableWidth entries struct VariableWidthEntry: Codable { let rules: [String: String] } } extension StringsDict.PluralEntry { /// `Variable`s are a key-value pair specifying the rule to use for each variable (name). struct Variable: Codable { let name: String let rule: VariableRule } /// A VariableRule contains the actual localized plural strings for every possible plural case that /// is available in a specific locale. Since some locales only support a subset of plural forms, /// most of them are optional. struct VariableRule: Codable { /// The only possible value is `NSStringPluralRuleType`. let specTypeKey: String /// A string format specifier for a number, but without the `%` prefix; as in `d` for an integer. let valueTypeKey: String let zero: String? let one: String? let two: String? let few: String? let many: String? let other: String private enum CodingKeys: String, CodingKey { case specTypeKey = "NSStringFormatSpecTypeKey" case valueTypeKey = "NSStringFormatValueTypeKey" case zero, one, two, few, many, other } } } // - MARK: Decodable conformance extension StringsDict: Decodable { // Custom CodingKeys struct to be able to parse dictionaries with dynamic keys. // This is necessary, because each variable used in the formatKey is used as the key // to another dictionary containing the rules for that variable. private struct CodingKeys: CodingKey { var intValue: Int? var stringValue: String init?(intValue: Int) { self.intValue = intValue self.stringValue = "\(intValue)" } init?(stringValue: String) { self.stringValue = stringValue } init(key: String) { self.stringValue = key } // fixed keys static let formatKey = CodingKeys(key: "NSStringLocalizedFormatKey") static let variableWidthRules = CodingKeys(key: "NSStringVariableWidthRuleType") } init(from coder: Decoder) throws { let container = try coder.container(keyedBy: CodingKeys.self) let formatKey = try container.decodeIfPresent(String.self, forKey: .formatKey) let variableWidthRules = try container.decodeIfPresent([String: String].self, forKey: .variableWidthRules) // We either have a formatKey OR we have a variableWidthRule. switch (formatKey, variableWidthRules) { case (.none, .none), (.some, .some): let entry = coder.codingPath.last?.stringValue ?? "<unknown>" throw Strings.ParserError.invalidFormat( reason: """ Entry "\(entry)" expects either "\(CodingKeys.formatKey.stringValue)" or \ "\(CodingKeys.variableWidthRules.stringValue)" but got either neither or both """ ) case let (.some(formatKey), .none): let variableNames = StringsDict.variableNames(fromFormatKey: formatKey).map(\.name) let variables = try variableNames.reduce(into: [PluralEntry.Variable]()) { variables, variableName in let variableRule = try container.decode(PluralEntry.VariableRule.self, forKey: CodingKeys(key: variableName)) // Combination of the format specifiers of the `PlaceholderType.float` and `PlaceholderType.int`. guard ["a", "e", "f", "g", "d", "i", "o", "u", "x"].contains(variableRule.valueTypeKey.suffix(1)) else { throw Strings.ParserError.invalidVariableRuleValueType( variableName: variableName, valueType: variableRule.valueTypeKey ) } variables.append(PluralEntry.Variable(name: variableName, rule: variableRule)) } self = .pluralEntry(PluralEntry(formatKey: formatKey, variables: variables)) case let (.none, .some(variableWidthRules)): self = .variableWidthEntry(VariableWidthEntry(rules: variableWidthRules)) } } } // - MARK: Helpers extension StringsDict { typealias VariableNameResult = (name: String, range: NSRange, positionalArgument: Int?) /// Parses variable names and their ranges from a `NSStringLocalizedFormatKey`. /// Every variable name that is contained within the format key is preceded /// by the %#@ characters or by the positional variants, e.g. %1$#@, and followed by the @ character. /// /// - Parameter formatKey: The formatKey from which the variable names should be parsed. /// - Returns: An array of discovered variable names, their range within the `formatKey` and the positional argument. private static func variableNames(fromFormatKey formatKey: String) -> [VariableNameResult] { let pattern = #"%(?>(\d+)\$)?#@([\w\.\p{Pd}]+)@"# guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else { fatalError("Unable to compile regular expression when parsing StringsDict entries") } let nsrange = NSRange(formatKey.startIndex..<formatKey.endIndex, in: formatKey) let matches = regex.matches(in: formatKey, options: [], range: nsrange) return matches.lazy.compactMap { match -> VariableNameResult? in // the whole format string including delimeters let fullMatchNSRange = match.range(at: 0) // 1st capture group is the positional argument of the format string (Optional!) let positionalArgumentNSRange = match.range(at: 1) let positionalArgumentRange = Range(positionalArgumentNSRange, in: formatKey) // 2nd capture group is the name of the variable, the string in between the delimeters let nameNSRange = match.range(at: 2) guard let nameRange = Range(nameNSRange, in: formatKey) else { return nil } let position = positionalArgumentRange.flatMap { Int(formatKey[$0]) } return (String(formatKey[nameRange]), fullMatchNSRange, position) } } } extension StringsDict.PluralEntry { /// Extract the placeholders (`NSStringFormatValueTypeKey`) from the different variable /// definitions into a single flattened list of placeholders var formatKeyWithVariableValueTypes: String { var result = formatKey var offset = 0 for (name, var nsrange, positionalArgument) in StringsDict.variableNames(fromFormatKey: formatKey) { guard let variable = variables.first(where: { $0.name == name }) else { continue } let variablePlaceholder: String if let positionalArgument = positionalArgument { variablePlaceholder = "%\(positionalArgument)$\(variable.rule.valueTypeKey)" } else { variablePlaceholder = "%\(variable.rule.valueTypeKey)" } nsrange.location += offset guard let range = Range(nsrange, in: result) else { continue } result.replaceSubrange(range, with: variablePlaceholder) offset += variablePlaceholder.count - nsrange.length } return result } }
mit
6ec266be8453b7d4b3bf5eabc82e0fa0
40.46875
157
0.708365
4.478065
false
false
false
false
eppeo/FYSliderView
Example/FYBannerView/AppDelegate.swift
2
2357
// // AppDelegate.swift // FYBannerView // // Created by eppeo on 01/22/2018. // Copyright (c) 2018 eppeo. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let vc = CarouselNewViewController() vc.title = "FYBannerView" let nav = UINavigationController(rootViewController: vc) window?.rootViewController = nav window?.makeKeyAndVisible() window?.backgroundColor = .white return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
07159066d5ad6acd10c85d5866bafe45
46.14
285
0.742045
5.545882
false
false
false
false
perrychen901105/ObjectMapper
ObjectMapperTests/NestedKeysTests.swift
4
6193
// // NestedKeysTests.swift // ObjectMapper // // Created by Syo Ikeda on 3/10/15. // Copyright (c) 2015 hearst. All rights reserved. // import Foundation import XCTest import ObjectMapper import Nimble class NestedKeysTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testNestedKeys() { let JSON: [String: AnyObject] = [ "nested": [ "int64": NSNumber(longLong: INT64_MAX), "bool": true, "int": 255, "double": 100.0 as Double, "float": 50.0 as Float, "string": "String!", "nested": [ "int64Array": [NSNumber(longLong: INT64_MAX), NSNumber(longLong: INT64_MAX - 1), NSNumber(longLong: INT64_MAX - 10)], "boolArray": [false, true, false], "intArray": [1, 2, 3], "doubleArray": [1.0, 2.0, 3.0], "floatArray": [1.0 as Float, 2.0 as Float, 3.0 as Float], "stringArray": ["123", "ABC"], "int64Dict": ["1": NSNumber(longLong: INT64_MAX)], "boolDict": ["2": true], "intDict": ["3": 999], "doubleDict": ["4": 999.999], "floatDict": ["5": 123.456 as Float], "stringDict": ["6": "InDict"], "int64Enum": 1000, "intEnum": 255, "doubleEnum": 100.0, "floatEnum": 100.0, "stringEnum": "String B", "nested": [ "object": ["value": 987], "objectArray": [ ["value": 123], ["value": 456] ], "objectDict": ["key": ["value": 999]] ] ] ] ] let mapper = Mapper<NestedKeys>() let value: NestedKeys! = mapper.map(JSON) expect(value).notTo(beNil()) let JSONFromValue = mapper.toJSON(value) let valueFromParsedJSON: NestedKeys! = mapper.map(JSONFromValue) expect(valueFromParsedJSON).notTo(beNil()) expect(value.int64).to(equal(valueFromParsedJSON.int64)) expect(value.bool).to(equal(valueFromParsedJSON.bool)) expect(value.int).to(equal(valueFromParsedJSON.int)) expect(value.double).to(equal(valueFromParsedJSON.double)) expect(value.float).to(equal(valueFromParsedJSON.float)) expect(value.string).to(equal(valueFromParsedJSON.string)) expect(value.int64Array).to(equal(valueFromParsedJSON.int64Array)) expect(value.boolArray).to(equal(valueFromParsedJSON.boolArray)) expect(value.intArray).to(equal(valueFromParsedJSON.intArray)) expect(value.doubleArray).to(equal(valueFromParsedJSON.doubleArray)) expect(value.floatArray).to(equal(valueFromParsedJSON.floatArray)) expect(value.stringArray).to(equal(valueFromParsedJSON.stringArray)) expect(value.int64Dict).to(equal(valueFromParsedJSON.int64Dict)) expect(value.boolDict).to(equal(valueFromParsedJSON.boolDict)) expect(value.intDict).to(equal(valueFromParsedJSON.intDict)) expect(value.doubleDict).to(equal(valueFromParsedJSON.doubleDict)) expect(value.floatDict).to(equal(valueFromParsedJSON.floatDict)) expect(value.stringDict).to(equal(valueFromParsedJSON.stringDict)) expect(value.int64Enum).to(equal(valueFromParsedJSON.int64Enum)) expect(value.intEnum).to(equal(valueFromParsedJSON.intEnum)) expect(value.doubleEnum).to(equal(valueFromParsedJSON.doubleEnum)) expect(value.floatEnum).to(equal(valueFromParsedJSON.floatEnum)) expect(value.stringEnum).to(equal(valueFromParsedJSON.stringEnum)) expect(value.object).to(equal(valueFromParsedJSON.object)) expect(value.objectArray).to(equal(valueFromParsedJSON.objectArray)) expect(value.objectDict).to(equal(valueFromParsedJSON.objectDict)) } } class NestedKeys: Mappable { var int64: NSNumber? var bool: Bool? var int: Int? var double: Double? var float: Float? var string: String? var int64Array: [NSNumber] = [] var boolArray: [Bool] = [] var intArray: [Int] = [] var doubleArray: [Double] = [] var floatArray: [Float] = [] var stringArray: [String] = [] var int64Dict: [String: NSNumber] = [:] var boolDict: [String: Bool] = [:] var intDict: [String: Int] = [:] var doubleDict: [String: Double] = [:] var floatDict: [String: Float] = [:] var stringDict: [String: String] = [:] var int64Enum: Int64Enum? var intEnum: IntEnum? var doubleEnum: DoubleEnum? var floatEnum: FloatEnum? var stringEnum: StringEnum? var object: Object? var objectArray: [Object] = [] var objectDict: [String: Object] = [:] required init?(_ map: Map) { mapping(map) } func mapping(map: Map) { int64 <- map["nested.int64"] bool <- map["nested.bool"] int <- map["nested.int"] double <- map["nested.double"] float <- map["nested.float"] string <- map["nested.string"] int64Array <- map["nested.nested.int64Array"] boolArray <- map["nested.nested.boolArray"] intArray <- map["nested.nested.intArray"] doubleArray <- map["nested.nested.doubleArray"] floatArray <- map["nested.nested.floatArray"] stringArray <- map["nested.nested.stringArray"] int64Dict <- map["nested.nested.int64Dict"] boolDict <- map["nested.nested.boolDict"] intDict <- map["nested.nested.intDict"] doubleDict <- map["nested.nested.doubleDict"] floatDict <- map["nested.nested.floatDict"] stringDict <- map["nested.nested.stringDict"] int64Enum <- map["nested.nested.int64Enum"] intEnum <- map["nested.nested.intEnum"] doubleEnum <- map["nested.nested.doubleEnum"] floatEnum <- map["nested.nested.floatEnum"] stringEnum <- map["nested.nested.stringEnum"] object <- map["nested.nested.nested.object"] objectArray <- map["nested.nested.nested.objectArray"] objectDict <- map["nested.nested.nested.objectDict"] } } class Object: Mappable, Equatable { var value: Int = Int.min required init?(_ map: Map) { mapping(map) } func mapping(map: Map) { value <- map["value"] } } func == (lhs: Object, rhs: Object) -> Bool { return lhs.value == rhs.value } enum Int64Enum: NSNumber { case A = 0 case B = 1000 } enum IntEnum: Int { case A = 0 case B = 255 } enum DoubleEnum: Double { case A = 0.0 case B = 100.0 } enum FloatEnum: Float { case A = 0.0 case B = 100.0 } enum StringEnum: String { case A = "String A" case B = "String B" }
mit
7f736c97f44c2facb68ff366addbf3e9
27.408257
122
0.687066
3.179158
false
false
false
false
aleffert/dials
Desktop/Source/ViewsViewController.swift
1
5215
// // ViewsViewController.swift // Dials-Desktop // // Created by Akiva Leffert on 4/2/15. // // import Cocoa protocol ViewsViewControllerDelegate : class { func viewsController(_ controller : ViewsViewController, selectedViewWithID viewID : String?) func viewsController(_ controller : ViewsViewController, valueChangedWithRecord record : DLSChangeViewValueRecord) func viewController(_ controller : ViewsViewController, appliedInsets : EdgeInsets, toViewWithID viewID : String) } class ViewsViewController: NSViewController, ViewHierarchyOutlineControllerDelegate, ViewPropertyTableControllerDelegate, ViewsVisualOutlineControllerDelegate, ConstraintInfoOwner { weak var delegate : ViewsViewControllerDelegate? weak var constraintInfoSource : ConstraintInfoSource? @IBOutlet var propertyTableController : ViewPropertyTableController! @IBOutlet var hierarchyOutlineController : ViewsHierarchyOutlineController! @IBOutlet var visualOutlineController : ViewsVisualOutlineController! override func viewDidLoad() { super.viewDidLoad() hierarchyOutlineController.delegate = self propertyTableController.delegate = self visualOutlineController.delegate = self visualOutlineController.hierarchy = hierarchyOutlineController.hierarchy propertyTableController.hierarchy = hierarchyOutlineController.hierarchy } func receivedHierarchy(_ hierarchy : [String : DLSViewHierarchyRecord], roots : [String], screenSize : CGSize) { hierarchyOutlineController.useHierarchy(hierarchy, roots : roots) visualOutlineController.updateViews() visualOutlineController.screenSize = screenSize } func receivedViewRecord(_ record : DLSViewRecord) { propertyTableController?.useRecord(record) } func receivedUpdatedViews(_ records : [DLSViewHierarchyRecord], roots : [String], screenSize : CGSize) { hierarchyOutlineController.takeUpdateRecords(records, roots : roots) if !hierarchyOutlineController.hasSelection { propertyTableController.clear() } visualOutlineController.updateViews() visualOutlineController.screenSize = screenSize } func receivedContents(_ contents : [String:Data], empties:[String]) { visualOutlineController.takeContents(contents, empties : empties) } func outlineController(_ controller: ViewsHierarchyOutlineController, selectedViewWithID viewID: String?) { delegate?.viewsController(self, selectedViewWithID: viewID) visualOutlineController.selectViewWithID(viewID) } func visualOutlineController(_ controller: ViewsVisualOutlineController, selectedViewWithID viewID: String?) { hierarchyOutlineController.selectViewWithID(viewID) } func visualOutlineController(_ controller: ViewsVisualOutlineController, appliedInsets insets: EdgeInsets, toViewWithID viewID: String) { delegate?.viewController(self, appliedInsets: insets, toViewWithID: viewID) } func tableController(_ controller: ViewPropertyTableController, valueChangedWithRecord record : DLSChangeViewValueRecord) { delegate?.viewsController(self, valueChangedWithRecord: record) } func tableController(_ controller: ViewPropertyTableController, highlightViewWithID viewID: String) { visualOutlineController.highlightViewWithID(viewID) } func tableController(_ controller: ViewPropertyTableController, clearHighlightForViewWithID viewID: String) { visualOutlineController.unhighlightViewWithID(viewID) } func tableController(_ controller: ViewPropertyTableController, selectViewWithID viewID: String) { visualOutlineController.highlightViewWithID(nil) hierarchyOutlineController.selectViewWithID(viewID) delegate?.viewsController(self, selectedViewWithID: viewID) } func tableController(_ controller: ViewPropertyTableController, nameOfConstraintWithInfo info: DLSAuxiliaryConstraintInformation) -> String? { guard let plugin = self.constraintInfoSource?.constraintSources.filter({$0.identifier == info.pluginIdentifier }).first else { print("Plugin not found: \(info.pluginIdentifier)") return nil } return plugin.displayName(ofConstraint: info) } func tableController(_ controller: ViewPropertyTableController, saveConstraintWithInfo info: DLSAuxiliaryConstraintInformation, constant: CGFloat) { guard let plugin = self.constraintInfoSource?.constraintSources.filter({$0.identifier == info.pluginIdentifier }).first else { showSaveError("Plugin not found: " + info.pluginIdentifier) return } do { try plugin.saveConstraint(info, constant: constant) } catch let e as NSError { showSaveError(e.localizedDescription) } } func showSaveError(_ message : String) { let alert = NSAlert() alert.messageText = "Error Updating Code" alert.informativeText = message alert.addButton(withTitle: "Okay") alert.runModal() } }
mit
ffe7983aa53142b40c8c346ad81061ff
42.099174
152
0.733653
5.241206
false
false
false
false
salesawagner/WASKit
Sources/Extensions/Enum/WASCountable.swift
1
1855
// // WASKit // // Copyright (c) Wagner Sales (http://wagnersales.com.br/) // // 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 /// Protocol to use with enum to provide a count of its cases public protocol WASCountable: Hashable { } public extension WASCountable { /// Get array with all cases static var WASall: [Self] { let sequence = AnySequence { () -> AnyIterator<Self> in var raw = 0 return AnyIterator { let current: Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: Self.self, capacity: 1) { $0.pointee } } guard current.hashValue == raw else { return nil } raw += 1 return current } } return Array(sequence) } /// Count the number of cases in the enum. static var WAScount: Int { return self.WASall.count } }
mit
18a75928303838f2474f1bdae74c6fb0
33.351852
81
0.713208
3.913502
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeCore/AwesomeCore/Classes/NetworkServices/QuestPageNS.swift
1
1867
// // QuestPageNS.swift // AwesomeCore // // Created by Evandro Harrison Hoffmann on 3/5/18. // import Foundation class QuestPageNS: BaseNS { static let shared = QuestPageNS() lazy var requester: AwesomeCoreRequester = AwesomeCoreRequester(cacheType: .realm) override init() {} var lastQuestPageRequest: URLSessionDataTask? func fetchPage(withId id: String, params: AwesomeCoreNetworkServiceParams = .standard, response: @escaping (QuestPage?, ErrorData?) -> Void) { func processResponse(data: Data?, error: ErrorData? = nil, response: @escaping (QuestPage?, ErrorData?) -> Void ) -> Bool { guard let data = data else { response(nil, nil) return false } if let error = error { print("Error fetching from API: \(error.message)") response(nil, error) return false } let page = QuestPageMP.parseQuestPageFrom(data) response(page, nil) return page != nil } let jsonBody = QuestGraphQLModel.querySingleQuestPage(withId: id) let method: URLMethod = .POST let url = ACConstants.shared.questsURL if params.contains(.shouldFetchFromCache) { _ = processResponse(data: dataFromCache(url, method: method, params: params, bodyDict: jsonBody), response: response) } _ = requester.performRequestAuthorized( url, forceUpdate: true, method: method, jsonBody: jsonBody, completion: { (data, error, responseType) in if processResponse(data: data, error: error, response: response) { self.saveToCache(url, method: method, bodyDict: jsonBody, data: data) } }) } }
mit
efe0806c1b88c96a7c2bf93a68f5d312
33.574074
146
0.585967
4.811856
false
false
false
false
paulyoung/Quick
Quick/World.swift
2
7203
import Foundation /** A closure that, when evaluated, returns a dictionary of key-value pairs that can be accessed from within a group of shared examples. */ public typealias SharedExampleContext = () -> (NSDictionary) /** A closure that is used to define a group of shared examples. This closure may contain any number of example and example groups. */ public typealias SharedExampleClosure = (SharedExampleContext) -> () /** A collection of state Quick builds up in order to work its magic. World is primarily responsible for maintaining a mapping of QuickSpec classes to root example groups for those classes. It also maintains a mapping of shared example names to shared example closures. You may configure how Quick behaves by calling the -[World configure:] method from within an overridden +[QuickConfiguration configure:] method. */ final internal class World: NSObject { /** The example group that is currently being run. The DSL requires that this group is correctly set in order to build a correct hierarchy of example groups and their examples. */ internal var currentExampleGroup: ExampleGroup! /** The example metadata of the test that is currently being run. This is useful for using the Quick test metadata (like its name) at runtime. */ internal var currentExampleMetadata: ExampleMetadata? /** A flag that indicates whether additional test suites are being run within this test suite. This is only true within the context of Quick functional tests. */ internal var isRunningAdditionalSuites = false private var specs: Dictionary<String, ExampleGroup> = [:] private var sharedExamples: [String: SharedExampleClosure] = [:] private let configuration = Configuration() private var isConfigurationFinalized = false internal var exampleHooks: ExampleHooks {return configuration.exampleHooks } internal var suiteHooks: SuiteHooks { return configuration.suiteHooks } // MARK: Singleton Constructor private override init() {} static let sharedWorld = World() // MARK: Public Interface /** Exposes the World's Configuration object within the scope of the closure so that it may be configured. This method must not be called outside of an overridden +[QuickConfiguration configure:] method. - parameter closure: A closure that takes a Configuration object that can be mutated to change Quick's behavior. */ internal func configure(closure: QuickConfigurer) { assert(!isConfigurationFinalized, "Quick cannot be configured outside of a +[QuickConfiguration configure:] method. You should not call -[World configure:] directly. Instead, subclass QuickConfiguration and override the +[QuickConfiguration configure:] method.") closure(configuration: configuration) } /** Finalizes the World's configuration. Any subsequent calls to World.configure() will raise. */ internal func finalizeConfiguration() { isConfigurationFinalized = true } /** Returns an internally constructed root example group for the given QuickSpec class. A root example group with the description "root example group" is lazily initialized for each QuickSpec class. This root example group wraps the top level of a -[QuickSpec spec] method--it's thanks to this group that users can define beforeEach and it closures at the top level, like so: override func spec() { // These belong to the root example group beforeEach {} it("is at the top level") {} } - parameter cls: The QuickSpec class for which to retrieve the root example group. - returns: The root example group for the class. */ internal func rootExampleGroupForSpecClass(cls: AnyClass) -> ExampleGroup { let name = NSStringFromClass(cls) if let group = specs[name] { return group } else { let group = ExampleGroup( description: "root example group", flags: [:], isInternalRootExampleGroup: true ) specs[name] = group return group } } /** Returns all examples that should be run for a given spec class. There are two filtering passes that occur when determining which examples should be run. That is, these examples are the ones that are included by inclusion filters, and are not excluded by exclusion filters. - parameter specClass: The QuickSpec subclass for which examples are to be returned. - returns: A list of examples to be run as test invocations. */ @objc(examplesForSpecClass:) internal func examples(specClass: AnyClass) -> [Example] { // 1. Grab all included examples. let included = includedExamples // 2. Grab the intersection of (a) examples for this spec, and (b) included examples. let spec = rootExampleGroupForSpecClass(specClass).examples.filter { included.contains($0) } // 3. Remove all excluded examples. return spec.filter { example in !self.configuration.exclusionFilters.reduce(false) { $0 || $1(example: example) } } } // MARK: Internal internal func registerSharedExample(name: String, closure: SharedExampleClosure) { raiseIfSharedExampleAlreadyRegistered(name) sharedExamples[name] = closure } internal func sharedExample(name: String) -> SharedExampleClosure { raiseIfSharedExampleNotRegistered(name) return sharedExamples[name]! } internal var exampleCount: Int { return allExamples.count } private var allExamples: [Example] { var all: [Example] = [] for (_, group) in specs { group.walkDownExamples { all.append($0) } } return all } private var includedExamples: [Example] { let all = allExamples let included = all.filter { example in return self.configuration.inclusionFilters.reduce(false) { $0 || $1(example: example) } } if included.isEmpty && configuration.runAllWhenEverythingFiltered { return all } else { return included } } private func raiseIfSharedExampleAlreadyRegistered(name: String) { if sharedExamples[name] != nil { NSException(name: NSInternalInconsistencyException, reason: "A shared example named '\(name)' has already been registered.", userInfo: nil).raise() } } private func raiseIfSharedExampleNotRegistered(name: String) { if sharedExamples[name] == nil { NSException(name: NSInternalInconsistencyException, reason: "No shared example named '\(name)' has been registered. Registered shared examples: '\(Array(sharedExamples.keys))'", userInfo: nil).raise() } } }
apache-2.0
ab49d8c941c6b1da428765c4028af1ea
36.515625
243
0.658892
5.265351
false
true
false
false
EdenShapiro/tip-calculator-with-yelp-review
SuperCoolTipCalculator/Constants.swift
1
582
// // Constants.swift // SuperCoolTipCalculator // // Created by Eden on 3/28/17. // Copyright © 2017 Eden Shapiro. All rights reserved. // import Foundation import UIKit struct Constants { static let YelpHost = "https://www.yelp.com" static let YelpBizPath = "/biz" static let consumerKey = "xd-t2iYRRdwUrHw2HwipLw" static let consumerSecret = "px9oATTwDkq5UTmvWzxzavE4itc" static let token = "M1vAa08Og5l0WOWNYo2sNwUGcx_x3Ige" static let tokenSecret = "M1R5bDSa3YERnNHCr2tdGSACKrg" static let yelpAPIBaseURL = "https://api.yelp.com/v2/" }
mit
8ede0ee6b9d16ec32d27e483cc8783dd
25.409091
61
0.717728
2.806763
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Venue
iOS/Venue/View Models/LeaderboardViewModel.swift
1
3731
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /// Handles all users on the leaderboard, there order, and points total class LeaderboardViewModel: NSObject { dynamic var leaders = [User]() var userPoints = [Int : Int]() var currentUser: User! override init() { super.init() UserDataManager.sharedInstance.getUsers(UserDataManager.sharedInstance.currentUser.group.id) { [weak self] (users: [User]) in guard let strongSelf = self else { return } strongSelf.leaders = users strongSelf.currentUser = UserDataManager.sharedInstance.currentUser strongSelf.calculateLeaderPoints(strongSelf.leaders) strongSelf.leaders = strongSelf.sortUsersByChallenges(strongSelf.leaders, userPoints: strongSelf.userPoints) } } /** Updates current user's score */ func updateLeaderScore() { for leader in leaders { if leader.id == UserDataManager.sharedInstance.currentUser.id { leader.challengesCompleted = UserDataManager.sharedInstance.currentUser.challengesCompleted self.calculateLeaderPoints(self.leaders) self.leaders = self.sortUsersByChallenges(self.leaders, userPoints: self.userPoints) } } } /** Configures tableview cell with user data :param: cell a LeaderboardTableViewCell :param: row index in tableview :returns: modified tableview cell */ func setupLeaderboardCell(cell: LeaderboardTableViewCell, row: Int) -> LeaderboardTableViewCell { let leader = leaders[row] if currentUser.id == leader.id { cell.contentView.backgroundColor = UIColor(red: 227.0/255.0, green: 239.0/255.0, blue: 246.0/255.0, alpha: 1.0) } else { cell.contentView.backgroundColor = UIColor(red: 252/255.0, green: 252/255.0, blue: 252/255.0, alpha: 1.0) } cell.usernameLabel.text = leader.name cell.rankLabel.text = "\(row + 1)" if let points = userPoints[leader.id] { cell.pointsLabel.text = "\(points)" } cell.avatarPlaceholderLabel.text = leader.initials if leader.pictureUrl != "" { cell.profileImageView.image = UIImage(named: leader.pictureUrl) } return cell } /** Method to calculate the sum of points a user has based on their challenges :param: leaders users to calculate points for :returns: dictionary mapping userID to points earned */ func calculateLeaderPoints(leaders: [User]) { for leader in leaders { let sum = leader.challengesCompleted.reduce(0) { $0 + $1.pointValue } userPoints[leader.id] = sum } } /** Sorting method of leaderboard tableview data :param: users users to be sorted :param: userPoints point dictionary for every user in leaderboard :returns: array of sorted users by points */ func sortUsersByChallenges(users: [User], userPoints: [Int:Int]) -> [User] { var sortedUsers = [User]() // sort dictionary by value and iterate through for (k,_) in (Array(userPoints).sort {$0.1 > $1.1}) { for user in users { // append to sorted array with updated order if user.id == k { sortedUsers.append(user) } } } return sortedUsers } }
epl-1.0
599d07a8f15c1ef3eb2949ba5c26001f
30.610169
133
0.592493
4.739517
false
false
false
false
ydi-core/nucleus-ios
Nucleus/TransUIView.swift
1
854
// // TransUIView.swift // Nucleus // // Created by Bezaleel Ashefor on 29/11/2017. // Copyright © 2017 Ephod. All rights reserved. // import UIKit class TransView: UIView { override func layoutSubviews() { // resize your layers based on the view's new frame super.layoutSubviews() //self.layer.addSublayer(gradientLayer) /*self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 0.0) self.layer.shadowRadius = 20 self.layer.shadowOpacity = 0.3*/ self.layer.cornerRadius = 5 } func haveFocus(){ self.layer.backgroundColor? = UIColor(white: 1, alpha: 1).cgColor } func loseFocus(){ self.layer.backgroundColor? = UIColor(white: 1, alpha: 0.5).cgColor } }
bsd-2-clause
db4cc82a159f61db79a7ca6112607ac0
24.088235
75
0.606096
3.967442
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/LinkPolicyCommand.swift
1
3982
// // LinkPolicyCommand.swift // Bluetooth // // Created by Alsey Coleman Miller on 3/23/18. // Copyright © 2018 PureSwift. All rights reserved. // @frozen public enum LinkPolicyCommand: UInt16, HCICommand { public static let opcodeGroupField = HCIOpcodeGroupField.linkPolicy /// Hold Mode Command /// /// The Hold Mode command is used to alter the behavior of the Link Manager, /// and have it place the ACL baseband connection associated by the specified /// Connection Handle into the hold mode. case holdMode = 0x0001 /// Sniff Mode Command /// /// The Sniff_Mode command is used to alter the behavior of the Link Manager and have it place the ACL baseband connection associated with the specified Connection_Handle into the sniff mode. case sniffMode = 0x0003 /// Exit Sniff Mode Command /// /// The Exit_Sniff_Mode command is used to end the sniff mode for a Connection_Handle, which is currently in sniff mode. case exitSniffMode = 0x0004 /// Park State Command /// /// The Park_State command is used to alter the behavior of the Link Manager, and have the LM place the baseband connection associated by the specified Connection_Handle into Park state. case parkState = 0x0005 /// Exit Park State Command /// /// The Exit_Park_State command is used to switch the BR/EDR Controller from park state back to the active mode. case exitParkState = 0x0006 /// QoS Setup Command /// /// The QoS_Setup command is used to specify Quality of Service parameters for a Connection_Handle. case qosSetup = 0x0007 /// Role Discovery Command /// /// The Role_Discovery command is used for a Host to determine which role the device is performing for a particular Connection_Handle. case roleDiscovery = 0x0009 /// Switch Role Command /// /// The Switch_Role command is used to switch the current BR/EDR role the device is performing for a particular connection with another specified BR/EDR Controller. case switchRole = 0x000B /// Read Link Policy Settings Command /// /// This command will read the Link Policy setting for the specified Connection_Handle. case readLinkPolicySettings = 0x000C /// Write Link Policy Settings Command /// /// This command writes the Link Policy setting for the specified Connection_Handle. case writeLinkPolicySettings = 0x000D /// Read Default Link Policy Settings Command /// /// This command reads the Default Link Policy setting for all new BR/EDR con- nections. case readDefaultLinkPolicySettings = 0x000E /// Write Default Link Policy Settings Command /// /// This command writes the Default Link Policy configuration value. case writeDefaultLinkPolicySettings = 0x000F /// Flow Specification Command /// /// The Flow_Specification command is used to specify the flow parameters for the traffic carried over the ACL connection identified by the Connection_Handle. case flowSpecification = 0x0010 /// Sniff Subrating Command /// /// The Sniff_Subrating command specifies the parameters for sniff subrating for a given link. case sniffSubrating = 0x0011 } // MARK: - Name public extension LinkPolicyCommand { var name: String { return type(of: self).names[Int(rawValue)] } private static let names = [ "Unknown", "Hold Mode", "Unknown", "Sniff Mode", "Exit Sniff Mode", "Park State", "Exit Park State", "QoS Setup", "Unknown", "Role Discovery", "Unknown", "Switch Role", "Read Link Policy Settings", "Write Link Policy Settings", "Read Default Link Policy Settings", "Write Default Link Policy Settings", "Flow Specification", "Sniff Subrating" ] }
mit
27681300e9d806b0448722e4beb4e5e9
33.318966
195
0.668676
4.683529
false
false
false
false
stripe/stripe-ios
Stripe/STPPaymentContext.swift
1
60308
// // STPPaymentContext.swift // StripeiOS // // Created by Jack Flintermann on 4/20/16. // Copyright © 2016 Stripe, Inc. All rights reserved. // import Foundation import ObjectiveC import PassKit @_spi(STP) import StripeCore /// An `STPPaymentContext` keeps track of all of the state around a payment. It will manage fetching a user's saved payment methods, tracking any information they select, and prompting them for required additional information before completing their purchase. It can be used to power your application's "payment confirmation" page with just a few lines of code. /// `STPPaymentContext` also provides a unified interface to multiple payment methods - for example, you can write a single integration to accept both credit card payments and Apple Pay. /// `STPPaymentContext` saves information about a user's payment methods to a Stripe customer object, and requires an `STPCustomerContext` to manage retrieving and modifying the customer. @objc(STPPaymentContext) public class STPPaymentContext: NSObject, STPAuthenticationContext, STPPaymentOptionsViewControllerDelegate, STPShippingAddressViewControllerDelegate { /// This is a convenience initializer; it is equivalent to calling /// `init(customerContext:customerContext /// configuration:STPPaymentConfiguration.shared /// theme:STPTheme.defaultTheme`. /// - Parameter customerContext: The customer context the payment context will use to fetch /// and modify its Stripe customer. - seealso: STPCustomerContext.h /// - Returns: the newly-instantiated payment context @objc public convenience init( customerContext: STPCustomerContext ) { self.init(apiAdapter: customerContext) } /// Initializes a new Payment Context with the provided customer context, configuration, /// and theme. After this class is initialized, you should also make sure to set its /// `delegate` and `hostViewController` properties. /// - Parameters: /// - customerContext: The customer context the payment context will use to fetch /// and modify its Stripe customer. - seealso: STPCustomerContext.h /// - configuration: The configuration for the payment context to use. This /// lets you set your Stripe publishable API key, required billing address fields, etc. /// - seealso: STPPaymentConfiguration.h /// - theme: The theme describing the visual appearance of all UI /// that the payment context automatically creates for you. - seealso: STPTheme.h /// - Returns: the newly-instantiated payment context @objc public convenience init( customerContext: STPCustomerContext, configuration: STPPaymentConfiguration, theme: STPTheme ) { self.init( apiAdapter: customerContext, configuration: configuration, theme: theme ) } /// Note: Instead of providing your own backend API adapter, we recommend using /// `STPCustomerContext`, which will manage retrieving and updating a /// Stripe customer for you. - seealso: STPCustomerContext.h /// This is a convenience initializer; it is equivalent to calling /// `init(apiAdapter:apiAdapter configuration:STPPaymentConfiguration.shared theme:STPTheme.defaultTheme)`. @objc public convenience init( apiAdapter: STPBackendAPIAdapter ) { self.init( apiAdapter: apiAdapter, configuration: STPPaymentConfiguration.shared, theme: STPTheme.defaultTheme ) } /// Note: Instead of providing your own backend API adapter, we recommend using /// `STPCustomerContext`, which will manage retrieving and updating a /// Stripe customer for you. - seealso: STPCustomerContext.h /// Initializes a new Payment Context with the provided API adapter and configuration. /// After this class is initialized, you should also make sure to set its `delegate` /// and `hostViewController` properties. /// - Parameters: /// - apiAdapter: The API adapter the payment context will use to fetch and /// modify its contents. You need to make a class conforming to this protocol that /// talks to your server. - seealso: STPBackendAPIAdapter.h /// - configuration: The configuration for the payment context to use. This lets /// you set your Stripe publishable API key, required billing address fields, etc. /// - seealso: STPPaymentConfiguration.h /// - theme: The theme describing the visual appearance of all UI that /// the payment context automatically creates for you. - seealso: STPTheme.h /// - Returns: the newly-instantiated payment context @objc public init( apiAdapter: STPBackendAPIAdapter, configuration: STPPaymentConfiguration, theme: STPTheme ) { STPAnalyticsClient.sharedClient.addClass(toProductUsageIfNecessary: STPPaymentContext.self) self.configuration = configuration self.apiAdapter = apiAdapter self.theme = theme paymentCurrency = "USD" paymentCountry = "US" apiClient = STPAPIClient.shared modalPresentationStyle = .fullScreen state = STPPaymentContextState.none super.init() retryLoading() } /// Note: Instead of providing your own backend API adapter, we recommend using /// `STPCustomerContext`, which will manage retrieving and updating a /// Stripe customer for you. - seealso: STPCustomerContext.h /// The API adapter the payment context will use to fetch and modify its contents. /// You need to make a class conforming to this protocol that talks to your server. /// - seealso: STPBackendAPIAdapter.h @objc public private(set) var apiAdapter: STPBackendAPIAdapter /// The configuration for the payment context to use internally. - seealso: STPPaymentConfiguration.h @objc public private(set) var configuration: STPPaymentConfiguration /// The visual appearance that will be used by any views that the context generates. - seealso: STPTheme.h @objc public private(set) var theme: STPTheme private var _prefilledInformation: STPUserInformation? /// If you've already collected some information from your user, you can set it here and it'll be automatically filled out when possible/appropriate in any UI that the payment context creates. @objc public var prefilledInformation: STPUserInformation? { get { _prefilledInformation } set(prefilledInformation) { _prefilledInformation = prefilledInformation if prefilledInformation?.shippingAddress != nil && shippingAddress == nil { shippingAddress = prefilledInformation?.shippingAddress shippingAddressNeedsVerification = true } } } private weak var _hostViewController: UIViewController? /// The view controller that any additional UI will be presented on. If you have a "checkout view controller" in your app, that should be used as the host view controller. @objc public weak var hostViewController: UIViewController? { get { _hostViewController } set(hostViewController) { assert( _hostViewController == nil, "You cannot change the hostViewController on an STPPaymentContext after it's already been set." ) _hostViewController = hostViewController if hostViewController is UINavigationController { originalTopViewController = (hostViewController as? UINavigationController)?.topViewController } if let hostViewController = hostViewController { artificiallyRetain(hostViewController) } } } private weak var _delegate: STPPaymentContextDelegate? /// This delegate will be notified when the payment context's contents change. - seealso: STPPaymentContextDelegate @objc public weak var delegate: STPPaymentContextDelegate? { get { _delegate } set(delegate) { _delegate = delegate DispatchQueue.main.async(execute: { self.delegate?.paymentContextDidChange(self) }) } } /// Whether or not the payment context is currently loading information from the network. @objc public var loading: Bool { return !(loadingPromise?.completed)! } /// @note This is no longer recommended as of v18.3.0 - the SDK automatically saves the Stripe ID of the last selected /// payment method using NSUserDefaults and displays it as the default pre-selected option. You can override this behavior /// by setting this property. /// The Stripe ID of a payment method to display as the default pre-selected option. /// @note Set this property immediately after initializing STPPaymentContext, or call `retryLoading` afterwards. @objc public var defaultPaymentMethod: String? private var _selectedPaymentOption: STPPaymentOption? /// The user's currently selected payment option. May be nil. @objc public private(set) var selectedPaymentOption: STPPaymentOption? { get { _selectedPaymentOption } set { if let newValue = newValue, let paymentOptions = self.paymentOptions { if !paymentOptions.contains(where: { (option) -> Bool in newValue.isEqual(option) }) { if newValue.isReusable { self.paymentOptions = paymentOptions + [newValue] } } } if !(_selectedPaymentOption?.isEqual(newValue) ?? false) { _selectedPaymentOption = newValue stpDispatchToMainThreadIfNecessary({ self.delegate?.paymentContextDidChange(self) }) } } } private var _paymentOptions: [STPPaymentOption]? /// The available payment options the user can choose between. May be nil. @objc public private(set) var paymentOptions: [STPPaymentOption]? { get { _paymentOptions } set { _paymentOptions = newValue?.sorted(by: { (obj1, obj2) -> Bool in let applePayKlass = STPApplePayPaymentOption.self let paymentMethodKlass = STPPaymentMethod.self if obj1.isKind(of: applePayKlass) { return true } else if obj2.isKind(of: applePayKlass) { return false } if obj1.isKind(of: paymentMethodKlass) && obj2.isKind(of: paymentMethodKlass) { return (obj1.label.compare(obj2.label) == .orderedAscending) } return false }) } } /// The user's currently selected shipping method. May be nil. @objc public internal(set) var selectedShippingMethod: PKShippingMethod? private var _shippingMethods: [PKShippingMethod]? /// An array of STPShippingMethod objects that describe the supported shipping methods. May be nil. @objc public private(set) var shippingMethods: [PKShippingMethod]? { get { _shippingMethods } set { _shippingMethods = newValue if let shippingMethods = newValue, let selectedShippingMethod = self.selectedShippingMethod { if shippingMethods.count == 0 { self.selectedShippingMethod = nil } else if shippingMethods.contains(selectedShippingMethod) { self.selectedShippingMethod = shippingMethods.first } } } } /// The user's shipping address. May be nil. /// If you've already collected a shipping address from your user, you may /// prefill it by setting a shippingAddress in PaymentContext's prefilledInformation. /// When your user enters a new shipping address, PaymentContext will save it to /// the current customer object. When PaymentContext loads, if you haven't /// manually set a prefilled value, any shipping information saved on the customer /// will be used to prefill the shipping address form. Note that because your /// customer's email may not be the same as the email provided with their shipping /// info, PaymentContext will not prefill the shipping form's email using your /// customer's email. /// You should not rely on the shipping information stored on the Stripe customer /// for order fulfillment, as your user may change this information if they make /// multiple purchases. We recommend adding shipping information when you create /// a charge (which can also help prevent fraud), or saving it to your own /// database. https://stripe.com/docs/api/payment_intents/create#create_payment_intent-shipping /// Note: by default, your user will still be prompted to verify a prefilled /// shipping address. To change this behavior, you can set /// `verifyPrefilledShippingAddress` to NO in your `STPPaymentConfiguration`. @objc public private(set) var shippingAddress: STPAddress? /// The amount of money you're requesting from the user, in the smallest currency /// unit for the selected currency. For example, to indicate $10 USD, use 1000 /// (i.e. 1000 cents). For more information, see https://stripe.com/docs/api/payment_intents/create#create_payment_intent-amount /// @note This value must be present and greater than zero in order for Apple Pay /// to be automatically enabled. /// @note You should only set either this or `paymentSummaryItems`, not both. /// The other will be automatically calculated on demand using your `paymentCurrency`. @objc public var paymentAmount: Int { get { return paymentAmountModel.paymentAmount( withCurrency: paymentCurrency, shippingMethod: selectedShippingMethod ) } set(paymentAmount) { paymentAmountModel = STPPaymentContextAmountModel(amount: paymentAmount) } } /// The three-letter currency code for the currency of the payment (i.e. USD, GBP, /// JPY, etc). Defaults to "USD". /// @note Changing this property may change the return value of `paymentAmount` /// or `paymentSummaryItems` (whichever one you didn't directly set yourself). @objc public var paymentCurrency: String /// The two-letter country code for the country where the payment will be processed. /// You should set this to the country your Stripe account is in. Defaults to "US". /// @note Changing this property will change the `countryCode` of your Apple Pay /// payment requests. /// - seealso: PKPaymentRequest for more information. @objc public var paymentCountry: String /// If you support Apple Pay, you can optionally set the PKPaymentSummaryItems /// you want to display here instead of using `paymentAmount`. Note that the /// grand total (the amount of the last summary item) must be greater than zero. /// If not set, a single summary item will be automatically generated using /// `paymentAmount` and your configuration's `companyName`. /// - seealso: PKPaymentRequest for more information /// @note You should only set either this or `paymentAmount`, not both. /// The other will be automatically calculated on demand using your `paymentCurrency.` @objc public var paymentSummaryItems: [PKPaymentSummaryItem] { get { return paymentAmountModel.paymentSummaryItems( withCurrency: paymentCurrency, companyName: configuration.companyName, shippingMethod: selectedShippingMethod ) ?? [] } set(paymentSummaryItems) { paymentAmountModel = STPPaymentContextAmountModel( paymentSummaryItems: paymentSummaryItems ) } } /// The presentation style used for all view controllers presented modally by the context. /// Since custom transition styles are not supported, you should set this to either /// `UIModalPresentationFullScreen`, `UIModalPresentationPageSheet`, or `UIModalPresentationFormSheet`. /// The default value is `UIModalPresentationFullScreen`. @objc public var modalPresentationStyle: UIModalPresentationStyle = .fullScreen /// The mode to use when displaying the title of the navigation bar in all view /// controllers presented by the context. The default value is `automatic`, /// which causes the title to use the same styling as the previously displayed /// navigation item (if the view controller is pushed onto the `hostViewController`). /// If the `prefersLargeTitles` property of the `hostViewController`'s navigation bar /// is false, this property has no effect and the navigation item's title is always /// displayed as a small title. /// If the view controller is presented modally, `automatic` and /// `never` always result in a navigation bar with a small title. @objc public var largeTitleDisplayMode = UINavigationItem.LargeTitleDisplayMode.automatic /// A view that will be placed as the footer of the payment options selection /// view controller. /// When the footer view needs to be resized, it will be sent a /// `sizeThatFits:` call. The view should respond correctly to this method in order /// to be sized and positioned properly. @objc public var paymentOptionsViewControllerFooterView: UIView? /// A view that will be placed as the footer of the add card view controller. /// When the footer view needs to be resized, it will be sent a /// `sizeThatFits:` call. The view should respond correctly to this method in order /// to be sized and positioned properly. @objc public var addCardViewControllerFooterView: UIView? /// The API Client to use to make requests. /// Defaults to STPAPIClient.shared public var apiClient: STPAPIClient = .shared /// If `paymentContext:didFailToLoadWithError:` is called on your delegate, you /// can in turn call this method to try loading again (if that hasn't been called, /// calling this will do nothing). If retrying in turn fails, `paymentContext:didFailToLoadWithError:` /// will be called again (and you can again call this to keep retrying, etc). @objc public func retryLoading() { // Clear any cached customer object and attached payment methods before refetching if apiAdapter is STPCustomerContext { let customerContext = apiAdapter as? STPCustomerContext customerContext?.clearCache() } weak var weakSelf = self loadingPromise = STPPromise<STPPaymentOptionTuple>.init().onSuccess({ tuple in guard let strongSelf = weakSelf else { return } strongSelf.paymentOptions = tuple.paymentOptions strongSelf.selectedPaymentOption = tuple.selectedPaymentOption }).onFailure({ error in guard let strongSelf = weakSelf else { return } if strongSelf.hostViewController != nil { if strongSelf.paymentOptionsViewController != nil && strongSelf.paymentOptionsViewController?.viewIfLoaded?.window != nil { if let paymentOptionsViewController1 = strongSelf.paymentOptionsViewController { strongSelf.appropriatelyDismiss(paymentOptionsViewController1) { strongSelf.delegate?.paymentContext( strongSelf, didFailToLoadWithError: error ) } } } else { strongSelf.delegate?.paymentContext(strongSelf, didFailToLoadWithError: error) } } }) apiAdapter.retrieveCustomer({ customer, retrieveCustomerError in stpDispatchToMainThreadIfNecessary({ guard let strongSelf = weakSelf else { return } if let retrieveCustomerError = retrieveCustomerError { strongSelf.loadingPromise?.fail(retrieveCustomerError) return } if strongSelf.shippingAddress == nil && customer?.shippingAddress != nil { strongSelf.shippingAddress = customer?.shippingAddress strongSelf.shippingAddressNeedsVerification = true } strongSelf.apiAdapter.listPaymentMethodsForCustomer(completion: { paymentMethods, error in guard let strongSelf2 = weakSelf else { return } stpDispatchToMainThreadIfNecessary({ if let error = error { strongSelf2.loadingPromise?.fail(error) return } if self.defaultPaymentMethod == nil && (strongSelf2.apiAdapter is STPCustomerContext) { // Retrieve the last selected payment method saved by STPCustomerContext (strongSelf2.apiAdapter as? STPCustomerContext)? .retrieveLastSelectedPaymentMethodIDForCustomer(completion: { paymentMethodID, `_` in guard let strongSelf3 = weakSelf else { return } if let paymentMethods = paymentMethods { let paymentTuple = STPPaymentOptionTuple( filteredForUIWith: paymentMethods, selectedPaymentMethod: paymentMethodID, configuration: strongSelf3.configuration ) strongSelf3.loadingPromise?.succeed(paymentTuple) } else { strongSelf3.loadingPromise?.fail( STPErrorCode.invalidRequestError as! Error ) } }) } else { if let paymentMethods = paymentMethods { let paymentTuple = STPPaymentOptionTuple( filteredForUIWith: paymentMethods, selectedPaymentMethod: self.defaultPaymentMethod, configuration: strongSelf2.configuration ) strongSelf2.loadingPromise?.succeed(paymentTuple) } } }) }) }) }) } /// This creates, configures, and appropriately presents an `STPPaymentOptionsViewController` /// on top of the payment context's `hostViewController`. It'll be dismissed automatically /// when the user is done selecting their payment method. /// @note This method will do nothing if it is called while STPPaymentContext is /// already showing a view controller or in the middle of requesting a payment. @objc public func presentPaymentOptionsViewController() { presentPaymentOptionsViewController(withNewState: .showingRequestedViewController) } /// This creates, configures, and appropriately pushes an `STPPaymentOptionsViewController` /// onto the navigation stack of the context's `hostViewController`. It'll be popped /// automatically when the user is done selecting their payment method. /// @note This method will do nothing if it is called while STPPaymentContext is /// already showing a view controller or in the middle of requesting a payment. @objc public func pushPaymentOptionsViewController() { assert( hostViewController != nil && hostViewController?.viewIfLoaded?.window != nil, "hostViewController must not be nil on STPPaymentContext when calling pushPaymentOptionsViewController on it. Next time, set the hostViewController property first!" ) var navigationController: UINavigationController? if hostViewController is UINavigationController { navigationController = hostViewController as? UINavigationController } else { navigationController = hostViewController?.navigationController } assert( navigationController != nil, "The payment context's hostViewController is not a navigation controller, or is not contained in one. Either make sure it is inside a navigation controller before calling pushPaymentOptionsViewController, or call presentPaymentOptionsViewController instead." ) if state == STPPaymentContextState.none { state = .showingRequestedViewController let paymentOptionsViewController = STPPaymentOptionsViewController(paymentContext: self) self.paymentOptionsViewController = paymentOptionsViewController paymentOptionsViewController.prefilledInformation = prefilledInformation paymentOptionsViewController.defaultPaymentMethod = defaultPaymentMethod paymentOptionsViewController.paymentOptionsViewControllerFooterView = paymentOptionsViewControllerFooterView paymentOptionsViewController.addCardViewControllerFooterView = addCardViewControllerFooterView paymentOptionsViewController.navigationItem.largeTitleDisplayMode = largeTitleDisplayMode navigationController?.pushViewController( paymentOptionsViewController, animated: transitionAnimationsEnabled() ) } } /// This creates, configures, and appropriately presents a view controller for /// collecting shipping address and shipping method on top of the payment context's /// `hostViewController`. It'll be dismissed automatically when the user is done /// entering their shipping info. /// @note This method will do nothing if it is called while STPPaymentContext is /// already showing a view controller or in the middle of requesting a payment. @objc public func presentShippingViewController() { presentShippingViewController(withNewState: .showingRequestedViewController) } /// This creates, configures, and appropriately pushes a view controller for /// collecting shipping address and shipping method onto the navigation stack of /// the context's `hostViewController`. It'll be popped automatically when the /// user is done entering their shipping info. /// @note This method will do nothing if it is called while STPPaymentContext is /// already showing a view controller, or in the middle of requesting a payment. @objc public func pushShippingViewController() { assert( hostViewController != nil && hostViewController?.viewIfLoaded?.window != nil, "hostViewController must not be nil on STPPaymentContext when calling pushShippingViewController on it. Next time, set the hostViewController property first!" ) var navigationController: UINavigationController? if hostViewController is UINavigationController { navigationController = hostViewController as? UINavigationController } else { navigationController = hostViewController?.navigationController } assert( navigationController != nil, "The payment context's hostViewController is not a navigation controller, or is not contained in one. Either make sure it is inside a navigation controller before calling pushShippingInfoViewController, or call presentShippingInfoViewController instead." ) if state == STPPaymentContextState.none { state = .showingRequestedViewController let addressViewController = STPShippingAddressViewController(paymentContext: self) addressViewController.navigationItem.largeTitleDisplayMode = largeTitleDisplayMode navigationController?.pushViewController( addressViewController, animated: transitionAnimationsEnabled() ) } } /// Requests payment from the user. This may need to present some supplemental UI /// to the user, in which case it will be presented on the payment context's /// `hostViewController`. For instance, if they've selected Apple Pay as their /// payment method, calling this method will show the payment sheet. If the user /// has a card on file, this will use that without presenting any additional UI. /// After this is called, the `paymentContext:didCreatePaymentResult:completion:` /// and `paymentContext:didFinishWithStatus:error:` methods will be called on the /// context's `delegate`. /// @note This method will do nothing if it is called while STPPaymentContext is /// already showing a view controller, or in the middle of requesting a payment. @objc public func requestPayment() { weak var weakSelf = self loadingPromise?.onSuccess({ _ in guard let strongSelf = weakSelf else { return } if strongSelf.state != STPPaymentContextState.none { return } if strongSelf.selectedPaymentOption == nil { strongSelf.presentPaymentOptionsViewController(withNewState: .requestingPayment) } else if strongSelf.requestPaymentShouldPresentShippingViewController() { strongSelf.presentShippingViewController(withNewState: .requestingPayment) } else if (strongSelf.selectedPaymentOption is STPPaymentMethod) || (self.selectedPaymentOption is STPPaymentMethodParams) { strongSelf.state = .requestingPayment let result = STPPaymentResult(paymentOption: strongSelf.selectedPaymentOption!) strongSelf.delegate?.paymentContext(self, didCreatePaymentResult: result) { status, error in stpDispatchToMainThreadIfNecessary({ strongSelf.didFinish(with: status, error: error) }) } } else if strongSelf.selectedPaymentOption is STPApplePayPaymentOption { assert( strongSelf.hostViewController != nil, "hostViewController must not be nil on STPPaymentContext. Next time, set the hostViewController property first!" ) strongSelf.state = .requestingPayment let paymentRequest = strongSelf.buildPaymentRequest() let shippingAddressHandler: STPShippingAddressSelectionBlock = { shippingAddress, completion in // Apple Pay always returns a partial address here, so we won't // update self.shippingAddress or self.shippingMethods if strongSelf.delegate?.responds( to: #selector( STPPaymentContextDelegate.paymentContext( _: didUpdateShippingAddress: completion: )) ) ?? false { strongSelf.delegate?.paymentContext?( strongSelf, didUpdateShippingAddress: shippingAddress ) { status, _, shippingMethods, _ in completion( status, shippingMethods ?? [], strongSelf.paymentSummaryItems ) } } else { completion( .valid, strongSelf.shippingMethods ?? [], strongSelf.paymentSummaryItems ) } } let shippingMethodHandler: STPShippingMethodSelectionBlock = { shippingMethod, completion in strongSelf.selectedShippingMethod = shippingMethod strongSelf.delegate?.paymentContextDidChange(strongSelf) completion(self.paymentSummaryItems) } let paymentHandler: STPPaymentAuthorizationBlock = { payment in strongSelf.selectedShippingMethod = payment.shippingMethod if let shippingContact = payment.shippingContact { strongSelf.shippingAddress = STPAddress(pkContact: shippingContact) } strongSelf.shippingAddressNeedsVerification = false strongSelf.delegate?.paymentContextDidChange(strongSelf) if strongSelf.apiAdapter is STPCustomerContext { let customerContext = strongSelf.apiAdapter as? STPCustomerContext if let shippingAddress1 = strongSelf.shippingAddress { customerContext?.updateCustomer( withShippingAddress: shippingAddress1, completion: nil ) } } } let applePayPaymentMethodHandler: STPApplePayPaymentMethodHandlerBlock = { paymentMethod, completion in strongSelf.apiAdapter.attachPaymentMethod(toCustomer: paymentMethod) { attachPaymentMethodError in stpDispatchToMainThreadIfNecessary({ if attachPaymentMethodError != nil { completion(.error, attachPaymentMethodError) } else { let result = STPPaymentResult(paymentOption: paymentMethod) strongSelf.delegate?.paymentContext( strongSelf, didCreatePaymentResult: result ) { status, error in // for Apple Pay, the didFinishWithStatus callback is fired later when Apple Pay VC finishes completion(status, error) } } }) } } if let paymentRequest = paymentRequest { strongSelf.applePayVC = PKPaymentAuthorizationViewController.stp_controller( with: paymentRequest, apiClient: strongSelf.apiClient, onShippingAddressSelection: shippingAddressHandler, onShippingMethodSelection: shippingMethodHandler, onPaymentAuthorization: paymentHandler, onPaymentMethodCreation: applePayPaymentMethodHandler, onFinish: { status, error in if strongSelf.applePayVC?.presentingViewController != nil { strongSelf.hostViewController?.dismiss( animated: strongSelf.transitionAnimationsEnabled() ) { strongSelf.didFinish(with: status, error: error) } } else { strongSelf.didFinish(with: status, error: error) } strongSelf.applePayVC = nil } ) } if let applePayVC1 = strongSelf.applePayVC { strongSelf.hostViewController?.present( applePayVC1, animated: strongSelf.transitionAnimationsEnabled() ) } } }).onFailure({ error in guard let strongSelf = weakSelf else { return } strongSelf.didFinish(with: .error, error: error) }) } private var loadingPromise: STPPromise<STPPaymentOptionTuple>? private weak var paymentOptionsViewController: STPPaymentOptionsViewController? private var state: STPPaymentContextState = .none private var paymentAmountModel = STPPaymentContextAmountModel(amount: 0) private var shippingAddressNeedsVerification = false // If hostViewController was set to a nav controller, the original VC on top of the stack private weak var originalTopViewController: UIViewController? private var applePayVC: PKPaymentAuthorizationViewController? // Disable transition animations in tests func transitionAnimationsEnabled() -> Bool { return NSClassFromString("XCTest") == nil } var currentValuePromise: STPPromise<STPPaymentOptionTuple> { weak var weakSelf = self return (loadingPromise?.map({ _ in guard let strongSelf = weakSelf, let paymentOptions = strongSelf.paymentOptions else { return STPPaymentOptionTuple() } return STPPaymentOptionTuple( paymentOptions: paymentOptions, selectedPaymentOption: strongSelf.selectedPaymentOption ) }))! } func remove(_ paymentOptionToRemove: STPPaymentOption?) { // Remove payment method from cached representation var paymentOptions = self.paymentOptions paymentOptions?.removeAll { $0 as AnyObject === paymentOptionToRemove as AnyObject } self.paymentOptions = paymentOptions // Elect new selected payment method if needed if let selectedPaymentOption = selectedPaymentOption, selectedPaymentOption.isEqual(paymentOptionToRemove) { self.selectedPaymentOption = self.paymentOptions?.first } } // MARK: - Payment Methods func presentPaymentOptionsViewController(withNewState state: STPPaymentContextState) { assert( hostViewController != nil && hostViewController?.viewIfLoaded?.window != nil, "hostViewController must not be nil on STPPaymentContext when calling pushPaymentOptionsViewController on it. Next time, set the hostViewController property first!" ) if self.state == STPPaymentContextState.none { self.state = state let paymentOptionsViewController = STPPaymentOptionsViewController(paymentContext: self) self.paymentOptionsViewController = paymentOptionsViewController paymentOptionsViewController.prefilledInformation = prefilledInformation paymentOptionsViewController.defaultPaymentMethod = defaultPaymentMethod paymentOptionsViewController.paymentOptionsViewControllerFooterView = paymentOptionsViewControllerFooterView paymentOptionsViewController.addCardViewControllerFooterView = addCardViewControllerFooterView paymentOptionsViewController.navigationItem.largeTitleDisplayMode = largeTitleDisplayMode let navigationController = UINavigationController( rootViewController: paymentOptionsViewController ) navigationController.navigationBar.stp_theme = theme navigationController.navigationBar.prefersLargeTitles = true navigationController.modalPresentationStyle = modalPresentationStyle hostViewController?.present( navigationController, animated: transitionAnimationsEnabled() ) } } @objc public func paymentOptionsViewController( _ paymentOptionsViewController: STPPaymentOptionsViewController, didSelect paymentOption: STPPaymentOption ) { selectedPaymentOption = paymentOption } @objc public func paymentOptionsViewControllerDidFinish( _ paymentOptionsViewController: STPPaymentOptionsViewController ) { appropriatelyDismiss(paymentOptionsViewController) { if self.state == .requestingPayment { self.state = STPPaymentContextState.none self.requestPayment() } else { self.state = STPPaymentContextState.none } } } @objc public func paymentOptionsViewControllerDidCancel( _ paymentOptionsViewController: STPPaymentOptionsViewController ) { appropriatelyDismiss(paymentOptionsViewController) { if self.state == .requestingPayment { self.didFinish( with: .userCancellation, error: nil ) } else { self.state = STPPaymentContextState.none } } } @objc public func paymentOptionsViewController( _ paymentOptionsViewController: STPPaymentOptionsViewController, didFailToLoadWithError error: Error ) { // we'll handle this ourselves when the loading promise fails. } @objc(appropriatelyDismissPaymentOptionsViewController:completion:) func appropriatelyDismiss( _ viewController: STPPaymentOptionsViewController, completion: @escaping STPVoidBlock ) { if viewController.stp_isAtRootOfNavigationController() { // if we're the root of the navigation controller, we've been presented modally. viewController.presentingViewController?.dismiss( animated: transitionAnimationsEnabled() ) { self.paymentOptionsViewController = nil completion() } } else { // otherwise, we've been pushed onto the stack. var destinationViewController = hostViewController // If hostViewController is a nav controller, pop to the original VC on top of the stack. if hostViewController is UINavigationController { destinationViewController = originalTopViewController } viewController.navigationController?.stp_pop( to: destinationViewController, animated: transitionAnimationsEnabled() ) { self.paymentOptionsViewController = nil completion() } } } // MARK: - Shipping Info func presentShippingViewController(withNewState state: STPPaymentContextState) { assert( hostViewController != nil && hostViewController?.viewIfLoaded?.window != nil, "hostViewController must not be nil on STPPaymentContext when calling presentShippingViewController on it. Next time, set the hostViewController property first!" ) if self.state == STPPaymentContextState.none { self.state = state let addressViewController = STPShippingAddressViewController(paymentContext: self) addressViewController.navigationItem.largeTitleDisplayMode = largeTitleDisplayMode let navigationController = UINavigationController( rootViewController: addressViewController ) navigationController.navigationBar.stp_theme = theme navigationController.navigationBar.prefersLargeTitles = true navigationController.modalPresentationStyle = modalPresentationStyle hostViewController?.present( navigationController, animated: transitionAnimationsEnabled() ) } } @objc public func shippingAddressViewControllerDidCancel( _ addressViewController: STPShippingAddressViewController ) { appropriatelyDismiss(addressViewController) { if self.state == .requestingPayment { self.didFinish( with: .userCancellation, error: nil ) } else { self.state = STPPaymentContextState.none } } } @objc public func shippingAddressViewController( _ addressViewController: STPShippingAddressViewController, didEnter address: STPAddress, completion: @escaping STPShippingMethodsCompletionBlock ) { if delegate?.responds( to: #selector( STPPaymentContextDelegate.paymentContext(_:didUpdateShippingAddress:completion:)) ) ?? false { delegate?.paymentContext?(self, didUpdateShippingAddress: address) { status, shippingValidationError, shippingMethods, selectedMethod in self.shippingMethods = shippingMethods completion(status, shippingValidationError, shippingMethods, selectedMethod) } } else { completion(.valid, nil, nil, nil) } } @objc public func shippingAddressViewController( _ addressViewController: STPShippingAddressViewController, didFinishWith address: STPAddress, shippingMethod method: PKShippingMethod? ) { shippingAddress = address shippingAddressNeedsVerification = false selectedShippingMethod = method delegate?.paymentContextDidChange(self) if apiAdapter.responds( to: #selector(STPCustomerContext.updateCustomer(withShippingAddress:completion:)) ) { if let shippingAddress = shippingAddress { apiAdapter.updateCustomer?(withShippingAddress: shippingAddress, completion: nil) } } appropriatelyDismiss(addressViewController) { if self.state == .requestingPayment { self.state = STPPaymentContextState.none self.requestPayment() } else { self.state = STPPaymentContextState.none } } } @objc(appropriatelyDismissViewController:completion:) func appropriatelyDismiss( _ viewController: UIViewController, completion: @escaping STPVoidBlock ) { if viewController.stp_isAtRootOfNavigationController() { // if we're the root of the navigation controller, we've been presented modally. viewController.presentingViewController?.dismiss( animated: transitionAnimationsEnabled() ) { completion() } } else { // otherwise, we've been pushed onto the stack. var destinationViewController = hostViewController // If hostViewController is a nav controller, pop to the original VC on top of the stack. if hostViewController is UINavigationController { destinationViewController = originalTopViewController } viewController.navigationController?.stp_pop( to: destinationViewController, animated: transitionAnimationsEnabled() ) { completion() } } } // MARK: - Request Payment func requestPaymentShouldPresentShippingViewController() -> Bool { let shippingAddressRequired = (configuration.requiredShippingAddressFields?.count ?? 0) > 0 var shippingAddressIncomplete: Bool? if let requiredShippingAddressFields1 = configuration.requiredShippingAddressFields { shippingAddressIncomplete = !(shippingAddress?.containsRequiredShippingAddressFields( requiredShippingAddressFields1 ) ?? false) } let shippingMethodRequired = configuration.shippingType == .shipping && delegate?.responds( to: #selector( STPPaymentContextDelegate.paymentContext(_:didUpdateShippingAddress:completion:) ) ) ?? false && selectedShippingMethod == nil let verificationRequired = configuration.verifyPrefilledShippingAddress && shippingAddressNeedsVerification // true if STPShippingVC should be presented to collect or verify a shipping address let shouldPresentShippingAddress = shippingAddressRequired && (shippingAddressIncomplete ?? false || verificationRequired) // this handles a corner case where STPShippingVC should be presented because: // - shipping address has been pre-filled // - no verification is required, but the user still needs to enter a shipping method let shouldPresentShippingMethods = shippingAddressRequired && !(shippingAddressIncomplete ?? false) && !verificationRequired && shippingMethodRequired return shouldPresentShippingAddress || shouldPresentShippingMethods } func didFinish( with status: STPPaymentStatus, error: Error? ) { state = STPPaymentContextState.none delegate?.paymentContext( self, didFinishWith: status, error: error ) } func buildPaymentRequest() -> PKPaymentRequest? { guard let appleMerchantIdentifier = configuration.appleMerchantIdentifier, paymentAmount > 0 else { return nil } let paymentRequest = StripeAPI.paymentRequest( withMerchantIdentifier: appleMerchantIdentifier, country: paymentCountry, currency: paymentCurrency ) let summaryItems = paymentSummaryItems paymentRequest.paymentSummaryItems = summaryItems let requiredFields = STPAddress.applePayContactFields( from: configuration.requiredBillingAddressFields ) paymentRequest.requiredBillingContactFields = requiredFields var shippingRequiredFields: Set<PKContactField>? if let requiredShippingAddressFields1 = configuration.requiredShippingAddressFields { shippingRequiredFields = STPAddress.pkContactFields( fromStripeContactFields: requiredShippingAddressFields1 ) } if let shippingRequiredFields = shippingRequiredFields { paymentRequest.requiredShippingContactFields = shippingRequiredFields } paymentRequest.currencyCode = paymentCurrency.uppercased() if let selectedShippingMethod = selectedShippingMethod { var orderedShippingMethods = shippingMethods orderedShippingMethods?.removeAll { $0 as AnyObject === selectedShippingMethod as AnyObject } orderedShippingMethods?.insert(selectedShippingMethod, at: 0) paymentRequest.shippingMethods = orderedShippingMethods } else { paymentRequest.shippingMethods = shippingMethods } paymentRequest.shippingType = STPPaymentContext.pkShippingType(configuration.shippingType) if let shippingAddress = shippingAddress { paymentRequest.shippingContact = shippingAddress.pkContactValue() } return paymentRequest } class func pkShippingType(_ shippingType: STPShippingType) -> PKShippingType { switch shippingType { case .shipping: return .shipping case .delivery: return .delivery @unknown default: fatalError() } } func artificiallyRetain(_ host: NSObject) { objc_setAssociatedObject( host, UnsafeRawPointer(&kSTPPaymentCoordinatorAssociatedObjectKey), self, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } // MARK: - STPAuthenticationContext @objc public func authenticationPresentingViewController() -> UIViewController { return hostViewController! } @objc public func prepare(forPresentation completion: @escaping STPVoidBlock) { if applePayVC != nil && applePayVC?.presentingViewController != nil { hostViewController?.dismiss( animated: transitionAnimationsEnabled() ) { completion() } } else { completion() } } } /// Implement `STPPaymentContextDelegate` to get notified when a payment context changes, finishes, encounters errors, etc. In practice, if your app has a "checkout screen view controller", that is a good candidate to implement this protocol. @objc public protocol STPPaymentContextDelegate: NSObjectProtocol { /// Called when the payment context encounters an error when fetching its initial set of data. A few ways to handle this are: /// - If you're showing the user a checkout page, dismiss the checkout page when this is called and present the error to the user. /// - Present the error to the user using a `UIAlertController` with two buttons: Retry and Cancel. If they cancel, dismiss your UI. If they Retry, call `retryLoading` on the payment context. /// To make it harder to get your UI into a bad state, this won't be called until the context's `hostViewController` has finished appearing. /// - Parameters: /// - paymentContext: the payment context that encountered the error /// - error: the error that was encountered func paymentContext(_ paymentContext: STPPaymentContext, didFailToLoadWithError error: Error) /// This is called every time the contents of the payment context change. When this is called, you should update your app's UI to reflect the current state of the payment context. For example, if you have a checkout page with a "selected payment method" row, you should update its payment method with `paymentContext.selectedPaymentOption.label`. If that checkout page has a "buy" button, you should enable/disable it depending on the result of `paymentContext.isReadyForPayment`. /// - Parameter paymentContext: the payment context that changed func paymentContextDidChange(_ paymentContext: STPPaymentContext) /// Inside this method, you should make a call to your backend API to make a PaymentIntent with that Customer + payment method, and invoke the `completion` block when that is done. /// - Parameters: /// - paymentContext: The context that succeeded /// - paymentResult: Information associated with the payment that you can pass to your server. You should go to your backend API with this payment result and use the PaymentIntent API to complete the payment. See https://stripe.com/docs/mobile/ios/basic#submit-payment-intents Once that's done call the `completion` block with any error that occurred (or none, if the payment succeeded). - seealso: STPPaymentResult.h /// - completion: Call this block when you're done creating a payment intent (or subscription, etc) on your backend. If it succeeded, call `completion(STPPaymentStatusSuccess, nil)`. If it failed with an error, call `completion(STPPaymentStatusError, error)`. If the user canceled, call `completion(STPPaymentStatusUserCancellation, nil)`. func paymentContext( _ paymentContext: STPPaymentContext, didCreatePaymentResult paymentResult: STPPaymentResult, completion: @escaping STPPaymentStatusBlock ) /// This is invoked by an `STPPaymentContext` when it is finished. This will be called after the payment is done and all necessary UI has been dismissed. You should inspect the returned `status` and behave appropriately. For example: if it's `STPPaymentStatusSuccess`, show the user a receipt. If it's `STPPaymentStatusError`, inform the user of the error. If it's `STPPaymentStatusUserCancellation`, do nothing. /// - Parameters: /// - paymentContext: The payment context that finished /// - status: The status of the payment - `STPPaymentStatusSuccess` if it succeeded, `STPPaymentStatusError` if it failed with an error (in which case the `error` parameter will be non-nil), `STPPaymentStatusUserCancellation` if the user canceled the payment. /// - error: An error that occurred, if any. func paymentContext( _ paymentContext: STPPaymentContext, didFinishWith status: STPPaymentStatus, error: Error? ) /// Inside this method, you should verify that you can ship to the given address. /// You should call the completion block with the results of your validation /// and the available shipping methods for the given address. If you don't implement /// this method, the user won't be prompted to select a shipping method and all /// addresses will be valid. If you call the completion block with nil or an /// empty array of shipping methods, the user won't be prompted to select a /// shipping method. /// @note If a user updates their shipping address within the Apple Pay dialog, /// this address will be anonymized. For example, in the US, it will only include the /// city, state, and zip code. The payment context will have the user's complete /// shipping address by the time `paymentContext:didFinishWithStatus:error` is /// called. /// - Parameters: /// - paymentContext: The context that updated its shipping address /// - address: The current shipping address /// - completion: Call this block when you're done validating the shipping /// address and calculating available shipping methods. If you call the completion /// block with nil or an empty array of shipping methods, the user won't be prompted /// to select a shipping method. @objc optional func paymentContext( _ paymentContext: STPPaymentContext, didUpdateShippingAddress address: STPAddress, completion: @escaping STPShippingMethodsCompletionBlock ) } /// The current state of the payment context /// - STPPaymentContextStateNone: No view controllers are currently being shown. The payment may or may not have already been completed /// - STPPaymentContextStateShowingRequestedViewController: The view controller that you requested the context show is being shown (via the push or present payment methods or shipping view controller methods) /// - STPPaymentContextStateRequestingPayment: The payment context is in the middle of requesting payment. It may be showing some other UI or view controller if more information is necessary to complete the payment. enum STPPaymentContextState: Int { case none case showingRequestedViewController case requestingPayment } private var kSTPPaymentCoordinatorAssociatedObjectKey = 0 /// :nodoc: @_spi(STP) extension STPPaymentContext: STPAnalyticsProtocol { @_spi(STP) public static var stp_analyticsIdentifier = "STPPaymentContext" }
mit
0555755a0e9bc21096a77853a1c822ef
49.047303
484
0.638268
6.142493
false
false
false
false
eurofurence/ef-app_ios
Packages/EurofurenceComponents/Sources/ComponentBase/Alerts/WindowAlertRouter.swift
1
1194
import UIKit public struct WindowAlertRouter: AlertRouter { private let window: UIWindow public init(window: UIWindow) { self.window = window } public func show(_ alert: Alert) { let alertController = UIAlertController(title: alert.title, message: alert.message, preferredStyle: .alert) for action in alert.actions { alertController.addAction(UIAlertAction(title: action.title, style: .default, handler: { (_) in action.invoke() alertController.dismiss(animated: true) })) } var presenting: UIViewController? = window.rootViewController if let presented = presenting?.presentedViewController { presenting = presented } presenting?.present(alertController, animated: true) { alert.onCompletedPresentation?(Dismissable(viewController: presenting)) } } private struct Dismissable: AlertDismissable { var viewController: UIViewController? func dismiss(_ completionHandler: (() -> Void)?) { viewController?.dismiss(animated: true, completion: completionHandler) } } }
mit
733171b63e1a920a5849b651e0b47096
28.85
115
0.637353
5.427273
false
false
false
false
VernonVan/SmartClass
SmartClass/Paper/Create Paper/View/QuestionCell.swift
1
1546
// // QuestionCell.swift // SmartClass // // Created by Vernon on 16/7/21. // Copyright © 2016年 Vernon. All rights reserved. // import UIKit class QuestionCell: UITableViewCell { @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var topicLabel: UILabel! @IBOutlet weak var isCompletedImageView: UIImageView! } extension QuestionCell { func configurForQuestion(_ question: Question?) { guard let question = question else { return } switch QuestionType(typeNum: question.type)! { case .singleChoice: typeLabel.text = NSLocalizedString("单选", comment: "") case .multipleChoice: typeLabel.text = NSLocalizedString("多选", comment: "") case .trueOrFalse: typeLabel.text = NSLocalizedString("判断", comment: "") } // topicLabel.text = question.topic let isEmptyTopic = (question.topic ?? "").isEmpty let text = (isEmptyTopic ? NSLocalizedString("尚未填写题目描述", comment: "") : question.topic!) let attributes = [NSForegroundColorAttributeName: (isEmptyTopic ? UIColor.lightGray : UIColor.darkText)] let attributedText = NSAttributedString(string: text, attributes: attributes) topicLabel.attributedText = attributedText let isCompletedImageName = question.isCompleted ? "completeQuestion" : "uncompleteQuestion" isCompletedImageView.image = UIImage(named: isCompletedImageName) } }
mit
b3b40fddb6791b49ae116c1ca08cca71
29.3
112
0.648845
4.794304
false
false
false
false
hgl888/firefox-ios
Storage/DiskImageStore.swift
4
3366
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import UIKit private class DiskImageStoreErrorType: MaybeErrorType { let description: String init(description: String) { self.description = description } } /** * Disk-backed key-value image store. */ public class DiskImageStore { private let files: FileAccessor private let filesDir: String private let queue = dispatch_queue_create("DiskImageStore", DISPATCH_QUEUE_CONCURRENT) private let quality: CGFloat private var keys: Set<String> required public init(files: FileAccessor, namespace: String, quality: Float) { self.files = files self.filesDir = try! files.getAndEnsureDirectory(namespace) self.quality = CGFloat(quality) // Build an in-memory set of keys from the existing images on disk. var keys = [String]() if let fileEnumerator = NSFileManager.defaultManager().enumeratorAtPath(filesDir) { for file in fileEnumerator { keys.append(file as! String) } } self.keys = Set(keys) } /// Gets an image for the given key if it is in the store. public func get(key: String) -> Deferred<Maybe<UIImage>> { if !keys.contains(key) { return deferMaybe(DiskImageStoreErrorType(description: "Image key not found")) } return deferDispatchAsync(queue) { () -> Deferred<Maybe<UIImage>> in let imagePath = (self.filesDir as NSString).stringByAppendingPathComponent(key) if let data = NSData(contentsOfFile: imagePath), image = UIImage.imageFromDataThreadSafe(data) { return deferMaybe(image) } return deferMaybe(DiskImageStoreErrorType(description: "Invalid image data")) } } /// Adds an image for the given key. /// This put is asynchronous; the image is not recorded in the cache until the write completes. /// Does nothing if this key already exists in the store. public func put(key: String, image: UIImage) -> Success { if keys.contains(key) { return deferMaybe(DiskImageStoreErrorType(description: "Key already in store")) } return deferDispatchAsync(queue) { () -> Success in let imagePath = (self.filesDir as NSString).stringByAppendingPathComponent(key) if let data = UIImageJPEGRepresentation(image, self.quality) { if data.writeToFile(imagePath, atomically: false) { self.keys.insert(key) return succeed() } } return deferMaybe(DiskImageStoreErrorType(description: "Could not write image to file")) } } /// Clears all images from the cache, excluding the given set of keys. public func clearExcluding(keys: Set<String>) { let keysToDelete = self.keys.subtract(keys) for key in keysToDelete { let path = NSString(string: filesDir).stringByAppendingPathComponent(key) try! NSFileManager.defaultManager().removeItemAtPath(path) } self.keys = self.keys.intersect(keys) } }
mpl-2.0
3e47c085a11d7a52ebcec0ce20dea332
36.4
100
0.644088
4.754237
false
false
false
false
darkdong/DarkSwift
Source/Extension/UIScrollView.swift
1
2005
// // UIScrollView.swift // DarkSwift // // Created by Dark Dong on 2017/7/29. // Copyright © 2017年 Dark Dong. All rights reserved. // import UIKit public extension UIScrollView { func scrollToEnd(animated: Bool, scrollDirection: UICollectionView.ScrollDirection = .vertical) { switch scrollDirection { case .vertical: let diff = contentSize.height + contentInset.bottom - frame.height if (diff > 0) { setContentOffset(CGPoint(x: contentOffset.x, y: diff), animated: animated) } case .horizontal: let diff = contentSize.width + contentInset.right - frame.width if (diff > 0) { setContentOffset(CGPoint(x: diff, y: contentOffset.y), animated: animated) } @unknown default: fatalError() } } func visibleContentImage(extraScale: CGFloat = 1) -> UIImage? { UIGraphicsBeginImageContextWithOptions(bounds.size, true, UIScreen.main.scale * extraScale) let context = UIGraphicsGetCurrentContext()! context.translateBy(x: -contentOffset.x, y: -contentOffset.y) layer.render(in: context) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } var contentOffsetForCentering: CGPoint { return CGPoint(x: (contentSize.width - frame.width) / 2, y: (contentSize.height - frame.height) / 2) } } public extension UITableView { func clearsSelection(animated: Bool) { if let indexPaths = indexPathsForSelectedRows { for indexPath in indexPaths { deselectRow(at: indexPath, animated: animated) } } } } public extension UICollectionView { func clearsSelection(animated: Bool) { if let indexPaths = indexPathsForSelectedItems { for indexPath in indexPaths { deselectItem(at: indexPath, animated: animated) } } } }
mit
175fd15e8aa191efa05b688926111735
31.290323
108
0.631369
4.800959
false
false
false
false
VirrageS/TDL
TDL/ListEditCell.swift
1
5216
import UIKit let listEditCellHeight: CGFloat = 35 let listEditCellButtonCornerRadius: CGFloat = 5.0 class ListEditCell: UITableViewCell { let deleteButton: UIButton let editButton: UIButton override init(style: UITableViewCellStyle, reuseIdentifier: String) { deleteButton = UIButton.buttonWithType(UIButtonType.System) as UIButton deleteButton.layer.cornerRadius = listEditCellButtonCornerRadius deleteButton.setTitle("Delete", forState: UIControlState.Normal) deleteButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) deleteButton.frame = CGRectMake(20, 5, 60, 25) deleteButton.backgroundColor = UIColor.redColor() editButton = UIButton.buttonWithType(UIButtonType.System) as UIButton editButton.layer.cornerRadius = listEditCellButtonCornerRadius editButton.setTitle("Edit", forState: UIControlState.Normal) editButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal) editButton.backgroundColor = editButton.tintColor editButton.frame = CGRectMake(250, 5, 60, 25) super.init(style: style, reuseIdentifier: reuseIdentifier) deleteButton.addTarget(self, action: "deleteButtonAction:", forControlEvents: UIControlEvents.TouchUpInside) editButton.addTarget(self, action: "editButtonAction:", forControlEvents: UIControlEvents.TouchUpInside) contentView.addSubview(deleteButton) contentView.addSubview(editButton) /*deleteButton.setTranslatesAutoresizingMaskIntoConstraints(false) contentView.addConstraint(NSLayoutConstraint(item: deleteButton, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1, constant: 20)) contentView.addConstraint(NSLayoutConstraint(item: deleteButton, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 5)) contentView.addConstraint(NSLayoutConstraint(item: deleteButton, attribute: .Right, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1, constant: -250)) contentView.addConstraint(NSLayoutConstraint(item: deleteButton, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: 0)) editButton.setTranslatesAutoresizingMaskIntoConstraints(false) contentView.addConstraint(NSLayoutConstraint(item: editButton, attribute: .Left, relatedBy: .Equal, toItem: contentView, attribute: .Left, multiplier: 1, constant: 250)) contentView.addConstraint(NSLayoutConstraint(item: editButton, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 5)) contentView.addConstraint(NSLayoutConstraint(item: editButton, attribute: .Right, relatedBy: .Equal, toItem: contentView, attribute: .Right, multiplier: 1, constant: -20)) contentView.addConstraint(NSLayoutConstraint(item: editButton, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: 0))*/ } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setButtonsHidden(indexPath: NSIndexPath) { deleteButton.hidden = hiddenEditCell[indexPath.section][indexPath.row/2] editButton.hidden = hiddenEditCell[indexPath.section][indexPath.row/2] } func deleteButtonAction(sender: UIButton!) { let buttonCell = sender.superview?.superview as UITableViewCell let tableView = buttonCell.superview?.superview as UITableView let indexPath = tableView.indexPathForCell(buttonCell) as NSIndexPath let newIndexPath = NSIndexPath(forRow: indexPath.row-1, inSection: indexPath.section) tableView.beginUpdates() sectionItems[indexPath.section].removeAtIndex(indexPath.row/2) if sectionItems[indexPath.section].count > 0 { for i in 0...sectionItems[indexPath.section].count-1 { if indexPath.row/2 <= i { hiddenEditCell[indexPath.section][i] = hiddenEditCell[indexPath.section][i+1] } } } hiddenEditCell[indexPath.section][sectionItems[indexPath.section].count] = false tableView.deleteRowsAtIndexPaths([indexPath, newIndexPath], withRowAnimation: UITableViewRowAnimation.Left) tableView.endUpdates() } func editButtonAction(sender: UIButton!) { // for index path let buttonCell = sender.superview?.superview as UITableViewCell let tableView = buttonCell.superview?.superview as UITableView let indexPath = tableView.indexPathForCell(buttonCell) as NSIndexPath // search window var window: AnyObject = sender.superview! while !(window is UIWindow) { window = window.superview!! } window = window.rootViewController as UINavigationController let controller: ListViewController = window.topViewController as ListViewController controller.openEditTaskController(indexPath) } }
mit
6e8f6d39e7ecab7138f6ad0a26ec4a85
53.905263
182
0.716641
5.344262
false
false
false
false
ZeroFengLee/ZRNotify
ZRNotify/ZRNotify.swift
1
2942
// // ZRNotify.swift // Planetoid // // Created by Zero on 2017/3/21. // Copyright © 2017年 Zero. All rights reserved. // import Foundation public class ZRNotify { public init() {} typealias notifierIdentifier = String public typealias notifyType = ((Notification) -> Void) fileprivate var notifyPool: [(String, notifyType?)] = [] fileprivate var notifyStatus: [String: Bool] = [:] fileprivate lazy var lock: NSLock = { var lock = NSLock() return lock }() /* one <-> one */ @discardableResult public func on(_ notifyIdentifier: String, notify: notifyType?) -> Self { NotificationCenter.default.addObserver(self, selector: #selector(receiveNotify(_:)), name: NSNotification.Name(rawValue: notifyIdentifier), object: nil) lock.lock() self.notifyPool.append((notifyIdentifier, notify)) lock.unlock() self.notifyStatus[notifyIdentifier] = true return self } /* one <-> many */ @discardableResult public func ons(_ notifyIdentifiers: [String], notify: notifyType?) -> Self { lock.lock() notifyIdentifiers.forEach { NotificationCenter.default.addObserver(self, selector: #selector(receiveNotify(_:)), name: NSNotification.Name(rawValue: $0), object: nil) self.notifyPool.append(($0, notify)) self.notifyStatus[$0] = true } lock.unlock() return self } /* remove notification */ @discardableResult public func remove(_ notifyIdentifier: String) -> Self { NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: notifyIdentifier), object: nil) notifyPool = notifyPool.filter { $0.0 == notifyIdentifier } return self } /* remove all notifications */ @discardableResult public func removeAll() -> Self { NotificationCenter.default.removeObserver(self) notifyPool.removeAll() return self } /* switch notification's status */ @discardableResult public func opStatus(_ notifyIdentifier: String, _ open: Bool) -> Self { self.notifyStatus[notifyIdentifier] = open return self } /* switch all notifacations' status */ @discardableResult public func opStatusForAll(_ open: Bool) -> Self { self.notifyStatus.keys.forEach { self.notifyStatus[$0] = open } return self } /** ! `default`: ZRNotify remove all notification in deinit */ deinit { removeAll() } } extension ZRNotify { @objc fileprivate func receiveNotify(_ notification: Notification) { for notify in notifyPool { guard let status = self.notifyStatus[notify.0], status == true, notify.0 == notification.name.rawValue else { continue } notify.1?(notification) } } }
mit
12c3c0c81f5911a4e87f36a666ea532b
27.813725
160
0.62096
4.599374
false
false
false
false
NextFaze/FazeKit
Sources/FazeKit/Classes/UIColorAdditions.swift
1
4596
// // Copyright 2016 NextFaze // // 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. // // UIColorAdditions.swift // Pods // // Created by Ricardo Santos on 30/11/2016. // // import UIKit public extension UIColor { var redInt: Int { var red: CGFloat = 0 self.getRed(&red, green: nil, blue: nil, alpha: nil) return Int(red * 255) } var greenInt: Int { var green: CGFloat = 0 self.getRed(nil, green: &green, blue: nil, alpha: nil) return Int(green * 255) } var blueInt: Int { var blue: CGFloat = 0 self.getRed(nil, green: nil, blue: &blue, alpha: nil) return Int(blue * 255) } var alphaInt: Int { var alpha: CGFloat = 0 self.getRed(nil, green: nil, blue: nil, alpha: &alpha) return Int(alpha * 255) } var rgba: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else { return (0, 0, 0, 0) } return (red, green, blue, alpha) } var rgbaInt: (r: Int, g: Int, b: Int, a: Int) { var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else { return (0, 0, 0, 0) } return (Int(red * 255), Int(green * 255), Int(blue * 255), Int(alpha * 255)) } convenience init(redInt: Int, greenInt: Int, blueInt: Int, alpha: CGFloat) { self.init(red: CGFloat(redInt)/255.0, green: CGFloat(greenInt)/255.0, blue: CGFloat(blueInt)/255.0, alpha: alpha) } // adapted from: https://gist.github.com/arshad/de147c42d7b3063ef7bc convenience init(hexString: String, alpha: Double = 1.0) { let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) var int = UInt32() Scanner(string: hex).scanHexInt32(&int) let r, g, b: UInt32 switch hex.count { case 3: // RGB (12-bit) (r, g, b) = ((int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (r, g, b) = (int >> 16, int >> 8 & 0xFF, int & 0xFF) default: (r, g, b) = (1, 1, 0) } self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(255 * alpha) / 255) } var hexStringRGB: String { let rgbaInt = self.rgbaInt return String(format: "%02x%02x%02x", rgbaInt.r, rgbaInt.g, rgbaInt.b) } var hexStringARGB: String { let rgbaInt = self.rgbaInt return String(format: "%02x%02x%02x%02x", rgbaInt.a, rgbaInt.r, rgbaInt.g, rgbaInt.b) } var htmlStringRGB: String { return "#" + self.hexStringRGB } var htmlStringARGB: String { return "#" + self.hexStringARGB } convenience init(source: String, minBrightness: CGFloat = 0.66, maxBrightness: CGFloat = 1.0) { guard !source.isEmpty, let md5 = source.md5() else { self.init(red: 0, green: 0, blue: 0, alpha: 1) return } self.init(md5: md5, minBrightness: minBrightness, maxBrightness: maxBrightness) } convenience init(md5: String, minBrightness: CGFloat = 0.66, maxBrightness: CGFloat = 1.0) { let mid = md5.index(md5.startIndex, offsetBy: md5.count / 2) let firstHalf = md5[md5.startIndex..<mid] let secondHalf = md5[mid..<md5.endIndex] let firstHash = abs(firstHalf.hashValue % 100) let secondHash = abs(secondHalf.hashValue % 100) let hue = CGFloat(firstHash) / 100.0 let brightness: CGFloat = minBrightness + (maxBrightness - minBrightness) * CGFloat(secondHash) / 100.0 self.init(hue: hue, saturation: 0.8, brightness: brightness, alpha: 1.0) } class var random: UIColor { return UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1.0) } }
apache-2.0
33275ac3cdf1258439326bd9a0859bfb
36.365854
124
0.596606
3.442697
false
false
false
false
blitzagency/events
Events/EventManagerBase/EventManagerBase.swift
1
514
// // EventManagerBase.swift // Events // // Created by Adam Venturella on 7/19/16. // Copyright © 2016 BLITZ. All rights reserved. // import Foundation public class EventManagerBase : EventManageable { public let listenId = uniqueId() public var listeningTo: [String: Listener] = [:] public var events = [String: [HandlerBase]]() public var listeners = [String: Listener]() public let lockingQueue = DispatchQueue(label: "com.events.manager.queue.\(uniqueId)") public init(){} }
mit
87f7ec1c00b267d93ace85dd9af21a09
23.428571
90
0.684211
3.946154
false
false
false
false
tardieu/swift
test/ClangImporter/submodules_scoped.swift
13
1062
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck -verify %s -DCHECK_SCOPING // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t %s -module-name submodules // RUN: echo 'import submodules; let s = "\(x), \(y)"' | %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck - -I %t // RUN: echo 'import submodules; let s = "\(x), \(y)"' | not %target-swift-frontend -typecheck - -I %t 2>&1 | %FileCheck -check-prefix=MISSING %s import typealias ctypes.bits.DWORD // MISSING: missing required modules: // MISSING-DAG: 'ctypes.bits' // MISSING-DAG: 'ctypes' // From bits submodule public var x : DWORD = 0 public var y : CInt = x let _: ctypes.DWORD = 0 func markUsed<T>(_ t: T) {} #if CHECK_SCOPING markUsed(MY_INT) // expected-error {{use of unresolved identifier 'MY_INT'}} markUsed(ctypes.MY_INT) // expected-error {{module 'ctypes' has no member named 'MY_INT'}} let _: ctypes.Color? = nil // expected-error {{no type named 'Color' in module 'ctypes'}} #endif
apache-2.0
fd6fdd213632badf70c9e7496676bf50
41.48
145
0.675141
3.051724
false
false
false
false
tigclaw/days-of-swift
Project 22/SettingTheDate/SettingTheDate/ViewController.swift
1
1244
// // ViewController.swift // SettingTheDate // // Created by Angela Lin on 1/10/17. // Copyright © 2017 Angela Lin. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var datePicker: UIDatePicker! @IBOutlet weak var setDateButton: UIButton! override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = "Date" // add function to SetDate button setDateButton.setTitle("Set Date", for: .normal) setDateButton.addTarget(self, action: #selector(clickSetDate(sender:)), for: .touchUpInside) // add function to datePicker datePicker.datePickerMode = .date datePicker.addTarget(self, action: #selector(selectDate(sender:)), for: .valueChanged) } func clickSetDate(sender: UIButton) { print("clicked uibutton") let dateFormatter = DateFormatter() dateFormatter.dateStyle = .medium dateFormatter.timeStyle = .none self.navigationItem.title = dateFormatter.string(from: datePicker.date) } func selectDate(sender: UIDatePicker) { print("uidatepicker was changed") } }
mit
8558b0bc0dd8262ef81cbe0fb122e905
25.446809
100
0.635559
4.762452
false
false
false
false
DrabWeb/Komikan
Komikan/Komikan/ViewController.swift
1
70787
// // ViewController.swift // Komikan // // Created by Seth on 2015-12-31. // Copyright © 2015 DrabWeb. All rights reserved. // import Cocoa import SWXMLHash class ViewController: NSViewController, NSWindowDelegate { // The main window of the application var window : NSWindow = NSWindow(); // The visual effect view for the main windows titlebar @IBOutlet weak var titlebarVisualEffectView: NSVisualEffectView! // The visual effect view for the main windows background @IBOutlet weak var backgroundVisualEffectView: NSVisualEffectView! // The visual effect view for the info bottom bar @IBOutlet weak var infoBarVisualEffectView: NSVisualEffectView! // The container for the info bar @IBOutlet weak var infoBarContainer: NSView! // The label on the info bar that shows how many manga you have @IBOutlet weak var infoBarMangaCountLabel: NSTextField! // The collection view that manages displayig manga covers in the main window @IBOutlet weak var mangaCollectionView: NSCollectionView! // The scroll view for the manga collection view @IBOutlet weak var mangaCollectionViewScrollView: NSScrollView! // The array controller for the manga collection view @IBOutlet var mangaCollectionViewArray: NSArrayController! /// The scroll view for groupCollectionView @IBOutlet var groupCollectionViewScrollView: NSScrollView! /// The collection view for showing manga in their groups(Series, Artist, Writer, ETC.) @IBOutlet var groupCollectionView: NSCollectionView! /// The controller for the manga groups(groupCollectionView) @IBOutlet var mangaGroupController: KMMangaGroupController! // The grid controller for the manga grid @IBOutlet var mangaGridController: KMMangaGridController! /// The list controller for the manga list @IBOutlet var mangaListController: KMMangaListController! /// The controller for showing the thumbnail of a manga on hover in the list view @IBOutlet var thumbnailImageHoverController: KMThumbnailImageHoverController! /// The table view the user can switch to to see their manga in a list instead of a grid @IBOutlet var mangaTableView: NSTableView! /// The scroll view for mangaTableView @IBOutlet var mangaTableViewScrollView: NSScrollView! // The search field in the titlebar @IBOutlet weak var titlebarSearchField: NSTextField! // When we finish editing the titlebarSearchField... @IBAction func titlebarSearchFieldInteracted(_ sender: AnyObject) { // Search for the passed string mangaGridController.searchFor((sender as? NSTextField)!.stringValue); } // The disclosure button in the titlebatr that lets you ascend/descend the sort order of the manga grid @IBOutlet weak var titlebarToggleSortDirectionButton: NSButton! // When we interact with titlebarToggleSortDirectionButton... @IBAction func titlebarToggleSortDirectionButtonInteracted(_ sender: AnyObject) { // Set the current ascending order on the grid controller mangaGridController.currentSortAscending = Bool(titlebarToggleSortDirectionButton.state as NSNumber); // Resort the grid based on which direction we said to sort it in mangaGridController.arrayController.sortDescriptors = [NSSortDescriptor(key: mangaGridController.arrayController.sortDescriptors[0].key, ascending: Bool(titlebarToggleSortDirectionButton.state as NSNumber))]; } // The view controller we will load for the add manga popover var addMangaViewController: KMAddMangaViewController? // Is this the first time we've clicked on the add button in the titlebar? var addMangaViewFirstLoad : Bool = true; // The bool to say if we have the info bar showing var infoBarOpen : Bool = false; /// The slider in the info bar that lets us set the size of the grid items @IBOutlet weak var infoBarGridSizeSlider: NSSlider! /// When the value for infoBarGridSizeSlider changes... @IBAction func infoBarGridSizeSliderInteracted(_ sender: AnyObject) { // Set the manga grid and group's min and max size to the sliders value mangaCollectionView.minItemSize = NSSize(width: infoBarGridSizeSlider.integerValue, height: infoBarGridSizeSlider.integerValue); mangaCollectionView.maxItemSize = NSSize(width: infoBarGridSizeSlider.integerValue + 100, height: infoBarGridSizeSlider.integerValue + 100); groupCollectionView.minItemSize = NSSize(width: infoBarGridSizeSlider.integerValue, height: infoBarGridSizeSlider.integerValue); groupCollectionView.maxItemSize = NSSize(width: infoBarGridSizeSlider.integerValue + 100, height: infoBarGridSizeSlider.integerValue + 100); } // The button in the titlebar that lets us add manga @IBOutlet weak var titlebarAddMangaButton: NSButton! // When we click titlebarAddMangaButton... @IBAction func titlebarAddMangaButtonInteracted(_ sender: AnyObject) { // Show the add / import popover showAddImportPopover(titlebarAddMangaButton.bounds, preferredEdge: NSRectEdge.maxY, fileUrls: []); } /// The segmented control in the titlebar that allows sorting the manga grid @IBOutlet weak var titlebarSortingSegmentedControl: NSSegmentedControl! /// Called when the selected item in `titlebarSortingSegmentedControl` is changed @IBAction func titlebarSortingSegmentedControlChanged(_ sender : NSSegmentedControl) { // Sort the manga grid mangaGridController.sort(KMMangaGridSortType(rawValue: sender.selectedSegment)!, ascending: Bool(titlebarToggleSortDirectionButton.state as NSNumber)); } /// The button in the titlebar that lets us toggle between list and grid view @IBOutlet var titlebarToggleListViewCheckbox: NSButton! /// When we interact with titlebarToggleListViewCheckbox... @IBAction func titlebarToggleListViewCheckboxAction(_ sender: AnyObject) { // Toggle the view we are in(List or grid) toggleView(); } /// The button group for saying how the group view items should group @IBOutlet var titlebarGroupViewTypeSelectionSegmentedControl: NSSegmentedControl! /// When we interact with titlebarGroupViewTypeSelectionSegmentedControl... @IBAction func titlebarGroupViewTypeSelectionSegmentedControlInteracted(_ sender: AnyObject) { // Update the group view to show the now selected group type updateGroupViewToSegmentedControl(); } /// The text field in the titlebar for searching in the group view @IBOutlet var titlebarGroupViewSearchField: KMAlwaysActiveTextField! /// When we interact with titlebarGroupViewSearchField... @IBAction func titlebarGroupViewSearchFieldInteracted(_ sender: AnyObject) { // Search for the entered text mangaGroupController.searchFor(titlebarGroupViewSearchField.stringValue); } // Called when we hit "Add" in the addmanga popover func addMangaFromAddMangaPopover(_ notification: Notification) { // Print to the log that we are adding from the add popover print("ViewController: Adding from the add popover..."); // If we were passed an array of manga... if((notification.object as? [KMManga]) != nil) { // Print to the log that we are batch adding print("ViewController: Batch adding manga"); // For every manga in the notifications manga array... for (_, currentManga) in ((notification.object as? [KMManga])?.enumerated())! { // Add the current manga to the grid mangaGridController.addManga(currentManga, updateFilters: false); } // Create the new notification to tell the user the import has finished let finishedImportNotification = NSUserNotification(); // Set the title finishedImportNotification.title = "Komikan"; // Set the informative text finishedImportNotification.informativeText = "Finished importing \"" + (notification.object as? [KMManga])![0].series + "\""; // Set the notifications identifier to be an obscure string, so we can show multiple at once finishedImportNotification.identifier = UUID().uuidString; // Deliver the notification NSUserNotificationCenter.default.deliver(finishedImportNotification); // Reload the filters mangaGridController.updateFilters(); } else { // Print to the log that we have recieved it and its name print("ViewController: Recieving manga \"" + ((notification.object as? KMManga)?.title)! + "\" from Add Manga popover"); // Add the manga to the grid, and store the item in a new variable mangaGridController.addManga((notification.object as? KMManga)!, updateFilters: true); } // Stop addMangaViewController.addButtonUpdateLoop, so it stops eating resources when it doesnt need to addMangaViewController?.addButtonUpdateLoop.invalidate(); // If we are in group view... if(groupViewOpen) { // Update the group view updateGroupViewToSegmentedControl(); } // Resort the manga grid mangaGridController.resort(); } override func viewDidLoad() { super.viewDidLoad(); // Style the window to be fancy styleWindow(); // Hide the window so we dont see any ugly loading "artifacts" window.alphaValue = 0; // Set the collections views item prototype to the collection view item we created in Main.storyboard mangaCollectionView.itemPrototype = storyboard?.instantiateController(withIdentifier: "mangaCollectionViewItem") as? NSCollectionViewItem; // Set the group collection view's item prototype groupCollectionView.itemPrototype = storyboard?.instantiateController(withIdentifier: "groupCollectionViewItem") as? NSCollectionViewItem; // Set the min and max item size for the manga grid mangaCollectionView.minItemSize = NSSize(width: 200, height: 200); mangaCollectionView.maxItemSize = NSSize(width: 300, height: 300); // Set the max and min item sizes for the group grid groupCollectionView.minItemSize = NSSize(width: 200, height: 200); groupCollectionView.maxItemSize = NSSize(width: 300, height: 300); // Set the addFromEHMenuItem menu items action (NSApplication.shared().delegate as! AppDelegate).addFromEHMenuItem.action = #selector(ViewController.showAddFromEHPopover); // Set the toggle info bar menu items action (NSApplication.shared().delegate as! AppDelegate).toggleInfoBarMenuItem.action = #selector(ViewController.toggleInfoBar); // Set the delete selected manga menu items action (NSApplication.shared().delegate as! AppDelegate).deleteSelectedMangaMenuItem.action = #selector(ViewController.removeSelectedItemsFromMangaGrid); // Set the mark selected manga as read menu items action (NSApplication.shared().delegate as! AppDelegate).markSelectedAsReadMenuItem.action = #selector(ViewController.markSelectedItemsAsRead); // Set the mark selected manga as unread menu items action (NSApplication.shared().delegate as! AppDelegate).markSelectedAsUnreadMenuItem.action = #selector(ViewController.markSelectedItemsAsUnread); // Set the delete all manga menubar items action (NSApplication.shared().delegate as? AppDelegate)?.deleteAllMangaMenuItem.action = #selector(ViewController.deleteAllManga); // Set the add / import manga menubar items action (NSApplication.shared().delegate as? AppDelegate)?.importAddMenuItem.action = #selector(ViewController.showAddImportPopoverMenuItem); // Set the set selected items properties menubar items action (NSApplication.shared().delegate as? AppDelegate)?.setSelectedItemsPropertiesMenuItems.action = #selector(ViewController.showSetSelectedItemsPropertiesPopover); // Set the export manga JSON menubar items action (NSApplication.shared().delegate as? AppDelegate)?.exportJsonForAllMangaMenuItem.action = #selector(ViewController.exportMangaJSONForSelected); // Set the export manga JSON for migration menubar items action (NSApplication.shared().delegate as? AppDelegate)?.exportJsonForAllMangaForMigrationMenuItem.action = #selector(ViewController.exportMangaJSONForSelectedForMigration); // Set the fetch metadata for selected menubar items action (NSApplication.shared().delegate as? AppDelegate)?.fetchMetadataForSelectedMenuItem.action = #selector(ViewController.showFetchMetadataForSelectedItemsPopoverAtCenter); // Set the import menubar items action (NSApplication.shared().delegate as? AppDelegate)?.importMenuItem.action = #selector(ViewController.importMigrationFolder); // Set the toggle list view menubar items action (NSApplication.shared().delegate as? AppDelegate)?.toggleListViewMenuItem.action = #selector(ViewController.toggleView); // Set the open menubar items action (NSApplication.shared().delegate as? AppDelegate)?.openMenuItem.action = #selector(ViewController.openSelectedManga); // Set the select search field menubar items action (NSApplication.shared().delegate as? AppDelegate)?.selectSearchFieldMenuItem.action = #selector(ViewController.selectSearchField); // Set the edit selected menubar items action (NSApplication.shared().delegate as? AppDelegate)?.editSelectedMenuItem.action = #selector(ViewController.openEditPopoverForSelected); // Set the select manga view menubar items action (NSApplication.shared().delegate as? AppDelegate)?.selectMangaViewMenuItem.action = #selector(ViewController.selectMangaView); // Set the hide and show Komikan folders menubar items actions (NSApplication.shared().delegate as? AppDelegate)?.hideKomikanFoldersMenuItem.action = #selector(ViewController.hideKomikanMetadataFolders); (NSApplication.shared().delegate as? AppDelegate)?.showKomikanFoldersMenuItem.action = #selector(ViewController.showKomikanMetadataFolders); // Set the toggle group view menubar items action (NSApplication.shared().delegate as? AppDelegate)?.toggleGroupViewMenuItem.action = #selector(ViewController.toggleGroupView); // Set the AppDelegate's manga grid controller (NSApplication.shared().delegate as! AppDelegate).mangaGridController = mangaGridController; // Set the AppDelegate's search text field (NSApplication.shared().delegate as! AppDelegate).searchTextField = titlebarSearchField; // Set the AppDelegate's main view controller (NSApplication.shared().delegate as! AppDelegate).mainViewController = self; // Load the manga we had in the grid loadManga(); // Do application initialization (NSApplication.shared().delegate as! AppDelegate).initialize(); // Scroll to the top of the manga grid mangaCollectionViewScrollView.pageUp(self); // Init the thumbnail image hover controller thumbnailImageHoverController.styleWindow(); // Set the main windows delegate to this window.delegate = self; // Sort the manga grid mangaGridController.sort(KMMangaGridSortType(rawValue: titlebarSortingSegmentedControl.selectedSegment)!, ascending: Bool(titlebarToggleSortDirectionButton.state as NSNumber)); // Subscribe to the magnify event NSEvent.addLocalMonitorForEvents(matching: NSEventMask.magnify, handler: magnifyEvent); // Create some options for the manga grid KVO let options = NSKeyValueObservingOptions([.new, .old, .initial, .prior]); // Subscribe to when the manga grid changes its values in any way mangaGridController.arrayController.addObserver(self, forKeyPath: "arrangedObjects", options: options, context: nil); // Show the window after 0.1 seconds, so we dont get loading artifacts Timer.scheduledTimer(timeInterval: TimeInterval(0.1), target: self, selector: #selector(ViewController.showWindowAlpha), userInfo: nil, repeats: false); // Subscribe to the edit manga popovers remove notification NotificationCenter.default.addObserver(self, selector: #selector(ViewController.removeSelectItemFromMangaGrid(_:)), name:NSNotification.Name(rawValue: "KMEditMangaViewController.Remove"), object: nil); // Subscribe to the global redraw manga grid notification NotificationCenter.default.addObserver(self, selector: #selector(ViewController.updateMangaGrid), name:NSNotification.Name(rawValue: "ViewController.UpdateMangaGrid"), object: nil); // Subscribe to the global application will quit notification NotificationCenter.default.addObserver(self, selector: #selector(ViewController.saveManga), name:NSNotification.Name(rawValue: "Application.WillQuit"), object: nil); // Subscribe to the global application will quit notification with the manga grid scale NotificationCenter.default.addObserver(self, selector: #selector(ViewController.saveMangaGridScale), name:NSNotification.Name(rawValue: "Application.WillQuit"), object: nil); // Subscribe to the Drag and Drop add / import notification NotificationCenter.default.addObserver(self, selector: #selector(ViewController.showAddImportPopoverDragAndDrop(_:)), name:NSNotification.Name(rawValue: "MangaGrid.DropFiles"), object: nil); } override func viewWillAppear() { super.viewWillAppear(); // Switch on the default screen and act appropriately switch((NSApplication.shared().delegate as! AppDelegate).preferences.defaultScreen) { case 0: displayGridView(); break; case 1: displayListView(); break; case 2: showGroupView(); break; default: break; } // Load the preference values loadPreferenceValues(); } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { // If the keyPath is the one for the manga grids arranged objets... if(keyPath == "arrangedObjects") { // Update the manga count in the info bar updateInfoBarMangaCountLabel(); // Reload the manga table so it gets updated when items change mangaListController.mangaListTableView.reloadData(); } } /// Deselects all the items in the list/grid, depending on which we are in func clearMangaSelection() { // If we are in list view... if(inListView) { // Deselect all the items in the list mangaTableView.deselectAll(self); } // If we are in grid view... else { // Deselect all the items in the grid mangaCollectionView.deselectAll(self); } } /// The grid selection stored by storeCurrentSelection var storedGridSelection : IndexSet = IndexSet(); /// The list selection stored by storeCurrentSelection var storedListSelection : IndexSet = IndexSet(); /// The grid scroll point stored by storeCurrentSelection var storedGridScrollPoint : NSPoint = NSPoint(); /// The list scroll point stored by storeCurrentSelection var storedListScrollPoint : NSPoint = NSPoint(); /// Restores the selection that was stored by storeCurrentSelection func restoreSelection() { // If we are in list view... if(inListView) { // Restore the selection mangaTableView.selectRowIndexes(storedListSelection, byExtendingSelection: false); // Restore the scroll position mangaTableViewScrollView.contentView.scroll(to: storedListScrollPoint); } // If we are in grid view... else { // Restore the selection mangaCollectionView.selectionIndexes = storedGridSelection; // Restore the scroll position mangaCollectionViewScrollView.contentView.scroll(to: storedGridScrollPoint); } } /// Stores the current selection in the grid/list, to be called later by restoreSelection func storeCurrentSelection() { // Store the scroll point for the grid storedGridScrollPoint = mangaCollectionViewScrollView.contentView.bounds.origin; // Store the selection for the grid storedGridSelection = mangaCollectionView.selectionIndexes; // Store the scroll point for the list storedListScrollPoint = mangaTableViewScrollView.contentView.bounds.origin; // Store the selection for the list storedListSelection = mangaTableView.selectedRowIndexes; } /// Selects titlebarGroupViewSearchField func selectGroupViewSearchField() { // Make titlebarGroupViewSearchField the first responder window.makeFirstResponder(titlebarGroupViewSearchField); } /// Shows the selected group in the group view's manga func openSelectedGroupItem() { /// Display the manga for the selected item (groupCollectionView.item(at: groupCollectionView.selectionIndexes.first!) as! KMMangaGroupCollectionItem).displayManga(); } /// Updates the group view to match the selected cell in titlebarGroupViewTypeSelectionSegmentedControl func updateGroupViewToSegmentedControl() { // Switch on the selected segment, no comments(Its pretty obvious what it's doing) switch(titlebarGroupViewTypeSelectionSegmentedControl.selectedSegment) { case 0: mangaGroupController.showGroupType(.series); break; case 1: mangaGroupController.showGroupType(.artist); break; case 2: mangaGroupController.showGroupType(.writer); break; case 3: mangaGroupController.showGroupType(.group); break; default: mangaGroupController.showGroupType(.series); break; } // Scroll to the top of the group view(Content insets make it so when you add items they are under the titlebar, this fixes that) groupCollectionViewScrollView.pageUp(self); } /// Is the group view open? var groupViewOpen : Bool = false; /// Toggles if the group view is open func toggleGroupView() { // Toggle groupViewOpen groupViewOpen = !groupViewOpen; // If the group view should now be open... if(groupViewOpen) { // Show the group showGroupView(); } // If the group view should now be closed... else { // Hide the group view hideGroupView(); } } /// Shows the group view func showGroupView() { // Say the group view is open groupViewOpen = true; // Update the items in the group view updateGroupViewToSegmentedControl(); // Show the group view groupCollectionViewScrollView.isHidden = false; // Select the group view self.window.makeFirstResponder(groupCollectionViewScrollView); // If we are in list view... if(inListView) { // Hide the list view mangaTableViewScrollView.isHidden = true; // Hide any possible hover thumbnails thumbnailImageHoverController.hide(); } // If we are in grid view... else { // Hide the grid view mangaCollectionViewScrollView.isHidden = true; } // Disable/enable titlebarGroupViewSearchField.isEnabled = true; titlebarSearchField.isEnabled = false; titlebarToggleListViewCheckbox.isEnabled = false; if(!inListView) { titlebarSortingSegmentedControl.isEnabled = false; titlebarToggleSortDirectionButton.isEnabled = false; } // Fade out/hide titlebarToggleListViewCheckbox.animator().alphaValue = 0; titlebarAddMangaButton.animator().alphaValue = 0; if(!inListView) { titlebarSortingSegmentedControl.animator().alphaValue = 0; titlebarToggleSortDirectionButton.animator().alphaValue = 0; } titlebarGroupViewSearchField.isHidden = false; titlebarSearchField.isHidden = true; // Fade in titlebarGroupViewTypeSelectionSegmentedControl.isEnabled = true; titlebarGroupViewTypeSelectionSegmentedControl.animator().alphaValue = 1; // Menubar actions (NSApplication.shared().delegate as? AppDelegate)?.selectSearchFieldMenuItem.action = #selector(ViewController.selectGroupViewSearchField); (NSApplication.shared().delegate as? AppDelegate)?.openMenuItem.action = #selector(ViewController.openSelectedGroupItem); } /// Hides the group view func hideGroupView() { // Say the group view is closed groupViewOpen = false; // Hide the group view groupCollectionViewScrollView.isHidden = true; // If we are in list view... if(inListView) { // Show the list view mangaTableViewScrollView.isHidden = false; // Select the list view self.window.makeFirstResponder(mangaTableView); } // If we are in grid view... else { // Show the grid view mangaCollectionViewScrollView.isHidden = false; // Select the grid view self.window.makeFirstResponder(mangaCollectionView); } // Disable/enable titlebarGroupViewSearchField.isEnabled = false; titlebarGroupViewTypeSelectionSegmentedControl.isEnabled = false; titlebarSearchField.isEnabled = true; titlebarToggleListViewCheckbox.isEnabled = true; if(!inListView) { titlebarSortingSegmentedControl.isEnabled = true; titlebarToggleSortDirectionButton.isEnabled = true; } // Fade out/hide titlebarToggleListViewCheckbox.animator().alphaValue = 1; titlebarAddMangaButton.animator().alphaValue = 1; titlebarGroupViewTypeSelectionSegmentedControl.animator().alphaValue = 0; if(!inListView) { titlebarSortingSegmentedControl.animator().alphaValue = 1; titlebarToggleSortDirectionButton.animator().alphaValue = 1; } titlebarGroupViewSearchField.isHidden = true; titlebarSearchField.isHidden = false; // Fade in titlebarToggleListViewCheckbox.animator().alphaValue = 1; titlebarAddMangaButton.animator().alphaValue = 1; // Menubar actions (NSApplication.shared().delegate as? AppDelegate)?.selectSearchFieldMenuItem.action = #selector(ViewController.selectSearchField); (NSApplication.shared().delegate as? AppDelegate)?.openMenuItem.action = #selector(ViewController.openSelectedManga); } /// Asks the user for a folder, then hides all the Komikan metadata folders in that folder and it's subfolders func hideKomikanMetadataFolders() { /// The open panel for asking the user which folder to hide Komikan folders in let hideOpenPanel : NSOpenPanel = NSOpenPanel(); // Dont allow any files to be selected hideOpenPanel.allowedFileTypes = [""]; // Allow folders to be selected hideOpenPanel.canChooseDirectories = true; // Set the prompt hideOpenPanel.prompt = "Select"; // Run the modal, and if they clicked "Select"... if(Bool(hideOpenPanel.runModal() as NSNumber)) { /// The path to the folder we want to hide Komikan folders in let hideFolderPath : String = hideOpenPanel.url!.absoluteString.removingPercentEncoding!.replacingOccurrences(of: "file://", with: ""); /// The file enumerator for the folder we want to hide Komikan folders in let hideFolderFileEnumerator : FileManager.DirectoryEnumerator = FileManager.default.enumerator(atPath: hideFolderPath)!; // For every file in the folder we want to hide Komikan folders in... for(_, currentFile) in hideFolderFileEnumerator.enumerated() { // If the current file is a folder... if(NSString(string: hideFolderPath + String(describing: currentFile)).pathExtension == "") { // If the current file's name is "Komikan"... if(NSString(string: hideFolderPath + String(describing: currentFile)).lastPathComponent == "Komikan") { // Hide the current folder _ = KMCommandUtilities().runCommand("/usr/bin/chflags", arguments: ["hidden", hideFolderPath + String(describing: currentFile)], waitUntilExit: true); } } } } } /// Asks the user for a folder, then shows all the Komikan metadata folders in that folder and it's subfolders func showKomikanMetadataFolders() { /// The open panel for asking the user which folder to show Komikan folders in let showOpenPanel : NSOpenPanel = NSOpenPanel(); // Dont allow any files to be selected showOpenPanel.allowedFileTypes = [""]; // Allow folders to be selected showOpenPanel.canChooseDirectories = true; // Set the prompt showOpenPanel.prompt = "Select"; // Run the modal, and if they clicked "Select"... if(Bool(showOpenPanel.runModal() as NSNumber)) { /// The path to the folder we want to show Komikan folders in let showFolderPath : String = showOpenPanel.url!.absoluteString.removingPercentEncoding!.replacingOccurrences(of: "file://", with: ""); /// The file enumerator for the folder we want to show Komikan folders in let showFolderFileEnumerator : FileManager.DirectoryEnumerator = FileManager.default.enumerator(atPath: showFolderPath)!; // For every file in the folder we want to show Komikan folders in... for(_, currentFile) in showFolderFileEnumerator.enumerated() { // If the current file is a folder... if(NSString(string: showFolderPath + String(describing: currentFile)).pathExtension == "") { // If the current file's name is "Komikan"... if(NSString(string: showFolderPath + String(describing: currentFile)).lastPathComponent == "Komikan") { // Show the current folder _ = KMCommandUtilities().runCommand("/usr/bin/chflags", arguments: ["nohidden", showFolderPath + String(describing: currentFile)], waitUntilExit: true); } } } } } /// Prompts the user for a folder to import from migration, and then imports them. func importMigrationFolder() { /// The open panel for asking the user which folder to import let importOpenPanel : NSOpenPanel = NSOpenPanel(); // Dont allow any single files to be selected importOpenPanel.allowedFileTypes = [""]; // Allow folders to be selected importOpenPanel.canChooseDirectories = true; // Set the prompt importOpenPanel.prompt = "Import"; // Run the modal, and if they click "Choose".... if(Bool(importOpenPanel.runModal() as NSNumber)) { /// The path to the folder the user said to import let importFolderPath : String = (importOpenPanel.url!.absoluteString.removingPercentEncoding?.replacingOccurrences(of: "file://", with: ""))!; /// The migration importer we will use let migrationImporter : KMMigrationImporter = KMMigrationImporter(); // Set the migration importer's manga grid controller migrationImporter.mangaGridController = mangaGridController; // Tell the migration importer to import the chosen folder migrationImporter.importFolder(importFolderPath); } } /// Selects the manga list/grid func selectMangaView() { // If we are in list view... if(inListView) { // Make the manga list the first responder window.makeFirstResponder(mangaTableView); } // If we are in grid view... else { // Make the manga grid the first responder window.makeFirstResponder(mangaCollectionView); } } /// Opens the edit popover for the selected manga items func openEditPopoverForSelected() { /// The index of the item we want to open the edit popover for(The first index in the selection indexes) let indexToPopover : Int = selectedItemIndexes().first!; // If we are in list view... if(inListView) { // Deselect all the list items mangaListController.mangaListTableView.deselectAll(self); // Select the one we wanted to popover mangaListController.mangaListTableView.selectRowIndexes(IndexSet(integer: indexToPopover), byExtendingSelection: false); // Open the popover for the selected item mangaListController.openPopover(false, manga: mangaListController.selectedManga()); } // If we are in grid view... else { // Deselect all the grid items mangaCollectionView.deselectAll(self); // Select the item at indexToPopover mangaCollectionView.item(at: indexToPopover)?.isSelected = true; // Open the popover for the item at indexToPopover (mangaCollectionView.item(at: indexToPopover) as! KMMangaGridCollectionItem).openPopover(false); } } /// Opens the selected manga in the reader(If in list view it selects the first one and opens that) func openSelectedManga() { // If we are in list view... if(inListView) { // Open the first selected manga mangaListController.openManga(); } // If we are in grid view... else { // For every selection index... for(_, currentSelectionIndex) in selectedItemIndexes().enumerated() { // Get the KMMangaGridCollectionItem at the current selection index and open it in the reader (mangaCollectionView.item(at: currentSelectionIndex) as? KMMangaGridCollectionItem)!.openManga(); } } } /// Makes the search field frontmost func selectSearchField() { // Make the search field frontmost window.makeFirstResponder(titlebarSearchField); } /// Are we in list view? var inListView : Bool = false; /// The sort descriptors that were in the manga grid before we switched to table view var oldGridSortDescriptors : [NSSortDescriptor] = []; /// Toggles between list and grid view func toggleView() { // If the group view isn't open... if(!groupViewOpen) { // Toggle in list view inListView = !inListView; // If we are now in list view... if(inListView) { // Display list view displayListView(); } // If we are now in grid view... else { // Display grid view displayGridView(); } } } /// Switches from the grid view to the table view func displayListView() { // Print to the log that we are going into list view print("ViewController: Switching to list view"); // Say we are in list view inListView = true; // Store the current sort descriptors oldGridSortDescriptors = mangaGridController.arrayController.sortDescriptors; // Change the toggle list view button to show the list icon titlebarToggleListViewCheckbox.state = 1; // Deselect all the items in the list mangaTableView.deselectAll(self); // Select every item in the list that we had selected in the grid mangaTableView.selectRowIndexes(mangaCollectionView.selectionIndexes, byExtendingSelection: false); // Deselect all the items in the grid mangaCollectionView.deselectAll(self); // Redraw the table view graphically so we dont get artifacts mangaTableViewScrollView.needsDisplay = true; mangaTableView.needsDisplay = true; // Show the list view mangaTableViewScrollView.isHidden = false; // Hide the grid view mangaCollectionViewScrollView.isHidden = true; // Hide the group search field titlebarGroupViewSearchField.isHidden = true; titlebarGroupViewSearchField.isEnabled = false; // Hide the group view tabs titlebarGroupViewTypeSelectionSegmentedControl.isEnabled = false; titlebarGroupViewTypeSelectionSegmentedControl.alphaValue = 0; // Hide the thumbnail window thumbnailImageHoverController.hide(); // Fade out the manga grid only titlebar items titlebarSortingSegmentedControl.animator().alphaValue = 0; titlebarToggleSortDirectionButton.animator().alphaValue = 0; // Select the list view window.makeFirstResponder(mangaListController.mangaListTableView); } /// Switches from the table view to the grid view func displayGridView() { // Print to the log that we are going into grid view print("ViewController: Switching to grid view"); hideGroupView(); // Say we arent in list view inListView = false; // Restore the old sort descriptors mangaGridController.arrayController.sortDescriptors = oldGridSortDescriptors; // Change the toggle list view button to show the grid icon titlebarToggleListViewCheckbox.state = 0; // Deselect all the items in the grid mangaCollectionView.deselectAll(self); // For every selected index in the list... for(_, currentIndexSet) in mangaTableView.selectedRowIndexes.enumerated() { // Select the item at the given index in the grid mangaCollectionView.item(at: currentIndexSet)?.isSelected = true; } // Deselect all the items in the list mangaTableView.deselectAll(self); // Redraw the grid view graphically so we dont get artifacts mangaCollectionView.needsDisplay = true; mangaCollectionViewScrollView.needsDisplay = true; // Hide the list view mangaTableViewScrollView.isHidden = true; // Show the grid view mangaCollectionViewScrollView.isHidden = false; // Hide the group search field titlebarGroupViewSearchField.isHidden = true; titlebarGroupViewSearchField.isEnabled = false; // Hide the group view tabs titlebarGroupViewTypeSelectionSegmentedControl.isEnabled = false; titlebarGroupViewTypeSelectionSegmentedControl.alphaValue = 0; // Hide the thumbnail window thumbnailImageHoverController.hide(); // Fade in the manga grid only titlebar items titlebarSortingSegmentedControl.animator().alphaValue = 1; titlebarToggleSortDirectionButton.animator().alphaValue = 1; // Select the grid view window.makeFirstResponder(mangaCollectionView); } /// Returns the indexes of the selected manga items func selectedItemIndexes() -> IndexSet { /// The indexes of the selected manga items var selectionIndexes : IndexSet = IndexSet(); // If we are in list view... if(inListView) { // Set selection indexes to the manga lists selected rows selectionIndexes = mangaTableView.selectedRowIndexes; } // If we are in grid view... else { // Set selection indexes to the manga grids selection indexes selectionIndexes = mangaCollectionView.selectionIndexes; } // Return the selection indexes return selectionIndexes; } /// Returns the count of how many manga items we have selected func selectedItemCount() -> Int { /// The amount of selected items var selectedCount : Int = 0; // If we are in list view... if(inListView) { // Set selected count to the amount of selected rows in the manga list selectedCount = mangaTableView.selectedRowIndexes.count; } // If we are in grid view... else { // Set selected count to the amount of selected items in the manga grid selectedCount = mangaCollectionView.selectionIndexes.count; } // Return the selected count return selectedCount; } /// Returns the selected KMMangaGridItem manga item func selectedGridItems() -> [KMMangaGridItem] { /// The selected KMMangaGridItem from the manga grid var selectedGridItems : [KMMangaGridItem] = []; // For every selection index of the manga grid... for(_, currentIndex) in selectedItemIndexes().enumerated() { // Add the item at the set index to the selected items selectedGridItems.append((mangaGridController.arrayController.arrangedObjects as? [KMMangaGridItem])![currentIndex]); } // Return the selected grid items return selectedGridItems; } /// Returns the KMManga of the selected KMMangaGridItem manga item func selectedGridItemManga() -> [KMManga] { /// The selected KMManga from the manga grid var selectedManga : [KMManga] = []; // For every item in the selected grid items... for(_, currentGridItem) in selectedGridItems().enumerated() { // Add the current grid item's manga to the selected manga selectedManga.append(currentGridItem.manga); } // Return the selected manga return selectedManga; } /// Called when the user does a magnify gesture on the trackpad func magnifyEvent(_ event : NSEvent) -> NSEvent { // Add the magnification amount to the grid size slider infoBarGridSizeSlider.floatValue += Float(event.magnification); // Update the grid scale infoBarGridSizeSliderInteracted(infoBarGridSizeSlider); // Return the event return event; } /// Called after AppDelegate has loaded the preferences from the preferences file func loadPreferenceValues() { // Load the manga grid scale infoBarGridSizeSlider.integerValue = (NSApplication.shared().delegate as! AppDelegate).preferences.mangaGridScale; // Update the grid size with the grid size slider infoBarGridSizeSliderInteracted(infoBarGridSizeSlider); } /// Saves the scale of the manga grid func saveMangaGridScale() { // Save the manga grid scale into AppDelegate (NSApplication.shared().delegate as! AppDelegate).preferences.mangaGridScale = infoBarGridSizeSlider.integerValue; } /// Exports JSON for all the selected manga in the grid without internal information func exportMangaJSONForSelected() { // Print to the log that we are exporting metadata for selected manga print("ViewController: Exporting JSON metadata for selected manga"); /// The selected KMManga in the grid let selectedManga : [KMManga] = selectedGridItemManga(); // For every selected manga... for(_, currentManga) in selectedManga.enumerated() { // Export the current manga's JSON KMFileUtilities().exportMangaJSON(currentManga, exportInternalInfo: false); } // Create the new notification to tell the user the Metadata exporting has finished let finishedNotification = NSUserNotification(); // Set the title finishedNotification.title = "Komikan"; // Set the informative text finishedNotification.informativeText = "Finshed exporting Metadata"; // Set the notifications identifier to be an obscure string, so we can show multiple at once finishedNotification.identifier = UUID().uuidString; // Deliver the notification NSUserNotificationCenter.default.deliver(finishedNotification); } /// Exports the internal JSON for the selected manga items(Meant for when the user switches computers or something and wants to keep metadata) func exportMangaJSONForSelectedForMigration() { // For every selected manga item... for(_, currentGridItem) in selectedGridItems().enumerated() { // Export this items manga's info KMFileUtilities().exportMangaJSON(currentGridItem.manga, exportInternalInfo: true); } // Create the new notification to tell the user the Metadata exporting has finished let finishedNotification = NSUserNotification(); // Set the title finishedNotification.title = "Komikan"; // Set the informative text finishedNotification.informativeText = "Finshed exporting Metadata"; // Set the notifications identifier to be an obscure string, so we can show multiple at once finishedNotification.identifier = UUID().uuidString; // Deliver the notification NSUserNotificationCenter.default.deliver(finishedNotification); } /// The view controller that will load for the metadata fetching popover var fetchMetadataViewController: KMMetadataFetcherViewController? // Is this the first time opened the fetch metadata popover? var fetchMetadataViewFirstLoad : Bool = true; /// Shows the fetch metadata popover at the given rect on the given side func showFetchMetadataForSelectedItemsPopover(_ relativeToRect: NSRect, preferredEdge: NSRectEdge) { // If there are any selected manga... if(selectedItemCount() != 0) { // Get the main storyboard let storyboard = NSStoryboard(name: "Main", bundle: nil); // Instanstiate the view controller for the fetch metadata popover fetchMetadataViewController = storyboard.instantiateController(withIdentifier: "metadataFetcherViewController") as? KMMetadataFetcherViewController; // Set the fetch metadata popover's selected manga fetchMetadataViewController?.selectedMangaGridItems = selectedGridItems(); // Present the fetchMetadataViewController as a popover at the given relative rect on the given preferred edge fetchMetadataViewController!.presentViewController(fetchMetadataViewController!, asPopoverRelativeTo: relativeToRect, of: backgroundVisualEffectView, preferredEdge: preferredEdge, behavior: NSPopoverBehavior.transient); // If this is the first time we have opened the popover... if(fetchMetadataViewFirstLoad) { // Subscribe to the popovers finished notification NotificationCenter.default.addObserver(self, selector: #selector(ViewController.fetchMetadataForSelectedItemsPopoverFinished(_:)), name:NSNotification.Name(rawValue: "KMMetadataFetcherViewController.Finished"), object: nil); // Say that all the next loads are not the first fetchMetadataViewFirstLoad = false; } } } /// Calls showFetchMetadataForSelectedItemsPopover so it opens in the center func showFetchMetadataForSelectedItemsPopoverAtCenter() { // Show the fetch metadata popover in the center of the window with the arrow pointing down showFetchMetadataForSelectedItemsPopover(NSRect(x: 0, y: 0, width: window.contentView!.bounds.width, height: window.contentView!.bounds.height / 2), preferredEdge: NSRectEdge.maxY); } /// Called when the fetch metadata for selected manga popover is done func fetchMetadataForSelectedItemsPopoverFinished(_ notification : Notification) { // Update the manga updateMangaGrid(); // Reload the manga list mangaTableView.reloadData(); } /// The view controller we will load for the popover that lets us set the selected items properties(Artist, Group, ETC.) var setSelectedItemsPropertiesViewController: KMSetSelectedItemsPropertiesViewController? // Is this the first time opened the set selected items properties popover? var setSelectedItemsPropertiesViewFirstLoad : Bool = true; /// Shows the set selected items properties popover func showSetSelectedItemsPropertiesPopover() { // If there are any selected manga... if(selectedItemCount() != 0) { // Get the main storyboard let storyboard = NSStoryboard(name: "Main", bundle: nil); // Instanstiate the view controller for the set selected items properties popover setSelectedItemsPropertiesViewController = storyboard.instantiateController(withIdentifier: "setSelectedItemsPropertiesViewController") as? KMSetSelectedItemsPropertiesViewController; // Present the setSelectedItemsPropertiesViewController as a popover so it is in the center of the window and the arrow is pointing down setSelectedItemsPropertiesViewController!.presentViewController(setSelectedItemsPropertiesViewController!, asPopoverRelativeTo: NSRect(x: 0, y: 0, width: window.contentView!.bounds.width, height: window.contentView!.bounds.height / 2), of: backgroundVisualEffectView, preferredEdge: NSRectEdge.maxY, behavior: NSPopoverBehavior.transient); // If this is the first time we have opened the popover... if(setSelectedItemsPropertiesViewFirstLoad) { // Subscribe to the popovers finished notification NotificationCenter.default.addObserver(self, selector: #selector(ViewController.setSelectedItemsProperties(_:)), name:NSNotification.Name(rawValue: "KMSetSelectedItemsPropertiesViewController.Finished"), object: nil); // Say that all the next loads are not the first setSelectedItemsPropertiesViewFirstLoad = false; } } } /// Called by the set selected items properties popover to apply the given values to the selected items func setSelectedItemsProperties(_ notification : Notification) { // Print to the log thatr we are setting the selected items properties print("ViewController: Setting selected items properties to properties from popover"); /// The manga grid items that we want to set properties of let selectionItemsToSetProperties : [KMMangaGridItem] = selectedGridItems(); // Get the notification object as a KMSetSelectedPropertiesHolder let propertiesHolder : KMSetSelectedPropertiesHolder = (notification.object as! KMSetSelectedPropertiesHolder); // For every item in the manga grid that we set the properties of... for(_, currentItem) in selectionItemsToSetProperties.enumerated() { // Apply the propertie holders values to the current item propertiesHolder.applyValuesToManga(currentItem.manga); } // Store the selection and scroll position storeCurrentSelection(); // Resort the grid mangaGridController.resort(); // Reload the filters mangaGridController.updateFilters(); // Restore the selection and scroll position restoreSelection(); // Clear the selection clearMangaSelection(); } /// Shows the add / import popover, without passing variables for the menu item func showAddImportPopoverMenuItem() { // Show the add / import popover showAddImportPopover(titlebarAddMangaButton.bounds, preferredEdge: NSRectEdge.maxY, fileUrls: []); } /// Shows the add / import popover with the passed notifications object(Should be a list of file URL strings)(Used only by drag and drop import) func showAddImportPopoverDragAndDrop(_ notification : Notification) { /// The file URLs we will pass to the popover var fileUrls : [URL] = []; // For every item in the notifications objects(As a list of strings)... for(_, currentStringURL) in (notification.object as! [String]).enumerated() { /// The NSURL of the current file let currentFileURL : URL = URL(fileURLWithPath: currentStringURL); /// The extension of the current file let currentFileExtension : String = KMFileUtilities().getFileExtension(currentFileURL); // If the extension is supported(CBZ, CBR, ZIP, RAR or Folder)... if(currentFileExtension == "cbz" || currentFileExtension == "cbr" || currentFileExtension == "zip" || currentFileExtension == "rar" || KMFileUtilities().isFolder(currentStringURL)) { // Append the current file URL to the array of files we will pass to the popover fileUrls.append(currentFileURL); } // If the extension is unsupported... else { // Print to the log that it is unsupported and what the extension is print("ViewController: Unsupported file extension \"" + currentFileExtension + "\""); } } // If there were any files that matched the extension... if(fileUrls != []) { // Show the add / import popover under the add button with the file URLs we dragged in showAddImportPopover(titlebarAddMangaButton.bounds, preferredEdge: NSRectEdge.maxY, fileUrls: fileUrls); } } /// Shows the add / import popover with the origin rect as where the arrow comes from, and the preferredEdge as to which side to come from. Also if fileUrls is not [], it will not show the file choosing dialog and go staright to the properties popover with the passed file URLs func showAddImportPopover(_ origin : NSRect, preferredEdge : NSRectEdge, fileUrls : [URL]) { // Get the main storyboard let storyboard = NSStoryboard(name: "Main", bundle: nil); // Instanstiate the view controller for the add manga view controller addMangaViewController = storyboard.instantiateController(withIdentifier: "addMangaViewController") as? KMAddMangaViewController; // Set the add manga view controllers add manga file URLs that we were passed addMangaViewController!.addingMangaURLs = fileUrls; // Present the addMangaViewController as a popover using the add buttons rect, on the max y edge, and with a semitransient behaviour addMangaViewController!.presentViewController(addMangaViewController!, asPopoverRelativeTo: origin, of: titlebarAddMangaButton, preferredEdge: preferredEdge, behavior: NSPopoverBehavior.semitransient); // If this is the first time we have pushed this button... if(addMangaViewFirstLoad) { // Subscribe to the popovers finished notification NotificationCenter.default.addObserver(self, selector: #selector(ViewController.addMangaFromAddMangaPopover(_:)), name:NSNotification.Name(rawValue: "KMAddMangaViewController.Finished"), object: nil); // Say that all the next loads are not the first addMangaViewFirstLoad = false; } } func showWindowAlpha() { // Set the windows alpha value to 1 window.alphaValue = 1; } // When changing the values, it doesnt update right. Call this function to reload it func updateMangaGrid() { // Redraw the collection view to match the updated content mangaCollectionView.itemPrototype = storyboard?.instantiateController(withIdentifier: "mangaCollectionViewItem") as? NSCollectionViewItem; } // The view controller we will load for the add manga popover var addFromEHViewController: KMEHViewController? // Is this the first time weve clicked on the add button in the titlebar? var addFromEHViewFirstLoad : Bool = true; func showAddFromEHPopover() { // Get the main storyboard let storyboard = NSStoryboard(name: "Main", bundle: nil); // Instanstiate the view controller for the add from eh view controller addFromEHViewController = storyboard.instantiateController(withIdentifier: "addFromEHViewController") as? KMEHViewController; // Present the addFromEHViewController as a popover using the add buttons rect, on the max y edge, and with a semitransient behaviour addFromEHViewController!.presentViewController(addFromEHViewController!, asPopoverRelativeTo: titlebarAddMangaButton.bounds, of: titlebarAddMangaButton, preferredEdge: NSRectEdge.maxY, behavior: NSPopoverBehavior.semitransient); // If this is the first time we have opened the popover... if(addFromEHViewFirstLoad) { // Subscribe to the popovers finished notification NotificationCenter.default.addObserver(self, selector: #selector(ViewController.addMangaFromEHPopover(_:)), name:NSNotification.Name(rawValue: "KMEHViewController.Finished"), object: nil); // Say that all the next loads are not the first addFromEHViewFirstLoad = false; } } func addMangaFromEHPopover(_ notification : Notification) { // Print to the log that we are adding a manga from the EH popover print("ViewController: Adding from EH..."); // If we were passed an array of manga... if((notification.object as? [KMManga]) != nil) { /// Print to the log that we are batch adding print("ViewController: Batch adding manga from EH"); // For every manga in the passed manga... for (_, currentManga) in ((notification.object as? [KMManga])?.enumerated())! { // Add the current manga to the grid mangaGridController.addManga(currentManga, updateFilters: false); } // Reload the filters mangaGridController.updateFilters(); } // If we only passed a single manga... else { // Print to the log that we have recieved it and its name print("ViewController: Recieving manga \"" + ((notification.object as? KMManga)?.title)! + "\" from Add From EH Manga popover"); // Add the manga to the grid mangaGridController.addManga((notification.object as? KMManga)!, updateFilters: true); } // Stop the loop so we dont take up precious memory addFromEHViewController?.addButtonUpdateLoop.invalidate(); /// Resort the grid mangaGridController.resort(); // If we are in group view... if(groupViewOpen) { // Update the group view updateGroupViewToSegmentedControl(); } } /// Makes the manga grid the first responder func makeMangaGridFirstResponder() { // Set the manga grid as the first responder window.makeFirstResponder(mangaCollectionView); } // Deletes all the manga in the manga grid array controller func deleteAllManga() { // Remove all the objects from the collection view mangaGridController.removeAllGridItems(true); } // Removes the last selected manga item func removeSelectItemFromMangaGrid(_ notification : Notification) { // Print to the log that we are removing this manga print("ViewController: Removing \"" + (notification.object as? KMManga)!.title + "\" manga item"); // Remove this item from the grid controller mangaGridController.removeGridItem((mangaGridController.arrayController.arrangedObjects as? [KMMangaGridItem])![selectedItemIndexes().last!], resort: true); } /// Removes all the selected manga items(Use this for multiple) func removeSelectedItemsFromMangaGrid() { // Print to the log that we are removing the selected manga items print("ViewController: Removing selected manga items"); /// The manga grid items that we want to remove let selectionItemsToRemove : [KMMangaGridItem] = selectedGridItems(); // For every item in the manga grid items we want to remove... for(_, currentItem) in selectionItemsToRemove.enumerated() { // Remove the curent item from the grid, with resorting mangaGridController.removeGridItem(currentItem, resort: true); } } /// Marks the selected manga items as unread func markSelectedItemsAsUnread() { // Print to the log that we are marking the selected items as unread print("ViewController: Marking selected manga items as unread"); /// The selected manga items that we will mark as read let selectionItemsToMarkAsUnread : [KMMangaGridItem] = selectedGridItems(); // For every manga item that we want to mark as read... for(_, currentItem) in selectionItemsToMarkAsUnread.enumerated() { // Set the current item's manga's current page to 0 so its marked as 0% done currentItem.manga.currentPage = 0; // Update the current manga's percent finished currentItem.manga.updatePercent(); // Update the item's manga currentItem.changeManga(currentItem.manga); } // Save the scroll position and selection storeCurrentSelection(); // Reload the manga list mangaTableView.reloadData(); // Update the grid updateMangaGrid(); // Redo the current search, if we are searching mangaGridController.redoSearch(); // Restore the selection and scroll position restoreSelection(); } /// Marks the selected manga items as read func markSelectedItemsAsRead() { // Print to the log that we are marking the selected manga items as read print("ViewController: Marking selected manga items as read"); /// The selected manga items that we will mark as read let selectionItemsToMarkAsRead : [KMMangaGridItem] = selectedGridItems(); // For every manga item that we want to mark as read... for(_, currentItem) in selectionItemsToMarkAsRead.enumerated() { // Set the current item's manga's current page to the last page, so we get it marked as 100% finished currentItem.manga.currentPage = currentItem.manga.pageCount - 1; // Update the current manga's percent finished currentItem.manga.updatePercent(); // Update the item's manga currentItem.changeManga(currentItem.manga); } // Save the scroll position and selection storeCurrentSelection(); // Reload the manga list mangaTableView.reloadData(); // Update the grid updateMangaGrid(); // Redo the current search, if we are searching mangaGridController.redoSearch(); // Restore the selection and scroll position restoreSelection(); } func toggleInfoBar() { // Set infoBarOpen to the opposite of its current value infoBarOpen = !infoBarOpen; // If the info bar is now open... if(infoBarOpen) { // Enable the grid size slider infoBarGridSizeSlider.isEnabled = true; // Fade it in infoBarContainer.animator().alphaValue = 1; } // If the info bar is now closed... else { // Disable the grid size slider infoBarGridSizeSlider.isEnabled = false; // Fade it out infoBarContainer.animator().alphaValue = 0; } } func styleWindow() { // Get a reference to the main window window = NSApplication.shared().windows.last!; // Set the main window to have a full size content view window.styleMask.insert(NSFullSizeContentViewWindowMask); // Hide the titlebar background window.titlebarAppearsTransparent = true; // Hide the titlebar title window.titleVisibility = NSWindowTitleVisibility.hidden; // Set the background visual effect view to be dark backgroundVisualEffectView.material = NSVisualEffectMaterial.dark; // Set the titlebar visual effect view to be ultra dark if #available(OSX 10.11, *) { titlebarVisualEffectView.material = NSVisualEffectMaterial.ultraDark } else { titlebarVisualEffectView.material = NSVisualEffectMaterial.titlebar }; // Set the info visual effect view to be ultra dark if #available(OSX 10.11, *) { infoBarVisualEffectView.material = NSVisualEffectMaterial.ultraDark } else { infoBarVisualEffectView.material = NSVisualEffectMaterial.titlebar }; // Hide the info bar infoBarContainer.alphaValue = 0; // Disable the grid size slider infoBarGridSizeSlider.isEnabled = false; } func windowDidEnterFullScreen(_ notification: Notification) { // Move the toggle list view button over to the edge titlebarToggleListViewCheckbox.frame.origin = CGPoint(x: 2, y: titlebarToggleListViewCheckbox.frame.origin.y); // Set the appearance back to vibrant dark self.window.appearance = NSAppearance(named: NSAppearanceNameVibrantDark); } func windowWillEnterFullScreen(_ notification: Notification) { // Hide the toolbar so we dont get a grey bar at the top window.toolbar?.isVisible = false; } func windowDidExitFullScreen(_ notification: Notification) { // Show the toolbar again in non-fullscreen(So we still get the traffic lights in the right place) window.toolbar?.isVisible = true; // Move the toggle list view button beside the traffic lights titlebarToggleListViewCheckbox.frame.origin = CGPoint(x: 72, y: titlebarToggleListViewCheckbox.frame.origin.y); // Set the appearance back to aqua self.window.appearance = NSAppearance(named: NSAppearanceNameAqua); } func updateInfoBarMangaCountLabel() { // Set the manga count labels label to the manga count awith "Manga" on the end infoBarMangaCountLabel.stringValue = String(mangaGridController.gridItems.count) + " Manga"; } // Saves the manga in the grid func saveManga() { // Create a NSKeyedArchiver data with the manga grid controllers grid items let data = NSKeyedArchiver.archivedData(withRootObject: mangaGridController.gridItems); // Set the standard user defaults mangaArray key to that data UserDefaults.standard.set(data, forKey: "mangaArray"); // Synchronize the data UserDefaults.standard.synchronize(); } // Load the saved manga back to the grid func loadManga() { // If we have any data to load... if let data = UserDefaults.standard.object(forKey: "mangaArray") as? Data { // For every KMMangaGridItem in the saved manga grids items... for (_, currentManga) in (NSKeyedUnarchiver.unarchiveObject(with: data) as! [KMMangaGridItem]).enumerated() { // Add the current object to the manga grid mangaGridController.addGridItem(currentManga); } } // Update the grid updateMangaGrid(); } func windowDidResignKey(_ notification: Notification) { // Hide the thumbnail hover window thumbnailImageHoverController.hide(); } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
gpl-3.0
b91b6e150937396a0d02a8609827d8fc
44.580167
351
0.653109
5.325459
false
false
false
false
BGDigital/mckuai2.0
mckuai/mckuai/chat/chatViewController.swift
1
5905
// // chatViewController.swift // mckuai // // Created by XingfuQiu on 15/4/21. // Copyright (c) 2015年 XingfuQiu. All rights reserved. // import UIKit class chatViewController: RCChatListViewController, RCIMReceiveMessageDelegate{ class func mainRoot()->UIViewController{ var main = UIStoryboard(name: "chat", bundle: nil).instantiateViewControllerWithIdentifier("chatViewController") as! RCChatListViewController //tabbar main.tabBarItem = UITabBarItem(title: "聊天", image: UIImage(named: "third_normal"), selectedImage: UIImage(named: "third_selected")) return UINavigationController(rootViewController: main) } override func viewDidLoad() { super.viewDidLoad() RCIM.sharedRCIM().setReceiveMessageDelegate(self) customNavBackButton() setUserPortraitClick() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //接收到消息时处理 func didReceivedMessage(message: RCMessage!, left: Int32) { println(left) Async.main({ if left == 0 { MCUtils.RCTabBarItem.badgeValue = RCIM.sharedRCIM().totalUnreadCount > 0 ? "\(RCIM.sharedRCIM().totalUnreadCount)" : nil UIApplication.sharedApplication().applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber+1 } }) } //点击用户头像 func setUserPortraitClick() { RCIM.sharedRCIM().setUserPortraitClickEvent { (_, userInfo) -> Void in if userInfo != nil { if let uId = MCUtils.friends[userInfo.userId] { MCUtils.openOtherZone(self.navigationController, userId: uId.toInt()!, showPop: false) } else { if String(appUserRCID) != userInfo.userId { MCUtils.showCustomHUD("该用户还不在你的背包中,快把他加到背包中吧.", aType: .Warning) } } } } } func customNavBackButton() { self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor(hexString: MCUtils.COLOR_NavBG)) //设置标题颜色 self.setNavigationTitle("聊天", textColor: UIColor.whiteColor()) var back = UIBarButtonItem(image: UIImage(named: "sidemenu"), style: UIBarButtonItemStyle.Bordered, target: self, action: "leftBarButtonItemPressed:") back.tintColor = UIColor.whiteColor() self.navigationItem.leftBarButtonItem = back } override func leftBarButtonItemPressed(sender: AnyObject!) { self.sideMenuViewController.presentLeftMenuViewController() } override func rightBarButtonItemPressed(sender: AnyObject!) { //跳转好友列表界面,可是是融云提供的UI组件,也可以是自己实现的UI var temp: RCSelectPersonViewController = RCSelectPersonViewController() //控制多选 temp.isMultiSelect = true temp.portaitStyle = RCUserAvatarStyle.Cycle var nav = UINavigationController(rootViewController: temp) //导航和的配色保持一直 nav.navigationBar.lt_setBackgroundColor(UIColor(hexString: MCUtils.COLOR_NavBG)) temp.delegate = self self.presentViewController(nav, animated: true, completion: nil) //self.tabBarController?.tabBar.hidden = true } //这个是选择好友来聊天 override func startPrivateChat(userInfo: RCUserInfo!) { if let c: customChatViewController = self.getChatController(userInfo.userId, conversationType: .ConversationType_PRIVATE) as? customChatViewController { self.addChatController(c) c.currentTarget = userInfo.userId c.currentTargetName = userInfo.name c.conversationType = .ConversationType_PRIVATE self.navigationController?.pushViewController(c, animated: true) } else { // var chat = RCChatViewController() var chat = customChatViewController() chat.portraitStyle = .Cycle chat.hidesBottomBarWhenPushed = true chat.currentTarget = userInfo.userId chat.currentTargetName = userInfo.name chat.conversationType = .ConversationType_PRIVATE self.navigationController?.pushViewController(chat, animated: true) } } //这个是在会话列表里面打开 override func onSelectedTableRow(conversation: RCConversation!) { //该方法目的延长会话聊天UI的生命周期 if let c: customChatViewController = self.getChatController(conversation.targetId, conversationType: conversation.conversationType) as? customChatViewController { self.addChatController(c) c.currentTarget = conversation.targetId c.conversationType = conversation.conversationType c.currentTargetName = conversation.conversationTitle self.navigationController?.pushViewController(c, animated: true) } else { var chat = customChatViewController() chat.portraitStyle = .Cycle chat.hidesBottomBarWhenPushed = true chat.currentTarget = conversation.targetId chat.conversationType = conversation.conversationType chat.currentTargetName = conversation.conversationTitle self.navigationController?.pushViewController(chat, animated: true) } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) MobClick.beginLogPageView("chatView") MCUtils.RCTabBarItem.badgeValue = nil } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) MobClick.endLogPageView("chatView") } }
mit
4f33bf0dfa70436ccbf1d2fe96a94a35
40.262774
170
0.661596
4.998232
false
false
false
false
dangquochoi2007/cleancodeswift
CleanStore/CleanStore/App/Scenes/Support/Configurator/SupportConfigurator.swift
1
664
// // SupportConfigurator.swift // CleanStore // // Created by hoi on 27/6/17. // Copyright (c) 2017 hoi. All rights reserved. // import UIKit final class SupportConfigurator { // MARK: - Singleton static let sharedInstance: SupportConfigurator = SupportConfigurator() // MARK: - Configuration func configure(viewController: SupportViewController) { let router = SupportRouter(viewController: viewController) let presenter = SupportPresenter(output: viewController) let interactor = SupportInteractor(output: presenter) viewController.output = interactor viewController.router = router } }
mit
57e4bec2370a39eeedad234264b09d12
21.133333
74
0.700301
4.846715
false
true
false
false
lorentey/swift
test/SILGen/tsan_instrumentation.swift
7
3526
// RUN: %target-swift-emit-silgen -sanitize=thread %s | %FileCheck %s // TSan is only supported on 64 bit. // REQUIRES: PTRSIZE=64 func takesInout(_ p: inout Int) { } func takesInout(_ p: inout MyStruct) { } struct MyStruct { var storedProperty: Int = 77 } class MyClass { var storedProperty: Int = 22 } var gStruct = MyStruct() var gClass = MyClass() // CHECK-LABEL: sil hidden [ossa] @$s20tsan_instrumentation17inoutGlobalStructyyF : $@convention(thin) () -> () { // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$s20tsan_instrumentation7gStructAA02MyC0Vvp : $*MyStruct // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBAL_ADDR]] : $*MyStruct // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[WRITE]] : $*MyStruct) : $() // CHECK: [[TAKES_INOUT_FUNC:%.*]] = function_ref @$s20tsan_instrumentation10takesInoutyyAA8MyStructVzF : $@convention(thin) (@inout MyStruct) -> () // CHECK: {{%.*}} = apply [[TAKES_INOUT_FUNC]]([[WRITE]]) : $@convention(thin) (@inout MyStruct) -> () func inoutGlobalStruct() { takesInout(&gStruct) } // CHECK-LABEL: sil hidden [ossa] @$s20tsan_instrumentation31inoutGlobalStructStoredPropertyyyF : $@convention(thin) () -> () { // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$s20tsan_instrumentation7gStructAA02MyC0Vvp : $*MyStruct // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBAL_ADDR]] : $*MyStruct // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[WRITE]] : $*MyStruct) : $() // CHECK: [[ELEMENT_ADDR:%.*]] = struct_element_addr [[WRITE]] : $*MyStruct, #MyStruct.storedProperty // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[ELEMENT_ADDR]] : $*Int) : $() // CHECK: [[TAKES_INOUT_FUNC:%.*]] = function_ref @$s20tsan_instrumentation10takesInoutyySizF : $@convention(thin) (@inout Int) -> () // CHECK: {{%.*}} = apply [[TAKES_INOUT_FUNC]]([[ELEMENT_ADDR]]) : $@convention(thin) (@inout Int) -> () func inoutGlobalStructStoredProperty() { // This should generate two TSan inout instrumentations; one for the address // of the global and one for the address of the struct stored property. takesInout(&gStruct.storedProperty) } // CHECK-LABEL: sil hidden [ossa] @$s20tsan_instrumentation30inoutGlobalClassStoredPropertyyyF : $@convention(thin) () -> () { // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$s20tsan_instrumentation6gClassAA02MyC0Cvp : $*MyClass // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBAL_ADDR]] : $*MyClass // CHECK: [[LOADED_CLASS:%.*]] = load [copy] [[READ]] : $*MyClass // CHECK: end_access [[READ]] // CHECK: [[BORROWED_CLASS:%.*]] = begin_borrow [[LOADED_CLASS]] // CHECK: [[MODIFY:%.*]] = class_method [[BORROWED_CLASS]] : $MyClass, #MyClass.storedProperty!modify.1 : // CHECK: ([[BUFFER_ADDRESS:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFY]]([[BORROWED_CLASS]]) : $@yield_once @convention(method) (@guaranteed MyClass) -> @yields @inout Int // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[BUFFER_ADDRESS]] : $*Int) : $() // CHECK: [[TAKES_INOUT_FUNC:%.*]] = function_ref @$s20tsan_instrumentation10takesInoutyySizF : $@convention(thin) (@inout Int) -> () // CHECK: {{%.*}} apply [[TAKES_INOUT_FUNC]]([[BUFFER_ADDRESS]]) : $@convention(thin) (@inout Int) -> () // CHECK: end_apply [[TOKEN]] // CHECK: destroy_value [[LOADED_CLASS]] func inoutGlobalClassStoredProperty() { // This generates two TSan inout instrumentations. One for the value // buffer that is passed inout to materializeForSet and one for the // temporary buffer passed to takesInout(). takesInout(&gClass.storedProperty) }
apache-2.0
f22ab6ac0e8cd0b37709d6396cb25294
54.09375
174
0.660238
3.558022
false
false
false
false
AimobierCocoaPods/OddityUI
Classes/OddityModal/Classes/Swaggers/ORM/Special.swift
1
1462
// // Special.swift // Pods // // Created by 荆文征 on 2016/11/29. // // import Realm import RealmSwift /// 频道的数据模型 open class Special: Object { open dynamic var id = 0 // 专题ID open dynamic var name = "" // 专题名称 open dynamic var cover = "" // 专题封面 open dynamic var desc = "" // 专题简介 open dynamic var class_count = 0 //类别树木 open dynamic var news_count = 0 // 新闻树木 open dynamic var online = 0 //专题是否上线 open dynamic var top = 0 //专题是否置顶 open dynamic var create_time = "" //专题创建时间 let topicClasss = List<TopicClass>() override open static func primaryKey() -> String? { return "id" } class func getSpecById(id:Int) -> Special? { let realm = try! Realm() return realm.object(ofType: Special.self, forPrimaryKey: id) } class func getSpecsById(id:Int) -> Results<Special> { let realm = try! Realm() return realm.objects(Special.self).filter("id = %@",id) } } open class TopicClass: Object { open dynamic var id = 0 // 专题ID open dynamic var name = "" // 专题名称 open dynamic var topic = 1 // 专题封面 open dynamic var order = 1 // 专题简介 let news = List<New>() override open static func primaryKey() -> String? { return "id" } }
mit
fb070f3b94eab1055db157996578a69d
21.610169
68
0.571214
3.557333
false
false
false
false
lordrio/speedvote
Sources/CommentController.swift
1
2655
// // CommentController.swift // PerfectTemplate // // Created by MD FADZLI BIN MD FADZIL on 6/22/17. // // import Foundation import PerfectLib class CommentController: BaseController { public func LoadComment(_ id:UInt64) -> CommentData { let comment = CommentData() let result = GrabWithDataVar([comment.id, comment.event_id, comment.user_id, comment.comment, comment.datetime], whereStr: "id = \(id)", base: comment) if result { let user = UserController() user.LoadUser(comment.user_id.GetValue() as! UInt64) comment.user_name.Parse([ "user_name" : user.userData.name.Value as! String]) } return comment } public func LoadAllComment(_ event_id:UInt64 = 0) -> [CommentData] { let comment = CommentData() let res = GrabWithDataVar([comment.id.Key, comment.event_id.Key, comment.user_id.Key, comment.comment.Key, comment.datetime.Key], whereStr: "event_id = \(event_id)", base: comment) as [CommentData] let user = UserController() for i in res { user.LoadUser(i.user_id.Value as! UInt64) i.user_name.Value = user.userData.name.Value } return res } public func CreateComment(_ comment:CommentData) { let data = [comment.event_id.Key: comment.event_id.Value, comment.user_id.Key:comment.user_id.Value, comment.comment.Key:comment.comment.Value, comment.datetime.Key: comment.datetime.SQLSafeValue, ] as [String : Any] _ = Transaction({ (sql) -> Bool in guard sql.query(statement: "start transaction") else { return false } let query = CreateInsert(comment._tableName, val: data) guard sql.query(statement: query) else { Log.info(message: "Failure: \(sql.errorCode()) \(sql.errorMessage())") return false } guard sql.query(statement: "commit") else { return false } return true }) } }
apache-2.0
a6e2a467dba357a04f828bb00a26c33c
30.235294
101
0.468927
4.836066
false
false
false
false
Palleas/Batman
Batman/Flow Coordinators/SelectProjectFlowCoordinator.swift
1
1283
import Foundation import ReactiveSwift import Result final class SelectProjectFlowCoordinator: Coordinator { private(set) lazy var controller: ProjectsViewController = { let controller = StoryboardScene.Main.projects.instantiate() controller.modalPresentationStyle = .custom controller.transitioningDelegate = self return controller }() private let projects: ProjectsController let selected = MutableProperty<Project?>(nil) init(projects: ProjectsController) { self.projects = projects } func start() { let fetched = projects.fetch() .flatMapError { _ in SignalProducer<[Project], NoError>.empty } controller.projects <~ fetched controller.delegate = self } } extension SelectProjectFlowCoordinator: ProjectsViewControllerDelegate { func didSelect(project: Project) { selected.swap(project) } } extension SelectProjectFlowCoordinator: UIViewControllerTransitioningDelegate { func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { return BlurPresentationController(presentedViewController: presented, presenting: presenting) } }
mit
5c4717349ce327bebf05c06cd2239af8
28.159091
161
0.731878
5.912442
false
false
false
false
lanit-tercom-school/grouplock
GroupLockiOS/GroupLock/Scenes/Home_Stack/ProcessedFileScene/ProcessedFileInteractor.swift
1
3710
// // ProcessedFileInteractor.swift // GroupLock // // Created by Sergej Jaskiewicz on 22.07.16. // Copyright (c) 2016 Lanit-Tercom School. All rights reserved. // import UIKit protocol ProcessedFileInteractorInput { var files: [File] { get set } var processedFiles: [File] { get } var cryptographicKey: [String] { get set } var isEncryption: Bool { get set } func processFiles(_ request: ProcessedFile.Fetch.Request) func prepareFilesForSharing(_ request: ProcessedFile.Share.Request) func fileSelected(_ request: ProcessedFile.SelectFiles.Request) func fileDeselected(_ request: ProcessedFile.SelectFiles.Request) func saveFiles(_ request: ProcessedFile.SaveFiles.Request) } protocol ProcessedFileInteractorOutput { func presentFiles(_ response: ProcessedFile.Fetch.Response) func shareFiles(_ response: ProcessedFile.Share.Response) } class ProcessedFileInteractor: ProcessedFileInteractorInput { var output: ProcessedFileInteractorOutput! var cryptoLibrary: CryptoWrapperProtocol = CryptoFake() // MARK: - Business logic var files: [File] = [] var processedFiles: [File] = [] private var selectedFiles = Set<IndexPath>() var cryptographicKey: [String] = [] var isEncryption = true func processFiles(_ request: ProcessedFile.Fetch.Request) { func process(_ file: File, withKey key: [String]) -> File { if let dataToEncrypt = file.contents { let processedData = isEncryption ? cryptoLibrary.encrypt(image: dataToEncrypt, withEncryptionKey: key) : cryptoLibrary.decrypt(image: dataToEncrypt, withDecryptionKey: key) var processedFile = file processedFile.contents = processedData processedFile.encrypted = isEncryption return processedFile } else { return file } } DispatchQueue.global(qos: .userInitiated).async { [weak self] in if let strongSelf = self { strongSelf.processedFiles = strongSelf .files .map { process($0, withKey: strongSelf.cryptographicKey) } } DispatchQueue.main.async { [weak self] in if let strongSelf = self { strongSelf.output.presentFiles(ProcessedFile.Fetch.Response(files: strongSelf.processedFiles)) } } } } func prepareFilesForSharing(_ request: ProcessedFile.Share.Request) { let dataToShare = selectedFiles.map { processedFiles[$0.item].contents ?? Data() } let excludedActivityTypes: [UIActivityType] = [ .print, .postToVimeo, .postToWeibo, .postToFlickr, .postToTwitter, .postToFacebook, .addToReadingList, .postToTencentWeibo ] let response = ProcessedFile.Share.Response(dataToShare: dataToShare, excludedActivityTypes: excludedActivityTypes) output.shareFiles(response) } func fileSelected(_ request: ProcessedFile.SelectFiles.Request) { selectedFiles.insert(request.indexPath) } func fileDeselected(_ request: ProcessedFile.SelectFiles.Request) { selectedFiles.remove(request.indexPath) } func saveFiles(_ request: ProcessedFile.SaveFiles.Request) { for file in processedFiles { _ = ManagedFile(file, insertIntoManagedObjectContext: AppDelegate.sharedInstance.managedObjectContext) } AppDelegate.sharedInstance.saveContext() } }
apache-2.0
74e9d0c11b1005a42d5eb340d8ddb584
32.423423
114
0.636388
5.0271
false
false
false
false
Mindera/Alicerce
Tests/AlicerceTests/AutoLayout/SizeConstrainableProxyTestCase.swift
1
11356
import XCTest @testable import Alicerce class SizeConstrainableProxyTestCase: BaseConstrainableProxyTestCase { private(set) var constraints0: [NSLayoutConstraint]! private(set) var constraints1: [NSLayoutConstraint]! private(set) var constraints2: [NSLayoutConstraint]! private(set) var constraints3: [NSLayoutConstraint]! private(set) var constraints4: [NSLayoutConstraint]! private(set) var constraints5: [NSLayoutConstraint]! override func tearDown() { constraints0 = nil constraints1 = nil constraints2 = nil constraints3 = nil constraints4 = nil constraints5 = nil super.tearDown() } func testConstrain_WithOneSizeConstraint_ShouldSupportAbsoluteWidth() { constrain(view0) { view0 in constraints0 = view0.size(Constants.size0) } XCTAssertConstraints(constraints0, expectedConstraints(view: view0, size: Constants.size0)) host.layoutIfNeeded() XCTAssertEqual(view0.frame.size, Constants.size0) } func testConstrain_WithTwoSizeConstraint_ShouldSupportAbsoluteWidth() { constrain(view0, view1) { view0, view1 in constraints0 = view0.size(Constants.size0) constraints1 = view1.size(Constants.size1) } XCTAssertConstraints(constraints0, expectedConstraints(view: view0, size: Constants.size0)) XCTAssertConstraints(constraints1, expectedConstraints(view: view1, size: Constants.size1)) host.layoutIfNeeded() XCTAssertEqual(view0.frame.size, Constants.size0) XCTAssertEqual(view1.frame.size, Constants.size1) } func testConstrain_WithThreeSizeConstraint_ShouldSupportAbsoluteWidth() { constrain(view0, view1, view2) { view0, view1, view2 in constraints0 = view0.size(Constants.size0) constraints1 = view1.size(Constants.size1) constraints2 = view2.size(Constants.size2) } XCTAssertConstraints(constraints0, expectedConstraints(view: view0, size: Constants.size0)) XCTAssertConstraints(constraints1, expectedConstraints(view: view1, size: Constants.size1)) XCTAssertConstraints(constraints2, expectedConstraints(view: view2, size: Constants.size2)) host.layoutIfNeeded() XCTAssertEqual(view0.frame.size, Constants.size0) XCTAssertEqual(view1.frame.size, Constants.size1) XCTAssertEqual(view2.frame.size, Constants.size2) } func testConstrain_WithFourSizeConstraint_ShouldSupportAbsoluteWidth() { constrain(view0, view1, view2, view3) { view0, view1, view2, view3 in constraints0 = view0.size(Constants.size0) constraints1 = view1.size(Constants.size1) constraints2 = view2.size(Constants.size2) constraints3 = view3.size(Constants.size3) } XCTAssertConstraints(constraints0, expectedConstraints(view: view0, size: Constants.size0)) XCTAssertConstraints(constraints1, expectedConstraints(view: view1, size: Constants.size1)) XCTAssertConstraints(constraints2, expectedConstraints(view: view2, size: Constants.size2)) XCTAssertConstraints(constraints3, expectedConstraints(view: view3, size: Constants.size3)) host.layoutIfNeeded() XCTAssertEqual(view0.frame.size, Constants.size0) XCTAssertEqual(view1.frame.size, Constants.size1) XCTAssertEqual(view2.frame.size, Constants.size2) XCTAssertEqual(view3.frame.size, Constants.size3) } func testConstrain_WithFiveSizeConstraint_ShouldSupportAbsoluteWidth() { constrain(view0, view1, view2, view3, view4) { view0, view1, view2, view3, view4 in constraints0 = view0.size(Constants.size0) constraints1 = view1.size(Constants.size1) constraints2 = view2.size(Constants.size2) constraints3 = view3.size(Constants.size3) constraints4 = view4.size(Constants.size4) } XCTAssertConstraints(constraints0, expectedConstraints(view: view0, size: Constants.size0)) XCTAssertConstraints(constraints1, expectedConstraints(view: view1, size: Constants.size1)) XCTAssertConstraints(constraints2, expectedConstraints(view: view2, size: Constants.size2)) XCTAssertConstraints(constraints3, expectedConstraints(view: view3, size: Constants.size3)) XCTAssertConstraints(constraints4, expectedConstraints(view: view4, size: Constants.size4)) host.layoutIfNeeded() XCTAssertEqual(view0.frame.size, Constants.size0) XCTAssertEqual(view1.frame.size, Constants.size1) XCTAssertEqual(view2.frame.size, Constants.size2) XCTAssertEqual(view3.frame.size, Constants.size3) XCTAssertEqual(view4.frame.size, Constants.size4) } func testConstrain_WithSixSizeConstraint_ShouldSupportAbsoluteWidth() { constrain(view0, view1, view2, view3, view4, view5) { view0, view1, view2, view3, view4, view5 in constraints0 = view0.size(Constants.size0) constraints1 = view1.size(Constants.size1) constraints2 = view2.size(Constants.size2) constraints3 = view3.size(Constants.size3) constraints4 = view4.size(Constants.size4) constraints5 = view5.size(Constants.size5) } XCTAssertConstraints(constraints0, expectedConstraints(view: view0, size: Constants.size0)) XCTAssertConstraints(constraints1, expectedConstraints(view: view1, size: Constants.size1)) XCTAssertConstraints(constraints2, expectedConstraints(view: view2, size: Constants.size2)) XCTAssertConstraints(constraints3, expectedConstraints(view: view3, size: Constants.size3)) XCTAssertConstraints(constraints4, expectedConstraints(view: view4, size: Constants.size4)) XCTAssertConstraints(constraints5, expectedConstraints(view: view5, size: Constants.size5)) host.layoutIfNeeded() XCTAssertEqual(view0.frame.size, Constants.size0) XCTAssertEqual(view1.frame.size, Constants.size1) XCTAssertEqual(view2.frame.size, Constants.size2) XCTAssertEqual(view3.frame.size, Constants.size3) XCTAssertEqual(view4.frame.size, Constants.size4) XCTAssertEqual(view5.frame.size, Constants.size5) } func testConstrain_WithSizeConstraint_ShouldSupportRelativeWidth() { constrain(host, view0) { host, view0 in constraints0 = view0.size(to: host) } XCTAssertConstraints(constraints0, expectedConstraints(view: view0, to: host)) host.layoutIfNeeded() XCTAssertEqual(view0.frame.size, host.frame.size) } func testConstrain_WithSizeConstraintAndTwoConstraintGroups_ShouldReturnCorrectIsActiveValue() { let constraintGroup0 = constrain(view0, activate: false) { view0 in constraints0 = view0.size(Constants.size0) } let constraintGroup1 = constrain(view0, activate: false) { view0 in constraints1 = view0.size(Constants.size1) } XCTAssertConstraints(constraints0, expectedConstraints(view: view0, size: Constants.size0, active: false)) XCTAssertConstraints(constraints1, expectedConstraints(view: view0, size: Constants.size1, active: false)) constraintGroup0.isActive = true host.layoutIfNeeded() XCTAssert(constraintGroup0.isActive) XCTAssertFalse(constraintGroup1.isActive) XCTAssertEqual(view0.frame.size, Constants.size0) constraintGroup0.isActive = false constraintGroup1.isActive = true host.setNeedsLayout() host.layoutIfNeeded() XCTAssertFalse(constraintGroup0.isActive) XCTAssert(constraintGroup1.isActive) XCTAssertEqual(view0.frame.size, Constants.size1) } func testConstrain_WithAbsoluteWidthAndAspectRatioConstraint_ShouldSupportRelativeSize() { var constraint: NSLayoutConstraint! constrain(view0) { view0 in view0.width(1920) constraint = view0.aspectRatio(16/9) } let expected = NSLayoutConstraint( item: view0!, attribute: .width, relatedBy: .equal, toItem: view0!, attribute: .height, multiplier: 16/9, constant: 0, priority: .required, active: true ) XCTAssertConstraint(expected, constraint) host.layoutIfNeeded() XCTAssertEqual(view0.frame.size, CGSize(width: 1920, height: 1080)) } func testConstrain_WithRelativeHeightAndAspectRatioConstraint_ShouldSupportRelativeSize() { var constraint: NSLayoutConstraint! constrain(view0, host) { view0, host in view0.top(to: host, offset: 100) view0.bottom(to: host) constraint = view0.aspectRatio(0.5) } let expected = NSLayoutConstraint( item: view0!, attribute: .width, relatedBy: .equal, toItem: view0!, attribute: .height, multiplier: 0.5, constant: 0, priority: .required, active: true ) XCTAssertConstraint(constraint, expected) host.layoutIfNeeded() XCTAssertEqual(view0.frame.size, CGSize(width: 200, height: 400)) } } private extension SizeConstrainableProxyTestCase { private func expectedConstraints(view: UIView, size: CGSize, active: Bool = true) -> [NSLayoutConstraint] { let width = NSLayoutConstraint( item: view, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .width, multiplier: 1, constant: size.width, priority: .required, active: active ) let height = NSLayoutConstraint( item: view, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1, constant: size.height, priority: .required, active: active ) return [width, height] } private func expectedConstraints(view: UIView, to host: UIView) -> [NSLayoutConstraint] { let width = NSLayoutConstraint( item: view, attribute: .width, relatedBy: .equal, toItem: host, attribute: .width, multiplier: 1, constant: 0, priority: .required, active: true ) let height = NSLayoutConstraint( item: view, attribute: .height, relatedBy: .equal, toItem: host, attribute: .height, multiplier: 1, constant: 0, priority: .required, active: true ) return [width, height] } } private enum Constants { static let size0 = CGSize(width: 100, height: 100) static let size1 = CGSize(width: 200, height: 200) static let size2 = CGSize(width: 300, height: 300) static let size3 = CGSize(width: 400, height: 400) static let size4 = CGSize(width: 500, height: 500) static let size5 = CGSize(width: 600, height: 600) }
mit
ecf618b9644afc253a3aadbbadff384d
34.4875
114
0.657538
4.429017
false
false
false
false
Liuyingao/SwiftRepository
Inheritance.swift
1
2163
class Vehicle{ var currentSpeed = 1.0 var description : String{ return "traveling at \(currentSpeed) miles per hour" } func makeNoise(){ } } let someVehicle = Vehicle() print("Vehicle: \(someVehicle.description)") class Bicycle : Vehicle{ var hasBasket = false } let bicycle = Bicycle() bicycle.hasBasket = true bicycle.currentSpeed = 15.8 print("Bicycle: \(bicycle.description)") class Tandem: Bicycle { var currentNumberOfPassengers = 0 } let tandem = Tandem() tandem.hasBasket = true tandem.currentNumberOfPassengers = 2 tandem.currentSpeed = 22.0 print("Tandem: \(tandem.description)") class Train : Vehicle{ override func makeNoise(){ print("Choo Choo") } } let train = Train() train.makeNoise() //你可以提供定制的 getter(或 setter)来重写任意继承来的属性, //无论继承来的属性是存储型的还是计算型的属性。子类并不知道继承来的属性是存储型的还是计算型的, //它只知道继承来的属性会有一个名字和类型。你在重写一个属性时,必需将它的名字和类型都写出来。 //这样才能使编译器去检查你重写的属性是与超类中同名同类型的属性相匹配的。 class Car : Vehicle{ var gear = 1.0 override var currentSpeed : Double{ get { return gear * 25.0 } set { self.gear = newValue / 25 } } override var description : String{ return super.description + " in gear \(gear)" } } let car = Car() car.currentSpeed = 50.0 car.gear = 3 print("Car: \(car.description)") //重新属性观察器-计算属性或者存储属性在子类中可以随心所欲的变换 class AutoCar : Car { final override var currentSpeed : Double{ willSet { print("AutoCar'S willSet is calling: \(newValue)") print("Call super class's currentSpeed: \(super.currentSpeed)") } } } var autoCar = AutoCar() autoCar.gear = 5 autoCar.currentSpeed = 0.0 //final的问题,爷爷、爸爸和儿子。爷爷有个属性,爸爸继承过来了以后 ,可以改成final的,然后儿子就不可以重写了 //上面的例子中,在Car的currentSpeed属性前面加final后会报错,因为儿子不可以重写他
gpl-2.0
42d5c8a6f778e4e090a30e147f82acb7
19.182927
66
0.726284
2.669355
false
false
false
false
suzp1984/IOS-ApiDemo
ApiDemo-Swift/ApiDemo-Swift/ModalDialogSampleViewController.swift
1
2647
// // ModalDialogSampleViewController.swift // ApiDemo-Swift // // Created by Jacob su on 7/30/16. // Copyright © 2016 [email protected]. All rights reserved. // import UIKit class ModalDialogSampleViewController: UIViewController, UINavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource { let cellIdentifier = "Modal Dialogs" let demos: [String] = ["alert"] override func viewDidLoad() { super.viewDidLoad() self.title = "Modal Dialogs" let table = UITableView(frame: self.view.bounds) table.delegate = self table.dataSource = self table.backgroundColor = UIColor.cyan table.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier) self.view.addSubview(table) self.navigationItem.leftItemsSupplementBackButton = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return demos.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell : UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) if cell == nil { cell = UITableViewCell(style:.default, reuseIdentifier:cellIdentifier) cell.textLabel!.textColor = UIColor.white let v2 = UIView() // no need to set frame v2.backgroundColor = UIColor.blue.withAlphaComponent(0.2) cell.selectedBackgroundView = v2 // next line didn't work until iOS 7! cell.backgroundColor = UIColor.red } let v2 = UIView() // no need to set frame v2.backgroundColor = UIColor.blue.withAlphaComponent(0.2) cell.selectedBackgroundView = v2 cell.textLabel!.textColor = UIColor.white cell.backgroundColor = UIColor.red cell.textLabel!.text = demos[(indexPath as NSIndexPath).row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch demos[(indexPath as NSIndexPath).row] { case demos[0]: self.navigationController?.pushViewController(AlertViewController(), animated: true) default: break } } }
apache-2.0
bb539c398bd68f8b1c8d0786b2eafb8d
32.923077
115
0.6387
5.356275
false
false
false
false
kstaring/swift
stdlib/public/core/CommandLine.swift
4
2505
//===----------------------------------------------------------------------===// // // 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 SwiftShims /// Command-line arguments for the current process. public enum CommandLine { /// The backing static variable for argument count may come either from the /// entry point or it may need to be computed e.g. if we're in the REPL. @_versioned internal static var _argc: Int32 = Int32() /// The backing static variable for arguments may come either from the /// entry point or it may need to be computed e.g. if we're in the REPL. /// /// Care must be taken to ensure that `_swift_stdlib_getUnsafeArgvArgc` is /// not invoked more times than is necessary (at most once). @_versioned internal static var _unsafeArgv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> = _swift_stdlib_getUnsafeArgvArgc(&_argc) /// Access to the raw argc value from C. public static var argc: Int32 { _ = CommandLine.unsafeArgv // Force evaluation of argv. return _argc } /// Access to the raw argv value from C. Accessing the argument vector /// through this pointer is unsafe. public static var unsafeArgv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> { return _unsafeArgv } /// Access to the swift arguments, also use lazy initialization of static /// properties to safely initialize the swift arguments. public static var arguments: [String] = (0..<Int(argc)).map { String(cString: _unsafeArgv[$0]!) } } // FIXME(ABI)#25 : Remove this and the entrypoints in SILGen. // rdar://problem/19696522 @_transparent public // COMPILER_INTRINSIC func _stdlib_didEnterMain( argc: Int32, argv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>?> ) { // Initialize the CommandLine.argc and CommandLine.unsafeArgv variables with the // values that were passed in to main. CommandLine._argc = Int32(argc) CommandLine._unsafeArgv = argv } // FIXME: Move this to HashedCollections.swift.gyb internal class _Box<Wrapped> { internal var _value: Wrapped internal init(_ value: Wrapped) { self._value = value } }
apache-2.0
adaa6a808a6fee4ae051b14f0b8ba3de
35.304348
82
0.675848
4.473214
false
false
false
false
AlexZd/SwiftUtils
Pod/Utils/String+Helpers.swift
1
4684
// // String+Helpers.swift // // Created by Alex Zdorovets on 6/17/15. // Copyright (c) 2015 Alex Zdorovets. All rights reserved. // import Foundation extension String { /** Returns localizedUppercaseString for iOS 9+ or uppercaseString for below */ public var up: String { if #available(iOS 9, *) { return self.localizedUppercase } return self.uppercased() } /** Returns localizedLowercaseString for iOS 9+ or lowercaseString for below */ public var down: String { if #available(iOS 9, *) { return self.localizedLowercase } return self.lowercased() } /** Returns localizedCapitalizedString for iOS 9+ or capitalizedString for below */ public var cap: String { if #available(iOS 9, *) { return self.localizedCapitalized } return self.capitalized } /** Returns string with first capitalized letter */ public var capFirst: String { return String(characters.prefix(1)).up + String(self.characters.dropFirst()) } /** Converts String to Gregorian NSDate */ public func toDate(_ mask: String) -> Date? { let dateFormatter = DateFormatter(dateFormat: mask) dateFormatter.locale = Locale(identifier: "en_US_POSIX") dateFormatter.calendar = Calendar(identifier: .gregorian) return dateFormatter.date(from: self) } /** Returns truncated string with ending which you spicify in trailing */ public func truncate(length: Int, trailing: String? = nil) -> String { if self.characters.count > length { let index = self.index(self.startIndex, offsetBy: length) return String(self[..<index]) + (trailing ?? "") } else { return self } } /** Returns `true` in case string contains substring */ func contains(substring: String) -> Bool { return self.ranges(of: substring) != nil } /** Returns array of ranges of substring */ public func ranges(of string: String) -> Array<NSRange> { var searchRange = NSMakeRange(0, self.characters.count) var ranges : Array<NSRange> = [] while searchRange.location < self.characters.count { searchRange.length = self.characters.count - searchRange.location let foundRange = (self as NSString).range(of: string, options: .caseInsensitive, range: searchRange) if foundRange.location != NSNotFound { ranges.append(foundRange) searchRange.location = foundRange.location + foundRange.length } else { break } } return ranges } /** Trim whitespacesAndNewlines */ public func trim(set: CharacterSet = CharacterSet.whitespacesAndNewlines) -> String { return self.trimmingCharacters(in: set) } public func height(width: CGFloat, font: UIFont?) -> CGFloat { let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude) var attributes: [NSAttributedString.Key: Any] = [:] if let font = font { attributes[.font] = font } let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: attributes, context: nil) return ceil(boundingBox.height) } public func width(height: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height) let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil) return ceil(boundingBox.width) } /// Returns values from string with RegExp pattern public func regexValues(with pattern: String) -> [String] { var results: [String] = [] do { let regex = try NSRegularExpression(pattern: pattern, options: []) let matches = regex.matches(in: self, options: [], range: NSRange(self.startIndex..., in: self)) for match in matches { let lastRangeIndex = match.numberOfRanges - 1 guard lastRangeIndex >= 1 else { return results } for i in 1...lastRangeIndex { let capturedGroupIndex = match.range(at: i) let matchedString = (self as NSString).substring(with: capturedGroupIndex) results.append(matchedString) } } return results } catch { return results } } }
mit
69c77e612db8fa7a9c368b823daee7d2
36.472
140
0.605038
4.988285
false
false
false
false
Shashikant86/XCFit
XCFit_Templates/XCFit/Cucumberish UI Test Bundle Base.xctemplate/CommonStepDefinitions.swift
1
5653
ery// // CommonStepDefinitions.swift // Copyright © 2017 XCFit Framework. All rights reserved. // // /* This is sample code created by XCFit Framework and can be edited/Removed as needed. This class has some mostly used step definitions included here. You can add some more here if needed. */ import XCTest import Cucumberish class CommonStepDefinitions: NSObject { fileprivate var application : XCUIApplication! fileprivate func elementByLabel(_ label : String, type: String) -> XCUIElement { var elementQurey : XCUIElementQuery! switch(type){ case "button": elementQuery = application.buttons case "label": elementQuery = application.staticTexts case "tab": elementQuery = application.tabs case "field", "text field": elementQuery = application.textFields case "textView", "text view": elementQuery = application.textViews case "view": elementQuery = application.otherElements default: elementQurey = application.otherElements } return elementQuery[label] } fileprivate func setup(_ application: XCUIApplication) { self.application = application MatchAll("I launched an App") { (args, userInfo) in application.launch() } MatchAll("I terminated an App") { (args, userInfo) in application.terminate() } MatchAll("^I see an alert with title \"([^\\\"]*)\" and clicked \"([^\\\"]*)\" action$") { (args, userInfo) in let alert = application.alerts[(args?[0])!] alert.buttons[(args?[0])!].tap() } MatchAll("^I allow system alert with \"([^\\\"]*)\" description$") { (args, userInfo) in let alertDescription = args?[0] XCTestCase().addUIInterruptionMonitor(withDescription: alertDescription!) { (alert) -> Bool in alert.buttons["Allow"].tap() return true } XCUIApplication().tap() } MatchAll("^I slide a slider by \"([^\\\"]*)\" normalised Value$") { (args, userInfo) in let sliderPosition = args?[0] let slidervalue :CGFloat = CGFloat((sliderPosition! as NSString).doubleValue) application.sliders.element.adjust(toNormalizedSliderPosition: slidervalue) } MatchAll("^I select an item \"([^\\\"]*)\" from picker$") { (args, userInfo) in let pickerPosition = args?[0] application.pickerWheels.element.adjust(toPickerWheelValue: pickerPosition!) } MatchAll("^I click link \"([^\\\"]*)\" from webview$") { (args, userInfo) in let linkText = args?[0] application.links[linkText!].tap() } MatchAll("^I should see menubar with \"([^\\\"]*)\" header$") { (args, userInfo) in let menubarText = args?[0] XCTAssertTrue(application.menuBars[menubarText!].exists) } MatchAll("^I should see menu with \"([^\\\"]*)\" items$") { (args, userInfo) in let menuCount = args![0] let expectedMenuCount: UInt = UInt(menuCount)! let appMenuCount = application.menus.count XCTAssertEqual(expectedMenuCount, appMenuCount, "Comparing MenuCount") } MatchAll("^I should see screen with \"([^\\\"]*)\" cells$") { (args, userInfo) in let cellCount = args![0] let expectedCellCount: UInt = UInt(cellCount)! let appCellCount = application.cells.count XCTAssertEqual(expectedCellCount, appCellCount, "Comparing Cell Count") } MatchAll("^I check \"([^\\\"]*)\" checkbox$") { (args, userInfo) in let checkBox = args?[0] application.checkBoxes[checkBox!].tap() } //And/When/Then/But I tap the "Header" view MatchAll("^I tap (?:the )?\"([^\\\"]*)\" (button|label|tab|view|field|textView)$") { (args, userInfo) -> Void in let label = args?[0] let type = args?[1] self.elementByLabel(label!, type: type!).tap() } //And/When/Then/But I tap the "Increment" button 5 times MatchAll("^I tap (?:the )?\"([^\\\"]*)\" (button|label|tab|view) ([1-9]{1}) time(?:s)?$") { (args, userInfo) -> Void in let label = args?[0] let type = args?[1] let times = NSString(string: (args?[2])!).integerValue let element = self.elementByLabel(label!, type: type!) for _ in 0 ..< times{ element.tap() } } //When/And/But/When I write "London" in the "City" field MatchAll("^I write \"([^\\\"]*)\" (?:into|in) (?:the )?\"([^\\\"]*)\" (field|text view)$") { (args, userInfo) -> Void in let type = args?[2] let label = args?[1] let element = self.elementByLabel(label!, type: type!) element.tap() element.typeText((args?[0])!) } MatchAll("^I switch (on|off) the \"([^\\\"]*)\" switch$") { (args, userInfo) -> Void in let theSwitch = application.switches[(args?[1])!] let currentValu = NSString(string: theSwitch.value as! String).integerValue let newValue = args?[0] == "on" ? 1 : 0 if(currentValu != newValue){ theSwitch.tap() } } } class func setup(_ application: XCUIApplication) { CommonStepDefinitions().setup(application) } }
mit
1d1ec046bfa5480864b06e800da48530
33.254545
128
0.551663
4.49642
false
false
false
false
900116/GodEyeClear
Classes/Console/ConsoleController.swift
1
1612
// // ConsoleViewController.swift // Pods // // Created by zixun on 16/12/27. // // import Foundation import AppBaseKit import ASLEye import ANREye class ConsoleController: UIViewController { init() { super.init(nibName: nil, bundle: nil) self.openEyes() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.niceBlack() self.view.addSubview(self.tableView) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.tableView.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) } lazy var tableView: UITableView = { [unowned self] in let new = UITableView(frame: CGRect.zero, style: .grouped) new.delegate = self new.dataSource = self new.backgroundColor = UIColor.clear return new }() private(set) lazy var dataSource: [[RecordType]] = { var new = [[RecordType]]() var section1 = [RecordType]() section1.append(RecordType.log) section1.append(RecordType.crash) section1.append(RecordType.network) section1.append(RecordType.anr) section1.append(RecordType.leak) new.append(section1) var section2 = [RecordType]() section2.append(RecordType.command) new.append(section2) return new }() weak var printViewController: ConsolePrintViewController? }
mit
e94b31cb9826d42b5ba9c0008c46d348
24.1875
121
0.641439
4.242105
false
false
false
false
grpc/grpc-swift
Tests/GRPCTests/ZeroLengthWriteTests.swift
1
8863
/* * Copyright 2020, gRPC 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. */ #if canImport(NIOSSL) import Dispatch import EchoImplementation import EchoModel import Foundation import GRPC import GRPCSampleData import NIOCore import NIOSSL import NIOTransportServices import XCTest final class ZeroLengthWriteTests: GRPCTestCase { func clientBuilder( group: EventLoopGroup, secure: Bool, debugInitializer: @escaping GRPCChannelInitializer ) -> ClientConnection.Builder { if secure { return ClientConnection.usingTLSBackedByNIOSSL(on: group) .withTLS(trustRoots: .certificates([SampleCertificate.ca.certificate])) .withDebugChannelInitializer(debugInitializer) } else { return ClientConnection.insecure(group: group) .withDebugChannelInitializer(debugInitializer) } } func serverBuilder( group: EventLoopGroup, secure: Bool, debugInitializer: @escaping (Channel) -> EventLoopFuture<Void> ) -> Server.Builder { if secure { return Server.usingTLSBackedByNIOSSL( on: group, certificateChain: [SampleCertificate.server.certificate], privateKey: SamplePrivateKey.server ).withTLS(trustRoots: .certificates([SampleCertificate.ca.certificate])) .withDebugChannelInitializer(debugInitializer) } else { return Server.insecure(group: group) .withDebugChannelInitializer(debugInitializer) } } func makeServer( group: EventLoopGroup, secure: Bool, debugInitializer: @escaping (Channel) -> EventLoopFuture<Void> ) throws -> Server { return try self.serverBuilder(group: group, secure: secure, debugInitializer: debugInitializer) .withServiceProviders([self.makeEchoProvider()]) .withLogger(self.serverLogger) .bind(host: "127.0.0.1", port: 0) .wait() } func makeClientConnection( group: EventLoopGroup, secure: Bool, port: Int, debugInitializer: @escaping GRPCChannelInitializer ) throws -> ClientConnection { return self.clientBuilder(group: group, secure: secure, debugInitializer: debugInitializer) .withBackgroundActivityLogger(self.clientLogger) .withConnectionReestablishment(enabled: false) .connect(host: "127.0.0.1", port: port) } func makeEchoProvider() -> Echo_EchoProvider { return EchoProvider() } func makeEchoClient( group: EventLoopGroup, secure: Bool, port: Int, debugInitializer: @escaping GRPCChannelInitializer ) throws -> Echo_EchoNIOClient { return Echo_EchoNIOClient( channel: try self.makeClientConnection( group: group, secure: secure, port: port, debugInitializer: debugInitializer ), defaultCallOptions: self.callOptionsWithLogger ) } func zeroLengthWriteExpectation() -> XCTestExpectation { let expectation = self.expectation(description: "Expecting zero length write workaround") expectation.expectedFulfillmentCount = 1 expectation.assertForOverFulfill = true return expectation } func noZeroLengthWriteExpectation() -> XCTestExpectation { let expectation = self.expectation(description: "Not expecting zero length write workaround") expectation.expectedFulfillmentCount = 1 expectation.assertForOverFulfill = true return expectation } func debugPipelineExpectation( _ callback: @escaping (Result<NIOFilterEmptyWritesHandler, Error>) -> Void ) -> GRPCChannelInitializer { return { channel in channel.pipeline.handler(type: NIOFilterEmptyWritesHandler.self).always { result in callback(result) }.map { _ in () }.recover { _ in () } } } private func _runTest( networkPreference: NetworkPreference, secure: Bool, clientHandlerCallback: @escaping (Result<NIOFilterEmptyWritesHandler, Error>) -> Void, serverHandlerCallback: @escaping (Result<NIOFilterEmptyWritesHandler, Error>) -> Void ) { // We can only run this test on platforms where the zero-length write workaround _could_ be added. #if canImport(Network) guard #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) else { return } let group = PlatformSupport.makeEventLoopGroup( loopCount: 1, networkPreference: networkPreference ) let server = try! self.makeServer( group: group, secure: secure, debugInitializer: self.debugPipelineExpectation(serverHandlerCallback) ) defer { XCTAssertNoThrow(try server.close().wait()) XCTAssertNoThrow(try group.syncShutdownGracefully()) } let port = server.channel.localAddress!.port! let client = try! self.makeEchoClient( group: group, secure: secure, port: port, debugInitializer: self.debugPipelineExpectation(clientHandlerCallback) ) defer { XCTAssertNoThrow(try client.channel.close().wait()) } // We need to wait here to confirm that the RPC completes. All expectations should have completed by then. let call = client.get(Echo_EchoRequest(text: "foo bar baz")) XCTAssertNoThrow(try call.status.wait()) self.waitForExpectations(timeout: 1.0) #endif } func testZeroLengthWriteTestPosixSecure() throws { // We can only run this test on platforms where the zero-length write workaround _could_ be added. #if canImport(Network) guard #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) else { return } let serverExpectation = self.noZeroLengthWriteExpectation() let clientExpectation = self.noZeroLengthWriteExpectation() self._runTest( networkPreference: .userDefined(.posix), secure: true, clientHandlerCallback: { result in if case .failure = result { clientExpectation.fulfill() } }, serverHandlerCallback: { result in if case .failure = result { serverExpectation.fulfill() } } ) #endif } func testZeroLengthWriteTestPosixInsecure() throws { // We can only run this test on platforms where the zero-length write workaround _could_ be added. #if canImport(Network) guard #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) else { return } let serverExpectation = self.noZeroLengthWriteExpectation() let clientExpectation = self.noZeroLengthWriteExpectation() self._runTest( networkPreference: .userDefined(.posix), secure: false, clientHandlerCallback: { result in if case .failure = result { clientExpectation.fulfill() } }, serverHandlerCallback: { result in if case .failure = result { serverExpectation.fulfill() } } ) #endif } func testZeroLengthWriteTestNetworkFrameworkSecure() throws { // We can only run this test on platforms where the zero-length write workaround _could_ be added. #if canImport(Network) guard #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) else { return } let serverExpectation = self.noZeroLengthWriteExpectation() let clientExpectation = self.noZeroLengthWriteExpectation() self._runTest( networkPreference: .userDefined(.networkFramework), secure: true, clientHandlerCallback: { result in if case .failure = result { clientExpectation.fulfill() } }, serverHandlerCallback: { result in if case .failure = result { serverExpectation.fulfill() } } ) #endif } func testZeroLengthWriteTestNetworkFrameworkInsecure() throws { // We can only run this test on platforms where the zero-length write workaround _could_ be added. #if canImport(Network) guard #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) else { return } let serverExpectation = self.zeroLengthWriteExpectation() let clientExpectation = self.zeroLengthWriteExpectation() self._runTest( networkPreference: .userDefined(.networkFramework), secure: false, clientHandlerCallback: { result in if case .success = result { clientExpectation.fulfill() } }, serverHandlerCallback: { result in if case .success = result { serverExpectation.fulfill() } } ) #endif } } #endif // canImport(NIOSSL)
apache-2.0
26a7c3c4fa0f3ba426bb21183cc42db7
32.070896
110
0.691639
4.494422
false
true
false
false
grpc/grpc-swift
Performance/QPSBenchmark/Sources/BenchmarkUtils/Histogram.swift
1
4324
/* * Copyright 2020, gRPC 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 struct HistorgramShapeMismatch: Error {} /// Histograms are stored with exponentially increasing bucket sizes. /// The first bucket is [0, `multiplier`) where `multiplier` = 1 + resolution /// Bucket n (n>=1) contains [`multiplier`**n, `multiplier`**(n+1)) /// There are sufficient buckets to reach max_bucket_start public struct Histogram { public private(set) var sum: Double public private(set) var sumOfSquares: Double public private(set) var countOfValuesSeen: Double private var multiplier: Double private var oneOnLogMultiplier: Double public private(set) var minSeen: Double public private(set) var maxSeen: Double private var maxPossible: Double public private(set) var buckets: [UInt32] /// Initialise a histogram. /// - parameters: /// - resolution: Defines the width of the buckets - see the description of this structure. /// - maxBucketStart: Defines the start of the greatest valued bucket. public init(resolution: Double = 0.01, maxBucketStart: Double = 60e9) { precondition(resolution > 0.0) precondition(maxBucketStart > resolution) self.sum = 0.0 self.sumOfSquares = 0.0 self.multiplier = 1.0 + resolution self.oneOnLogMultiplier = 1.0 / log(1.0 + resolution) self.maxPossible = maxBucketStart self.countOfValuesSeen = 0.0 self.minSeen = maxBucketStart self.maxSeen = 0.0 let numBuckets = Histogram.bucketForUnchecked( value: maxBucketStart, oneOnLogMultiplier: self.oneOnLogMultiplier ) + 1 precondition(numBuckets > 1) precondition(numBuckets < 100_000_000) self.buckets = .init(repeating: 0, count: numBuckets) } /// Determine a bucket index given a value - does no bounds checking private static func bucketForUnchecked(value: Double, oneOnLogMultiplier: Double) -> Int { return Int(log(value) * oneOnLogMultiplier) } private func bucketFor(value: Double) -> Int { let bucket = Histogram.bucketForUnchecked( value: self.clamp(value: value), oneOnLogMultiplier: self.oneOnLogMultiplier ) assert(bucket < self.buckets.count) assert(bucket >= 0) return bucket } /// Force a value to be within the bounds of 0 and `self.maxPossible` /// - parameters: /// - value: The value to force within bounds /// - returns: The value forced into the bounds for buckets. private func clamp(value: Double) -> Double { return min(self.maxPossible, max(0, value)) } /// Add a value to this histogram, updating buckets and stats /// - parameters: /// - value: The value to add. public mutating func add(value: Double) { self.sum += value self.sumOfSquares += value * value self.countOfValuesSeen += 1 if value < self.minSeen { self.minSeen = value } if value > self.maxSeen { self.maxSeen = value } self.buckets[self.bucketFor(value: value)] += 1 } /// Merge two histograms together updating `self` /// - parameters: /// - source: the other histogram to merge into this. public mutating func merge(source: Histogram) throws { guard (self.buckets.count == source.buckets.count) || (self.multiplier == source.multiplier) else { // Fail because these histograms don't match. throw HistorgramShapeMismatch() } self.sum += source.sum self.sumOfSquares += source.sumOfSquares self.countOfValuesSeen += source.countOfValuesSeen if source.minSeen < self.minSeen { self.minSeen = source.minSeen } if source.maxSeen > self.maxSeen { self.maxSeen = source.maxSeen } for bucket in 0 ..< self.buckets.count { self.buckets[bucket] += source.buckets[bucket] } } }
apache-2.0
01ade24c8d527ff7b3ea2b6572d64e4a
34.442623
97
0.693802
3.956084
false
false
false
false
SmallElephant/FEAlgorithm-Swift
7-String/7-String/Convert.swift
1
1397
// // Convert.swift // 7-String // // Created by FlyElephant on 17/1/14. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation class Convert { func stringToInt(str:String?)->Int? { if str == nil || str?.characters.count == 0 { return nil } var result:Int = 0 var begin:Int = 0 let count:Int = str!.characters.count var flag:Int = 1 let curStr:String = str![0] if curStr == "+" { flag = 1 begin = 1 } else if curStr == "-" { flag = -1 begin = 1 } else if !isNumberDigit(str: curStr) { return nil } for i in begin..<count { let curStr:String = str![i] if !isNumberDigit(str: curStr) { return nil } let temp:Int = Int(curStr)! if flag == 1 && result > (Int.max - temp * flag) / 10 { return nil } if flag == -1 && result < (Int.min - temp * flag) / 10 { return nil } result = result * 10 + temp * flag } return result } func isNumberDigit(str:String)->Bool { return str >= "0" && str <= "9" } }
mit
7886e1c264172d38afac0e71ac782858
22.233333
69
0.418221
4.276074
false
false
false
false
zhou9734/Warm
Warm/Classes/Home/Controller/SalonViewController.swift
1
3738
// // SalonViewController.swift // Warm // // Created by zhoucj on 16/9/22. // Copyright © 2016年 zhoucj. All rights reserved. // import UIKit import SVProgressHUD let SalonTableReuseIdentifier = "SalonTableReuseIdentifier" class SalonViewController: UIViewController { let homeViewModel = HomeViewModel() var salons: WSalon? var salonId: Int64?{ didSet{ guard let id = salonId else{ return } SVProgressHUD.setDefaultMaskType(.Black) SVProgressHUD.show() unowned let tmpSelf = self homeViewModel.loadSalonDetail(id) { (data, error) -> () in guard let _salon = data as? WSalon else { return } tmpSelf.salons = _salon let height = tmpSelf.scrollView.caluHeight(_salon) tmpSelf.scrollView.contentSize = CGSize(width: ScreenWidth, height: height + 30) tmpSelf.view.layoutIfNeeded() SVProgressHUD.dismiss() } } } var _lastPosition: CGFloat = 0.0 override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Color_GlobalBackground navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: shareBtn), UIBarButtonItem(customView: loveBtn)] view.addSubview(scrollView) view.addSubview(editBtn) } private lazy var loveBtn: UIButton = { let btn = UIButton() btn.setBackgroundImage(UIImage(named: "navigationLoveNormal_22x20_"), forState: .Normal) btn.addTarget(self, action: Selector("loveBtnClick:"), forControlEvents: .TouchUpInside) btn.setBackgroundImage(UIImage(named: "navigation_liked_22x22_"), forState: .Selected) btn.sizeToFit() return btn }() private lazy var shareBtn: UIButton = UIButton(target: self, backgroundImage: "navigationShare_20x20_", action: Selector("shareBtnClick")) private lazy var scrollView: SalonScrollView = { let sv = SalonScrollView(frame: ScreenBounds) sv.delegate = self return sv }() private lazy var editBtn: UIButton = { let btn = UIButton() btn.setBackgroundImage(UIImage(named: "edit_54x54_"), forState: .Normal) btn.addTarget(self, action: Selector("editBtnClick"), forControlEvents: .TouchUpInside) btn.frame = CGRect(x: 25.0, y: ScreenHeight - 70.0, width: 40.0, height: 40.0) btn.layer.cornerRadius = 20 btn.layer.masksToBounds = true return btn }() @objc func loveBtnClick(btn: UIButton){ btn.selected = !btn.selected } @objc func shareBtnClick(){ ShareTools.shareApp(self, shareText: nil) } @objc func editBtnClick(){ CJLog("edit") } deinit{ SVProgressHUD.dismiss() } } extension SalonViewController: UIScrollViewDelegate{ //滚动事件 func scrollViewDidScroll(scrollView: UIScrollView) { unowned let tmpSelf = self let currentPostion = scrollView.contentOffset.y; if (currentPostion - _lastPosition > 40) { _lastPosition = currentPostion; //消失 UIView.animateWithDuration(0.5, animations: { () -> Void in tmpSelf.editBtn.frame = CGRect(x: -65.0, y: ScreenHeight - 70.0, width: 40.0, height: 40.0) }) }else if (_lastPosition - currentPostion > 40){ _lastPosition = currentPostion; //隐藏 UIView.animateWithDuration(0.5, animations: { () -> Void in tmpSelf.editBtn.frame = CGRect(x: 25.0, y: ScreenHeight - 70.0, width: 40.0, height: 40.0) }) } } }
mit
515072802f957f87e610e7e72b0b06aa
35.821782
142
0.612799
4.546455
false
false
false
false
boxenjim/SwiftyFaker
SwiftyFaker/faker/PhoneNumber.swift
1
4486
// // PhoneNumber.swift // SwiftyFaker // // Created by Jim Schultz on 9/18/15. // Copyright © 2015 Jim Schultz. All rights reserved. // import Foundation extension Faker { open class PhoneNumber: Faker { fileprivate var areaCodes: [String]? fileprivate var exchangeCodes: [String]? // MARK: NSKeyValueCoding open override func setValue(_ value: Any?, forKey key: String) { if key == "area_code" { areaCodes = value as? [String] } else if key == "exchange_code" { exchangeCodes = value as? [String] } else { super.setValue(value, forKey: key) } } fileprivate static let _phoneNumber = PhoneNumber(dictionary: Faker.JSON("phone_number")) // MARK: Private Methods fileprivate func phoneFormats() -> [String] { return cellFormats() + ["\(PhoneNumber.areaCode())-\(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber()) x\(PhoneNumber.extensionNumber())", "(\(PhoneNumber.areaCode())) \(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber()) x\(PhoneNumber.extensionNumber())", "1-\(PhoneNumber.areaCode())-\(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber()) x\(PhoneNumber.extensionNumber())", "\(PhoneNumber.areaCode()).\(PhoneNumber.exchangeCode()).\(PhoneNumber.subscriberNumber()) x\(PhoneNumber.extensionNumber())", "\(PhoneNumber.areaCode())-\(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber()) x\(PhoneNumber.extensionNumber())", "(\(PhoneNumber.areaCode())) \(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber()) x\(PhoneNumber.extensionNumber())", "1-\(PhoneNumber.areaCode())-\(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber()) x\(PhoneNumber.extensionNumber())", "\(PhoneNumber.areaCode()).\(PhoneNumber.exchangeCode()).\(PhoneNumber.subscriberNumber()) x\(PhoneNumber.extensionNumber())", "\(PhoneNumber.areaCode())-\(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber()) x\(PhoneNumber.extensionNumber())", "(\(PhoneNumber.areaCode())) \(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber()) x\(PhoneNumber.extensionNumber())", "1-\(PhoneNumber.areaCode())-\(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber()) x\(PhoneNumber.extensionNumber())", "\(PhoneNumber.areaCode()).\(PhoneNumber.exchangeCode()).\(PhoneNumber.subscriberNumber()) x\(PhoneNumber.extensionNumber())"] } fileprivate func cellFormats() -> [String] { return ["\(PhoneNumber.areaCode())-\(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber())", "(\(PhoneNumber.areaCode())) \(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber())", "1-\(PhoneNumber.areaCode())-\(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber())", "\(PhoneNumber.areaCode()).\(PhoneNumber.exchangeCode()).\(PhoneNumber.subscriberNumber())", "\(PhoneNumber.areaCode())-\(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber())", "(\(PhoneNumber.areaCode())) \(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber())", "1-\(PhoneNumber.areaCode())-\(PhoneNumber.exchangeCode())-\(PhoneNumber.subscriberNumber())", "\(PhoneNumber.areaCode()).\(PhoneNumber.exchangeCode()).\(PhoneNumber.subscriberNumber())"] } // MARK: Methods open static func phoneNumber() -> String { return numerify(_phoneNumber.phoneFormats().random()) } open static func cellPhone() -> String { return numerify(_phoneNumber.cellFormats().random()) } open static func areaCode() -> String { guard let codes = _phoneNumber.areaCodes else { return "" } return codes.random() } open static func exchangeCode() -> String { guard let codes = _phoneNumber.exchangeCodes else { return "" } return codes.random() } open static func subscriberNumber() -> String { return extensionNumber(4) } open static func extensionNumber(_ length: Int = 3) -> String { return numerify(numerifyable(length)) } } }
mit
9099f6bde8d5a8ed685dbf0d0fb9d993
53.036145
162
0.613601
5.178984
false
false
false
false
davidlivadaru/DLAngle
Sources/DLAngle/Angle/Radian+InverseHyperbolicTrigonometricFunctions.swift
1
9681
// // File.swift // DLAngle // // Created by David Livadaru on 1/4/18. // import Foundation #if !os(Linux) import CoreGraphics #endif public extension Radian { /// Create a Radian angle by computing asinh. /// /// - Parameter asinh: The asinh value. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=asinh+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcSinh.html) public convenience init(asinh: Double) { self.init(rawValue: Trigonometry.asinh(asinh)) } /// Create a Radian angle by computing asinh. /// /// - Parameter asinh: The asinh value. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=asinh+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcSinh.html) public convenience init(asinh: Float) { self.init(float: GenericTrigonometry.asinh(asinh)) } #if !os(Linux) /// Create a Radian angle by computing asinh. /// /// - Parameter asinh: The asinh value. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=asinh+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcSinh.html) public convenience init(asinh: CGFloat) { self.init(cgFloat: Trigonometry.asinh(asinh)) } #endif /// Create a Radian angle by computing acosh. /// /// - Parameter acosh: The acosh value. /// - Throws: Throws an error if acosh value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=acosh+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcCosh.html) public convenience init(acosh: Double) throws { let rawValue: Double = try Trigonometry.acosh(acosh) self.init(rawValue: rawValue) } /// Create a Radian angle by computing acosh. /// /// - Parameter acosh: The acosh value. /// - Throws: Throws an error if acosh value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=acosh+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcCosh.html) public convenience init(acosh: Float) throws { let rawValue: Double = try Trigonometry.acosh(Double(acosh)) self.init(rawValue: rawValue) } #if !os(Linux) /// Create a Radian angle by computing acosh. /// /// - Parameter acosh: The acosh value. /// - Throws: Throws an error if acosh value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=acosh+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcCosh.html) public convenience init(acosh: CGFloat) throws { let rawValue: CGFloat = try Trigonometry.acosh(acosh) self.init(cgFloat: rawValue) } #endif /// Create a Radian angle by computing atanh. /// /// - Parameter atanh: The atanh value. /// - Throws: Throws an error if atanh value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=atanh+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcTanh.html) public convenience init(atanh: Double) throws { let rawValue: Double = try Trigonometry.atanh(atanh) self.init(rawValue: rawValue) } /// Create a Radian angle by computing atanh. /// /// - Parameter atanh: The atanh value. /// - Throws: Throws an error if atanh value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=atanh+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcTanh.html) public convenience init(atanh: Float) throws { let rawValue: Double = try Trigonometry.atanh(Double(atanh)) self.init(rawValue: rawValue) } #if !os(Linux) /// Create a Radian angle by computing atanh. /// /// - Parameter atanh: The atanh value. /// - Throws: Throws an error if atanh value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=atanh+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcTanh.html) public convenience init(atanh: CGFloat) throws { let rawValue: CGFloat = try Trigonometry.atanh(atanh) self.init(cgFloat: rawValue) } #endif /// Create a Radian angle by computing acoth. /// /// - Parameter acoth: The acoth value. /// - Throws: Throws an error if acoth value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=acoth+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcCoth.html) public convenience init(acoth: Double) throws { let rawValue: Double = try Trigonometry.acoth(acoth) self.init(rawValue: rawValue) } /// Create a Radian angle by computing acoth. /// /// - Parameter acoth: The acoth value. /// - Throws: Throws an error if acoth value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=acoth+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcCoth.html) public convenience init(acoth: Float) throws { let rawValue: Double = try Trigonometry.acoth(Double(acoth)) self.init(rawValue: rawValue) } #if !os(Linux) /// Create a Radian angle by computing acoth. /// /// - Parameter acoth: The acoth value. /// - Throws: Throws an error if acoth value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=acoth+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcCoth.html) public convenience init(acoth: CGFloat) throws { let rawValue: CGFloat = try Trigonometry.acoth(acoth) self.init(cgFloat: rawValue) } #endif /// Create a Radian angle by computing asech. /// /// - Parameter asech: The asech value. /// - Throws: Throws an error if asech value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=asech+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcSech.html) public convenience init(asech: Double) throws { let rawValue: Double = try Trigonometry.asech(asech) self.init(rawValue: rawValue) } /// Create a Radian angle by computing asech. /// /// - Parameter asech: The asech value. /// - Throws: Throws an error if asech value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=asech+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcSech.html) public convenience init(asech: Float) throws { let rawValue: Double = try Trigonometry.asech(Double(asech)) self.init(rawValue: rawValue) } #if !os(Linux) /// Create a Radian angle by computing asech. /// /// - Parameter asech: The asech value. /// - Throws: Throws an error if asech value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=asech+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcSech.html) public convenience init(asech: CGFloat) throws { let rawValue: CGFloat = try Trigonometry.asech(asech) self.init(cgFloat: rawValue) } #endif /// Create a Radian angle by computing acsch. /// /// - Parameter acsch: The acsch value. /// - Throws: Throws an error if asech value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=acsch+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcCsch.html) public convenience init(acsch: Double) throws { let rawValue: Double = try Trigonometry.acsch(acsch) self.init(rawValue: rawValue) } /// Create a Radian angle by computing acsch. /// /// - Parameter acsch: The acsch value. /// - Throws: Throws an error if asech value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=acsch+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcCsch.html) public convenience init(acsch: Float) throws { let rawValue: Double = try Trigonometry.acsch(Double(acsch)) self.init(rawValue: rawValue) } #if !os(Linux) /// Create a Radian angle by computing acsch. /// /// - Parameter acsch: The acsch value. /// - Throws: Throws an error if asech value is not valid. /// /// ## Reference: /// [Wolfram Alpha](https://www.wolframalpha.com/input/?i=acsch+(x)) /// /// [Wolfram Documentation Center](http://reference.wolfram.com/language/ref/ArcCsch.html) public convenience init(acsch: CGFloat) throws { let rawValue: CGFloat = try Trigonometry.acsch(acsch) self.init(cgFloat: rawValue) } #endif }
mit
8c3d2822061f0c3debd97d1d2ea8fd3f
34.723247
97
0.619667
3.686596
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/Services/SiteAssemblyService.swift
1
6862
import Foundation // MARK: - EnhancedSiteCreationService /// Working implementation of a `SiteAssemblyService`. /// final class EnhancedSiteCreationService: LocalCoreDataService, SiteAssemblyService { // MARK: Properties /// A service for interacting with WordPress accounts. private let accountService: AccountService /// A service for interacting with WordPress blogs. private let blogService: BlogService /// A facade for WPCOM services. private let remoteService: WordPressComServiceRemote /// The site creation request that's been enqueued. private var creationRequest: SiteCreationRequest? /// This handler is called with changes to the site assembly status. private var statusChangeHandler: SiteAssemblyStatusChangedHandler? /// The most recently created blog corresponding to the site creation request; `nil` otherwise. private(set) var createdBlog: Blog? // MARK: LocalCoreDataService override init(managedObjectContext context: NSManagedObjectContext) { self.accountService = AccountService(managedObjectContext: context) self.blogService = BlogService(managedObjectContext: context) let api: WordPressComRestApi if let wpcomApi = accountService.defaultWordPressComAccount()?.wordPressComRestApi { api = wpcomApi } else { api = WordPressComRestApi.defaultApi(userAgent: WPUserAgent.wordPress()) } self.remoteService = WordPressComServiceRemote(wordPressComRestApi: api) super.init(managedObjectContext: context) } // MARK: SiteAssemblyService private(set) var currentStatus: SiteAssemblyStatus = .idle { didSet { DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.statusChangeHandler?(self.currentStatus) } } } /// This method serves as the entry point for creating an enhanced site. It consists of a few steps: /// 1. The creation request is first validated. /// 2. If a site passes validation, a new service invocation triggers creation. /// 3. The details of the created Blog are persisted to the client. /// /// Previously the site's theme & tagline were set post-creation. This is now handled on the server via Headstart. /// /// - Parameters: /// - creationRequest: the request with which to initiate site creation. /// - changeHandler: this closure is invoked when site assembly status changes occur. /// func createSite(creationRequest: SiteCreationRequest, changeHandler: SiteAssemblyStatusChangedHandler? = nil) { self.creationRequest = creationRequest self.statusChangeHandler = changeHandler beginAssembly() validatePendingRequest() } // MARK: Private behavior private func beginAssembly() { currentStatus = .inProgress } private func endFailedAssembly() { currentStatus = .failed } private func endSuccessfulAssembly() { // Here we designate the new site as the last used, so that it will be presented post-creation if let siteUrl = createdBlog?.url { RecentSitesService().touch(site: siteUrl) StoreContainer.shared.statsWidgets.refreshStatsWidgetsSiteList() } currentStatus = .succeeded } private func performRemoteSiteCreation() { guard let request = creationRequest else { self.endFailedAssembly() return } let validatedRequest = SiteCreationRequest(request: request) remoteService.createWPComSite(request: validatedRequest) { result in // Our result is of type SiteCreationResult, which can be either success or failure switch result { case .success(let response): // A successful response includes a separate success field advising of the outcome of the call. // In my testing, this has never been `false`, but we will be cautious. guard response.success == true else { DDLogError("The service response indicates that it failed.") self.endFailedAssembly() return } self.synchronize(createdSite: response.createdSite) case .failure(let creationError): DDLogError("\(creationError)") self.endFailedAssembly() } } } private func synchronize(createdSite: CreatedSite) { guard let defaultAccount = accountService.defaultWordPressComAccount() else { endFailedAssembly() return } let xmlRpcUrlString = createdSite.xmlrpcString let blog: Blog if let existingBlog = blogService.findBlog(withXmlrpc: xmlRpcUrlString, in: defaultAccount) { blog = existingBlog } else { blog = blogService.createBlog(with: defaultAccount) blog.xmlrpc = xmlRpcUrlString } // The response payload returns a number encoded as a JSON string if let wpcomSiteIdentifier = Int(createdSite.identifier) { blog.dotComID = NSNumber(value: wpcomSiteIdentifier) } blog.url = createdSite.urlString blog.settings?.name = createdSite.title // the original service required a separate call to update the tagline post-creation blog.settings?.tagline = creationRequest?.tagline defaultAccount.defaultBlog = blog ContextManager.sharedInstance().save(managedObjectContext) { [weak self] in guard let self = self else { return } self.blogService.syncBlogAndAllMetadata(blog, completionHandler: { self.accountService.updateUserDetails(for: defaultAccount, success: { self.createdBlog = blog self.endSuccessfulAssembly() }, failure: { error in self.endFailedAssembly() }) }) } } private func validatePendingRequest() { guard let requestPendingValidation = creationRequest else { endFailedAssembly() return } remoteService.createWPComSite(request: requestPendingValidation) { result in switch result { case .success: self.performRemoteSiteCreation() case .failure(let validationError): DDLogError("\(validationError)") self.endFailedAssembly() } } } }
gpl-2.0
78a5d5dc4f4e42056572be6758e5335f
35.5
118
0.624745
5.629204
false
false
false
false
ekreutz/CornerCal
CornerCal/MainMenuController.swift
1
4451
// // MainMenuController.swift // CornerCal // // Created by Emil Kreutzman on 23/09/2017. // Copyright © 2017 Emil Kreutzman. All rights reserved. // import Cocoa class MainMenuController: NSObject, NSCollectionViewDataSource { func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int { return controller.itemCount() } func collectionView(_ collectionView: NSCollectionView, itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem { let id = NSUserInterfaceItemIdentifier.init(rawValue: "CalendarDayItem") let item = collectionView.makeItem(withIdentifier: id, for: indexPath) guard let calendarItem = item as? CalendarDayItem else { return item } let day = controller.getItemAt(index: indexPath.item) calendarItem.setBold(bold: !day.isNumber) calendarItem.setText(text: day.text) calendarItem.setPartlyTransparent(partlyTransparent: !day.isCurrentMonth) calendarItem.setHasRedBackground(hasRedBackground: day.isToday) return calendarItem } @IBOutlet weak var controller: CalendarController! @IBOutlet weak var statusMenu: NSMenu! @IBOutlet weak var monthLabel: NSButton! @IBOutlet weak var buttonLeft: NSButton! @IBOutlet weak var buttonRight: NSButton! @IBOutlet weak var collectionView: NSCollectionView! @IBOutlet weak var settingsWindow: NSWindow! let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) private func updateMenuTime() { statusItem.title = controller.getFormattedDate() } private func updateCalendar() { monthLabel.title = controller.getMonth() applyUIModifications() collectionView.reloadData() } private func getBasicAttributes(button: NSButton, color: NSColor, alpha: CGFloat) -> [NSAttributedStringKey : Any] { let style = NSMutableParagraphStyle() style.alignment = .center return [ NSAttributedStringKey.foregroundColor: color.withAlphaComponent(alpha), NSAttributedStringKey.font: NSFont.systemFont(ofSize: (button.font?.pointSize)!, weight: NSFont.Weight.light), NSAttributedStringKey.backgroundColor: NSColor.clear, NSAttributedStringKey.paragraphStyle: style, NSAttributedStringKey.kern: 0.5 // some additional character spacing ] } private func applyButtonHighlightSettings(button: NSButton) { let color = NSColor.textColor let defaultAlpha: CGFloat = 0.75 let pressedAlpha: CGFloat = 0.45 let defaultAttributes = getBasicAttributes(button: button, color: color, alpha: defaultAlpha) let pressedAttributes = getBasicAttributes(button: button, color: color, alpha: pressedAlpha) button.attributedTitle = NSAttributedString(string: button.title, attributes: defaultAttributes) button.attributedAlternateTitle = NSAttributedString(string: button.title, attributes: pressedAttributes) button.alignment = .center } private func applyUIModifications() { statusItem.button?.font = NSFont.monospacedDigitSystemFont(ofSize: (statusItem.button?.font?.pointSize)!, weight: .regular) applyButtonHighlightSettings(button: monthLabel) applyButtonHighlightSettings(button: buttonLeft) applyButtonHighlightSettings(button: buttonRight) } func refreshState() { statusItem.menu = statusMenu controller.subscribe(onTimeUpdate: updateMenuTime, onCalendarUpdate: updateCalendar) } func deactivate() { controller.pause() } @IBAction func openSettingsClicked(_ sender: NSMenuItem) { let settingsWindowController = NSWindowController.init(window: settingsWindow) settingsWindowController.showWindow(sender) // bring settings window to front NSApp.activate(ignoringOtherApps: true) } @IBAction func leftClicked(_ sender: NSButton) { controller.decrementMonth() } @IBAction func rightClicked(_ sender: NSButton) { controller.incrementMonth() } @IBAction func clearMonthHopping(_ sender: Any) { controller.resetMonth() } }
mit
9a19eeefb9ca8eb766d74cc7ff204b26
34.6
134
0.68382
5.310263
false
false
false
false
wow1881/flybu-hangman
Hangman/HangmanView.swift
1
4196
// // HangmanView.swift // Hangman // // Created by Alex Banh on 8/8/16. // Copyright © 2016 Flybu. All rights reserved. // // HangmanView.swift provides code for the paths and drawing of the gallows image and the // hangman image. HangmanView is called by ViewController.swift in order to update the hangman // image accordingly for every guess. import UIKit // Code to render live preview of drawings in Storyboard @IBDesignable class HangmanView: UIView { // Represents the number of wrong guesses. Can also check to see if value was changed externally @IBInspectable var wrongs: Int = 0 { didSet { if wrongs <= 6 { setNeedsDisplay() // Don't exactly understand this code yet } } } // Represents the scale of the drawings. 1.00 and 0.00 are 100% and 0%, respectively var scale: CGFloat = 1.00 // Represents a relative unit of width to be used var relWidth: CGFloat { return (bounds.width/8) * scale } // Represents a relative unit of height to be used var relHeight: CGFloat { return (bounds.height/8) * scale } // Represents a value for the radius of the skull var skullRadius: CGFloat { return relHeight / 2 } // A point which represents the center point for the hangman's head var skullCenter: CGPoint { return CGPoint(x: relWidth * 6, y: (relHeight * 3) + skullRadius) } // returns a path representing the path to follow for drawing the gallows private func pathForGallows() -> UIBezierPath { let gallowPath = UIBezierPath() gallowPath.moveToPoint(CGPoint(x:relWidth,y:(relHeight)*7)) gallowPath.addLineToPoint(CGPoint(x:(relWidth)*5, y:(relHeight)*7)) gallowPath.moveToPoint(CGPoint(x:(relWidth)*3, y:(relHeight)*7)) gallowPath.addLineToPoint(CGPoint(x:(relWidth)*3, y:(relHeight)*2)) gallowPath.addLineToPoint(CGPoint(x:(relWidth)*6, y:(relHeight)*2)) gallowPath.addLineToPoint(CGPoint(x:(relWidth)*6, y:(relHeight)*3)) gallowPath.lineWidth = 5.0 return gallowPath } // returns a path representing the path to follow for drawing the head private func pathForHead() -> UIBezierPath { let headPath = UIBezierPath(arcCenter: skullCenter, radius: skullRadius, startAngle: 0.0, endAngle: CGFloat(2 * M_PI), clockwise: false) return headPath } // returns a path representing the path to follow for drawing the body private func pathForBody() -> UIBezierPath { let bodyPath = UIBezierPath() bodyPath.moveToPoint(CGPoint(x: relWidth * 6, y: relHeight * 4)) bodyPath.addLineToPoint(CGPoint(x: relWidth * 6, y: relHeight * 5 + relHeight / 2)) return bodyPath } // returns a path representing the path to follow for drawing a leg private func pathForLeg(x_value: CGFloat) -> UIBezierPath { let legPath = UIBezierPath() legPath.moveToPoint(CGPoint(x: relWidth * 6, y: relHeight * 5.5)) legPath.addLineToPoint(CGPoint(x: relWidth * x_value, y: relHeight * 6.5)) return legPath } // returns a path representing the path to follow for drawing an arm private func pathForArm(x_value: CGFloat) -> UIBezierPath { let armPath = UIBezierPath() armPath.moveToPoint(CGPoint(x: relWidth * 6, y: relHeight * 4.5)) armPath.addLineToPoint(CGPoint(x: relWidth * x_value, y: relHeight * 4)) return armPath } // draws various hangman paths depending on the number of guesses which have been used override func drawRect(rect: CGRect) { pathForGallows().stroke() if (wrongs >= 1) { pathForHead().stroke() } if (wrongs >= 2) { pathForBody().stroke() } if (wrongs >= 3) { pathForLeg(5).stroke() } if (wrongs >= 4) { pathForLeg(7).stroke() } if (wrongs >= 5) { pathForArm(4.5).stroke() } if (wrongs >= 6) { pathForArm(7.5).stroke() } } }
mit
45d1910af1a0e18cb757e0f27ac34ba9
34.550847
144
0.620977
4.002863
false
false
false
false
lorentey/GlueKit
Tests/GlueKitTests/TestUtilities.swift
1
587
// // TestUtilities.swift // GlueKit // // Created by Károly Lőrentey on 2015-12-03. // Copyright © 2015–2017 Károly Lőrentey. // import XCTest import Foundation @testable import GlueKit @inline(never) func noop<Value>(_ value: Value) { } func XCTAssertEqual<E: Equatable>(_ a: @autoclosure () -> [[E]], _ b: @autoclosure () -> [[E]], message: String? = nil, file: StaticString = #file, line: UInt = #line) { let av = a() let bv = b() if !av.elementsEqual(bv, by: ==) { XCTFail(message ?? "\(av) is not equal to \(bv)", file: file, line: line) } }
mit
41cd25c49e5707c0503646fe2ef43c93
23.166667
169
0.608621
3.314286
false
true
false
false
zehrer/SOGraphDB
Sources/SOGraphDB_iOS/NodeTableViewController.swift
1
2784
// // NodeTableViewController.swift // SOGraphDB // // Created by Stephan Zehrer on 10.06.14. // Copyright (c) 2014 Stephan Zehrer. All rights reserved. // import UIKit class NodeTableViewController: UITableViewController { var nodeList: SONode? // #pragma mark - Table view data source override func numberOfSectionsInTableView(tableView: UITableView?) -> Int { // Return the number of sections. return 1; } override func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. if let node = nodeList { return Int(node.outRelationshipCount) } return 0 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("A", forIndexPath: indexPath) as UITableViewCell return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView?, canEditRowAtIndexPath indexPath: NSIndexPath?) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView?, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath?) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView?, moveRowAtIndexPath fromIndexPath: NSIndexPath?, toIndexPath: NSIndexPath?) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView?, canMoveRowAtIndexPath indexPath: NSIndexPath?) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
ec9e675a42d33ffbde39e1755b912d09
31.752941
159
0.668822
5.4375
false
false
false
false
cburrows/swift-protobuf
Tests/SwiftProtobufTests/Test_Unknown_proto2.swift
1
9888
// Tests/SwiftProtobufTests/Test_Unknown_proto2.swift - Exercise unknown field handling for proto2 messages // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Proto2 messages preserve unknown fields when decoding and recoding binary /// messages, but drop unknown fields when decoding and recoding JSON format. /// // ----------------------------------------------------------------------------- import Foundation import XCTest import SwiftProtobuf // Verify that unknown fields are correctly preserved by // proto2 messages. class Test_Unknown_proto2: XCTestCase, PBTestHelpers { typealias MessageTestType = ProtobufUnittest_TestEmptyMessage /// Verify that json decode ignores the provided fields but otherwise succeeds func assertJSONIgnores(_ json: String, file: XCTestFileArgType = #file, line: UInt = #line) { do { var options = JSONDecodingOptions() options.ignoreUnknownFields = true let empty = try ProtobufUnittest_TestEmptyMessage(jsonString: json, options: options) do { let json = try empty.jsonString() XCTAssertEqual("{}", json, file: file, line: line) } catch let e { XCTFail("Recoding empty threw error \(e)", file: file, line: line) } } catch { XCTFail("Error decoding into an empty message \(json)", file: file, line: line) } } // Binary PB coding preserves unknown fields for proto2 func testBinaryPB() { func assertRecodes(_ protobufBytes: [UInt8], file: XCTestFileArgType = #file, line: UInt = #line) { do { let empty = try ProtobufUnittest_TestEmptyMessage(serializedData: Data(protobufBytes)) do { let pb = try empty.serializedData() XCTAssertEqual(Data(protobufBytes), pb, file: file, line: line) } catch { XCTFail("Recoding empty failed", file: file, line: line) } } catch { XCTFail("Decoding threw error \(protobufBytes)", file: file, line: line) } } func assertFails(_ protobufBytes: [UInt8], file: XCTestFileArgType = #file, line: UInt = #line) { XCTAssertThrowsError(try ProtobufUnittest_TestEmptyMessage(serializedData: Data(protobufBytes)), file: file, line: line) } // Well-formed input should decode/recode as-is; malformed input should fail to decode assertFails([0]) // Invalid field number assertFails([0, 0]) assertFails([1]) // Invalid field number assertFails([2]) // Invalid field number assertFails([3]) // Invalid field number assertFails([4]) // Invalid field number assertFails([5]) // Invalid field number assertFails([6]) // Invalid field number assertFails([7]) // Invalid field number assertFails([8]) // Varint field #1 but no varint body assertRecodes([8, 0]) assertFails([8, 128]) // Truncated varint assertRecodes([9, 0, 0, 0, 0, 0, 0, 0, 0]) assertFails([9, 0, 0, 0, 0, 0, 0, 0]) // Truncated 64-bit field assertFails([9, 0, 0, 0, 0, 0, 0]) assertFails([9, 0, 0, 0, 0, 0]) assertFails([9, 0, 0, 0, 0]) assertFails([9, 0, 0, 0]) assertFails([9, 0, 0]) assertFails([9, 0]) assertFails([9]) assertFails([10]) // Length-delimited field but no length assertRecodes([10, 0]) // Valid 0-length field assertFails([10, 1]) // Length 1 but truncated assertRecodes([10, 1, 2]) // Length 1 with 1 byte assertFails([10, 2, 1]) // Length 2 truncated assertFails([11]) // Start group #1 but no end group assertRecodes([11, 12]) // Start/end group #1 assertFails([12]) // Bare end group assertRecodes([13, 0, 0, 0, 0]) assertFails([13, 0, 0, 0]) assertFails([13, 0, 0]) assertFails([13, 0]) assertFails([13]) assertFails([14]) assertFails([15]) assertRecodes([248, 255, 255, 255, 15, 0]) // Maximum field number assertFails([128, 128, 128, 128, 16, 0]) // Out-of-range field number assertFails([248, 255, 255, 255, 127, 0]) // Out-of-range field number } // JSON coding drops unknown fields for both proto2 and proto3 func testJSON() { // Unknown fields should be ignored if they are well-formed JSON assertJSONIgnores("{\"unknown\":7}") assertJSONIgnores("{\"unknown\":null}") assertJSONIgnores("{\"unknown\":false}") assertJSONIgnores("{\"unknown\":true}") assertJSONIgnores("{\"unknown\": 7.0}") assertJSONIgnores("{\"unknown\": -3.04}") assertJSONIgnores("{\"unknown\": -7.0e-55}") assertJSONIgnores("{\"unknown\": 7.308e+8}") assertJSONIgnores("{\"unknown\": \"hi!\"}") assertJSONIgnores("{\"unknown\": []}") assertJSONIgnores("{\"unknown\": [3, 4, 5]}") assertJSONIgnores("{\"unknown\": [[3], [4], [5, [6, [7], 8, null, \"no\"]]]}") assertJSONIgnores("{\"unknown\": [3, {}, \"5\"]}") assertJSONIgnores("{\"unknown\": {}}") assertJSONIgnores("{\"unknown\": {\"foo\": 1}}") assertJSONIgnores("{\"unknown\": 7, \"also_unknown\": 8}") assertJSONIgnores("{\"unknown\": 7, \"unknown\": 8}") // ??? // Badly formed JSON should fail to decode, even in unknown sections var options = JSONDecodingOptions() options.ignoreUnknownFields = true assertJSONDecodeFails("{\"unknown\": 1e999}", options: options) assertJSONDecodeFails("{\"unknown\": \"hi!\"", options: options) assertJSONDecodeFails("{\"unknown\": \"hi!}", options: options) assertJSONDecodeFails("{\"unknown\": qqq }", options: options) assertJSONDecodeFails("{\"unknown\": { }", options: options) assertJSONDecodeFails("{\"unknown\": [ }", options: options) assertJSONDecodeFails("{\"unknown\": { ]}", options: options) assertJSONDecodeFails("{\"unknown\": ]}", options: options) assertJSONDecodeFails("{\"unknown\": null true}", options: options) assertJSONDecodeFails("{\"unknown\": nulll }", options: options) assertJSONDecodeFails("{\"unknown\": nul }", options: options) assertJSONDecodeFails("{\"unknown\": Null }", options: options) assertJSONDecodeFails("{\"unknown\": NULL }", options: options) assertJSONDecodeFails("{\"unknown\": True }", options: options) assertJSONDecodeFails("{\"unknown\": False }", options: options) assertJSONDecodeFails("{\"unknown\": nan }", options: options) assertJSONDecodeFails("{\"unknown\": NaN }", options: options) assertJSONDecodeFails("{\"unknown\": Infinity }", options: options) assertJSONDecodeFails("{\"unknown\": infinity }", options: options) assertJSONDecodeFails("{\"unknown\": Inf }", options: options) assertJSONDecodeFails("{\"unknown\": inf }", options: options) assertJSONDecodeFails("{\"unknown\": 1}}", options: options) assertJSONDecodeFails("{\"unknown\": {1, 2}}", options: options) assertJSONDecodeFails("{\"unknown\": 1.2.3.4.5}", options: options) assertJSONDecodeFails("{\"unknown\": -.04}", options: options) assertJSONDecodeFails("{\"unknown\": -19.}", options: options) assertJSONDecodeFails("{\"unknown\": -9.3e+}", options: options) assertJSONDecodeFails("{\"unknown\": 1 2 3}", options: options) assertJSONDecodeFails("{\"unknown\": { true false }}", options: options) assertJSONDecodeFails("{\"unknown\"}", options: options) assertJSONDecodeFails("{\"unknown\": }", options: options) assertJSONDecodeFails("{\"unknown\", \"a\": 1}", options: options) } func assertUnknownFields(_ message: Message, _ bytes: [UInt8], line: UInt = #line) { XCTAssertEqual(message.unknownFields.data, Data(bytes), line: line) } func test_MessageNoStorageClass() throws { var msg1 = ProtobufUnittest_Msg2NoStorage() assertUnknownFields(msg1, []) try msg1.merge(serializedData: Data([24, 1])) // Field 3, varint assertUnknownFields(msg1, [24, 1]) var msg2 = msg1 assertUnknownFields(msg2, [24, 1]) assertUnknownFields(msg1, [24, 1]) try msg2.merge(serializedData: Data([34, 1, 52])) // Field 4, length delimted assertUnknownFields(msg2, [24, 1, 34, 1, 52]) assertUnknownFields(msg1, [24, 1]) try msg1.merge(serializedData: Data([61, 7, 0, 0, 0])) // Field 7, 32-bit value assertUnknownFields(msg2, [24, 1, 34, 1, 52]) assertUnknownFields(msg1, [24, 1, 61, 7, 0, 0, 0]) } func test_MessageUsingStorageClass() throws { var msg1 = ProtobufUnittest_Msg2UsesStorage() assertUnknownFields(msg1, []) try msg1.merge(serializedData: Data([24, 1])) // Field 3, varint assertUnknownFields(msg1, [24, 1]) var msg2 = msg1 assertUnknownFields(msg2, [24, 1]) assertUnknownFields(msg1, [24, 1]) try msg2.merge(serializedData: Data([34, 1, 52])) // Field 4, length delimted assertUnknownFields(msg2, [24, 1, 34, 1, 52]) assertUnknownFields(msg1, [24, 1]) try msg1.merge(serializedData: Data([61, 7, 0, 0, 0])) // Field 7, 32-bit value assertUnknownFields(msg2, [24, 1, 34, 1, 52]) assertUnknownFields(msg1, [24, 1, 61, 7, 0, 0, 0]) } }
apache-2.0
ae4822974cbf1f689533228f79f6ec3b
47.234146
132
0.595065
4.697387
false
true
false
false
lorentey/swift
test/SILOptimizer/definite_init_hang.swift
5
1848
// RUN: %target-swift-frontend -emit-sil %s -parse-as-library -o /dev/null -verify // RUN: %target-swift-frontend -emit-sil %s -parse-as-library -o /dev/null -verify -enable-ownership-stripping-after-serialization var gg: Bool = false var rg: Int = 0 func f1() { } func f2() { } // The old implementation of the LifetimeChecker in DefiniteInitialization had // an exponential computation complexity in some cases. // This test should finish in almost no time. With the old implementation it // took about 8 minutes. func testit() { var tp: (a: Int, b: Int, c: Int) // expected-note {{variable defined here}} tp.a = 1 while gg { if gg { rg = tp.a rg = tp.b // expected-error {{variable 'tp.b' used before being initialized}} tp.c = 27 } // Create some control flow. // With the old implementation each line doubles the computation time. if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } if gg { f1() } else { f2() } } }
apache-2.0
5f63baa5e16b22e78ca0085a60c191f1
29.295082
130
0.511905
2.8
false
false
false
false
kinyong/KYWeiboDemo-Swfit
AYWeibo/AYWeibo/classes/Home/StatuseModel.swift
1
1501
// // StatusesModel.swift // AYWeibo // // Created by Ayong on 16/6/23. // Copyright © 2016年 Ayong. All rights reserved. // import UIKit class StatuseModel: NSObject { /// 微博创建时间 var created_at: String? /// 字符串型的微博ID var idstr: String? /// 微博信息内容 var text: String? /// 微博来源 var source: String? /// 微博作者的用户信息 var user: UserModel? /// 缩略图片地址,没有时不返回此字段 var pic_urls: [[String: AnyObject]]? /// 转发微博 var retweeted_status: StatuseModel? init(dict: [String: AnyObject]) { super.init() self.setValuesForKeysWithDictionary(dict) } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } override func setValue(value: AnyObject?, forKey key: String) { if key == "user" { user = UserModel(dict: value as! [String: AnyObject]) return } if key == "retweeted_status" { retweeted_status = StatuseModel(dict: value as! [String: AnyObject]) return } super.setValue(value, forKey: key) } override var description: String { let keys = ["created_at", "idstr", "text", "source", "user", "thumbnail_pic", "retweeted_status"] let dict = dictionaryWithValuesForKeys(keys) return "\(dict)" } }
apache-2.0
6a0aa3131c56ebd59cd05c1a41e234d3
21.126984
105
0.557389
4.06414
false
false
false
false
dcutting/Syft
Tests/SyftTests/SequenceTests.swift
1
3175
import XCTest @testable import Syft class SequenceTests: XCTestCase { func test_twoPatternsMatchInputPrefix_sequenceMatches() { let sequence = Parser.sequence(Parser.str("abcd"), Parser.str("efg")) let (actualResult, actualRemainder) = sequence.parse("abcdefghij") let expectedResult = Result.match(match: "abcdefg", index: 0) let expectedRemainder = Remainder(text: "hij", index: 7) XCTAssertEqual(expectedResult, actualResult) XCTAssertEqual(expectedRemainder, actualRemainder) } func test_twoPatternsMatchInputExactly_sequenceMatches() { let sequence = Parser.sequence(Parser.str("abc"), Parser.str("def")) let (actualResult, actualRemainder) = sequence.parse("abcdef") let expectedResult = Result.match(match: "abcdef", index: 0) let expectedRemainder = Remainder(text: "", index: 6) XCTAssertEqual(expectedResult, actualResult) XCTAssertEqual(expectedRemainder, actualRemainder) } func test_firstElementDoesNotMatchInput_sequenceDoesNotMatch() { let first = Parser.str("abc") let second = Parser.str("def") let (actualResult, actualRemainder) = Parser.sequence(first, second).parse("zdef") let expectedResult = Result.failure let expectedRemainder = Remainder(text: "zdef", index: 0) XCTAssertEqual(expectedResult, actualResult) XCTAssertEqual(expectedRemainder, actualRemainder) } func test_secondElementDoesNotMatchInput_sequenceDoesNotMatch() { let first = Parser.str("abc") let second = Parser.str("def") let (actualResult, actualRemainder) = Parser.sequence(first, second).parse("abcz") let expectedResult = Result.failure let expectedRemainder = Remainder(text: "z", index: 3) XCTAssertEqual(expectedResult, actualResult) XCTAssertEqual(expectedRemainder, actualRemainder) } func test_sequenceTaggedFollowedBySeriesOfTagged_returnsSeriesOfTagged() { let one = Parser.str("1") let two = Parser.str("2") let repeatedOnes = Parser.repeat(Parser.tagged("o", one), minimum: 1, maximum: nil) let someOnes = Parser.tagged("ones", repeatedOnes) let someTwos = Parser.repeat(Parser.tagged("t", two), minimum: 1, maximum: nil) let someOnesAndTwos = Parser.sequence(someOnes, someTwos) let (actualResult, actualRemainder) = someOnesAndTwos.parse("1122b") let taggedMatch0 = Result.tagged(["o": Result.match(match: "1", index: 0)]) let taggedMatch1 = Result.tagged(["o": Result.match(match: "1", index: 1)]) let taggedOnes = Result.tagged(["ones": Result.series([taggedMatch0, taggedMatch1])]) let taggedMatch2 = Result.tagged(["t": Result.match(match: "2", index: 2)]) let taggedMatch3 = Result.tagged(["t": Result.match(match: "2", index: 3)]) let expectedResult = Result.series([taggedOnes, taggedMatch2, taggedMatch3]) let expectedRemainder = Remainder(text: "b", index: 4) XCTAssertEqual(expectedResult, actualResult) XCTAssertEqual(expectedRemainder, actualRemainder) } }
mit
3e73799de6221eb350ca6eadb7fd3825
39.705128
93
0.68063
4.367263
false
true
false
false