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
banxi1988/BXCityPicker
Pod/Classes/Province.swift
1
1743
// // Province.swift // Pods // // Created by Haizhen Lee on 11/22/16. // // import Foundation import SwiftyJSON import BXModel //Province(tos,eq,hash,public): //name;code;pinyin;City:[r public struct Province :BXModel,RegionInfo{ public let name : String public let code : String public let pinyin : String public let children : [City] public init(json:JSON){ self.name = json["name"].stringValue self.code = json["code"].stringValue self.pinyin = json["pinyin"].stringValue self.children = City.arrayFrom(json["children"]) } public func toDict() -> [String:Any]{ var dict : [String:Any] = [ : ] dict["name"] = self.name dict["code"] = self.code dict["pinyin"] = self.pinyin dict["children"] = self.children.map{ $0.toDict() } return dict } } extension Province: Equatable{ } public func ==(lhs:Province,rhs:Province) -> Bool{ return lhs.code == rhs.code } extension Province : Hashable{ public var hashValue:Int{ return code.hashValue } } extension Province : CustomStringConvertible{ public var description:String { return name } } public func loadLocalProvinces() -> [Province]{ let mainBundle = Bundle.init(for: DistrictPickerController.classForCoder()) let resourceBundle = Bundle(path: mainBundle.bundlePath + "/BXCityPicker.bundle") if let jsonUrl = resourceBundle?.url(forResource: "area", withExtension: "json"){ if let content = try? String(contentsOf:jsonUrl, encoding: String.Encoding.utf8) { let jsonObject = JSON.parse(content) return Province.arrayFrom(jsonObject) } }else{ NSLog("failed to locate area.json in \(resourceBundle?.bundlePath)") } return [] }
mit
a2f318bfcd3ae84974cce459017161fe
25.014925
88
0.666667
3.700637
false
false
false
false
questbeat/SystemInfo
SystemInfo/SystemInfo.swift
1
2636
// // SystemInfo.swift // SystemInfo // // Created by Katsuma Tanaka on 2015/10/15. // Copyright © 2015 Katsuma Tanaka. All rights reserved. // import UIKit public class SystemInfo { // MARK: - Properties public let modelID: String? public let modelName: String? public let systemName: String public let systemVersion: String public let applicationName: String? public let applicationVersion: String? // MARK: - Initializers public class func currentSystemInfo() -> SystemInfo { // Get model ID var mib: [Int32] = [CTL_HW, HW_MACHINE] var len: Int = 0 sysctl(&mib, u_int(mib.count), nil, &len, nil, 0) let machine = UnsafeMutablePointer<CChar>.alloc(len) sysctl(&mib, u_int(mib.count), machine, &len, nil, 0) let modelID = String(CString: machine, encoding: NSASCIIStringEncoding) machine.dealloc(len) // Get model name var modelName: String? if modelID != nil { let bundle = NSBundle(forClass: SystemInfo.self) if let filePath = bundle.pathForResource("ModelNames", ofType: "plist"), let modelNames = NSDictionary(contentsOfFile: filePath) as? [String: String] { modelName = modelNames[modelID!] } } // Get system info let currentDevice = UIDevice.currentDevice() let systemName = currentDevice.systemName let systemVersion = currentDevice.systemVersion // Get application info let mainBundle = NSBundle.mainBundle() let applicationName = mainBundle.objectForInfoDictionaryKey("CFBundleName") as? String let applicationVersion = mainBundle.objectForInfoDictionaryKey("CFBundleShortVersionString") as? String // Create system info object let systemInfo = SystemInfo( modelID: modelID, modelName: modelName, systemName: systemName, systemVersion: systemVersion, applicationName: applicationName, applicationVersion: applicationVersion ) return systemInfo } private init(modelID: String?, modelName: String?, systemName: String, systemVersion: String, applicationName: String?, applicationVersion: String?) { self.modelID = modelID self.modelName = modelName self.systemName = systemName self.systemVersion = systemVersion self.applicationName = applicationName self.applicationVersion = applicationVersion } }
mit
7658af37e8125d917f17513df61d5306
32.782051
154
0.627324
5.377551
false
false
false
false
xuzhuoxi/SearchKit
Source/ExSwift/ExSwift.swift
1
8697
// // ExSwift.swift // ExSwift // // Created by pNre on 07/06/14. // Copyright (c) 2014 pNre. All rights reserved. // import Foundation infix operator =~ infix operator |~ infix operator .. infix operator <=> public typealias Ex = ExSwift open class ExSwift { /** Creates a wrapper that, executes function only after being called n times. - parameter n: No. of times the wrapper has to be called before function is invoked - parameter function: Function to wrap - returns: Wrapper function */ open class func after <P, T> (_ n: Int, function: @escaping (P...) -> T) -> ((P...) -> T?) { typealias Function = ([P]) -> T var times = n return { (params: P...) -> T? in // Workaround for the now illegal (T...) type. let adaptedFunction = unsafeBitCast(function, to: Function.self) times -= 1 if times <= 0 { return adaptedFunction(params) } return nil } } /** Creates a wrapper that, executes function only after being called n times - parameter n: No. of times the wrapper has to be called before function is invoked - parameter function: Function to wrap - returns: Wrapper function */ /*public class func after <T> (n: Int, function: Void -> T) -> (Void -> T?) { func callAfter (args: Any?...) -> T { return function() } let f = ExSwift.after(n, function: callAfter) return { f([nil]) } }*/ /** Creates a wrapper function that invokes function once. Repeated calls to the wrapper function will return the value of the first call. - parameter function: Function to wrap - returns: Wrapper function */ open class func once <P, T> (_ function: @escaping (P...) -> T) -> ((P...) -> T) { typealias Function = ([P]) -> T var returnValue: T? = nil return { (params: P...) -> T in if returnValue != nil { return returnValue! } let adaptedFunction = unsafeBitCast(function, to: Function.self) returnValue = adaptedFunction(params) return returnValue! } } /** Creates a wrapper function that invokes function once. Repeated calls to the wrapper function will return the value of the first call. - parameter function: Function to wrap - returns: Wrapper function */ /*public class func once <T> (function: Void -> T) -> (Void -> T) { let f = ExSwift.once { (params: Any?...) -> T in return function() } return { f([nil]) } }*/ /** Creates a wrapper that, when called, invokes function with any additional partial arguments prepended to those provided to the new function. - parameter function: Function to wrap - parameter parameters: Arguments to prepend - returns: Wrapper function */ open class func partial <P, T> (_ function: @escaping (P...) -> T, _ parameters: P...) -> ((P...) -> T) { typealias Function = ([P]) -> T return { (params: P...) -> T in let adaptedFunction = unsafeBitCast(function, to: Function.self) return adaptedFunction(parameters + params) } } /** Creates a wrapper (without any parameter) that, when called, invokes function automatically passing parameters as arguments. - parameter function: Function to wrap - parameter parameters: Arguments to pass to function - returns: Wrapper function */ open class func bind <P, T> (_ function: @escaping (P...) -> T, _ parameters: P...) -> ((Void) -> T) { typealias Function = ([P]) -> T return { Void -> T in let adaptedFunction = unsafeBitCast(function, to: Function.self) return adaptedFunction(parameters) } } /** Creates a wrapper for function that caches the result of function's invocations. - parameter function: Function with one parameter to cache - returns: Wrapper function */ open class func cached <P: Hashable, R> (_ function: @escaping (P) -> R) -> ((P) -> R) { var cache = [P:R]() return { (param: P) -> R in let key = param if let cachedValue = cache[key] { return cachedValue } else { let value = function(param) cache[key] = value return value } } } /** Creates a wrapper for function that caches the result of function's invocations. - parameter function: Function to cache - parameter hash: Parameters based hashing function that computes the key used to store each result in the cache - returns: Wrapper function */ open class func cached <P: Hashable, R> (_ function: @escaping (P...) -> R, hash: @escaping ((P...) -> P)) -> ((P...) -> R) { typealias Function = ([P]) -> R typealias Hash = ([P]) -> P var cache = [P:R]() return { (params: P...) -> R in let adaptedFunction = unsafeBitCast(function, to: Function.self) let adaptedHash = unsafeBitCast(hash, to: Hash.self) let key = adaptedHash(params) if let cachedValue = cache[key] { return cachedValue } else { let value = adaptedFunction(params) cache[key] = value return value } } } /** Creates a wrapper for function that caches the result of function's invocations. - parameter function: Function to cache - returns: Wrapper function */ open class func cached <P: Hashable, R> (_ function: @escaping (P...) -> R) -> ((P...) -> R) { return cached(function, hash: { (params: P...) -> P in return params[0] }) } /** Utility method to return an NSRegularExpression object given a pattern. - parameter pattern: Regex pattern - parameter ignoreCase: If true the NSRegularExpression is created with the NSRegularExpressionOptions.CaseInsensitive flag - returns: NSRegularExpression object */ internal class func regex (_ pattern: String, ignoreCase: Bool = false) throws -> NSRegularExpression? { var options = NSRegularExpression.Options.dotMatchesLineSeparators.rawValue if ignoreCase { options = NSRegularExpression.Options.caseInsensitive.rawValue | options } return try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options(rawValue: options)) } } func <=> <T: Comparable>(lhs: T, rhs: T) -> Int { if lhs < rhs { return -1 } else if lhs > rhs { return 1 } else { return 0 } } /** * Internal methods */ extension ExSwift { /** * Converts, if possible, and flattens an object from its Objective-C * representation to the Swift one. * @param object Object to convert * @returns Flattenend array of converted values */ internal class func bridgeObjCObject <T, S> (_ object: S) -> [T] { var result = [T]() let reflection = Mirror(reflecting: object) let mirrorChildrenCollection = AnyRandomAccessCollection(reflection.children) // object has an Objective-C type if let obj = object as? T { // object has type T result.append(obj) } else if reflection.subjectType == NSArray.self { // If it is an NSArray, flattening will produce the expected result if let array = object as? NSArray { result += array.flatten() } else if let bridged = mirrorChildrenCollection as? T { result.append(bridged) } } else if object is Array<T> { // object is a native Swift array // recursively convert each item for (_, value) in mirrorChildrenCollection! { result += Ex.bridgeObjCObject(value) } } return result } }
mit
2c8d011f41d860450bece68d1d1ddb66
30.397112
131
0.543176
4.955556
false
false
false
false
gurenupet/hah-auth-ios-swift
hah-auth-ios-swift/Pods/Mixpanel-swift/Mixpanel/Decide.swift
1
8100
// // Decide.swift // Mixpanel // // Created by Yarden Eitan on 8/5/16. // Copyright © 2016 Mixpanel. All rights reserved. // import Foundation import UIKit struct DecideResponse { var unshownInAppNotifications: [InAppNotification] var newCodelessBindings: Set<CodelessBinding> var newVariants: Set<Variant> var toFinishVariants: Set<Variant> init() { unshownInAppNotifications = [] newCodelessBindings = Set() newVariants = Set() toFinishVariants = Set() } } class Decide { let decideRequest: DecideRequest var decideFetched = false var notificationsInstance = InAppNotifications() var codelessInstance = Codeless() var ABTestingInstance = ABTesting() var webSocketWrapper: WebSocketWrapper? var gestureRecognizer: UILongPressGestureRecognizer? var automaticEventsEnabled: Bool? var inAppDelegate: InAppNotificationsDelegate? { set { notificationsInstance.delegate = newValue } get { return notificationsInstance.delegate } } var enableVisualEditorForCodeless = true let switchboardURL = "wss://switchboard.mixpanel.com" required init(basePathIdentifier: String) { self.decideRequest = DecideRequest(basePathIdentifier: basePathIdentifier) } func checkDecide(forceFetch: Bool = false, distinctId: String, token: String, completion: @escaping ((_ response: DecideResponse?) -> Void)) { var decideResponse = DecideResponse() if !decideFetched || forceFetch { let semaphore = DispatchSemaphore(value: 0) decideRequest.sendRequest(distinctId: distinctId, token: token) { decideResult in guard let result = decideResult else { semaphore.signal() completion(nil) return } var parsedNotifications = [InAppNotification]() if let rawNotifications = result["notifications"] as? [[String: Any]] { for rawNotif in rawNotifications { if let notificationType = rawNotif["type"] as? String { if notificationType == InAppType.takeover.rawValue, let notification = TakeoverNotification(JSONObject: rawNotif) { parsedNotifications.append(notification) } else if notificationType == InAppType.mini.rawValue, let notification = MiniNotification(JSONObject: rawNotif) { parsedNotifications.append(notification) } } } } else { Logger.error(message: "in-app notifications check response format error") } self.notificationsInstance.inAppNotifications = parsedNotifications var parsedCodelessBindings = Set<CodelessBinding>() if let rawCodelessBindings = result["event_bindings"] as? [[String: Any]] { for rawBinding in rawCodelessBindings { if let binding = Codeless.createBinding(object: rawBinding) { parsedCodelessBindings.insert(binding) } } } else { Logger.debug(message: "codeless event bindings check response format error") } let finishedCodelessBindings = self.codelessInstance.codelessBindings.subtracting(parsedCodelessBindings) for finishedBinding in finishedCodelessBindings { finishedBinding.stop() } let newCodelessBindings = parsedCodelessBindings.subtracting(self.codelessInstance.codelessBindings) decideResponse.newCodelessBindings = newCodelessBindings self.codelessInstance.codelessBindings.formUnion(newCodelessBindings) self.codelessInstance.codelessBindings.subtract(finishedCodelessBindings) var parsedVariants = Set<Variant>() if let rawVariants = result["variants"] as? [[String: Any]] { for rawVariant in rawVariants { if let variant = Variant(JSONObject: rawVariant) { parsedVariants.insert(variant) } } } else { Logger.debug(message: "variants check response format error") } let runningVariants = Set(self.ABTestingInstance.variants.filter { return $0.running }) decideResponse.toFinishVariants = runningVariants.subtracting(parsedVariants) let newVariants = parsedVariants.subtracting(runningVariants) decideResponse.newVariants = newVariants self.ABTestingInstance.variants = newVariants.union(runningVariants) if let automaticEvents = result["automatic_events"] as? Bool { self.automaticEventsEnabled = automaticEvents } self.decideFetched = true semaphore.signal() } _ = semaphore.wait(timeout: DispatchTime.distantFuture) } else { Logger.info(message: "decide cache found, skipping network request") } decideResponse.unshownInAppNotifications = notificationsInstance.inAppNotifications.filter { !notificationsInstance.shownNotifications.contains($0.ID) } Logger.info(message: "decide check found \(decideResponse.unshownInAppNotifications.count) " + "available notifications out of " + "\(notificationsInstance.inAppNotifications.count) total") Logger.info(message: "decide check found \(decideResponse.newCodelessBindings.count) " + "new codeless bindings out of \(codelessInstance.codelessBindings)") Logger.info(message: "decide check found \(decideResponse.newVariants.count) " + "new variants out of \(ABTestingInstance.variants)") completion(decideResponse) } func connectToWebSocket(token: String, mixpanelInstance: MixpanelInstance, reconnect: Bool = false) { var oldInterval = 0.0 let webSocketURL = "\(switchboardURL)/connect?key=\(token)&type=device" guard let url = URL(string: webSocketURL) else { Logger.error(message: "bad URL to connect to websocket \(webSocketURL)") return } let connectCallback = { [weak mixpanelInstance] in guard let mixpanelInstance = mixpanelInstance else { return } oldInterval = mixpanelInstance.flushInterval mixpanelInstance.flushInterval = 1 UIApplication.shared.isIdleTimerDisabled = true for binding in self.codelessInstance.codelessBindings { binding.stop() } for variant in self.ABTestingInstance.variants { variant.stop() } } let disconnectCallback = { [weak mixpanelInstance] in guard let mixpanelInstance = mixpanelInstance else { return } mixpanelInstance.flushInterval = oldInterval UIApplication.shared.isIdleTimerDisabled = false for binding in self.codelessInstance.codelessBindings { binding.execute() } for variant in self.ABTestingInstance.variants { variant.execute() } } webSocketWrapper = WebSocketWrapper(url: url, keepTrying: reconnect, connectCallback: connectCallback, disconnectCallback: disconnectCallback) } }
mit
13dabe3318fbffe2b0431323f6e07c45
39.495
121
0.588838
5.695499
false
false
false
false
fahidattique55/FAPanels
FAPanels/Classes/FAPanel.swift
1
19517
// // FAPanel.swift // FAPanels // // Created by Fahid Attique on 10/06/2017. // Copyright © 2017 Fahid Attique. All rights reserved. // import UIKit // FAPanel Delegate public protocol FAPanelStateDelegate { func centerPanelWillBecomeActive() func leftPanelWillBecomeActive() func rightPanelWillBecomeActive() func centerPanelDidBecomeActive() func leftPanelDidBecomeActive() func rightPanelDidBecomeActive() } public extension FAPanelStateDelegate { func centerPanelWillBecomeActive() {} func leftPanelWillBecomeActive() {} func rightPanelWillBecomeActive() {} func centerPanelDidBecomeActive() {} func leftPanelDidBecomeActive() {} func rightPanelDidBecomeActive() {} } // Left Panel Position public enum FASidePanelPosition: Int { case front = 0, back } // FAPanel Controller open class FAPanelController: UIViewController { // MARK:- Open open var configs = FAPanelConfigurations() open func center( _ controller: UIViewController, afterThat completion: (() -> Void)?) { setCenterPanelVC(controller, afterThat: completion) } @discardableResult open func center( _ controller: UIViewController) -> FAPanelController { centerPanelVC = controller return self } @discardableResult open func left( _ controller: UIViewController?) -> FAPanelController { leftPanelVC = controller return self } @discardableResult open func right( _ controller: UIViewController?) -> FAPanelController { rightPanelVC = controller return self } open func openLeft(animated:Bool) { openLeft(animated: animated, shouldBounce: configs.bounceOnLeftPanelOpen) } open func openRight(animated:Bool) { openRight(animated: animated, shouldBounce: configs.bounceOnRightPanelOpen) } open func openCenter(animated:Bool) { // Can be used for the same menu option selected if centerPanelHidden { centerPanelHidden = false unhideCenterPanel() } openCenter(animated: animated, shouldBounce: configs.bounceOnCenterPanelOpen, afterThat: nil) } open func closeLeft() { if isLeftPanelOnFront { slideLeftPanelOut(animated: true, afterThat: nil) } else { openCenter(animated: true) } } open func closeRight() { if isRightPanelOnFront { slideRightPanelOut(animated: true, afterThat: nil) } else { openCenter(animated: true) } } // MARK:- Life Cycle public init() { super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func viewDidLoad() { super.viewDidLoad() viewConfigurations() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) layoutSideContainers(withDuration: 0.0, animated: false) layoutSidePanelVCs() centerPanelContainer.frame = updateCenterPanelSlidingFrame() } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) _ = updateCenterPanelSlidingFrame() } override open func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let shadowPath = UIBezierPath(rect: leftPanelContainer.bounds) leftPanelContainer.layer.masksToBounds = false leftPanelContainer.layer.shadowColor = configs.shadowColor leftPanelContainer.layer.shadowOffset = configs.shadowOffset leftPanelContainer.layer.shadowOpacity = configs.shadowOppacity leftPanelContainer.layer.shadowPath = shadowPath.cgPath } deinit { if centerPanelVC != nil { centerPanelVC!.removeObserver(self, forKeyPath: keyPathOfView) } } private func viewConfigurations() { view.autoresizingMask = [.flexibleHeight, .flexibleWidth] centerPanelContainer = UIView(frame: view.bounds) centeralPanelSlidingFrame = self.centerPanelContainer.frame centerPanelHidden = false leftPanelContainer = UIView(frame: view.bounds) layoutLeftContainer() leftPanelContainer.isHidden = true rightPanelContainer = UIView(frame: view.bounds) layoutRightContainer() rightPanelContainer.isHidden = true containersConfigurations() view.addSubview(centerPanelContainer) view.addSubview(leftPanelContainer) view.addSubview(rightPanelContainer) state = .center swapCenter(animated: false, FromVC: nil, withVC: centerPanelVC) view.bringSubviewToFront(centerPanelContainer) tapView = UIView() tapView?.alpha = 0.0 } private func containersConfigurations() { leftPanelContainer.autoresizingMask = [.flexibleHeight, .flexibleRightMargin] rightPanelContainer.autoresizingMask = [.flexibleHeight, .flexibleLeftMargin] centerPanelContainer.autoresizingMask = [.flexibleHeight, .flexibleWidth] centerPanelContainer.frame = view.bounds } // MARK:- internal Properties internal var leftPanelContainer : UIView! internal var rightPanelContainer : UIView! internal var centerPanelContainer: UIView! internal var visiblePanelVC: UIViewController! internal var centeralPanelSlidingFrame: CGRect = CGRect.zero internal var centerPanelOriginBeforePan: CGPoint = CGPoint.zero internal var leftPanelOriginBeforePan: CGPoint = CGPoint.zero internal var rightPanelOriginBeforePan: CGPoint = CGPoint.zero internal let keyPathOfView = "view" internal static var kvoContext: Character! internal var _leftPanelPosition : FASidePanelPosition = .back { didSet { if _leftPanelPosition == .front { configs.resizeLeftPanel = false } layoutLeftContainer() } } internal var isLeftPanelOnFront : Bool { return leftPanelPosition == .front } open var leftPanelPosition : FASidePanelPosition { get { return _leftPanelPosition } set { _leftPanelPosition = newValue } } internal var _rightPanelPosition : FASidePanelPosition = .back { didSet { if _rightPanelPosition == .front { configs.resizeRightPanel = true } layoutRightContainer() layoutSidePanelVCs() } } internal var isRightPanelOnFront : Bool { return rightPanelPosition == .front } open var rightPanelPosition : FASidePanelPosition { get { return _rightPanelPosition } set { _rightPanelPosition = newValue } } internal enum GestureStartDirection: UInt { case left = 0, right, none } internal var paningStartDirection: GestureStartDirection = .none internal var _leftPanelVC: UIViewController? = nil internal var leftPanelVC : UIViewController? { get{ return _leftPanelVC } set{ if newValue != _leftPanelVC { _leftPanelVC?.willMove(toParent: nil) _leftPanelVC?.view.removeFromSuperview() _leftPanelVC?.removeFromParent() _leftPanelVC = newValue if _leftPanelVC != nil { addChild(_leftPanelVC!) _leftPanelVC!.didMove(toParent: self) } else { leftPanelContainer.isHidden = true } if state == .left { visiblePanelVC = _leftPanelVC } } } } open var left: UIViewController? { get { return leftPanelVC } } internal var _rightPanelVC: UIViewController? = nil internal var rightPanelVC : UIViewController? { get{ return _rightPanelVC } set{ if newValue != _rightPanelVC { _rightPanelVC?.willMove(toParent: nil) _rightPanelVC?.view.removeFromSuperview() _rightPanelVC?.removeFromParent() _rightPanelVC = newValue if _rightPanelVC != nil { addChild(_rightPanelVC!) _rightPanelVC?.didMove(toParent: self) } else { rightPanelContainer.isHidden = true } if state == .right { visiblePanelVC = _rightPanelVC } } } } open var right: UIViewController? { get { return rightPanelVC } } internal var _centerPanelVC: UIViewController? = nil internal var centerPanelVC : UIViewController? { get{ return _centerPanelVC } set{ setCenterPanelVC(newValue, afterThat: nil) } } open var center: UIViewController? { get { return centerPanelVC } } internal func setCenterPanelVC( _ newValue: UIViewController?, afterThat completion: (() -> Void)? = nil) { let previousVC: UIViewController? = _centerPanelVC if _centerPanelVC != newValue { _centerPanelVC?.removeObserver(self, forKeyPath: keyPathOfView) _centerPanelVC = newValue _centerPanelVC!.addObserver(self, forKeyPath: keyPathOfView, options: NSKeyValueObservingOptions.initial, context: &FAPanelController.kvoContext) if state == .center { visiblePanelVC = _centerPanelVC } } if isViewLoaded && state == .center { swapCenter(animated: configs.changeCenterPanelAnimated, FromVC: previousVC, withVC: _centerPanelVC!) } else if (self.isViewLoaded) { if state == .left { if isLeftPanelOnFront { swapCenter(animated: false,FromVC: previousVC, withVC: self._centerPanelVC) slideLeftPanelOut(animated: true, afterThat: completion) return } } else if state == .right { if isRightPanelOnFront { swapCenter(animated: false, FromVC: previousVC, withVC: self._centerPanelVC) slideRightPanelOut(animated: true, afterThat: completion) return } } UIView.animate(withDuration: 0.2, animations: { if self.configs.bounceOnCenterPanelChange { let x: CGFloat = (self.state == .left) ? self.view.bounds.size.width : -self.view.bounds.size.width self.centeralPanelSlidingFrame.origin.x = x } self.centerPanelContainer.frame = self.centeralPanelSlidingFrame }, completion: { (finised) in self.swapCenter(animated: false,FromVC: previousVC, withVC: self._centerPanelVC) self.openCenter(animated: true, shouldBounce: false, afterThat: completion) }) } } // Left panel frame on basis of its position type i.e: front or back internal func layoutLeftContainer() { if isLeftPanelOnFront { if leftPanelContainer != nil { var frame = leftPanelContainer.frame frame.size.width = widthForLeftPanelVC frame.origin.x = -widthForLeftPanelVC leftPanelContainer.frame = frame } } else { if leftPanelContainer != nil { leftPanelContainer.frame = view.bounds } } } internal func layoutRightContainer() { if isRightPanelOnFront { if rightPanelContainer != nil { var frame = rightPanelContainer.frame frame.size.width = widthForRightPanelVC frame.origin.x = view.frame.size.width rightPanelContainer.frame = frame } } else { if rightPanelContainer != nil { rightPanelContainer.frame = view.bounds } } } // tap view on centeral panel, to dismiss side panels if visible internal var _tapView: UIView? = nil internal var tapView: UIView? { get{ return _tapView } set{ if newValue != _tapView { _tapView?.removeFromSuperview() _tapView = newValue if _tapView != nil { _tapView?.backgroundColor = configs.colorForTapView _tapView?.frame = centerPanelContainer.bounds _tapView?.autoresizingMask = [.flexibleWidth, .flexibleHeight] addTapGestureToView(view: _tapView!) if configs.canRecognizePanGesture { addPanGesture(toView: _tapView!) } centerPanelContainer.addSubview(_tapView!) } } } } // visible widths for side panels internal var widthForLeftPanelVC: CGFloat { get{ if centerPanelHidden && configs.resizeLeftPanel { return view.bounds.size.width } else { return configs.leftPanelWidth == 0.0 ? CGFloat(floorf(Float(view.bounds.size.width * configs.leftPanelGapPercentage))) : configs.leftPanelWidth } } } internal var widthForRightPanelVC: CGFloat { get{ if centerPanelHidden && configs.resizeRightPanel { return view.bounds.size.width } else { return configs.rightPanelWidth == 0 ? CGFloat(floorf(Float(view.bounds.size.width * configs.rightPanelGapPercentage))) : configs.rightPanelWidth } } } // style for panels internal func applyStyle(onView: UIView) { onView.layer.cornerRadius = configs.cornerRadius onView.clipsToBounds = true } // Panel States open var delegate: FAPanelStateDelegate? = nil internal var _state: FAPanelVisibleState = .center { willSet { switch newValue { case .center: delegate?.centerPanelWillBecomeActive() break case .left: delegate?.leftPanelWillBecomeActive() break case .right: delegate?.rightPanelWillBecomeActive() break } } didSet { switch _state { case .center: delegate?.centerPanelDidBecomeActive() break case .left: delegate?.leftPanelDidBecomeActive() break case .right: delegate?.rightPanelDidBecomeActive() break } } } internal var state: FAPanelVisibleState { get{ return _state } set{ if _state != newValue { _state = newValue switch _state { case .center: visiblePanelVC = centerPanelVC leftPanelContainer.isUserInteractionEnabled = false rightPanelContainer.isUserInteractionEnabled = false break case .left: visiblePanelVC = leftPanelVC leftPanelContainer.isUserInteractionEnabled = true break case .right: visiblePanelVC = rightPanelVC rightPanelContainer.isUserInteractionEnabled = true break } setNeedsStatusBarAppearanceUpdate() } } } // Center Panel Hiding Functions internal var _centerPanelHidden: Bool = false internal var centerPanelHidden: Bool { get{ return _centerPanelHidden } set{ setCenterPanelHidden(newValue, animated: false, duration: 0.0) } } internal func setCenterPanelHidden(_ hidden: Bool, animated: Bool, duration: TimeInterval) { if hidden != _centerPanelHidden && state != .center { _centerPanelHidden = hidden let animationDuration = animated ? duration : 0.0 if hidden { UIView.animate(withDuration: animationDuration, animations: { var frame: CGRect = self.centerPanelContainer.frame frame.origin.x = self.state == .left ? self.centerPanelContainer.frame.size.width : -self.centerPanelContainer.frame.size.width self.centerPanelContainer.frame = frame self.layoutSideContainers(withDuration: 0.0, animated: false) if self.configs.resizeLeftPanel || self.configs.resizeRightPanel { self.layoutSidePanelVCs() } }, completion: { (finished) in if self._centerPanelHidden { self.hideCenterPanel() } }) } else { unhideCenterPanel() UIView.animate(withDuration: animationDuration, animations: { if self.state == .left { self.openLeft(animated: false) } else { self.openRight(animated: false) } if self.configs.resizeLeftPanel || self.configs.resizeRightPanel { self.layoutSidePanelVCs() } }) } } } }
apache-2.0
972ef3b67df854a90498b7dda246af27
25.125837
160
0.532076
5.728207
false
false
false
false
X140Yu/Lemon
Lemon/Library/Extension/UIResponder+Lemon.swift
1
662
import UIKit extension UIResponder { var findbleNavigationController: UINavigationController? { var navigationController: UINavigationController? if let nav = self as? UINavigationController { navigationController = nav } else if let vc = self as? UIViewController { navigationController = vc.navigationController } else { var nRes = next while nRes != nil && !(nRes?.isKind(of: UIViewController.self) ?? false) { nRes = nRes?.next } if nRes != nil, let nVC = nRes as? UIViewController { navigationController = nVC.navigationController } } return navigationController } }
gpl-3.0
58505c12003ad566d29248dc7a31fe7d
26.583333
80
0.670695
4.977444
false
false
false
false
kstaring/swift
stdlib/public/SDK/Foundation/Locale.swift
3
19272
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_exported import Foundation // Clang module @_silgen_name("__NSLocaleIsAutoupdating") internal func __NSLocaleIsAutoupdating(_ locale: NSLocale) -> Bool @_silgen_name("__NSLocaleAutoupdating") internal func __NSLocaleAutoupdating() -> NSLocale @_silgen_name("__NSLocaleCurrent") internal func __NSLocaleCurrent() -> NSLocale @_silgen_name("__NSLocaleBackstop") internal func __NSLocaleBackstop() -> NSLocale /** `Locale` encapsulates information about linguistic, cultural, and technological conventions and standards. Examples of information encapsulated by a locale include the symbol used for the decimal separator in numbers and the way dates are formatted. Locales are typically used to provide, format, and interpret information about and according to the user's customs and preferences. They are frequently used in conjunction with formatters. Although you can use many locales, you usually use the one associated with the current user. */ public struct Locale : Hashable, Equatable, ReferenceConvertible { public typealias ReferenceType = NSLocale public typealias LanguageDirection = NSLocale.LanguageDirection fileprivate var _wrapped : NSLocale private var _autoupdating : Bool /// Returns a locale which tracks the user's current preferences. /// /// The autoupdatingCurrent locale will stop auto-updating if mutated. It only compares equal to itself. public static var autoupdatingCurrent : Locale { return Locale(adoptingReference: __NSLocaleAutoupdating(), autoupdating: true) } /// Returns the user's current locale. public static var current : Locale { return Locale(adoptingReference: __NSLocaleCurrent(), autoupdating: false) } @available(*, unavailable, message: "Consider using the user's locale or nil instead, depending on use case") public static var system : Locale { fatalError() } // MARK: - // /// Return a locale with the specified identifier. public init(identifier: String) { _wrapped = NSLocale(localeIdentifier: identifier) _autoupdating = false } fileprivate init(reference: NSLocale) { _wrapped = reference.copy() as! NSLocale if __NSLocaleIsAutoupdating(reference) { _autoupdating = true } else { _autoupdating = false } } private init(adoptingReference reference: NSLocale, autoupdating: Bool) { _wrapped = reference _autoupdating = autoupdating } // MARK: - // /// Returns a localized string for a specified identifier. /// /// For example, in the "en" locale, the result for `"es"` is `"Spanish"`. public func localizedString(forIdentifier identifier: String) -> String? { return _wrapped.displayName(forKey: .identifier, value: identifier) } /// Returns a localized string for a specified language code. /// /// For example, in the "en" locale, the result for `"es"` is `"Spanish"`. public func localizedString(forLanguageCode languageCode: String) -> String? { return _wrapped.displayName(forKey: .languageCode, value: languageCode) } /// Returns a localized string for a specified region code. /// /// For example, in the "en" locale, the result for `"fr"` is `"France"`. public func localizedString(forRegionCode regionCode: String) -> String? { return _wrapped.displayName(forKey: .countryCode, value: regionCode) } /// Returns a localized string for a specified script code. /// /// For example, in the "en" locale, the result for `"Hans"` is `"Simplified Han"`. public func localizedString(forScriptCode scriptCode: String) -> String? { return _wrapped.displayName(forKey: .scriptCode, value: scriptCode) } /// Returns a localized string for a specified variant code. /// /// For example, in the "en" locale, the result for `"POSIX"` is `"Computer"`. public func localizedString(forVariantCode variantCode: String) -> String? { return _wrapped.displayName(forKey: .variantCode, value: variantCode) } /// Returns a localized string for a specified `Calendar.Identifier`. /// /// For example, in the "en" locale, the result for `.buddhist` is `"Buddhist Calendar"`. public func localizedString(for calendarIdentifier: Calendar.Identifier) -> String? { // NSLocale doesn't export a constant for this let result = CFLocaleCopyDisplayNameForPropertyValue(unsafeBitCast(_wrapped, to: CFLocale.self), .calendarIdentifier, Calendar._toNSCalendarIdentifier(calendarIdentifier).rawValue as CFString) as String return result } /// Returns a localized string for a specified ISO 4217 currency code. /// /// For example, in the "en" locale, the result for `"USD"` is `"US Dollar"`. /// - seealso: `Locale.isoCurrencyCodes` public func localizedString(forCurrencyCode currencyCode: String) -> String? { return _wrapped.displayName(forKey: .currencyCode, value: currencyCode) } /// Returns a localized string for a specified ICU collation identifier. /// /// For example, in the "en" locale, the result for `"phonebook"` is `"Phonebook Sort Order"`. public func localizedString(forCollationIdentifier collationIdentifier: String) -> String? { return _wrapped.displayName(forKey: .collationIdentifier, value: collationIdentifier) } /// Returns a localized string for a specified ICU collator identifier. public func localizedString(forCollatorIdentifier collatorIdentifier: String) -> String? { return _wrapped.displayName(forKey: .collatorIdentifier, value: collatorIdentifier) } // MARK: - // /// Returns the identifier of the locale. public var identifier: String { return _wrapped.localeIdentifier } /// Returns the language code of the locale, or nil if has none. /// /// For example, for the locale "zh-Hant-HK", returns "zh". public var languageCode: String? { return _wrapped.object(forKey: .languageCode) as? String } /// Returns the region code of the locale, or nil if it has none. /// /// For example, for the locale "zh-Hant-HK", returns "HK". public var regionCode: String? { // n.b. this is called countryCode in ObjC if let result = _wrapped.object(forKey: .countryCode) as? String { if result.isEmpty { return nil } else { return result } } else { return nil } } /// Returns the script code of the locale, or nil if has none. /// /// For example, for the locale "zh-Hant-HK", returns "Hant". public var scriptCode: String? { return _wrapped.object(forKey: .scriptCode) as? String } /// Returns the variant code for the locale, or nil if it has none. /// /// For example, for the locale "en_POSIX", returns "POSIX". public var variantCode: String? { if let result = _wrapped.object(forKey: .variantCode) as? String { if result.isEmpty { return nil } else { return result } } else { return nil } } /// Returns the exemplar character set for the locale, or nil if has none. public var exemplarCharacterSet: CharacterSet? { return _wrapped.object(forKey: .exemplarCharacterSet) as? CharacterSet } /// Returns the calendar for the locale, or the Gregorian calendar as a fallback. public var calendar: Calendar { // NSLocale should not return nil here if let result = _wrapped.object(forKey: .calendar) as? Calendar { return result } else { return Calendar(identifier: .gregorian) } } /// Returns the collation identifier for the locale, or nil if it has none. /// /// For example, for the locale "en_US@collation=phonebook", returns "phonebook". public var collationIdentifier: String? { return _wrapped.object(forKey: .collationIdentifier) as? String } /// Returns true if the locale uses the metric system. /// /// -seealso: MeasurementFormatter public var usesMetricSystem: Bool { // NSLocale should not return nil here, but just in case if let result = (_wrapped.object(forKey: .usesMetricSystem) as? NSNumber)?.boolValue { return result } else { return false } } /// Returns the decimal separator of the locale. /// /// For example, for "en_US", returns ".". public var decimalSeparator: String? { return _wrapped.object(forKey: .decimalSeparator) as? String } /// Returns the grouping separator of the locale. /// /// For example, for "en_US", returns ",". public var groupingSeparator: String? { return _wrapped.object(forKey: .groupingSeparator) as? String } /// Returns the currency symbol of the locale. /// /// For example, for "zh-Hant-HK", returns "HK$". public var currencySymbol: String? { return _wrapped.object(forKey: .currencySymbol) as? String } /// Returns the currency code of the locale. /// /// For example, for "zh-Hant-HK", returns "HKD". public var currencyCode: String? { return _wrapped.object(forKey: .currencyCode) as? String } /// Returns the collator identifier of the locale. public var collatorIdentifier: String? { return _wrapped.object(forKey: .collatorIdentifier) as? String } /// Returns the quotation begin delimiter of the locale. /// /// For example, returns `“` for "en_US", and `「` for "zh-Hant-HK". public var quotationBeginDelimiter: String? { return _wrapped.object(forKey: .quotationBeginDelimiterKey) as? String } /// Returns the quotation end delimiter of the locale. /// /// For example, returns `”` for "en_US", and `」` for "zh-Hant-HK". public var quotationEndDelimiter: String? { return _wrapped.object(forKey: .quotationEndDelimiterKey) as? String } /// Returns the alternate quotation begin delimiter of the locale. /// /// For example, returns `‘` for "en_US", and `『` for "zh-Hant-HK". public var alternateQuotationBeginDelimiter: String? { return _wrapped.object(forKey: .alternateQuotationBeginDelimiterKey) as? String } /// Returns the alternate quotation end delimiter of the locale. /// /// For example, returns `’` for "en_US", and `』` for "zh-Hant-HK". public var alternateQuotationEndDelimiter: String? { return _wrapped.object(forKey: .alternateQuotationEndDelimiterKey) as? String } // MARK: - // /// Returns a list of available `Locale` identifiers. public static var availableIdentifiers: [String] { return NSLocale.availableLocaleIdentifiers } /// Returns a list of available `Locale` language codes. public static var isoLanguageCodes: [String] { return NSLocale.isoLanguageCodes } /// Returns a list of available `Locale` region codes. public static var isoRegionCodes: [String] { // This was renamed from Obj-C return NSLocale.isoCountryCodes } /// Returns a list of available `Locale` currency codes. public static var isoCurrencyCodes: [String] { return NSLocale.isoCurrencyCodes } /// Returns a list of common `Locale` currency codes. public static var commonISOCurrencyCodes: [String] { return NSLocale.commonISOCurrencyCodes } /// Returns a list of the user's preferred languages. /// /// - note: `Bundle` is responsible for determining the language that your application will run in, based on the result of this API and combined with the languages your application supports. /// - seealso: `Bundle.preferredLocalizations(from:)` /// - seealso: `Bundle.preferredLocalizations(from:forPreferences:)` public static var preferredLanguages: [String] { return NSLocale.preferredLanguages } /// Returns a dictionary that splits an identifier into its component pieces. public static func components(fromIdentifier string: String) -> [String : String] { return NSLocale.components(fromLocaleIdentifier: string) } /// Constructs an identifier from a dictionary of components. public static func identifier(fromComponents components: [String : String]) -> String { return NSLocale.localeIdentifier(fromComponents: components) } /// Returns a canonical identifier from the given string. public static func canonicalIdentifier(from string: String) -> String { return NSLocale.canonicalLocaleIdentifier(from: string) } /// Returns a canonical language identifier from the given string. public static func canonicalLanguageIdentifier(from string: String) -> String { return NSLocale.canonicalLanguageIdentifier(from: string) } /// Returns the `Locale` identifier from a given Windows locale code, or nil if it could not be converted. public static func identifier(fromWindowsLocaleCode code: Int) -> String? { return NSLocale.localeIdentifier(fromWindowsLocaleCode: UInt32(code)) } /// Returns the Windows locale code from a given identifier, or nil if it could not be converted. public static func windowsLocaleCode(fromIdentifier identifier: String) -> Int? { let result = NSLocale.windowsLocaleCode(fromLocaleIdentifier: identifier) if result == 0 { return nil } else { return Int(result) } } /// Returns the character direction for a specified language code. public static func characterDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection { return NSLocale.characterDirection(forLanguage: isoLangCode) } /// Returns the line direction for a specified language code. public static func lineDirection(forLanguage isoLangCode: String) -> Locale.LanguageDirection { return NSLocale.lineDirection(forLanguage: isoLangCode) } // MARK: - @available(*, unavailable, renamed: "init(identifier:)") public init(localeIdentifier: String) { fatalError() } @available(*, unavailable, renamed: "identifier") public var localeIdentifier: String { fatalError() } @available(*, unavailable, renamed: "localizedString(forIdentifier:)") public func localizedString(forLocaleIdentifier localeIdentifier: String) -> String { fatalError() } @available(*, unavailable, renamed: "availableIdentifiers") public static var availableLocaleIdentifiers: [String] { fatalError() } @available(*, unavailable, renamed: "components(fromIdentifier:)") public static func components(fromLocaleIdentifier string: String) -> [String : String] { fatalError() } @available(*, unavailable, renamed: "identifier(fromComponents:)") public static func localeIdentifier(fromComponents dict: [String : String]) -> String { fatalError() } @available(*, unavailable, renamed: "canonicalIdentifier(from:)") public static func canonicalLocaleIdentifier(from string: String) -> String { fatalError() } @available(*, unavailable, renamed: "identifier(fromWindowsLocaleCode:)") public static func localeIdentifier(fromWindowsLocaleCode lcid: UInt32) -> String? { fatalError() } @available(*, unavailable, renamed: "windowsLocaleCode(fromIdentifier:)") public static func windowsLocaleCode(fromLocaleIdentifier localeIdentifier: String) -> UInt32 { fatalError() } @available(*, unavailable, message: "use regionCode instead") public var countryCode: String { fatalError() } @available(*, unavailable, message: "use localizedString(forRegionCode:) instead") public func localizedString(forCountryCode countryCode: String) -> String { fatalError() } @available(*, unavailable, renamed: "isoRegionCodes") public static var isoCountryCodes: [String] { fatalError() } // MARK: - // public var hashValue : Int { if _autoupdating { return 1 } else { return _wrapped.hash } } public static func ==(lhs: Locale, rhs: Locale) -> Bool { if lhs._autoupdating || rhs._autoupdating { return lhs._autoupdating == rhs._autoupdating } else { return lhs._wrapped.isEqual(rhs._wrapped) } } } extension Locale : CustomDebugStringConvertible, CustomStringConvertible, CustomReflectable { private var _kindDescription : String { if (self == Locale.autoupdatingCurrent) { return "autoupdatingCurrent" } else if (self == Locale.current) { return "current" } else { return "fixed" } } public var customMirror : Mirror { var c: [(label: String?, value: Any)] = [] c.append((label: "identifier", value: identifier)) c.append((label: "kind", value: _kindDescription)) return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct) } public var description: String { return "\(identifier) (\(_kindDescription))" } public var debugDescription : String { return "\(identifier) (\(_kindDescription))" } } extension Locale : _ObjectiveCBridgeable { @_semantics("convertToObjectiveC") public func _bridgeToObjectiveC() -> NSLocale { return _wrapped } public static func _forceBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) { if !_conditionallyBridgeFromObjectiveC(input, result: &result) { fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)") } } public static func _conditionallyBridgeFromObjectiveC(_ input: NSLocale, result: inout Locale?) -> Bool { result = Locale(reference: input) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSLocale?) -> Locale { var result: Locale? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } extension NSLocale : _HasCustomAnyHashableRepresentation { // Must be @nonobjc to avoid infinite recursion during bridging. @nonobjc public func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(self as Locale) } }
apache-2.0
dfc55e80a1996a354627827144938a8c
38.138211
282
0.656055
5.06204
false
false
false
false
petester42/RxSwift
Rx.playground/Pages/Subjects.xcplaygroundpage/Contents.swift
2
3706
//: [<< Previous](@previous) - [Index](Index) import RxSwift /*: A Subject is a sort of bridge or proxy that is available in some implementations of ReactiveX that acts both as an observer and as an Observable. Because it is an observer, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by reemitting them, and it can also emit new items. */ func writeSequenceToConsole<O: ObservableType>(name: String, sequence: O) -> Disposable { return sequence .subscribe { e in print("Subscription: \(name), event: \(e)") } } /*: ## PublishSubject `PublishSubject` emits to an observer only those items that are emitted by the source Observable(s) subsequent to the time of the subscription. ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/publishsubject.png) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/publishsubject_error.png) */ example("PublishSubject") { let disposeBag = DisposeBag() let subject = PublishSubject<String>() writeSequenceToConsole("1", sequence: subject).addDisposableTo(disposeBag) subject.on(.Next("a")) subject.on(.Next("b")) writeSequenceToConsole("2", sequence: subject).addDisposableTo(disposeBag) subject.on(.Next("c")) subject.on(.Next("d")) } /*: ## ReplaySubject `ReplaySubject` emits to any observer all of the items that were emitted by the source Observable(s), regardless of when the observer subscribes. ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/replaysubject.png) */ example("ReplaySubject") { let disposeBag = DisposeBag() let subject = ReplaySubject<String>.create(bufferSize: 1) writeSequenceToConsole("1", sequence: subject).addDisposableTo(disposeBag) subject.on(.Next("a")) subject.on(.Next("b")) writeSequenceToConsole("2", sequence: subject).addDisposableTo(disposeBag) subject.on(.Next("c")) subject.on(.Next("d")) } /*: ## BehaviorSubject When an observer subscribes to a `BehaviorSubject`, it begins by emitting the item most recently emitted by the source Observable (or a seed/default value if none has yet been emitted) and then continues to emit any other items emitted later by the source Observable(s). ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/behaviorsubject.png) ![](https://raw.githubusercontent.com/kzaher/rxswiftcontent/master/MarbleDiagrams/png/behaviorsubject_error.png) */ example("BehaviorSubject") { let disposeBag = DisposeBag() let subject = BehaviorSubject(value: "z") writeSequenceToConsole("1", sequence: subject).addDisposableTo(disposeBag) subject.on(.Next("a")) subject.on(.Next("b")) writeSequenceToConsole("2", sequence: subject).addDisposableTo(disposeBag) subject.on(.Next("c")) subject.on(.Next("d")) subject.on(.Completed) } /*: ## Variable `Variable` wraps `BehaviorSubject`. Advantage of using variable over `BehaviorSubject` is that variable can never explicitly complete or error out, and `BehaviorSubject` can in case `Error` or `Completed` message is send to it. `Variable` will also automatically complete in case it's being deallocated. */ example("Variable") { let disposeBag = DisposeBag() let variable = Variable("z") writeSequenceToConsole("1", sequence: variable).addDisposableTo(disposeBag) variable.value = "a" variable.value = "b" writeSequenceToConsole("2", sequence: variable).addDisposableTo(disposeBag) variable.value = "c" variable.value = "d" } //: [Index](Index) - [Next >>](@next)
mit
bef3e4b406921f63983407ae32225ace
34.634615
344
0.727739
4.304297
false
false
false
false
HTWDD/HTWDresden-iOS-Temp
HTWDresden/HTWDresden/MensaOverview/MensaMainViewController.swift
1
2500
import UIKit let getMensa = "http://www.studentenwerk-dresden.de/feeds/speiseplan.rss" let margin: CGFloat = 8 class MensaMainViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout { let identifier = "cell" let layout = UICollectionViewFlowLayout() var mensaData: [(name: String, meals: [MensaData])] = [] override func viewDidLoad() { self.title = "Mensa" super.viewDidLoad() collectionView?.backgroundColor = UIColor(red: 240 / 255, green: 240 / 255, blue: 240 / 255, alpha: 1) collectionView?.registerClass(MensaMainCollectionViewCell.self, forCellWithReuseIdentifier: identifier) collectionView?.alwaysBounceVertical = true collectionView?.pagingEnabled = true collectionView?.contentInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin) let activityView = UIActivityIndicatorView(activityIndicatorStyle: .Gray) activityView.center = view.center view.addSubview(activityView) activityView.hidesWhenStopped = true activityView.startAnimating() let p = Parser(strPath: getMensa) p.loadData() { result in self.mensaData = result.map { $0 }.sort { $0.0 < $1.0 } activityView.stopAnimating() self.collectionView?.reloadData() } } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return mensaData.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) } override func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) { if let cell = cell as? MensaMainCollectionViewCell { cell.mensa = mensaData[indexPath.row].name } } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: (collectionView.bounds.size.width - margin * 3) / 2 - 2, height: 50) } override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { collectionView.deselectItemAtIndexPath(indexPath, animated: true) let controller = MealMainViewController() controller.meals = mensaData[indexPath.row].meals self.navigationController?.pushViewController(controller, animated: true) } }
gpl-2.0
e124faada84145850937bf3cd5e096d2
38.68254
166
0.7856
4.612546
false
false
false
false
externl/ice
swift/test/Ice/operations/TestAMDI.swift
4
17911
// // Copyright (c) ZeroC, Inc. All rights reserved. // import Foundation import Ice import PromiseKit import TestCommon class BI: MBOperations { func opBAsync(current _: Ice.Current) -> Promise<Void> { return Promise.value(()) } func opIntfAsync(current _: Ice.Current) -> Promise<Void> { return Promise.value(()) } } class MyDerivedClassI: ObjectI<MyDerivedClassTraits>, MyDerivedClass { var _helper: TestHelper var _opByteSOnewayCallCount: Int32 = 0 var _lock = os_unfair_lock() init(_ helper: TestHelper) { _helper = helper } // // Override the Object "pseudo" operations to verify the operation mode. // override func ice_isA(id: String, current: Ice.Current) throws -> Bool { try _helper.test(current.mode == .Nonmutating) return try super.ice_isA(id: id, current: current) } override func ice_ping(current: Ice.Current) throws { try _helper.test(current.mode == .Nonmutating) } override func ice_ids(current: Ice.Current) throws -> [String] { try _helper.test(current.mode == .Nonmutating) return try super.ice_ids(current: current) } override func ice_id(current: Ice.Current) throws -> String { try _helper.test(current.mode == .Nonmutating) return try super.ice_id(current: current) } func opDerivedAsync(current _: Current) -> Promise<Void> { return Promise.value(()) } func opMyClass1Async(opMyClass1: MyClass1?, current _: Current) -> Promise<MyClass1?> { return Promise.value(opMyClass1) } func opMyStruct1Async(opMyStruct1: MyStruct1, current _: Current) -> Promise<MyStruct1> { return Promise.value(opMyStruct1) } func shutdownAsync(current: Current) -> Promise<Void> { return Promise<Void> { seal in current.adapter!.getCommunicator().shutdown() seal.fulfill(()) } } func supportsCompressAsync(current _: Current) -> Promise<Bool> { return Promise.value(true) } func opVoidAsync(current _: Current) -> Promise<Void> { return Promise.value(()) } func opByteAsync(p1: UInt8, p2: UInt8, current _: Current) -> Promise<(returnValue: UInt8, p3: UInt8)> { return Promise.value((p1, p1 ^ p2)) } func opBoolAsync(p1: Bool, p2: Bool, current _: Current) -> Promise<(returnValue: Bool, p3: Bool)> { return Promise.value((p2, p1)) } func opShortIntLongAsync(p1: Int16, p2: Int32, p3: Int64, current _: Current) -> Promise<(returnValue: Int64, p4: Int16, p5: Int32, p6: Int64)> { return Promise.value((p3, p1, p2, p3)) } func opFloatDoubleAsync(p1: Float, p2: Double, current _: Current) -> Promise<(returnValue: Double, p3: Float, p4: Double)> { return Promise.value((p2, p1, p2)) } func opStringAsync(p1: String, p2: String, current _: Current) -> Promise<(returnValue: String, p3: String)> { return Promise.value(("\(p1) \(p2)", "\(p2) \(p1)")) } func opMyEnumAsync(p1: MyEnum, current _: Current) -> Promise<(returnValue: MyEnum, p2: MyEnum)> { return Promise.value((MyEnum.enum3, p1)) } func opMyClassAsync(p1: MyClassPrx?, current: Current) -> Promise<(returnValue: MyClassPrx?, p2: MyClassPrx?, p3: MyClassPrx?)> { guard let adapter = current.adapter else { fatalError() } return Promise { seal in do { seal.fulfill( (try uncheckedCast(prx: adapter.createProxy(current.id), type: MyClassPrx.self), p1, try uncheckedCast(prx: adapter.createProxy(Ice.stringToIdentity("noSuchIdentity")), type: MyClassPrx.self))) } catch { seal.reject(error) } } } func opStructAsync(p1: Structure, p2: Structure, current _: Current) -> Promise<(returnValue: Structure, p3: Structure)> { var p3 = p1 p3.s.s = "a new string" return Promise.value((p2, p3)) } func opByteSAsync(p1: ByteS, p2: ByteS, current _: Current) -> Promise<(returnValue: ByteS, p3: ByteS)> { return Promise.value((p1 + p2, ByteSeq(p1.reversed()))) } func opBoolSAsync(p1: BoolS, p2: BoolS, current _: Current) -> Promise<(returnValue: BoolS, p3: BoolS)> { return Promise.value((p1.reversed(), p1 + p2)) } func opShortIntLongSAsync(p1: ShortS, p2: IntS, p3: LongS, current _: Current) -> Promise<(returnValue: LongS, p4: ShortS, p5: IntS, p6: LongS)> { return Promise.value((p3, p1, p2.reversed(), p3 + p3)) } func opFloatDoubleSAsync(p1: FloatS, p2: DoubleS, current _: Current) -> Promise<(returnValue: DoubleS, p3: FloatS, p4: DoubleS)> { return Promise.value((p2 + p1.map { Double($0) }, p1, p2.reversed())) } func opStringSAsync(p1: StringS, p2: StringS, current _: Current) -> Promise<(returnValue: StringS, p3: StringS)> { return Promise.value((p1.reversed(), p1 + p2)) } func opByteSSAsync(p1: ByteSS, p2: ByteSS, current _: Current) -> Promise<(returnValue: ByteSS, p3: ByteSS)> { return Promise.value((p1 + p2, p1.reversed())) } func opBoolSSAsync(p1: BoolSS, p2: BoolSS, current _: Current) -> Promise<(returnValue: BoolSS, p3: BoolSS)> { return Promise.value((p1.reversed(), p1 + p2)) } func opShortIntLongSSAsync(p1: ShortSS, p2: IntSS, p3: LongSS, current _: Current) -> Promise<(returnValue: LongSS, p4: ShortSS, p5: IntSS, p6: LongSS)> { return Promise.value((p3, p1, p2.reversed(), p3 + p3)) } func opFloatDoubleSSAsync(p1: FloatSS, p2: DoubleSS, current _: Current) -> Promise<(returnValue: DoubleSS, p3: FloatSS, p4: DoubleSS)> { return Promise.value((p2 + p2, p1, p2.reversed())) } func opStringSSAsync(p1: StringSS, p2: StringSS, current _: Current) -> Promise<(returnValue: StringSS, p3: StringSS)> { return Promise.value((p2.reversed(), p1 + p2)) } func opStringSSSAsync(p1: StringSSS, p2: StringSSS, current _: Current) -> Promise<(returnValue: StringSSS, p3: StringSSS)> { return Promise.value((p2.reversed(), p1 + p2)) } func opByteBoolDAsync(p1: ByteBoolD, p2: ByteBoolD, current _: Current) -> Promise<(returnValue: ByteBoolD, p3: ByteBoolD)> { return Promise.value((p1.merging(p2) { _, new in new }, p1)) } func opShortIntDAsync(p1: ShortIntD, p2: ShortIntD, current _: Current) -> Promise<(returnValue: ShortIntD, p3: ShortIntD)> { return Promise.value((p1.merging(p2) { _, new in new }, p1)) } func opLongFloatDAsync(p1: LongFloatD, p2: LongFloatD, current _: Current) -> Promise<(returnValue: LongFloatD, p3: LongFloatD)> { return Promise.value((p1.merging(p2) { _, new in new }, p1)) } func opStringStringDAsync(p1: StringStringD, p2: StringStringD, current _: Current) -> Promise<(returnValue: StringStringD, p3: StringStringD)> { return Promise.value((p1.merging(p2) { _, new in new }, p1)) } func opStringMyEnumDAsync(p1: StringMyEnumD, p2: StringMyEnumD, current _: Current) -> Promise<(returnValue: StringMyEnumD, p3: StringMyEnumD)> { return Promise.value((p1.merging(p2) { _, new in new }, p1)) } func opMyEnumStringDAsync(p1: MyEnumStringD, p2: MyEnumStringD, current _: Current) -> Promise<(returnValue: MyEnumStringD, p3: MyEnumStringD)> { return Promise.value((p1.merging(p2) { _, new in new }, p1)) } func opMyStructMyEnumDAsync(p1: MyStructMyEnumD, p2: MyStructMyEnumD, current _: Current) -> Promise<(returnValue: MyStructMyEnumD, p3: MyStructMyEnumD)> { return Promise.value((p1.merging(p2) { _, new in new }, p1)) } func opByteBoolDSAsync(p1: ByteBoolDS, p2: ByteBoolDS, current _: Current) -> Promise<(returnValue: ByteBoolDS, p3: ByteBoolDS)> { return Promise.value((p1.reversed(), p2 + p1)) } func opShortIntDSAsync(p1: ShortIntDS, p2: ShortIntDS, current _: Current) -> Promise<(returnValue: ShortIntDS, p3: ShortIntDS)> { return Promise.value((p1.reversed(), p2 + p1)) } func opLongFloatDSAsync(p1: LongFloatDS, p2: LongFloatDS, current _: Current) -> Promise<(returnValue: LongFloatDS, p3: LongFloatDS)> { return Promise.value((p1.reversed(), p2 + p1)) } func opStringStringDSAsync(p1: StringStringDS, p2: StringStringDS, current _: Current) -> Promise<(returnValue: StringStringDS, p3: StringStringDS)> { return Promise.value((p1.reversed(), p2 + p1)) } func opStringMyEnumDSAsync(p1: StringMyEnumDS, p2: StringMyEnumDS, current _: Current) -> Promise<(returnValue: StringMyEnumDS, p3: StringMyEnumDS)> { return Promise.value((p1.reversed(), p2 + p1)) } func opMyEnumStringDSAsync(p1: MyEnumStringDS, p2: MyEnumStringDS, current _: Current) -> Promise<(returnValue: MyEnumStringDS, p3: MyEnumStringDS)> { return Promise.value((p1.reversed(), p2 + p1)) } func opMyStructMyEnumDSAsync(p1: MyStructMyEnumDS, p2: MyStructMyEnumDS, current _: Current) -> Promise<(returnValue: MyStructMyEnumDS, p3: MyStructMyEnumDS)> { return Promise.value((p1.reversed(), p2 + p1)) } func opByteByteSDAsync(p1: ByteByteSD, p2: ByteByteSD, current _: Current) -> Promise<(returnValue: ByteByteSD, p3: ByteByteSD)> { return Promise.value((p1.merging(p2) { _, new in new }, p2)) } func opBoolBoolSDAsync(p1: BoolBoolSD, p2: BoolBoolSD, current _: Current) -> Promise<(returnValue: BoolBoolSD, p3: BoolBoolSD)> { return Promise.value((p1.merging(p2) { _, new in new }, p2)) } func opShortShortSDAsync(p1: ShortShortSD, p2: ShortShortSD, current _: Current) -> Promise<(returnValue: ShortShortSD, p3: ShortShortSD)> { return Promise.value((p1.merging(p2) { _, new in new }, p2)) } func opIntIntSDAsync(p1: IntIntSD, p2: IntIntSD, current _: Current) -> Promise<(returnValue: IntIntSD, p3: IntIntSD)> { return Promise.value((p1.merging(p2) { _, new in new }, p2)) } func opLongLongSDAsync(p1: LongLongSD, p2: LongLongSD, current _: Current) -> Promise<(returnValue: LongLongSD, p3: LongLongSD)> { return Promise.value((p1.merging(p2) { _, new in new }, p2)) } func opStringFloatSDAsync(p1: StringFloatSD, p2: StringFloatSD, current _: Current) -> Promise<(returnValue: StringFloatSD, p3: StringFloatSD)> { return Promise.value((p1.merging(p2) { _, new in new }, p2)) } func opStringDoubleSDAsync(p1: StringDoubleSD, p2: StringDoubleSD, current _: Current) -> Promise<(returnValue: StringDoubleSD, p3: StringDoubleSD)> { return Promise.value((p1.merging(p2) { _, new in new }, p2)) } func opStringStringSDAsync(p1: StringStringSD, p2: StringStringSD, current _: Current) -> Promise<(returnValue: StringStringSD, p3: StringStringSD)> { return Promise.value((p1.merging(p2) { _, new in new }, p2)) } func opMyEnumMyEnumSDAsync(p1: MyEnumMyEnumSD, p2: MyEnumMyEnumSD, current _: Current) -> Promise<(returnValue: MyEnumMyEnumSD, p3: MyEnumMyEnumSD)> { return Promise.value((p1.merging(p2) { _, new in new }, p2)) } func opIntSAsync(s: IntS, current _: Current) -> Promise<IntS> { return Promise.value(s.map { -$0 }) } func opByteSOnewayAsync(s _: ByteS, current _: Current) -> Promise<Void> { withLock(&_lock) { _opByteSOnewayCallCount += 1 } return Promise.value(()) } func opByteSOnewayCallCountAsync(current _: Current) -> Promise<Int32> { return withLock(&_lock) { let count = _opByteSOnewayCallCount _opByteSOnewayCallCount = 0 return Promise<Int32>.value(count) } } func opContextAsync(current: Current) -> Promise<Context> { return Promise.value(current.ctx) } func opDoubleMarshalingAsync(p1: Double, p2: DoubleS, current _: Current) -> Promise<Void> { return Promise<Void> { seal in do { let d = Double(1_278_312_346.0 / 13.0) try _helper.test(p1 == d) for p in p2 { try _helper.test(p == d) } seal.fulfill(()) } catch { seal.reject(error) } } } func opIdempotentAsync(current: Current) -> Promise<Void> { return Promise<Void> { seal in do { try _helper.test(current.mode == .Idempotent) seal.fulfill(()) } catch { seal.reject(error) } } } func opNonmutatingAsync(current: Current) -> Promise<Void> { return Promise<Void> { seal in do { try _helper.test(current.mode == .Nonmutating) seal.fulfill(()) } catch { seal.reject(error) } } } func opByte1Async(opByte1: UInt8, current _: Current) -> Promise<UInt8> { return Promise.value(opByte1) } func opShort1Async(opShort1: Int16, current _: Current) -> Promise<Int16> { return Promise.value(opShort1) } func opInt1Async(opInt1: Int32, current _: Current) -> Promise<Int32> { return Promise.value(opInt1) } func opLong1Async(opLong1: Int64, current _: Current) -> Promise<Int64> { return Promise.value(opLong1) } func opFloat1Async(opFloat1: Float, current _: Current) -> Promise<Float> { return Promise.value(opFloat1) } func opDouble1Async(opDouble1: Double, current _: Current) -> Promise<Double> { return Promise.value(opDouble1) } func opString1Async(opString1: String, current _: Current) -> Promise<String> { return Promise.value(opString1) } func opStringS1Async(opStringS1: StringS, current _: Current) -> Promise<StringS> { return Promise.value(opStringS1) } func opByteBoolD1Async(opByteBoolD1: ByteBoolD, current _: Current) -> Promise<ByteBoolD> { return Promise.value(opByteBoolD1) } func opStringS2Async(stringS: StringS, current _: Current) -> Promise<StringS> { return Promise.value(stringS) } func opByteBoolD2Async(byteBoolD: ByteBoolD, current _: Current) -> Promise<ByteBoolD> { return Promise.value(byteBoolD) } func opStringLiteralsAsync(current _: Current) -> Promise<StringS> { return Promise.value([s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, sw0, sw1, sw2, sw3, sw4, sw5, sw6, sw7, sw8, sw9, sw10, ss0, ss1, ss2, ss3, ss4, ss5, su0, su1, su2]) } func opWStringLiteralsAsync(current: Current) -> Promise<StringS> { return opStringLiteralsAsync(current: current) } func opMStruct1Async(current: Current) -> Promise<Structure> { var s = Structure() s.e = .enum1 return Promise.value(s) } func opMStruct2Async(p1: Structure, current: Current) -> Promise<(returnValue: Structure, p2: Structure)> { return Promise.value((p1, p1)) } func opMSeq1Async(current: Current) -> Promise<StringS> { return Promise.value([]) } func opMSeq2Async(p1: StringS, current: Current) -> Promise<(returnValue: StringS, p2: StringS)> { return Promise.value((p1, p1)) } func opMDict1Async(current: Current) -> Promise<StringStringD> { return Promise.value([:]) } func opMDict2Async(p1: StringStringD, current: Current) -> Promise<(returnValue: StringStringD, p2: StringStringD)> { return Promise.value((p1, p1)) } }
gpl-2.0
503e1d06f6d1e6555ebe08d5e6672f3d
36.866808
120
0.54782
3.906434
false
false
false
false
tinrobots/CoreDataPlus
Sources/Collection+CoreData.swift
1
3747
// CoreDataPlus import CoreData // MARK: - NSManagedObject extension Collection where Element: NSManagedObject { /// Specifies that all the `NSManagedObject` objects (with a `NSManangedObjectContext`) should be removed from its persistent store when changes are committed. public func deleteManagedObjects() { let managedObjectsWithContext = self.filter { $0.managedObjectContext != nil } for object in managedObjectsWithContext { let context = object.managedObjectContext! context.performAndWait { object.delete() } } } /// Materializes all the faulted objects in one batch, executing a single fetch request. /// Since this method is defined for a Collection of `NSManagedObject`, it does extra work to materialize all the objects; for this reason it's not optimized for performance. /// /// - Throws: It throws an error in cases of failure. /// - Note: Materializing all the objects in one batch is faster than triggering the fault for each object on its own. public func materializeFaults() throws { guard !self.isEmpty else { return } let faults = self.filter { $0.isFault } guard !faults.isEmpty else { return } let faultedObjectsByContext = Dictionary(grouping: faults) { $0.managedObjectContext } for (context, objects) in faultedObjectsByContext where !objects.isEmpty { // objects without context can trigger their fault one by one guard let context = context else { // important bits objects.forEach { $0.materialize() } continue } // objects not yet saved can trigger their fault one by one let temporaryObjects = objects.filter { $0.hasTemporaryID } if !temporaryObjects.isEmpty { temporaryObjects.forEach { $0.materialize() } } // avoid multiple fetches for subclass entities. let entities = objects.entities().entitiesKeepingOnlyCommonEntityAncestors() for entity in entities { // important bits // about batch faulting: // https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/Performance.html let request = NSFetchRequest<NSFetchRequestResult>() request.entity = entity request.returnsObjectsAsFaults = false request.predicate = NSPredicate(format: "self IN %@", faults) try context.performAndWait { try $0.fetch(request) } } } } /// Returns all the different `NSEntityDescription` defined in the collection. public func entities() -> Set<NSEntityDescription> { return Set(self.map { $0.entity }) } } // MARK: - NSEntityDescription extension Collection where Element: NSEntityDescription { /// Returns a collection of `NSEntityDescription` with only the commong entity ancestors. internal func entitiesKeepingOnlyCommonEntityAncestors() -> Set<NSEntityDescription> { let grouped = Dictionary(grouping: self) { return $0.topMostEntity } var result = [NSEntityDescription]() grouped.forEach { _, entities in let set = Set(entities) let test = set.reduce([]) { (result, entity) -> [NSEntityDescription] in var newResult = result guard !newResult.isEmpty else { return [entity] } for (index, entityResult) in result.enumerated() { if let ancestor = entityResult.commonEntityAncestor(with: entity) { if !newResult.contains(ancestor) { newResult.remove(at: index) newResult.append(ancestor) } } else { // this condition should be never verified newResult.append(entity) } } return newResult } result.append(contentsOf: test) } return Set(result) } }
mit
674802c8d04221420ec7dc5317ee0212
35.735294
176
0.680011
4.785441
false
false
false
false
sseitov/v-Chess-Swift
v-Chess/Extensions/DateExtension.swift
1
1253
// // DateExtension.swift // // Created by Сергей Сейтов on 10.06.17. // Copyright © 2017 V-Channel. All rights reserved. // import UIKit func utcFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter } func dateFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" return formatter } func textDateFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .short formatter.doesRelativeDateFormatting = true return formatter } func weekDateFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "EEEE, d MMM" return formatter } func hourlyFormatter() -> DateFormatter { let formatter = DateFormatter() formatter.dateFormat = "HH:mm" return formatter } extension Date { func isToday() -> Bool { return Calendar.current.isDateInToday(self) } func isTomorrow() -> Bool { return Calendar.current.isDateInTomorrow(self) } func isYesterday() -> Bool { return Calendar.current.isDateInYesterday(self) } }
gpl-3.0
c782bc361d050a4c0b94432488054635
21.545455
55
0.674194
4.350877
false
false
false
false
64characters/Telephone
Telephone/RepeatingSoundFactoryTests.swift
1
1384
// // RepeatingSoundFactoryTests.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone 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. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import UseCases import UseCasesTestDoubles import XCTest final class RepeatingSoundFactoryTests: XCTestCase { private var factory: SoundFactorySpy! private var sut: RepeatingSoundFactory! override func setUp() { super.setUp() factory = SoundFactorySpy() sut = RepeatingSoundFactory(soundFactory: factory, timerFactory: TimerFactorySpy()) } func testCallsCreateSound() { try! _ = sut.makeRingtone(interval: 0) XCTAssertTrue(factory.didCallCreateSound) } func testCreatesRingtoneWithSpecifiedInterval() { let interval: Double = 2 let result = try! sut.makeRingtone(interval: interval) XCTAssertEqual(result.interval, interval) } }
gpl-3.0
cd1352e8e12f0132eb248d6b2d29c089
29.043478
91
0.7178
4.44373
false
true
false
false
bitomule/SimpleTabsViewController
Source/SimpleTabsViewController.swift
1
10090
// // SimpleTabberViewController.swift // SimpleTabberViewController // // Created by David Collado Sela on 19/5/15. // Copyright (c) 2015 David Collado Sela. All rights reserved. // import UIKit public class SimpleTabsViewController: UIViewController { public class func create(parentVC:UIViewController?,baseView:UIView?,delegate:SimpleTabsDelegate?,items:[SimpleTabItem]) -> SimpleTabsViewController{ let newVC = SimpleTabsViewController(items: items) newVC.delegate = delegate if let parentVC = parentVC{ newVC.willMoveToParentViewController(parentVC) } if let baseView = baseView{ baseView.addSubview(newVC.view) }else{ parentVC?.view.addSubview(newVC.view) } newVC.didMoveToParentViewController(parentVC) if let baseView = baseView{ newVC.view.frame = CGRect(origin: CGPoint(x: 0,y: 0), size: baseView.frame.size) }else{ if let parentVC = parentVC{ newVC.view.frame = CGRect(origin: CGPoint(x: 0,y: 0), size: parentVC.view.frame.size) }else{ newVC.view.frame = CGRect(origin: CGPoint(x: 0,y: 0), size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 50)) } } return newVC } var items:[SimpleTabItem] = [SimpleTabItem]() var currentTab = 0 weak var delegate:SimpleTabsDelegate? var tabsContainer: UIView! var activeMarker: UIView! var bottomReference: UIView! var centerMarkerConstraint:NSLayoutConstraint? var widthMarkerConstraint:NSLayoutConstraint? override public func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. createBaseView() createMenu() setCurrentTab(0, animated: false) } convenience init(items:[SimpleTabItem]) { self.init(nibName: nil, bundle: nil) self.items = items } public func setTabCount(tabIndex:Int,count:Int){ if(self.items[tabIndex].tabView != nil){ self.items[tabIndex].updateCount(count) } } //MARK: - Base View private func createBaseView(){ self.view.backgroundColor = fillColor self.view.clipsToBounds = true createBottomView() createTabsContainer() createMarker() } private func createBottomView(){ bottomReference = UIView(frame: CGRect(x: -10, y: 48, width: self.view.bounds.width, height: 2)) bottomReference.backgroundColor = bottomFillColor bottomReference.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(bottomReference) let trailingConstraint = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: bottomReference, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -10) let leadingConstraint = NSLayoutConstraint(item: bottomReference, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: -10) let bottomSpaceConstraint = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: bottomReference, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0) let heightConstraint = NSLayoutConstraint(item: bottomReference, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 2) bottomReference.addConstraint(heightConstraint) self.view.addConstraints([trailingConstraint,leadingConstraint,bottomSpaceConstraint]) } private func createTabsContainer(){ tabsContainer = UIView(frame: CGRect(x: 0, y: 0, width: self.view.bounds.width, height: 50)) tabsContainer.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(tabsContainer) let centerXConstraint = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: tabsContainer, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) let centerYConstraint = NSLayoutConstraint(item: self.view, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: tabsContainer, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: -4) let topConstraint = NSLayoutConstraint(item: tabsContainer, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0) self.view.addConstraints([centerXConstraint,centerYConstraint,topConstraint]) } private func createMarker(){ activeMarker = UIView(frame: CGRect(x: 50, y: 50, width: 200, height: 2)) activeMarker.backgroundColor = markerFillColor activeMarker.translatesAutoresizingMaskIntoConstraints = false tabsContainer.addSubview(activeMarker) let bottomSpaceConstraint = NSLayoutConstraint(item: tabsContainer, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: activeMarker, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 8) let heightConstraint = NSLayoutConstraint(item: activeMarker, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Height, multiplier: 1, constant: 2) activeMarker.addConstraint(heightConstraint) tabsContainer.addConstraints([bottomSpaceConstraint]) } //MARK: - Tabs internal func tabSelected(tab:Int){ setCurrentTab(tab,animated:true) delegate?.tabSelected(tab) } public func setCurrentTab(tab:Int,animated:Bool){ currentTab = tab if(centerMarkerConstraint != nil && widthMarkerConstraint != nil){ self.tabsContainer.removeConstraints([centerMarkerConstraint!,widthMarkerConstraint!]) } centerMarkerConstraint = NSLayoutConstraint(item: activeMarker, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self.items[currentTab].tabView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0) widthMarkerConstraint = NSLayoutConstraint(item: activeMarker, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self.items[currentTab].tabView, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: 0) if(animated){ self.tabsContainer.addConstraints([self.widthMarkerConstraint!,self.centerMarkerConstraint!]) self.tabsContainer.setNeedsUpdateConstraints() UIView.animateWithDuration(0.1, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { self.view.layoutIfNeeded() }, completion: { finished in }) }else{ tabsContainer.addConstraints([widthMarkerConstraint!,centerMarkerConstraint!]) } } //MARK: - Menu Creation private func createMenu(){ for(var i=0;i<items.count;i++){ items[i].index = i let tab = createTab(items[i]) self.tabsContainer.addSubview(tab) items[i].setConstraints() } } private func createTab(item:SimpleTabItem) -> UIView{ var previousItem:SimpleTabItem? if((item.index - 1) >= 0){ previousItem = self.items[item.index - 1] } var nextItem:SimpleTabItem? if((item.index + 1) < self.items.count){ nextItem = self.items[item.index + 1] } return item.createTabView(tabsFont, textColor: textColor, numberFont: numbersFont, numberColor: numbersColor, numberBackgroundColor: numbersBackgroundColor, tabContainer: self,previousTab:previousItem,nextTab:nextItem) } // MARK: - Style var textColor:UIColor = UIColor.blackColor() var numbersColor:UIColor = UIColor.blackColor() var numbersBackgroundColor:UIColor = UIColor.yellowColor() var markerFillColor:UIColor = UIColor.redColor() var tabsFont = UIFont.systemFontOfSize(15) var numbersFont = UIFont.systemFontOfSize(15) var bottomFillColor = UIColor.grayColor() var fillColor = UIColor.whiteColor() public func setTabTitleColor(color:UIColor){ self.textColor = color updateTabsStyle() } public func setNumberColor(color:UIColor){ numbersColor = color updateTabsStyle() } public func setNumberBackgroundColor(color:UIColor){ numbersBackgroundColor = color updateTabsStyle() } public func setMarkerColor(color:UIColor){ markerFillColor = color activeMarker.backgroundColor = markerFillColor } public func setTabTitleFont(font:UIFont){ tabsFont = font updateTabsStyle() } public func setNumberFont(font:UIFont){ numbersFont = font updateTabsStyle() } public func setBottomBackgroundColor(color:UIColor){ bottomFillColor = color bottomReference.backgroundColor = bottomFillColor } public func setBackgroundColor(color:UIColor){ fillColor = color self.view.backgroundColor = fillColor } private func updateTabsStyle(){ for tab in self.items{ tab.titleColor = self.textColor tab.titleFont = self.tabsFont tab.numberFont = self.numbersFont tab.numberColor = self.numbersColor tab.numberBackgroundColor = self.numbersBackgroundColor tab.updateStyle() } } deinit{ delegate = nil tabsContainer = nil activeMarker = nil bottomReference = nil centerMarkerConstraint = nil widthMarkerConstraint = nil } }
mit
fba9e63b7a933b1127b6845122740de7
41.940426
250
0.685134
5.027404
false
false
false
false
duliodenis/Swiftris
Swiftris/Swiftris/Shape.swift
1
3032
// // Shape.swift // Swiftris // // Created by Dulio Denis on 10/10/14. // Copyright (c) 2014 ddApps. All rights reserved. // import Foundation import SpriteKit let NumOrientations: UInt32 = 4 // Shape's Orientation can face in one of four directions enum Orientation: Int, Printable { case Zero = 0, Ninety, OneEighty, TwoSeventy var description: String { switch self { case .Zero: return "0" case .Ninety: return "90" case .OneEighty: return "180" case .TwoSeventy: return "270" } } static func random() -> Orientation { return Orientation.fromRaw(Int(arc4random_uniform(NumOrientations)))! } static func rotate(orientation:Orientation, clockwise: Bool) -> Orientation { var rotated = orientation.toRaw() + (clockwise ? 1 : -1) if rotated > Orientation.TwoSeventy.toRaw() { rotated = Orientation.Zero.toRaw() } else if rotated < 0 { rotated = Orientation.TwoSeventy.toRaw() } return Orientation.fromRaw(rotated)! } } // the number of Shape varieties let NumShapeTypes: UInt32 = 7 // Shape Indexes let FirstBlockIdx: Int = 0 let SecondBlockIdx: Int = 1 let ThirdBlockIdx: Int = 2 let FourthBlockIdx: Int = 3 class Shape: Hashable, Printable { // the color of the shape let color:BlockColor // the blocks comprising the shape var blocks = Array<Block>() // the current orientation of the shape var orientation: Orientation // the column and row representing the shape's anchor point var column, row:Int // Required Overrides // Subclasses must override this property var blockRowColumnPosition: [Orientation: Array<(columnDiff: Int, rowDiff: Int)>] { return [:] } // Subclasses must override this property var bottomBlocksForOrientations: [Orientation: Array<Block>] { return [:] } var bottomBlocks:Array<Block> { if let bottomBlocks = bottomBlocksForOrientations[orientation] { return bottomBlocks } return [] } // Hashable var hashValue:Int { return reduce(blocks, 0) { $0.hashValue ^ $1.hashValue } } // Printable var description:String { return "\(color) block facing \(orientation): \(blocks[FirstBlockIdx]), \(blocks[SecondBlockIdx]), \(blocks[ThirdBlockIdx]), \(blocks[FourthBlockIdx])" } init(column:Int, row:Int, color:BlockColor, orientation:Orientation) { self.color = color self.column = column self.row = row self.orientation = orientation initializeBlocks() } convenience init(column:Int, row:Int) { self.init(column:column, row:row, color:BlockColor.random(), orientation:Orientation.random()) } } func ==(lhs:Shape, rhs:Shape) -> Bool { return lhs.row == rhs.row && lhs.column == rhs.column }
mit
a01b6cdea96f2712dc4650712ba7264c
25.596491
159
0.615765
4.478582
false
false
false
false
hejunbinlan/swiftmi-app
swiftmi/swiftmi/CodeCell.swift
4
1040
// // CodeCell.swift // swiftmi // // Created by yangyin on 15/4/1. // Copyright (c) 2015年 swiftmi. All rights reserved. // import UIKit class CodeCell: UICollectionViewCell { @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var preview: UIImageView! @IBOutlet weak var title: UILabel! override func awakeFromNib() { super.awakeFromNib() //self.layer.cornerRadius = 4 self.layer.borderWidth = 1 self.layer.borderColor = UIColor(red: 0.85, green: 0.85, blue:0.85, alpha: 0.9).CGColor self.layer.masksToBounds = false // addShadow() } func addShadow(){ self.layer.shadowColor = UIColor(red: 0, green: 0, blue:0, alpha: 0.3).CGColor self.layer.shadowOpacity = 0.5 self.layer.shadowRadius = 2 self.layer.shadowOffset = CGSize(width: 0, height: 0) self.layer.shadowPath = UIBezierPath(rect: self.bounds).CGPath println(" ...add... shadow.....") } }
mit
c0d1d36a0dafe11ecc25a61813d0ccc2
24.317073
95
0.597303
4.007722
false
false
false
false
DylanSecreast/uoregon-cis-portfolio
uoregon-cis-399/assignment6/Assignment6/Source/Controller/CatImagesViewController.swift
1
1461
// // CatImagesViewController.swift // Assignment6 // import CoreData import UIKit class CatImagesViewController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, NSFetchedResultsControllerDelegate { // MARK: UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return imagesFetchedResultsController.sections?.first?.numberOfObjects ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CatImageCell", for: indexPath) as! CatImageCell let image = imagesFetchedResultsController.object(at: indexPath) cell.update(for: image) return cell } // MARK: NSFetchedResultsControllerDelegate func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { imagesCollectionView.reloadData() } // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() imagesFetchedResultsController = CatService.shared.images(for: category) imagesFetchedResultsController.delegate = self } // MARK: Properties var category: Category! = nil // MARK: Properties (Private) private var imagesFetchedResultsController: NSFetchedResultsController<Image>! // MARK: Properties (IBOutlet) @IBOutlet private weak var imagesCollectionView: UICollectionView! }
gpl-3.0
088d963071d82c11cbb3a0d377d3d5be
30.085106
140
0.80219
5.162544
false
false
false
false
syoung-smallwisdom/BridgeAppSDK
BridgeAppSDK/SBATrackedSelectionStep.swift
1
18047
// // SBATrackedSelectionStep.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // open class SBATrackedSelectionStep: ORKPageStep, SBATrackedStep, SBATrackedDataSelectedItemsProtocol { open var trackingType: SBATrackingStepType? { return .selection } open var trackedItems: [SBATrackedDataObject] { return _trackedItems } fileprivate var _trackedItems: [SBATrackedDataObject] /** Define a non-generic factory-style initializer to hide the implementation details of creating the default selection/frequency steps in the owning class. */ init(inputItem: SBAFormStepSurveyItem, trackedItems: [SBATrackedDataObject], factory: SBASurveyFactory) { // Set the tracked items pointer _trackedItems = trackedItems // Create the steps with the *first* step as the selection step created from the inputItem let firstStep = SBATrackedSelectionFormStep(surveyItem: inputItem, items: trackedItems) let additionalSteps:[ORKStep] = inputItem.items?.mapAndFilter({ (element) -> ORKStep? in // If the item does not conform to survey item then return nil guard let surveyItem = element as? SBASurveyItem else { return nil } // If the item is not a frequency item then no special handling required // so fall back to the base level factory for creating the step guard let trackedSurveyItem = element as? SBATrackedStep, let type = trackedSurveyItem.trackingType , type == .frequency, let formSurveyItem = element as? SBAFormStepSurveyItem else { return factory.createSurveyStep(surveyItem) } // Otherwise for the case where this is a frequency step, special-case the return to // use the frequency subclass return SBATrackedFrequencyFormStep(surveyItem: formSurveyItem) }) ?? [] let steps = [firstStep] + additionalSteps super.init(identifier: inputItem.identifier, steps: steps) } /** Generic default initializer defined so that this class can include steps that are not the frequency and selection steps. */ public init(identifier: String, trackedItems: [SBATrackedDataObject], steps:[ORKStep]) { _trackedItems = trackedItems super.init(identifier: identifier, steps: steps) } override open func stepViewControllerClass() -> AnyClass { return SBATrackedSelectionStepViewController.classForCoder() } // MARK: SBATrackedDataSelectedItemsProtocol @objc(stepResultWithSelectedItems:) public func stepResult(selectedItems:[SBATrackedDataObject]?) -> ORKStepResult? { guard let items = selectedItems else { return nil } // Map the steps var results:[ORKResult] = self.steps.map { (step) -> [ORKResult] in let substepResults: [ORKResult] = { if let trackingStep = step as? SBATrackedDataSelectedItemsProtocol { // If the substeps implement the selected item result protocol then use that return trackingStep.stepResult(selectedItems: items)?.results ?? [] } else { // TODO: syoung 09/27/2016 Support mapping the results from steps that are not the // selection and frequency steps return step.defaultStepResult().results ?? [] } }() for result in substepResults { result.identifier = "\(step.identifier).\(result.identifier)" } return substepResults }.flatMap({$0}) // Add the tracked result last let trackedResult = SBATrackedDataSelectionResult(identifier: self.identifier) trackedResult.selectedItems = items results.append(trackedResult) return ORKStepResult(stepIdentifier: self.identifier, results: results) } // MARK: Selection filtering var trackedResultIdentifier: String? { return self.steps.find({ (step) -> Bool in if let trackedStep = step as? SBATrackedStep , trackedStep.trackingType == .selection { return true } return false })?.identifier } func filterItems(resultSource:ORKTaskResultSource) -> [SBATrackedDataObject]? { var items: [SBATrackedDataObject]? = trackedItems for step in self.steps { if let filterItems = items, let filterStep = step as? SBATrackedSelectionFilter, let stepResult = resultSource.stepResult(forStepIdentifier: step.identifier) { items = filterStep.filter(selectedItems: filterItems, stepResult: stepResult) } } return items } // MARK: Navigation override override open func stepAfterStep(withIdentifier identifier: String?, with result: ORKTaskResult) -> ORKStep? { // If the identifier is nil, then this is the first step and there isn't any // filtering of the selection that needs to occur guard identifier != nil else { return super.stepAfterStep(withIdentifier: nil, with: result) } // Check if the current state means that nothing was selected. In this case // there is no follow-up steps to further mutate the selection set. guard let selectedItems = filterItems(resultSource: result) else { return nil } // Loop through the next steps to look for the next valid step var shouldSkip = false var nextStep: ORKStep? var previousIdentifier = identifier repeat { nextStep = super.stepAfterStep(withIdentifier: previousIdentifier, with: result) shouldSkip = { guard let navStep = nextStep as? SBATrackedNavigationStep else { return false } navStep.update(selectedItems: selectedItems) return navStep.shouldSkipStep }() previousIdentifier = nextStep?.identifier } while shouldSkip && (nextStep != nil ) return nextStep } override open func stepBeforeStep(withIdentifier identifier: String, with result: ORKTaskResult) -> ORKStep? { // Check if the current state means that nothing was selected. In this case // return to the first step guard let _ = filterItems(resultSource: result) else { return self.steps.first } // Loop backward through the steps until one is found that is the first var shouldSkip = false var previousStep: ORKStep? var previousIdentifier: String? = identifier repeat { previousStep = super.stepBeforeStep(withIdentifier: previousIdentifier!, with: result) shouldSkip = { guard let navStep = previousStep as? SBATrackedNavigationStep else { return false } return navStep.shouldSkipStep }() previousIdentifier = previousStep?.identifier } while shouldSkip && (previousIdentifier != nil ) return previousStep } // MARK: NSCoding required public init(coder aDecoder: NSCoder) { _trackedItems = aDecoder.decodeObject(forKey: "trackedItems") as? [SBATrackedDataObject] ?? [] super.init(coder: aDecoder) } override open func encode(with aCoder: NSCoder){ super.encode(with: aCoder) aCoder.encode(self.trackedItems, forKey: "trackedItems") } // MARK: NSCopying convenience init(identifier: String) { // Copying requires defining the base class ORKStep init self.init(identifier: identifier, trackedItems: [], steps:[]) } override open func copy(with zone: NSZone? = nil) -> Any { let copy = super.copy(with: zone) as! SBATrackedSelectionStep copy._trackedItems = self._trackedItems return copy } // MARK: Equality override open func isEqual(_ object: Any?) -> Bool { guard let object = object as? SBATrackedSelectionStep else { return false } return super.isEqual(object) && SBAObjectEquality(object.trackedItems, self.trackedItems) } override open var hash: Int { return super.hash ^ SBAObjectHash(self.trackedItems) } } class SBATrackedSelectionStepViewController: ORKPageStepViewController { override var result: ORKStepResult? { guard let stepResult = super.result else { return nil } guard let selectionStep = self.pageStep as? SBATrackedSelectionStep, let trackedResultIdentifier = selectionStep.trackedResultIdentifier else { return nil } let trackingResult = SBATrackedDataSelectionResult(identifier: trackedResultIdentifier) trackingResult.startDate = stepResult.startDate trackingResult.endDate = stepResult.endDate trackingResult.selectedItems = selectionStep.filterItems(resultSource: self.resultSource()) stepResult.addResult(trackingResult) return stepResult } } class SBATrackedSelectionFormStep: ORKFormStep, SBATrackedSelectionFilter, SBATrackedDataSelectedItemsProtocol { let skipChoiceValue = "Skipped" let noneChoiceValue = "None" let choicesFormItemIdentifier = "choices" // If this is an optional step, then building the form items will add a skip option override var isOptional: Bool { get { return false } set (newValue) { super.isOptional = newValue } } init(surveyItem: SBAFormStepSurveyItem, items:[SBATrackedDataObject]) { super.init(identifier: surveyItem.identifier) surveyItem.mapStepValues(with: self) // choices var choices = items.map { (item) -> ORKTextChoice in return item.createORKTextChoice() } // Add a choice for none of the above let noneChoice = ORKTextChoice(text: Localization.localizedString("SBA_NONE_OF_THE_ABOVE"), detailText: nil, value: noneChoiceValue as NSString, exclusive: true) choices.append(noneChoice) // If this is an optional step, then include a choice for skipping if (super.isOptional) { let skipChoice = ORKTextChoice(text: Localization.localizedString("SBA_SKIP_CHOICE"), detailText: nil, value: skipChoiceValue as NSString, exclusive: true) choices.append(skipChoice) } // setup the form items let answerFormat = ORKTextChoiceAnswerFormat(style: .multipleChoice, textChoices: choices) let formItem = ORKFormItem(identifier: choicesFormItemIdentifier, text: nil, answerFormat: answerFormat) self.formItems = [formItem] } override init(identifier: String) { super.init(identifier: identifier) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // MARK: SBATrackedDataSelectedItemsProtocol @objc(stepResultWithSelectedItems:) public func stepResult(selectedItems:[SBATrackedDataObject]?) -> ORKStepResult? { guard let formItem = self.formItems?.first, let choices = selectedItems?.map({$0.identifier}) else { return self.defaultStepResult() } let answer: Any = (choices.count > 0) ? choices : noneChoiceValue return stepResult(answerMap: [formItem.identifier : answer] ) } // MARK: SBATrackedSelectionFilter var trackingType: SBATrackingStepType? { return .selection } func filter(selectedItems items: [SBATrackedDataObject], stepResult: ORKStepResult) -> [SBATrackedDataObject]? { // If the step result does not yet include the result of the step then just return all items guard let choiceResult = stepResult.result(forIdentifier: choicesFormItemIdentifier) as? ORKChoiceQuestionResult else { return items.map({ $0.copy() as! SBATrackedDataObject }) } // If the selection was skipped then return nil guard let choices = choiceResult.choiceAnswers as? [String] , choices != [skipChoiceValue] else { return nil } // filter and map the results return items.filter({ choices.contains($0.identifier) }).map({ $0.copy() as! SBATrackedDataObject }) } } class SBATrackedFrequencyFormStep: ORKFormStep, SBATrackedNavigationStep, SBATrackedSelectionFilter, SBATrackedDataSelectedItemsProtocol { var frequencyAnswerFormat: ORKAnswerFormat? init(surveyItem: SBAFormStepSurveyItem) { super.init(identifier: surveyItem.identifier) surveyItem.mapStepValues(with: self) if let range = surveyItem as? SBANumberRange { self.frequencyAnswerFormat = range.createAnswerFormat(with: .scale) } } // MARK: SBATrackedNavigationStep var trackingType: SBATrackingStepType? { return .frequency } var shouldSkipStep: Bool { return (self.formItems == nil) || (self.formItems!.count == 0) } func update(selectedItems:[SBATrackedDataObject]) { self.formItems = selectedItems.filter({ $0.usesFrequencyRange }).map { (item) -> ORKFormItem in return ORKFormItem(identifier: item.identifier, text: item.text, answerFormat: self.frequencyAnswerFormat) } } func filter(selectedItems items: [SBATrackedDataObject], stepResult: ORKStepResult) -> [SBATrackedDataObject]? { return items.map({ (item) -> SBATrackedDataObject in let copy = item.copy() as! SBATrackedDataObject if let scaleResult = stepResult.result(forIdentifier: item.identifier) as? ORKScaleQuestionResult, let answer = scaleResult.scaleAnswer { copy.frequency = answer.uintValue } return copy }) } // MARK: SBATrackedDataSelectedItemsProtocol @objc(stepResultWithSelectedItems:) public func stepResult(selectedItems:[SBATrackedDataObject]?) -> ORKStepResult? { let results = selectedItems?.mapAndFilter({ (item) -> ORKScaleQuestionResult? in guard item.usesFrequencyRange else { return nil } let scaleResult = ORKScaleQuestionResult(identifier: item.identifier) scaleResult.scaleAnswer = NSNumber(value: item.frequency) return scaleResult }) return ORKStepResult(stepIdentifier: self.identifier, results: results) } // MARK: NSCoding required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.frequencyAnswerFormat = aDecoder.decodeObject(forKey: #keyPath(frequencyAnswerFormat)) as? ORKAnswerFormat } override func encode(with aCoder: NSCoder){ super.encode(with: aCoder) aCoder.encode(self.frequencyAnswerFormat, forKey: #keyPath(frequencyAnswerFormat)) } // MARK: NSCopying override init(identifier: String) { super.init(identifier: identifier) } override func copy(with zone: NSZone? = nil) -> Any { let copy = super.copy(with: zone) as! SBATrackedFrequencyFormStep copy.frequencyAnswerFormat = self.frequencyAnswerFormat return copy } // MARK: Equality override func isEqual(_ object: Any?) -> Bool { guard let object = object as? SBATrackedFrequencyFormStep else { return false } return super.isEqual(object) && SBAObjectEquality(object.frequencyAnswerFormat, self.frequencyAnswerFormat) } override var hash: Int { return super.hash ^ SBAObjectHash(self.frequencyAnswerFormat) } }
bsd-3-clause
c740eac5beb638e0a1c80e938bbc4561
39.552809
138
0.645074
5.261224
false
false
false
false
anilkumarbp/ringcentral-swift-NEW
src/Transaction.swift
1
2723
// // Transaction.swift // src // // Created by Anil Kumar BP on 11/1/15. // Copyright (c) 2015 Anil Kumar BP. All rights reserved. // import Foundation class Transaction { internal var jsonAsArray = [String: AnyObject]() internal var jsonAsObject = AnyObject?() internal var multipartTransactions = AnyObject?() internal var request: NSMutableURLRequest? internal var raw = AnyObject?() internal var jsonAsString: String = "" private var data: NSData? private var response: NSURLResponse? private var error: NSError? private var dict: NSDictionary? init(request: NSMutableURLRequest, status: Int = 200) { self.request = request } func getText() -> String { if let check = data { return check.description } else { return "No data." } } func getRaw() -> Any { return raw } func getJson() -> [String: AnyObject] { return jsonAsArray } func getJsonAsString() -> String { return jsonAsString } func setData(data: NSData?) { self.data = data self.jsonAsString = JSONStringify(data!) } func setDict(dict: NSDictionary?) { self.dict = dict } func setResponse(response: NSURLResponse?) { self.response = response } func setError(error: NSError?) { self.error = error } func getMultipart() -> AnyObject? { return self.multipartTransactions } func isOK() -> Bool { return (self.response as! NSHTTPURLResponse).statusCode / 100 == 2 } func getError() -> NSError? { return error } func getData() -> NSData? { return self.data } func getDict() -> Dictionary<String,NSObject> { return self.dict as! Dictionary<String, NSObject> } func getRequest() -> NSMutableURLRequest? { return request } func getResponse() -> NSURLResponse? { return response } func isContentType(type: String) -> Bool { return false } func getContentType() { } func JSONStringify(value: AnyObject, prettyPrinted: Bool = false) -> String { var options = prettyPrinted ? NSJSONWritingOptions.PrettyPrinted : nil if NSJSONSerialization.isValidJSONObject(value) { if let data = NSJSONSerialization.dataWithJSONObject(value, options: options, error: nil) { if let string = NSString(data: data, encoding: NSUTF8StringEncoding) { return string as String } } } return "" } }
mit
1016af16d2e1e80c60af3066b5dc04c8
23.106195
103
0.577304
4.8625
false
false
false
false
beretis/SwipeToDeleteCollectionView
Example Project/Pods/SwipeToDeleteCollectionView/SwipeToDeleteCollectionView/SwipeToDeleteCollectionViewCell.swift
1
5108
// SwipeToDeleteCollectionView.h // SwipeToDeleteCollectionView // // Created by Jozef Matus on 14/05/2017. // Copyright © 2017 Jozef Matus. All rights reserved. // import UIKit import RxCocoa import RxSwift public protocol SwipeToDeleteCellAble { var swipeToDeleteButtons: [SwipeToDeleteButton] { get set } func setButtonsArray() } open class SwipeToDeleteCollectionViewCell: UICollectionViewCell, SwipeToDeleteCellAble { public var swipeToDeleteButtons: [SwipeToDeleteButton] = [] var subscriptions: [Disposable] = [] override open func awakeFromNib() { super.awakeFromNib() self.setButtonsArray() self.createDeleteView() } override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func prepareForReuse() { for subscription in subscriptions { subscription.dispose() } } func createDeleteView() { //create underlying view for swipe to delete self.contentView.backgroundColor = UIColor.white let deleteView = UIView(frame: self.bounds) deleteView.translatesAutoresizingMaskIntoConstraints = false deleteView.backgroundColor = UIColor.lightText deleteView.layer.zPosition = -10 self.backgroundView = deleteView self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[subview]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["subview" : deleteView])) self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[subview]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["subview" : deleteView])) self.addSwipeToDeleteButtons(ToView: deleteView) } open func configureWith(ViewModel vm: SwipeToDeleteCellVM) { for button in self.swipeToDeleteButtons { self.subscriptions.append(button.rx.tap.map { _ in return button.data.actionId } .bind(to: vm.swipeToDeleteActionsObserver)) } } open func setButtonsArray() { let deleteButton = SwipeToDeleteButton(data: SwipeToDeleteButtonData(width: 70, color: UIColor.red, title: "DELETE", font: UIFont.boldSystemFont(ofSize: 12), actionId: "delete")) self.swipeToDeleteButtons = [deleteButton] } private func addSwipeToDeleteButtons(ToView view: UIView) { guard self.swipeToDeleteButtons.count > 0 else { return } for i in 0...self.swipeToDeleteButtons.count - 1 { let deleteButton = self.swipeToDeleteButtons[i] view.addSubview(deleteButton) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[button]-\(self.getButtonOffset(ForIndex: i))-|", options: .directionLeadingToTrailing, metrics: nil, views: ["button" : deleteButton])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[button]-0-|", options: .directionLeadingToTrailing, metrics: nil, views: ["button" : deleteButton])) view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[button(\(deleteButton.data.width))]", options: .directionLeadingToTrailing, metrics: nil, views: ["button" : deleteButton])) } } private func getButtonOffset(ForIndex index: Int) -> Int { guard index < self.swipeToDeleteButtons.count && index > -1 else { fatalError("Index out of bounds") } var offset: Int = 0 guard index > 0 else { return offset } for i in 0...index-1 { offset += self.swipeToDeleteButtons[i].data.width } return offset } var combinedButtonsWidth: Int { return self.swipeToDeleteButtons.reduce(0, { (initialValue, button) -> Int in return initialValue + button.data.width }) } } open class SwipeToDeleteButton: UIButton { var data: SwipeToDeleteButtonData public init(data: SwipeToDeleteButtonData) { self.data = data super.init(frame: CGRect.zero) self.backgroundColor = data.color self.setTitle(data.title, for: .normal) self.translatesAutoresizingMaskIntoConstraints = false self.titleLabel?.font = data.font } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { return false } } public struct SwipeToDeleteButtonData { var width: Int var color: UIColor var title: String var font: UIFont var actionId: String public init(width: Int, color: UIColor, title: String, font: UIFont, actionId: SwipeToDeleteActionID) { self.width = width self.color = color self.title = title self.font = font self.actionId = actionId } }
mit
b3147f2d20be95c5451775a829ddd1ea
35.219858
220
0.661053
4.804327
false
false
false
false
OscarSwanros/swift
test/SILGen/addressors.swift
3
32254
// RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -emit-sil %s | %FileCheck %s // RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -emit-silgen %s | %FileCheck %s -check-prefix=SILGEN // RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -emit-ir %s // This test includes some calls to transparent stdlib functions. // We pattern match for the absence of access markers in the inlined code. // REQUIRES: optimized_stdlib import Swift func someValidPointer<T>() -> UnsafePointer<T> { fatalError() } func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() } struct A { var base: UnsafeMutablePointer<Int32> = someValidPointer() subscript(index: Int32) -> Int32 { unsafeAddress { return UnsafePointer(base) } unsafeMutableAddress { return base } } static var staticProp: Int32 { unsafeAddress { // Just don't trip up the verifier. fatalError() } } } // CHECK-LABEL: sil hidden @_T010addressors1AVs5Int32VAEcilu : $@convention(method) (Int32, A) -> UnsafePointer<Int32> // CHECK: bb0([[INDEX:%.*]] : $Int32, [[SELF:%.*]] : $A): // CHECK: [[BASE:%.*]] = struct_extract [[SELF]] : $A, #A.base // CHECK: [[T0:%.*]] = struct_extract [[BASE]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T1:%.*]] = struct $UnsafePointer<Int32> ([[T0]] : $Builtin.RawPointer) // CHECK: return [[T1]] : $UnsafePointer<Int32> // CHECK-LABEL: sil hidden @_T010addressors1AVs5Int32VAEciau : $@convention(method) (Int32, @inout A) -> UnsafeMutablePointer<Int32> // CHECK: bb0([[INDEX:%.*]] : $Int32, [[SELF:%.*]] : $*A): // CHECK: [[READ:%.*]] = begin_access [read] [static] [[SELF]] : $*A // CHECK: [[T0:%.*]] = struct_element_addr [[READ]] : $*A, #A.base // CHECK: [[BASE:%.*]] = load [[T0]] : $*UnsafeMutablePointer<Int32> // CHECK: return [[BASE]] : $UnsafeMutablePointer<Int32> // CHECK-LABEL: sil hidden @_T010addressors5test0yyF : $@convention(thin) () -> () { func test0() { // CHECK: [[A:%.*]] = alloc_stack $A // CHECK: [[T0:%.*]] = function_ref @_T010addressors1AV{{[_0-9a-zA-Z]*}}fC // CHECK: [[T1:%.*]] = metatype $@thin A.Type // CHECK: [[AVAL:%.*]] = apply [[T0]]([[T1]]) // CHECK: store [[AVAL]] to [[A]] var a = A() // CHECK: [[T0:%.*]] = function_ref @_T010addressors1AVs5Int32VAEcilu : // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[AVAL]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[Z:%.*]] = load [[T3]] : $*Int32 let z = a[10] // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[A]] : $*A // CHECK: [[T0:%.*]] = function_ref @_T010addressors1AVs5Int32VAEciau : // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: load // CHECK: sadd_with_overflow_Int{{32|64}} // CHECK: store {{%.*}} to [[T3]] a[5] += z // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[A]] : $*A // CHECK: [[T0:%.*]] = function_ref @_T010addressors1AVs5Int32VAEciau : // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: store {{%.*}} to [[T3]] a[3] = 6 } // CHECK-LABEL: sil hidden @_T010addressors5test1s5Int32VyF : $@convention(thin) () -> Int32 func test1() -> Int32 { // CHECK: [[CTOR:%.*]] = function_ref @_T010addressors1AV{{[_0-9a-zA-Z]*}}fC // CHECK: [[T0:%.*]] = metatype $@thin A.Type // CHECK: [[A:%.*]] = apply [[CTOR]]([[T0]]) : $@convention(method) (@thin A.Type) -> A // CHECK: [[ACCESSOR:%.*]] = function_ref @_T010addressors1AVs5Int32VAEcilu : $@convention(method) (Int32, A) -> UnsafePointer<Int32> // CHECK: [[PTR:%.*]] = apply [[ACCESSOR]]({{%.*}}, [[A]]) : $@convention(method) (Int32, A) -> UnsafePointer<Int32> // CHECK: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = load [[T1]] : $*Int32 // CHECK: return [[T2]] : $Int32 return A()[0] } let uninitAddr = UnsafeMutablePointer<Int32>.allocate(capacity: 1) var global: Int32 { unsafeAddress { return UnsafePointer(uninitAddr) } // CHECK: sil hidden @_T010addressors6globals5Int32Vvlu : $@convention(thin) () -> UnsafePointer<Int32> { // CHECK: [[T0:%.*]] = global_addr @_T010addressors10uninitAddrSpys5Int32VGvp : $*UnsafeMutablePointer<Int32> // CHECK: [[T1:%.*]] = load [[T0]] : $*UnsafeMutablePointer<Int32> // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T3:%.*]] = struct $UnsafePointer<Int32> ([[T2]] : $Builtin.RawPointer) // CHECK: return [[T3]] : $UnsafePointer<Int32> } func test_global() -> Int32 { return global } // CHECK-LABEL: sil hidden @_T010addressors11test_globals5Int32VyF : $@convention(thin) () -> Int32 { // CHECK: [[T0:%.*]] = function_ref @_T010addressors6globals5Int32Vvlu : $@convention(thin) () -> UnsafePointer<Int32> // CHECK: [[T1:%.*]] = apply [[T0]]() : $@convention(thin) () -> UnsafePointer<Int32> // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafePointer<Int32>, #UnsafePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T4:%.*]] = load [[T3]] : $*Int32 // CHECK: return [[T4]] : $Int32 // Test that having generated trivial accessors for something because // of protocol conformance doesn't force us down inefficient access paths. protocol Subscriptable { subscript(i: Int32) -> Int32 { get set } } struct B : Subscriptable { subscript(i: Int32) -> Int32 { unsafeAddress { return someValidPointer() } unsafeMutableAddress { return someValidPointer() } } } // CHECK-LABEL: sil hidden @_T010addressors6test_ByAA1BVzF : $@convention(thin) (@inout B) -> () { // CHECK: bb0([[B:%.*]] : $*B): // CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 0 // CHECK: [[INDEX:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32) // CHECK: [[RHS:%.*]] = integer_literal $Builtin.Int32, 7 // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[B]] : $*B // CHECK: [[T0:%.*]] = function_ref @_T010addressors1BVs5Int32VAEciau // CHECK: [[PTR:%.*]] = apply [[T0]]([[INDEX]], [[WRITE]]) // CHECK: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>, // CHECK: [[ADDR:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // Accept either of struct_extract+load or load+struct_element_addr. // CHECK: load // CHECK: [[T1:%.*]] = builtin "or_Int32" // CHECK: [[T2:%.*]] = struct $Int32 ([[T1]] : $Builtin.Int32) // CHECK: store [[T2]] to [[ADDR]] : $*Int32 func test_B(_ b: inout B) { b[0] |= 7 } // Test that we handle abstraction difference. struct CArray<T> { var storage: UnsafeMutablePointer<T> subscript(index: Int) -> T { unsafeAddress { return UnsafePointer(storage) + index } unsafeMutableAddress { return storage + index } } } func id_int(_ i: Int32) -> Int32 { return i } // CHECK-LABEL: sil hidden @_T010addressors11test_carrays5Int32VAA6CArrayVyA2DcGzF : $@convention(thin) (@inout CArray<(Int32) -> Int32>) -> Int32 { // CHECK: bb0([[ARRAY:%.*]] : $*CArray<(Int32) -> Int32>): func test_carray(_ array: inout CArray<(Int32) -> Int32>) -> Int32 { // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[ARRAY]] : $*CArray<(Int32) -> Int32> // CHECK: [[T0:%.*]] = function_ref @_T010addressors6CArrayVxSiciau : // CHECK: [[T1:%.*]] = apply [[T0]]<(Int32) -> Int32>({{%.*}}, [[WRITE]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<(Int32) -> Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*@callee_owned (@in Int32) -> @out Int32 // CHECK: store {{%.*}} to [[T3]] : array[0] = id_int // CHECK: [[READ:%.*]] = begin_access [read] [static] [[ARRAY]] : $*CArray<(Int32) -> Int32> // CHECK: [[T0:%.*]] = load [[READ]] // CHECK: [[T1:%.*]] = function_ref @_T010addressors6CArrayVxSicilu : // CHECK: [[T2:%.*]] = apply [[T1]]<(Int32) -> Int32>({{%.*}}, [[T0]]) // CHECK: [[T3:%.*]] = struct_extract [[T2]] : $UnsafePointer<(Int32) -> Int32>, #UnsafePointer._rawValue // CHECK: [[T4:%.*]] = pointer_to_address [[T3]] : $Builtin.RawPointer to [strict] $*@callee_owned (@in Int32) -> @out Int32 // CHECK: [[T5:%.*]] = load [[T4]] return array[1](5) } // rdar://17270560, redux struct D : Subscriptable { subscript(i: Int32) -> Int32 { get { return i } unsafeMutableAddress { return someValidPointer() } } } // Setter. // SILGEN-LABEL: sil hidden [transparent] @_T010addressors1DVs5Int32VAEcis // SILGEN: bb0([[VALUE:%.*]] : @trivial $Int32, [[I:%.*]] : @trivial $Int32, [[SELF:%.*]] : @trivial $*D): // SILGEN: debug_value [[VALUE]] : $Int32 // SILGEN: debug_value [[I]] : $Int32 // SILGEN: debug_value_addr [[SELF]] // SILGEN: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[SELF]] : $*D // users: %12, %8 // SILGEN: [[T0:%.*]] = function_ref @_T010addressors1DVs5Int32VAEciau{{.*}} // SILGEN: [[PTR:%.*]] = apply [[T0]]([[I]], [[ACCESS]]) // SILGEN: [[T0:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>, // SILGEN: [[ADDR:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // SILGEN: assign [[VALUE]] to [[ADDR]] : $*Int32 // materializeForSet. // SILGEN-LABEL: sil hidden [transparent] @_T010addressors1DVs5Int32VAEcim // SILGEN: bb0([[BUFFER:%.*]] : @trivial $Builtin.RawPointer, [[STORAGE:%.*]] : @trivial $*Builtin.UnsafeValueBuffer, [[I:%.*]] : @trivial $Int32, [[SELF:%.*]] : @trivial $*D): // SILGEN: [[T0:%.*]] = function_ref @_T010addressors1DVs5Int32VAEciau // SILGEN: [[PTR:%.*]] = apply [[T0]]([[I]], [[SELF]]) // SILGEN: [[ADDR_TMP:%.*]] = struct_extract [[PTR]] : $UnsafeMutablePointer<Int32>, // SILGEN: [[ADDR:%.*]] = pointer_to_address [[ADDR_TMP]] // SILGEN: [[PTR:%.*]] = address_to_pointer [[ADDR]] // SILGEN: [[OPT:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none!enumelt // SILGEN: [[T2:%.*]] = tuple ([[PTR]] : $Builtin.RawPointer, [[OPT]] : $Optional<Builtin.RawPointer>) // SILGEN: return [[T2]] : func make_int() -> Int32 { return 0 } func take_int_inout(_ value: inout Int32) {} // CHECK-LABEL: sil hidden @_T010addressors6test_ds5Int32VAA1DVzF : $@convention(thin) (@inout D) -> Int32 // CHECK: bb0([[ARRAY:%.*]] : $*D): func test_d(_ array: inout D) -> Int32 { // CHECK: [[T0:%.*]] = function_ref @_T010addressors8make_ints5Int32VyF // CHECK: [[V:%.*]] = apply [[T0]]() // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[ARRAY]] : $*D // CHECK: [[T0:%.*]] = function_ref @_T010addressors1DVs5Int32VAEciau // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, // CHECK: [[ADDR:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: store [[V]] to [[ADDR]] : $*Int32 array[0] = make_int() // CHECK: [[FN:%.*]] = function_ref @_T010addressors14take_int_inoutys5Int32VzF // CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[ARRAY]] : $*D // CHECK: [[T0:%.*]] = function_ref @_T010addressors1DVs5Int32VAEciau // CHECK: [[T1:%.*]] = apply [[T0]]({{%.*}}, [[WRITE]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, // CHECK: [[ADDR:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: apply [[FN]]([[ADDR]]) take_int_inout(&array[1]) // CHECK: [[READ:%.*]] = begin_access [read] [static] [[ARRAY]] : $*D // CHECK: [[T0:%.*]] = load [[READ]] // CHECK: [[T1:%.*]] = function_ref @_T010addressors1DVs5Int32VAEcig // CHECK: [[T2:%.*]] = apply [[T1]]({{%.*}}, [[T0]]) // CHECK: return [[T2]] return array[2] } struct E { var value: Int32 { unsafeAddress { return someValidPointer() } nonmutating unsafeMutableAddress { return someValidPointer() } } } // CHECK-LABEL: sil hidden @_T010addressors6test_eyAA1EVF // CHECK: bb0([[E:%.*]] : $E): // CHECK: [[T0:%.*]] = function_ref @_T010addressors1EV5values5Int32Vvau // CHECK: [[T1:%.*]] = apply [[T0]]([[E]]) // CHECK: [[T2:%.*]] = struct_extract [[T1]] // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] // CHECK: store {{%.*}} to [[T3]] : $*Int32 func test_e(_ e: E) { e.value = 0 } class F { var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100) final var value: Int32 { addressWithNativeOwner { return (UnsafePointer(data), Builtin.castToNativeObject(self)) } mutableAddressWithNativeOwner { return (data, Builtin.castToNativeObject(self)) } } } // CHECK-LABEL: sil hidden @_T010addressors1FC5values5Int32Vvlo : $@convention(method) (@guaranteed F) -> (UnsafePointer<Int32>, @owned Builtin.NativeObject) { // CHECK-LABEL: sil hidden @_T010addressors1FC5values5Int32Vvao : $@convention(method) (@guaranteed F) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject) { func test_f0(_ f: F) -> Int32 { return f.value } // CHECK-LABEL: sil hidden @_T010addressors7test_f0s5Int32VAA1FCF : $@convention(thin) (@owned F) -> Int32 { // CHECK: bb0([[SELF:%0]] : $F): // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1FC5values5Int32Vvlo : $@convention(method) (@guaranteed F) -> (UnsafePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject // CHECK: [[VALUE:%.*]] = load [[T2]] : $*Int32 // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // CHECK: strong_release [[SELF]] : $F // CHECK: return [[VALUE]] : $Int32 func test_f1(_ f: F) { f.value = 14 } // CHECK-LABEL: sil hidden @_T010addressors7test_f1yAA1FCF : $@convention(thin) (@owned F) -> () { // CHECK: bb0([[SELF:%0]] : $F): // CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 14 // CHECK: [[VALUE:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32) // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1FC5values5Int32Vvao : $@convention(method) (@guaranteed F) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject // CHECK: store [[VALUE]] to [[T2]] : $*Int32 // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // CHECK: strong_release [[SELF]] : $F class G { var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100) var value: Int32 { addressWithNativeOwner { return (UnsafePointer(data), Builtin.castToNativeObject(self)) } mutableAddressWithNativeOwner { return (data, Builtin.castToNativeObject(self)) } } } // CHECK-LABEL: sil hidden [transparent] @_T010addressors1GC5values5Int32Vvg : $@convention(method) (@guaranteed G) -> Int32 { // CHECK: bb0([[SELF:%0]] : $G): // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1GC5values5Int32Vvlo : $@convention(method) (@guaranteed G) -> (UnsafePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Builtin.NativeObject), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject // CHECK: [[VALUE:%.*]] = load [[T2]] : $*Int32 // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // CHECK: return [[VALUE]] : $Int32 // CHECK-LABEL: sil hidden [transparent] @_T010addressors1GC5values5Int32Vvs : $@convention(method) (Int32, @guaranteed G) -> () { // CHECK: bb0([[VALUE:%0]] : $Int32, [[SELF:%1]] : $G): // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1GC5values5Int32Vvao : $@convention(method) (@guaranteed G) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Builtin.NativeObject // CHECK: store [[VALUE]] to [[T2]] : $*Int32 // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // materializeForSet callback for G.value // CHECK-LABEL: sil private [transparent] @_T010addressors1GC5values5Int32VvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout G, @thick G.Type) -> () { // CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $*G, [[SELFTYPE:%3]] : $@thick G.Type): // CHECK: [[T0:%.*]] = project_value_buffer $Builtin.NativeObject in [[STORAGE]] : $*Builtin.UnsafeValueBuffer // CHECK: [[OWNER:%.*]] = load [[T0]] // CHECK: strong_release [[OWNER]] : $Builtin.NativeObject // CHECK: dealloc_value_buffer $Builtin.NativeObject in [[STORAGE]] : $*Builtin.UnsafeValueBuffer // materializeForSet for G.value // CHECK-LABEL: sil hidden [transparent] @_T010addressors1GC5values5Int32Vvm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed G) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $G): // Call the addressor. // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1GC5values5Int32Vvao : $@convention(method) (@guaranteed G) -> (UnsafeMutablePointer<Int32>, @owned Builtin.NativeObject) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[T1:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 0 // CHECK: [[T2:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Builtin.NativeObject), 1 // Get the address. // CHECK: [[PTR:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[ADDR_TMP:%.*]] = pointer_to_address [[PTR]] // CHECK: [[ADDR:%.*]] = mark_dependence [[ADDR_TMP]] : $*Int32 on [[T2]] // Initialize the callback storage with the owner. // CHECK: [[T0:%.*]] = alloc_value_buffer $Builtin.NativeObject in [[STORAGE]] : $*Builtin.UnsafeValueBuffer // CHECK: store [[T2]] to [[T0]] : $*Builtin.NativeObject // CHECK: [[PTR:%.*]] = address_to_pointer [[ADDR]] // Set up the callback. // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T010addressors1GC5values5Int32VvmytfU_ : // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // Epilogue. // CHECK: [[RESULT:%.*]] = tuple ([[PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[RESULT]] class H { var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100) final var value: Int32 { addressWithPinnedNativeOwner { return (UnsafePointer(data), Builtin.tryPin(Builtin.castToNativeObject(self))) } mutableAddressWithPinnedNativeOwner { return (data, Builtin.tryPin(Builtin.castToNativeObject(self))) } } } // CHECK-LABEL: sil hidden @_T010addressors1HC5values5Int32Vvlp : $@convention(method) (@guaranteed H) -> (UnsafePointer<Int32>, @owned Optional<Builtin.NativeObject>) { // CHECK-LABEL: sil hidden @_T010addressors1HC5values5Int32VvaP : $@convention(method) (@guaranteed H) -> (UnsafeMutablePointer<Int32>, @owned Optional<Builtin.NativeObject>) { func test_h0(_ f: H) -> Int32 { return f.value } // CHECK-LABEL: sil hidden @_T010addressors7test_h0s5Int32VAA1HCF : $@convention(thin) (@owned H) -> Int32 { // CHECK: bb0([[SELF:%0]] : $H): // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1HC5values5Int32Vvlp : $@convention(method) (@guaranteed H) -> (UnsafePointer<Int32>, @owned Optional<Builtin.NativeObject>) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: [[VALUE:%.*]] = load [[T2]] : $*Int32 // CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: strong_release [[SELF]] : $H // CHECK: return [[VALUE]] : $Int32 func test_h1(_ f: H) { f.value = 14 } // CHECK-LABEL: sil hidden @_T010addressors7test_h1yAA1HCF : $@convention(thin) (@owned H) -> () { // CHECK: bb0([[SELF:%0]] : $H): // CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 14 // CHECK: [[VALUE:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32) // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1HC5values5Int32VvaP : $@convention(method) (@guaranteed H) -> (UnsafeMutablePointer<Int32>, @owned Optional<Builtin.NativeObject>) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: store [[VALUE]] to [[T2]] : $*Int32 // CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: strong_release [[SELF]] : $H class I { var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100) var value: Int32 { addressWithPinnedNativeOwner { return (UnsafePointer(data), Builtin.tryPin(Builtin.castToNativeObject(self))) } mutableAddressWithPinnedNativeOwner { return (data, Builtin.tryPin(Builtin.castToNativeObject(self))) } } } // CHECK-LABEL: sil hidden [transparent] @_T010addressors1IC5values5Int32Vvg : $@convention(method) (@guaranteed I) -> Int32 { // CHECK: bb0([[SELF:%0]] : $I): // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1IC5values5Int32Vvlp : $@convention(method) (@guaranteed I) -> (UnsafePointer<Int32>, @owned Optional<Builtin.NativeObject>) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafePointer<Int32>, Optional<Builtin.NativeObject>), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: [[VALUE:%.*]] = load [[T2]] : $*Int32 // CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: return [[VALUE]] : $Int32 // CHECK-LABEL: sil hidden [transparent] @_T010addressors1IC5values5Int32Vvs : $@convention(method) (Int32, @guaranteed I) -> () { // CHECK: bb0([[VALUE:%0]] : $Int32, [[SELF:%1]] : $I): // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1IC5values5Int32VvaP : $@convention(method) (@guaranteed I) -> (UnsafeMutablePointer<Int32>, @owned Optional<Builtin.NativeObject>) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[PTR:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 0 // CHECK: [[OWNER:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 1 // CHECK: [[T0:%.*]] = struct_extract [[PTR]] // CHECK: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*Int32 // CHECK: [[T2:%.*]] = mark_dependence [[T1]] : $*Int32 on [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: store [[VALUE]] to [[T2]] : $*Int32 // CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // materializeForSet callback for I.value // CHECK-LABEL: sil private [transparent] @_T010addressors1IC5values5Int32VvmytfU_ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout I, @thick I.Type) -> () { // CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $*I, [[SELFTYPE:%3]] : $@thick I.Type): // CHECK: [[T0:%.*]] = project_value_buffer $Optional<Builtin.NativeObject> in [[STORAGE]] : $*Builtin.UnsafeValueBuffer // CHECK: [[OWNER:%.*]] = load [[T0]] // CHECK: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK: dealloc_value_buffer $Optional<Builtin.NativeObject> in [[STORAGE]] : $*Builtin.UnsafeValueBuffer // CHECK-LABEL: sil hidden [transparent] @_T010addressors1IC5values5Int32Vvm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed I) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%0]] : $Builtin.RawPointer, [[STORAGE:%1]] : $*Builtin.UnsafeValueBuffer, [[SELF:%2]] : $I): // Call the addressor. // CHECK: [[ADDRESSOR:%.*]] = function_ref @_T010addressors1IC5values5Int32VvaP : $@convention(method) (@guaranteed I) -> (UnsafeMutablePointer<Int32>, @owned Optional<Builtin.NativeObject>) // CHECK: [[T0:%.*]] = apply [[ADDRESSOR]]([[SELF]]) // CHECK: [[T1:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 0 // CHECK: [[T2:%.*]] = tuple_extract [[T0]] : $(UnsafeMutablePointer<Int32>, Optional<Builtin.NativeObject>), 1 // Pull out the address. // CHECK: [[PTR:%.*]] = struct_extract [[T1]] : $UnsafeMutablePointer<Int32>, #UnsafeMutablePointer._rawValue // CHECK: [[ADDR_TMP:%.*]] = pointer_to_address [[PTR]] // CHECK: [[ADDR:%.*]] = mark_dependence [[ADDR_TMP]] : $*Int32 on [[T2]] // Initialize the callback storage with the owner. // CHECK: [[T0:%.*]] = alloc_value_buffer $Optional<Builtin.NativeObject> in [[STORAGE]] : $*Builtin.UnsafeValueBuffer // CHECK: store [[T2]] to [[T0]] : $*Optional<Builtin.NativeObject> // CHECK: [[PTR:%.*]] = address_to_pointer [[ADDR]] // Set up the callback. // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_T010addressors1IC5values5Int32VvmytfU_ : // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // Epilogue. // CHECK: [[RESULT:%.*]] = tuple ([[PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[RESULT]] struct RecInner { subscript(i: Int32) -> Int32 { mutating get { return i } } } struct RecMiddle { var inner: RecInner } class RecOuter { var data: UnsafeMutablePointer<RecMiddle> = UnsafeMutablePointer.allocate(capacity: 100) final var middle: RecMiddle { addressWithPinnedNativeOwner { return (UnsafePointer(data), Builtin.tryPin(Builtin.castToNativeObject(self))) } mutableAddressWithPinnedNativeOwner { return (data, Builtin.tryPin(Builtin.castToNativeObject(self))) } } } func test_rec(_ outer: RecOuter) -> Int32 { return outer.middle.inner[0] } // This uses the mutable addressor. // CHECK-LABEL: sil hidden @_T010addressors8test_recs5Int32VAA8RecOuterCF : $@convention(thin) (@owned RecOuter) -> Int32 { // CHECK: function_ref @_T010addressors8RecOuterC6middleAA0B6MiddleVvaP // CHECK: struct_element_addr {{.*}} : $*RecMiddle, #RecMiddle.inner // CHECK: function_ref @_T010addressors8RecInnerVs5Int32VAEcig class Base { var data: UnsafeMutablePointer<Int32> = UnsafeMutablePointer.allocate(capacity: 100) var value: Int32 { addressWithNativeOwner { return (UnsafePointer(data), Builtin.castToNativeObject(self)) } mutableAddressWithNativeOwner { return (data, Builtin.castToNativeObject(self)) } } } class Sub : Base { override var value: Int32 { addressWithNativeOwner { return (UnsafePointer(data), Builtin.castToNativeObject(self)) } mutableAddressWithNativeOwner { return (data, Builtin.castToNativeObject(self)) } } } // Make sure addressors don't get vtable entries. // CHECK-LABEL: sil_vtable Base { // CHECK-NEXT: #Base.data!getter.1: (Base) -> () -> UnsafeMutablePointer<Int32> : _T010addressors4BaseC4dataSpys5Int32VGvg // CHECK-NEXT: #Base.data!setter.1: (Base) -> (UnsafeMutablePointer<Int32>) -> () : _T010addressors4BaseC4dataSpys5Int32VGvs // CHECK-NEXT: #Base.data!materializeForSet.1: (Base) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : _T010addressors4BaseC4dataSpys5Int32VGvm // CHECK-NEXT: #Base.value!getter.1: (Base) -> () -> Int32 : _T010addressors4BaseC5values5Int32Vvg // CHECK-NEXT: #Base.value!setter.1: (Base) -> (Int32) -> () : _T010addressors4BaseC5values5Int32Vvs // CHECK-NEXT: #Base.value!materializeForSet.1: (Base) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : _T010addressors4BaseC5values5Int32Vvm // CHECK-NEXT: #Base.init!initializer.1: (Base.Type) -> () -> Base : _T010addressors4BaseCACycfc // CHECK-NEXT: #Base.deinit!deallocator: _T010addressors4BaseCfD // CHECK-NEXT: } // CHECK-LABEL: sil_vtable Sub { // CHECK-NEXT: #Base.data!getter.1: (Base) -> () -> UnsafeMutablePointer<Int32> : _T010addressors4BaseC4dataSpys5Int32VGvg // CHECK-NEXT: #Base.data!setter.1: (Base) -> (UnsafeMutablePointer<Int32>) -> () : _T010addressors4BaseC4dataSpys5Int32VGvs // CHECK-NEXT: #Base.data!materializeForSet.1: (Base) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : _T010addressors4BaseC4dataSpys5Int32VGvm // CHECK-NEXT: #Base.value!getter.1: (Base) -> () -> Int32 : _T010addressors3SubC5values5Int32Vvg // CHECK-NEXT: #Base.value!setter.1: (Base) -> (Int32) -> () : _T010addressors3SubC5values5Int32Vvs // CHECK-NEXT: #Base.value!materializeForSet.1: (Base) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?) : _T010addressors3SubC5values5Int32Vvm // CHECK-NEXT: #Base.init!initializer.1: (Base.Type) -> () -> Base : _T010addressors3SubCACycfc // CHECK-NEXT: #Sub.deinit!deallocator: _T010addressors3SubCfD // CHECK-NEXT: }
apache-2.0
b898a422b630c79327e3fc0219f191da
54.51463
225
0.638618
3.343076
false
false
false
false
NemProject/NEMiOSApp
NEMWallet/Application/Account/AccountExportPasswordViewController.swift
1
6595
// // AccountExportPasswordViewController.swift // // This file is covered by the LICENSE file in the root of this project. // Copyright (c) 2016 NEM // import UIKit import SwiftyJSON /// The view controller that lets the user choose a password which will get used to encrypt the backup. final class AccountExportPasswordViewController: UIViewController { // MARK: - View Controller Properties fileprivate var account: Account? // MARK: - View Controller Outlets @IBOutlet weak var contentView: UIView! @IBOutlet weak var containerView: UIView! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var defaultPasswordDescriptionLabel: UILabel! @IBOutlet weak var defaultPasswordSwitch: UISwitch! @IBOutlet weak var navigationBar: UINavigationBar! @IBOutlet weak var customNavigationItem: UINavigationItem! @IBOutlet weak var viewTopConstraint: NSLayoutConstraint! @IBOutlet weak var confirmationButton: UIButton! // MARK: - View Controller Lifecycle override func viewDidLoad() { super.viewDidLoad() self.navigationBar.delegate = self account = AccountManager.sharedInstance.activeAccount guard account != nil else { print("Critical: Account not available!") return } updateViewControllerAppearance() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() viewTopConstraint.constant = self.navigationBar.frame.height + 70 } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier! { case "showAccountExportViewController": let destinationViewController = segue.destination as! AccountExportViewController let accountJsonString = sender as! String destinationViewController.accountJsonString = accountJsonString default: return } } // MARK: - View Controller Helper Methods /// Updates the appearance (coloring, titles) of the view controller. fileprivate func updateViewControllerAppearance() { customNavigationItem.title = "EXPORT_ACCOUNT".localized() descriptionLabel.text = "ENTET_PASSWORD_EXPORT".localized() descriptionLabel.text = "PASSWORD_PLACEHOLDER_EXPORT".localized() passwordTextField.placeholder = "PASSWORD_PLACEHOLDER".localized() confirmationButton.setTitle("CONFIRM".localized(), for: UIControlState()) containerView.layer.cornerRadius = 5 containerView.clipsToBounds = true } /** Shows an alert view controller with the provided alert message. - Parameter message: The message that should get shown. - Parameter completion: An optional action that should get performed on completion. */ fileprivate func showAlert(withMessage message: String, completion: ((Void) -> Void)? = nil) { let alert = UIAlertController(title: "INFO".localized(), message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK".localized(), style: UIAlertActionStyle.default, handler: { (action) -> Void in alert.dismiss(animated: true, completion: nil) completion?() })) present(alert, animated: true, completion: nil) } /// Validates the input password and prepares for the account export. fileprivate func prepareForExport() { guard passwordTextField.text != nil else { showAlert(withMessage: "FIELDS_EMPTY_ERROR".localized()) return } if defaultPasswordSwitch.isOn == false && passwordTextField.text! == "" { showAlert(withMessage: "FIELDS_EMPTY_ERROR".localized()) return } if defaultPasswordSwitch.isOn == false && passwordTextField.text!.characters.count < 6 { showAlert(withMessage: "PASSOWORD_LENGTH_ERROR".localized()) return } let accountTitle = account!.title let salt = SettingsManager.sharedInstance.authenticationSalt() var encryptedPrivateKey = account!.privateKey if passwordTextField.text != String() { let privateKey = AccountManager.sharedInstance.decryptPrivateKey(encryptedPrivateKey: encryptedPrivateKey) let saltData = NSData(bytes: salt!.asByteArray(), length: salt!.asByteArray().count) let passwordHash = try! HashManager.generateAesKeyForString(passwordTextField.text!, salt: saltData, roundCount: 2000) encryptedPrivateKey = HashManager.AES256Encrypt(inputText: privateKey, key: passwordHash!.hexadecimalString()) } let jsonData = JSON([QRKeys.dataType.rawValue: QRType.accountData.rawValue, QRKeys.version.rawValue: Constants.qrVersion, QRKeys.data.rawValue: [ QRKeys.name.rawValue: accountTitle, QRKeys.salt.rawValue: salt!, QRKeys.privateKey.rawValue: encryptedPrivateKey ]]) let jsonString = jsonData.rawString() performSegue(withIdentifier: "showAccountExportViewController", sender: jsonString) } // MARK: - View Controller Outlet Actions @IBAction func defaultPasswordSwitchChanged(_ sender: UISwitch) { var height: CGFloat = 0 if sender.isOn { height = 100 passwordTextField.text = String() passwordTextField.endEditing(true) } else { height = 152 } for constraint in containerView.constraints { if constraint.identifier == "height" { constraint.constant = height break } } UIView.animate(withDuration: 0.2, animations: { [unowned self] () -> Void in self.view.layoutIfNeeded() }) } @IBAction func confirmationButtonPressed(_ sender: UIButton) { passwordTextField.endEditing(true) prepareForExport() } @IBAction func cancel(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } } // MARK: - Navigation Bar Delegate extension AccountExportPasswordViewController: UINavigationBarDelegate { func position(for bar: UIBarPositioning) -> UIBarPosition { return .topAttached } }
mit
5fba84caabc5b92e93bb17ccd740812f
36.050562
270
0.651251
5.565401
false
false
false
false
Ashok28/Kingfisher
Sources/SwiftUI/KFAnimatedImage.swift
3
3929
// // KFAnimatedImage.swift // Kingfisher // // Created by wangxingbin on 2021/4/29. // // Copyright (c) 2021 Wei Wang <[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. #if canImport(SwiftUI) && canImport(Combine) && canImport(UIKit) && !os(watchOS) import SwiftUI import Combine @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) public struct KFAnimatedImage: KFImageProtocol { public typealias HoldingView = KFAnimatedImageViewRepresenter public var context: Context<HoldingView> public init(context: KFImage.Context<HoldingView>) { self.context = context } /// Configures current rendering view with a `block`. This block will be applied when the under-hood /// `AnimatedImageView` is created in `UIViewRepresentable.makeUIView(context:)` /// /// - Parameter block: The block applies to the animated image view. /// - Returns: A `KFAnimatedImage` view that being configured by the `block`. public func configure(_ block: @escaping (HoldingView.RenderingView) -> Void) -> Self { context.renderConfigurations.append(block) return self } } /// A wrapped `UIViewRepresentable` of `AnimatedImageView` @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) public struct KFAnimatedImageViewRepresenter: UIViewRepresentable, KFImageHoldingView { public typealias RenderingView = AnimatedImageView public static func created(from image: KFCrossPlatformImage?, context: KFImage.Context<Self>) -> KFAnimatedImageViewRepresenter { KFAnimatedImageViewRepresenter(image: image, context: context) } var image: KFCrossPlatformImage? let context: KFImage.Context<KFAnimatedImageViewRepresenter> public func makeUIView(context: Context) -> AnimatedImageView { let view = AnimatedImageView() self.context.renderConfigurations.forEach { $0(view) } view.image = image // Allow SwiftUI scale (fit/fill) working fine. view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) view.setContentCompressionResistancePriority(.defaultLow, for: .vertical) return view } public func updateUIView(_ uiView: AnimatedImageView, context: Context) { uiView.image = image } } #if DEBUG @available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) struct KFAnimatedImage_Previews : PreviewProvider { static var previews: some View { Group { KFAnimatedImage(source: .network(URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher-TestImages/master/DemoAppImage/GIF/1.gif")!)) .onSuccess { r in print(r) } .placeholder { ProgressView() } .padding() } } } #endif #endif
mit
b0248a5cfdcbf82af89cda945e690c7b
39.505155
156
0.693561
4.531719
false
true
false
false
samhann/Loader.swift
Loader.swift
1
6718
// // FBLoader.swift // FBAnimatedView // // Created by Samhan on 08/01/16. // Copyright © 2016 Samhan. All rights reserved. // import UIKit @objc public protocol ListLoadable { func ld_visibleContentViews()->[UIView] } extension UITableView : ListLoadable { public func ld_visibleContentViews()->[UIView] { return (self.visibleCells as NSArray).value(forKey: "contentView") as! [UIView] } } extension UICollectionView : ListLoadable { public func ld_visibleContentViews()->[UIView] { return (self.visibleCells as NSArray).value(forKey: "contentView") as! [UIView] } } extension UIColor { static func backgroundFadedGrey()->UIColor { return UIColor(red: (246.0/255.0), green: (247.0/255.0), blue: (248.0/255.0), alpha: 1) } static func gradientFirstStop()->UIColor { return UIColor(red: (238.0/255.0), green: (238.0/255.0), blue: (238.0/255.0), alpha: 1.0) } static func gradientSecondStop()->UIColor { return UIColor(red: (221.0/255.0), green: (221.0/255.0), blue:(221.0/255.0) , alpha: 1.0); } } extension UIView{ func boundInside(_ superView: UIView){ self.translatesAutoresizingMaskIntoConstraints = false superView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[subview]-0-|", options: NSLayoutFormatOptions(), metrics:nil, views:["subview":self])) superView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[subview]-0-|", options: NSLayoutFormatOptions(), metrics:nil, views:["subview":self])) } } open class Loader { static func addLoaderToViews(_ views : [UIView]) { CATransaction.begin() views.forEach { $0.ld_addLoader() } CATransaction.commit() } static func removeLoaderFromViews(_ views: [UIView]) { CATransaction.begin() views.forEach { $0.ld_removeLoader() } CATransaction.commit() } open static func addLoaderTo(_ list : ListLoadable ) { self.addLoaderToViews(list.ld_visibleContentViews()) } open static func removeLoaderFrom(_ list : ListLoadable ) { self.removeLoaderFromViews(list.ld_visibleContentViews()) } } class CutoutView : UIView { override func draw(_ rect: CGRect) { super.draw(rect) let context = UIGraphicsGetCurrentContext() context?.setFillColor(UIColor.white.cgColor) context?.fill(self.bounds) for view in (self.superview?.subviews)! { if view != self { context?.setBlendMode(.clear); context?.setFillColor(UIColor.clear.cgColor) context?.fill(view.frame) } } } override func layoutSubviews() { self.setNeedsDisplay() self.superview?.ld_getGradient()?.frame = (self.superview?.bounds)! } } // TODO :- Allow caller to tweak these var cutoutHandle: UInt8 = 0 var gradientHandle: UInt8 = 0 var loaderDuration = 0.85 var gradientWidth = 0.17 var gradientFirstStop = 0.1 extension CGFloat { func doubleValue()->Double { return Double(self) } } extension UIView { public func ld_getCutoutView()->UIView? { return objc_getAssociatedObject(self, &cutoutHandle) as! UIView? } func ld_setCutoutView(_ aView : UIView) { return objc_setAssociatedObject(self, &cutoutHandle, aView, .OBJC_ASSOCIATION_RETAIN) } func ld_getGradient()->CAGradientLayer? { return objc_getAssociatedObject(self, &gradientHandle) as! CAGradientLayer? } func ld_setGradient(_ aLayer : CAGradientLayer) { return objc_setAssociatedObject(self, &gradientHandle, aLayer, .OBJC_ASSOCIATION_RETAIN) } public func ld_addLoader() { let gradient: CAGradientLayer = CAGradientLayer() gradient.frame = CGRect(x: 0, y: 0, width: self.bounds.size.width , height: self.bounds.size.height) self.layer.insertSublayer(gradient, at:0) self.configureAndAddAnimationToGradient(gradient) self.addCutoutView() } public func ld_removeLoader() { self.ld_getCutoutView()?.removeFromSuperview() self.ld_getGradient()?.removeAllAnimations() self.ld_getGradient()?.removeFromSuperlayer() for view in self.subviews { view.alpha = 1 } } func configureAndAddAnimationToGradient(_ gradient : CAGradientLayer) { gradient.startPoint = CGPoint(x: -1.0 + CGFloat(gradientWidth), y: 0) gradient.endPoint = CGPoint(x: 1.0 + CGFloat(gradientWidth), y: 0) gradient.colors = [ UIColor.backgroundFadedGrey().cgColor, UIColor.gradientFirstStop().cgColor, UIColor.gradientSecondStop().cgColor, UIColor.gradientFirstStop().cgColor, UIColor.backgroundFadedGrey().cgColor ] let startLocations = [NSNumber(value: gradient.startPoint.x.doubleValue() as Double),NSNumber(value: gradient.startPoint.x.doubleValue() as Double),NSNumber(value: 0 as Double),NSNumber(value: gradientWidth as Double),NSNumber(value: 1 + gradientWidth as Double)] gradient.locations = startLocations let gradientAnimation = CABasicAnimation(keyPath: "locations") gradientAnimation.fromValue = startLocations gradientAnimation.toValue = [NSNumber(value: 0 as Double),NSNumber(value: 1 as Double),NSNumber(value: 1 as Double),NSNumber(value: 1 + (gradientWidth - gradientFirstStop) as Double),NSNumber(value: 1 + gradientWidth as Double)] gradientAnimation.repeatCount = Float.infinity gradientAnimation.fillMode = kCAFillModeForwards gradientAnimation.isRemovedOnCompletion = false gradientAnimation.duration = loaderDuration gradient.add(gradientAnimation ,forKey:"locations") self.ld_setGradient(gradient) } func addCutoutView() { let cutout = CutoutView() cutout.frame = self.bounds cutout.backgroundColor = UIColor.clear self.addSubview(cutout) cutout.setNeedsDisplay() cutout.boundInside(self) for view in self.subviews { if view != cutout { view.alpha = 0 } } self.ld_setCutoutView(cutout) } }
bsd-2-clause
630584d53e5a0d9c6b0e5b66d25d5cc3
27.222689
271
0.615304
4.483979
false
false
false
false
iWeslie/Ant
Ant/Ant/AppDelegate.swift
2
7608
// // AppDelegate.swift // AntDemo // // Created by LiuXinQiang on 2017/6/8. // Copyright © 2017年 LiuXinQiang. All rights reserved. // import UIKit import AFNetworking import SVProgressHUD @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var theme : UIColor = UIColor.red var fontSize : CGFloat = 1.0 var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.backgroundColor = UIColor.white let baseVC = BaseTabBarVC() window?.rootViewController = baseVC window?.makeKeyAndVisible() let mgr = AFNetworkReachabilityManager.shared() mgr.setReachabilityStatusChange { (Status) -> Void in switch(Status){ case AFNetworkReachabilityStatus.notReachable: SVProgressHUD.showError(withStatus: "网络错误") NetWorkTool.shareInstance.canConnect = false break case AFNetworkReachabilityStatus.reachableViaWiFi: SVProgressHUD.showSuccess(withStatus: "已接入wifi") NetWorkTool.shareInstance.canConnect = true break case AFNetworkReachabilityStatus.reachableViaWWAN: SVProgressHUD.showSuccess(withStatus: "已接入WWAN") NetWorkTool.shareInstance.canConnect = true break default: NetWorkTool.shareInstance.canConnect = true break } } mgr.startMonitoring() //读取偏好设置数据 let deafult = UserDefaults.standard let font = deafult.float(forKey: "font") appdelgate?.fontSize = font != 0 ? CGFloat(font) : CGFloat(1.0) swizzlingMethod(clzz: UIViewController.self, oldSelector: #selector(UIViewController.viewWillAppear(_:)), newSelector: Selector(("viewDidLoadForChangeTitleColor"))) ShareSDK.registerActivePlatforms( [ SSDKPlatformType.typeSinaWeibo.rawValue, SSDKPlatformType.typeWechat.rawValue, SSDKPlatformType.typeQQ.rawValue ], onImport: {(platform : SSDKPlatformType) -> Void in switch platform { case SSDKPlatformType.typeSinaWeibo: ShareSDKConnector.connectWeibo(WeiboSDK.classForCoder()) case SSDKPlatformType.typeWechat: ShareSDKConnector.connectWeChat(WXApi.classForCoder()) case SSDKPlatformType.typeQQ: ShareSDKConnector.connectQQ(QQApiInterface.classForCoder(), tencentOAuthClass: TencentOAuth.classForCoder()) default: break } }, onConfiguration: {(platform : SSDKPlatformType , appInfo : NSMutableDictionary?) -> Void in switch platform { case SSDKPlatformType.typeSinaWeibo: //设置新浪微博应用信息,其中authType设置为使用SSO+Web形式授权 appInfo?.ssdkSetupSinaWeibo(byAppKey: "568898243", appSecret: "38a4f8204cc784f81f9f0daaf31e02e3", redirectUri: "http://www.sharesdk.cn", authType: SSDKAuthTypeBoth) case SSDKPlatformType.typeWechat: //设置微信应用信息 appInfo?.ssdkSetupWeChat(byAppId: "wx4868b35061f87885", appSecret: "64020361b8ec4c99936c0e3999a9f249") case SSDKPlatformType.typeQQ: //设置QQ应用信息 appInfo?.ssdkSetupQQ(byAppId: "100371282", appKey: "aed9b0303e3ed1e27bae87c33761161d", authType: SSDKAuthTypeWeb) default: break } }) return true } class dynamic func getCurrentController() -> UIViewController? { guard let window = UIApplication.shared.windows.first else { return nil } var tempView: UIView? for subview in window.subviews.reversed() { if subview.classForCoder.description() == "UILayoutContainerView" { tempView = subview break } } if tempView == nil { tempView = window.subviews.last } var nextResponder = tempView?.next var next: Bool { return !(nextResponder is UIViewController) || nextResponder is UINavigationController || nextResponder is UITabBarController } while next{ tempView = tempView?.subviews.first if tempView == nil { return nil } nextResponder = tempView!.next } return nextResponder as? UIViewController } func swizzlingMethod(clzz: AnyClass, oldSelector: Selector, newSelector: Selector) { let oldMethod = class_getInstanceMethod(clzz, oldSelector) let newMethod = class_getInstanceMethod(clzz, newSelector) method_exchangeImplementations(oldMethod, newMethod) } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { let mgr = AFNetworkReachabilityManager.shared() mgr.stopMonitoring() //偏好设置 let userDefault = UserDefaults.standard //存储数据 userDefault.set(appdelgate?.fontSize, forKey: "font") //同步数据 userDefault.synchronize() } }
apache-2.0
9a951954edfc28f1fb982f87944cca89
38.125654
285
0.598153
5.851997
false
false
false
false
mtgto/madoka
madoka/StatusMenuController.swift
1
6719
// // StatusMenuController.swift // madoka // // Created by mtgto on 2016/01/30. // Copyright © 2016 mtgto. All rights reserved. // import Cocoa import ServiceManagement class StatusMenuController: NSObject, NSMenuDelegate { private let madokaService: MadokaService = MadokaService.sharedInstance private let colors: [NSColor] = [ NSColor.blue, NSColor.green, NSColor.yellow, NSColor.orange, NSColor.red, NSColor.purple ] enum IntervalIndex: Int { case oneHour = 0 case fourHours = 1 case eightHours = 2 case today = 3 func startDateFrom(_ current: Date) -> Date { switch self { case .oneHour: return current.addingTimeInterval(-60 * 60) case .fourHours: return current.addingTimeInterval(-4 * 60 * 60) case .eightHours: return current.addingTimeInterval(-8 * 60 * 60) case .today: let calendar = Calendar.current return calendar.date(from: (calendar as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: current))! } } } private var intervalIndex: IntervalIndex = .oneHour /** * Minimum duration to show in menu (inclusive). */ private let minimumDuration: TimeInterval = 60 @IBOutlet weak var oneHourMenuItem: NSMenuItem! @IBOutlet weak var fourHoursMenuItem: NSMenuItem! @IBOutlet weak var eightHoursMenuItem: NSMenuItem! @IBOutlet weak var todayMenuItem: NSMenuItem! @IBOutlet weak var launchAtLoginMenuItem: NSMenuItem! override init() { self.intervalIndex = IntervalIndex(rawValue: UserDefaults.standard.integer(forKey: Constants.KeyPreferenceIntervalIndex))! } @IBAction func toggleLaunchAtLogin(_ sender: Any) { if sender as? NSMenuItem == self.launchAtLoginMenuItem { let status = !UserDefaults.standard.bool(forKey: Constants.KeyPreferenceLaunchAtLogin) if SMLoginItemSetEnabled(Constants.HelperBundleIdentifier as CFString, status) { UserDefaults.standard.set(status, forKey: Constants.KeyPreferenceLaunchAtLogin) self.launchAtLoginMenuItem.state = status ? .on : .off } else { let alert = NSAlert() alert.messageText = NSLocalizedString("Error", comment: "Error") alert.informativeText = NSLocalizedString("Failed to set launch item at login.", comment: "Failed to set launch item at login.") alert.runModal() } } } @IBAction func menuSelected(_ sender: Any) { oneHourMenuItem.state = .off fourHoursMenuItem.state = .off eightHoursMenuItem.state = .off todayMenuItem.state = .off if let menuItem = sender as? NSMenuItem { if menuItem == oneHourMenuItem { oneHourMenuItem.state = .on intervalIndex = .oneHour } else if menuItem == fourHoursMenuItem { fourHoursMenuItem.state = .on intervalIndex = .fourHours } else if menuItem == eightHoursMenuItem { eightHoursMenuItem.state = .on intervalIndex = .eightHours } else if menuItem == todayMenuItem { todayMenuItem.state = .on intervalIndex = .today } } UserDefaults.standard.set(intervalIndex.rawValue, forKey: Constants.KeyPreferenceIntervalIndex) } func menuWillOpen(_ menu: NSMenu) { let current = Date() let applicationStatistics: [(name: String, icon: NSImage?, duration: TimeInterval)] = self.madokaService.usedAppsSince(intervalIndex.startDateFrom(current), to: current) .filter { $0.duration >= minimumDuration } let totalDuration = applicationStatistics.reduce(0) { return $0 + $1.duration } for _ in 0..<menu.items.count-4 { menu.removeItem(at: 0) } for (i, statistic) in applicationStatistics.enumerated() { let title = String(format: "%@ (%.1f %%)", statistic.name, statistic.duration * 100 / totalDuration) let menuItem = NSMenuItem(title: title, action: nil, keyEquivalent: "") menuItem.isEnabled = true if let sourceIcon = statistic.icon { menuItem.image = StatusMenuController.resizedIconImage(sourceIcon) } menu.insertItem(menuItem, at: i) let subtitle = String(format: "%02d:%02d", Int(statistic.duration) / 60, Int(statistic.duration) % 60) let subMenu = NSMenu(title: "") subMenu.addItem(NSMenuItem(title: subtitle, action: nil, keyEquivalent: "")) menuItem.submenu = subMenu } let menuItem = NSMenuItem(title: "", action: nil, keyEquivalent: "") if applicationStatistics.isEmpty { menuItem.title = NSLocalizedString("No app is used one minute or more", comment: "No app is used one minute or more") } else { let viewController: StatisticsViewController = StatisticsViewController(nibName: "StatisticsViewController", bundle: Bundle.main) viewController.updateData(applicationStatistics.enumerated().map { (legend: $0.1.name, color:self.colors[$0.0 % self.colors.count], ratio: Float($0.1.duration / totalDuration), icon: $0.1.icon) }) menuItem.view = viewController.view } menu.insertItem(menuItem, at: applicationStatistics.count) self.setIntervalMenuState() self.launchAtLoginMenuItem.state = UserDefaults.standard.bool(forKey: Constants.KeyPreferenceLaunchAtLogin) ? .on : .off } private func setIntervalMenuState() { switch self.intervalIndex { case .oneHour: oneHourMenuItem.state = .on case .fourHours: fourHoursMenuItem.state = .on case .eightHours: eightHoursMenuItem.state = .on case .today: todayMenuItem.state = .on } } private static func resizedIconImage(_ source: NSImage) -> NSImage { let width: CGFloat = 16 let height: CGFloat = 16 let newSize = NSMakeSize(width, height) let newImage = NSImage(size: newSize) newImage.lockFocus() NSGraphicsContext.current?.imageInterpolation = .high source.draw(in: NSMakeRect(0, 0, width, height), from: NSMakeRect(0, 0, source.size.width, source.size.height), operation: .copy, fraction: 1.0) newImage.unlockFocus() return newImage } }
mit
b0ced2f9e4a3533cfd54bab95411ea76
39.963415
208
0.623995
4.761162
false
false
false
false
SwiftORM/Postgres-StORM
Sources/PostgresStORM/parseRows.swift
1
2824
// // parseRows.swift // PostgresStORM // // Created by Jonathan Guthrie on 2016-10-06. // // import StORM import PerfectPostgreSQL import PerfectLib //import PerfectXML import Foundation /// Supplies the parseRows method extending the main class. extension PostgresStORM { /// parseRows takes the [String:Any] result and returns an array of StormRows public func parseRows(_ result: PGResult) -> [StORMRow] { var resultRows = [StORMRow]() let num = result.numTuples() for x in 0..<num { // rows var params = [String: Any]() for f in 0..<result.numFields() { guard let fieldName = result.fieldName(index: f) else { continue } switch PostgresMap(Int(result.fieldType(index: f)!)) { case "Int": params[fieldName] = result.getFieldInt(tupleIndex: x, fieldIndex: f) case "Bool": params[fieldName] = result.getFieldBool(tupleIndex: x, fieldIndex: f) case "String": params[fieldName] = result.getFieldString(tupleIndex: x, fieldIndex: f) case "json": let output = result.getFieldString(tupleIndex: x, fieldIndex: f) do { let decode = try output?.jsonDecode() // Here we are first trying to cast into the traditional json return. However, when using the json_agg function, it will return an array. The following considers both cases. params[fieldName] = decode as? [String:Any] ?? decode as? [[String:Any]] } catch { params[fieldName] = [String:Any]() } case "jsonb": let output = result.getFieldString(tupleIndex: x, fieldIndex: f) do { let decode = try output?.jsonDecode() // Here we are first trying to cast into the traditional json return. However, when using the jsonb_agg function, it will return an array. The following considers both cases. params[fieldName] = decode as? [String:Any] ?? decode as? [[String:Any]] } catch { params[fieldName] = [String:Any]() } // case "xml": // // will create an XML object // params[fieldName] = XDocument(fromSource: result.getFieldString(tupleIndex: x, fieldIndex: f)!) case "float": params[fieldName] = result.getFieldFloat(tupleIndex: x, fieldIndex: f) case "date": if let output = result.getFieldString(tupleIndex: x, fieldIndex: f) { let formatter = DateFormatter() formatter.dateFormat = "yyyy/MM/dd hh:mm Z" params[fieldName] = formatter.date(from: output) } else { params[fieldName] = nil } // time // timestamp // timestampz default: params[fieldName] = result.getFieldString(tupleIndex: x, fieldIndex: f) } } let thisRow = StORMRow() thisRow.data = params resultRows.append(thisRow) } return resultRows } }
apache-2.0
aa55abdad86db9dc9f158442a69f3714
32.619048
200
0.640581
3.648579
false
false
false
false
SoneeJohn/WWDC
PlayerUI/Views/PUITimelineView.swift
1
24189
// // PUITimelineView.swift // PlayerProto // // Created by Guilherme Rambo on 28/04/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa import AVFoundation protocol PUITimelineViewDelegate: class { func timelineViewWillBeginInteractiveSeek() func timelineViewDidSeek(to progress: Double) func timelineViewDidFinishInteractiveSeek() func timelineDidReceiveForceTouch(at timestamp: Double) } public final class PUITimelineView: NSView { // MARK: - Public API public override init(frame frameRect: NSRect) { super.init(frame: frameRect) buildUI() } public required init?(coder: NSCoder) { super.init(coder: coder) buildUI() } public override var intrinsicContentSize: NSSize { return NSSize(width: -1, height: 8) } public weak var delegate: PUITimelineDelegate? public var bufferingProgress: Double = 0 { didSet { layoutBufferingLayer() } } public var playbackProgress: Double = 0 { didSet { layoutPlaybackLayer() } } public var annotations: [PUITimelineAnnotation] = [] { didSet { layoutAnnotations() } } public var mediaDuration: Double = 0 { didSet { needsLayout = true } } public var hasValidMediaDuration: Bool { return AVPlayer.validateMediaDurationWithSeconds(mediaDuration) } // MARK: - Private API private var annotationWindowController: PUIAnnotationWindowController? weak var viewDelegate: PUITimelineViewDelegate? var loadedSegments = Set<PUIBufferSegment>() { didSet { bufferingProgressLayer.segments = loadedSegments } } struct Metrics { static let cornerRadius: CGFloat = 4 static let annotationBubbleDiameter: CGFloat = 12 static let annotationBubbleDiameterHoverScale: CGFloat = 1.3 static let annotationDragThresholdVertical: CGFloat = 15 static let annotationDragThresholdHorizontal: CGFloat = 6 } private var borderLayer: PUIBoringLayer! private var bufferingProgressLayer: PUIBufferLayer! private var playbackProgressLayer: PUIBoringLayer! private var ghostProgressLayer: PUIBoringLayer! private func buildUI() { wantsLayer = true layer = PUIBoringLayer() layer?.masksToBounds = false // Main border borderLayer = PUIBoringLayer() borderLayer.borderColor = NSColor.playerBorder.cgColor borderLayer.borderWidth = 1.0 borderLayer.frame = bounds borderLayer.cornerRadius = Metrics.cornerRadius layer?.addSublayer(borderLayer) // Buffering bar bufferingProgressLayer = PUIBufferLayer() bufferingProgressLayer.frame = bounds bufferingProgressLayer.cornerRadius = Metrics.cornerRadius bufferingProgressLayer.masksToBounds = true layer?.addSublayer(bufferingProgressLayer) // Playback bar playbackProgressLayer = PUIBoringLayer() playbackProgressLayer.backgroundColor = NSColor.playerProgress.cgColor playbackProgressLayer.frame = bounds playbackProgressLayer.cornerRadius = Metrics.cornerRadius playbackProgressLayer.masksToBounds = true layer?.addSublayer(playbackProgressLayer) // Ghost bar ghostProgressLayer = PUIBoringLayer() ghostProgressLayer.backgroundColor = NSColor.playerProgress.withAlphaComponent(0.5).cgColor ghostProgressLayer.frame = bounds ghostProgressLayer.cornerRadius = Metrics.cornerRadius ghostProgressLayer.masksToBounds = true layer?.addSublayer(ghostProgressLayer) } public override func layout() { super.layout() borderLayer.frame = bounds layoutBufferingLayer() layoutPlaybackLayer() layoutAnnotations(distributeOnly: true) } private func layoutBufferingLayer() { bufferingProgressLayer.frame = bounds } private func layoutPlaybackLayer() { guard hasValidMediaDuration else { return } let playbackWidth = bounds.width * CGFloat(playbackProgress) var playbackRect = bounds playbackRect.size.width = playbackWidth playbackProgressLayer.frame = playbackRect } private var hasMouseInside: Bool = false { didSet { reactToMouse() } } private var mouseTrackingArea: NSTrackingArea! public override func updateTrackingAreas() { super.updateTrackingAreas() if mouseTrackingArea != nil { removeTrackingArea(mouseTrackingArea) } let options: NSTrackingArea.Options = [NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.mouseMoved, NSTrackingArea.Options.activeInActiveApp] let trackingBounds = bounds.insetBy(dx: -2.5, dy: -7) mouseTrackingArea = NSTrackingArea(rect: trackingBounds, options: options, owner: self, userInfo: nil) addTrackingArea(mouseTrackingArea) } public override func mouseEntered(with event: NSEvent) { super.mouseEntered(with: event) hasMouseInside = true } public override func mouseExited(with event: NSEvent) { super.mouseExited(with: event) hasMouseInside = false unhighlightCurrentHoveredAnnotationIfNeeded() } public override func mouseMoved(with event: NSEvent) { super.mouseMoved(with: event) guard hasMouseInside else { return } updateGhostProgress(with: event) trackMouseAgainstAnnotations(with: event) } private func updateGhostProgress(with event: NSEvent) { let point = convert(event.locationInWindow, from: nil) guard point.x > 0 && point.x < bounds.width else { return } let ghostWidth = point.x var ghostRect = bounds ghostRect.size.width = ghostWidth ghostProgressLayer.frame = ghostRect } public override var mouseDownCanMoveWindow: Bool { set { } get { return false } } public override func mouseDown(with event: NSEvent) { if let targetAnnotation = hoveredAnnotation { mouseDown(targetAnnotation.0, layer: targetAnnotation.1, originalEvent: event) return } selectedAnnotation = nil delegate?.timelineDidSelectAnnotation(nil) unhighlightCurrentHoveredAnnotationIfNeeded() var startedInteractiveSeek = false window?.trackEvents(matching: [NSEvent.EventTypeMask.pressure, NSEvent.EventTypeMask.leftMouseUp, NSEvent.EventTypeMask.leftMouseDragged, NSEvent.EventTypeMask.tabletPoint], timeout: NSEvent.foreverDuration, mode: .eventTrackingRunLoopMode) { e, stop in let point = self.convert((e?.locationInWindow)!, from: nil) let progress = Double(point.x / self.bounds.width) switch e?.type { case .leftMouseUp?: if startedInteractiveSeek { self.viewDelegate?.timelineViewDidFinishInteractiveSeek() } else { // single click seek self.viewDelegate?.timelineViewDidSeek(to: progress) } stop.pointee = true case .pressure?, .tabletPoint?: switch e?.touchForce { case .forceTouch?: guard self.hasValidMediaDuration else { stop.pointee = true return } let timestamp = self.mediaDuration * progress DebugLog("Force touch at \(timestamp)s") self.viewDelegate?.timelineDidReceiveForceTouch(at: timestamp) stop.pointee = true default: break } case .leftMouseDragged?: if !startedInteractiveSeek { startedInteractiveSeek = true self.viewDelegate?.timelineViewWillBeginInteractiveSeek() } self.viewDelegate?.timelineViewDidSeek(to: progress) self.ghostProgressLayer.opacity = 0 default: break } } NSApp.discardEvents(matching: NSEvent.EventTypeMask.leftMouseDown, before: nil) } private func reactToMouse() { if hasMouseInside { borderLayer.animate { borderLayer.borderColor = NSColor.highlightedPlayerBorder.cgColor } ghostProgressLayer.animate { ghostProgressLayer.opacity = 1 } } else { borderLayer.animate { borderLayer.borderColor = NSColor.playerBorder.cgColor } ghostProgressLayer.animate { ghostProgressLayer.opacity = 0 } } } public override var allowsVibrancy: Bool { return true } public override var isFlipped: Bool { return true } // MARK: - Annotation management private var annotationLayers: [PUIAnnotationLayer] = [] private func layoutAnnotations(distributeOnly: Bool = false) { guard hasValidMediaDuration else { return } annotationLayers.forEach({ $0.removeFromSuperlayer() }) annotationLayers.removeAll() let sf = window?.screen?.backingScaleFactor ?? 1 annotationLayers = annotations.map { annotation in let l = PUIAnnotationLayer() l.backgroundColor = NSColor.playerHighlight.cgColor l.name = annotation.identifier l.zPosition = 999 l.cornerRadius = Metrics.annotationBubbleDiameter / 2 l.borderColor = NSColor.white.cgColor l.borderWidth = 0 let textLayer = PUIBoringTextLayer() textLayer.string = attributedString(for: annotation.timestamp) textLayer.contentsScale = sf textLayer.opacity = 0 l.attach(layer: textLayer, attribute: .top, spacing: 8) return l } annotations.forEach { annotation in guard let l = annotationLayers.first(where: { $0.name == annotation.identifier }) else { return } layoutAnnotationLayer(l, for: annotation, with: Metrics.annotationBubbleDiameter) } annotationLayers.forEach({ layer?.addSublayer($0) }) } private func attributedString(for timestamp: Double) -> NSAttributedString { let pStyle = NSMutableParagraphStyle() pStyle.alignment = .center let timeTextAttributes: [NSAttributedStringKey: Any] = [ .font: NSFont.systemFont(ofSize: 14, weight: NSFont.Weight.medium), .foregroundColor: NSColor.playerHighlight, .paragraphStyle: pStyle ] let timeStr = String(timestamp: timestamp) ?? "" return NSAttributedString(string: timeStr, attributes: timeTextAttributes) } private func layoutAnnotationLayer(_ layer: PUIBoringLayer, for annotation: PUITimelineAnnotation, with diameter: CGFloat, animated: Bool = false) { guard hasValidMediaDuration else { return } let x: CGFloat = (CGFloat(annotation.timestamp / mediaDuration) * bounds.width) - (diameter / 2) let y: CGFloat = bounds.height / 2 - diameter / 2 let f = CGRect(x: x, y: y, width: diameter, height: diameter) if animated { layer.animate { layer.frame = f layer.cornerRadius = f.width / 2 } } else { layer.frame = f layer.cornerRadius = f.width / 2 } if let (sa, _) = selectedAnnotation { if sa.identifier == annotation.identifier { configureAnnotationLayerAsHighlighted(layer: layer) } } } private var hoveredAnnotation: (PUITimelineAnnotation, PUIAnnotationLayer)? private var selectedAnnotation: (PUITimelineAnnotation, PUIAnnotationLayer)? { didSet { unhighlight(annotationTuple: oldValue) if selectedAnnotation != nil { showAnnotationWindow() hoveredAnnotation = nil } else { unhighlightCurrentHoveredAnnotationIfNeeded() hideAnnotationWindow() } } } private func annotationUnderMouse(with event: NSEvent, diameter: CGFloat = Metrics.annotationBubbleDiameter) -> (annotation: PUITimelineAnnotation, layer: PUIAnnotationLayer)? { var point = convert(event.locationInWindow, from: nil) point.x -= diameter / 2 let s = CGSize(width: diameter, height: diameter) let testRect = CGRect(origin: point, size: s) guard let annotationLayer = annotationLayers.first(where: { $0.frame.intersects(testRect) }) else { return nil } guard let name = annotationLayer.name else { return nil } guard let annotation = annotations.first(where: { $0.identifier == name }) else { return nil } return (annotation: annotation, layer: annotationLayer) } private func trackMouseAgainstAnnotations(with event: NSEvent) { guard let (annotation, annotationLayer) = annotationUnderMouse(with: event) else { unhighlightCurrentHoveredAnnotationIfNeeded() return } hoveredAnnotation = (annotation, annotationLayer) mouseOver(annotation, layer: annotationLayer) } private func unhighlightCurrentHoveredAnnotationIfNeeded() { guard let (ha, hal) = hoveredAnnotation else { return } if let (sa, _) = selectedAnnotation { guard sa.identifier != ha.identifier else { return } } mouseOut(ha, layer: hal) hoveredAnnotation = nil } private func unhighlight(annotationTuple: (PUITimelineAnnotation, PUIAnnotationLayer)?) { guard let (sa, sal) = annotationTuple else { return } mouseOut(sa, layer: sal) } private func mouseOver(_ annotation: PUITimelineAnnotation, layer: PUIAnnotationLayer) { CATransaction.begin() defer { CATransaction.commit() } layer.animate { configureAnnotationLayerAsHighlighted(layer: layer) } delegate?.timelineDidHighlightAnnotation(annotation) } private func configureAnnotationLayerAsHighlighted(layer: PUIBoringLayer) { guard let layer = layer as? PUIAnnotationLayer else { return } let s = Metrics.annotationBubbleDiameterHoverScale layer.transform = CATransform3DMakeScale(s, s, s) layer.borderWidth = 1 layer.attachedLayer.animate { layer.attachedLayer.opacity = 1 } } private func mouseOut(_ annotation: PUITimelineAnnotation, layer: PUIAnnotationLayer) { CATransaction.begin() defer { CATransaction.commit() } layer.animate { layer.transform = CATransform3DIdentity layer.borderWidth = 0 layer.attachedLayer.animate { layer.attachedLayer.opacity = 0 } } delegate?.timelineDidHighlightAnnotation(nil) } private enum AnnotationDragMode { case none case delete case move } private func mouseDown(_ annotation: PUITimelineAnnotation, layer: PUIAnnotationLayer, originalEvent: NSEvent) { let startingPoint = convert(originalEvent.locationInWindow, from: nil) let originalPosition = layer.position let originalTimestampString = layer.attachedLayer.string var cancelled = true let canDelete = delegate?.timelineCanDeleteAnnotation(annotation) ?? false let canMove = delegate?.timelineCanMoveAnnotation(annotation) ?? false var mode: AnnotationDragMode = .none { didSet { if oldValue != .delete && mode == .delete { NSCursor.disappearingItem.push() layer.attachedLayer.animate { layer.attachedLayer.opacity = 0 } } else if oldValue == .delete && mode != .delete { NSCursor.pop() layer.attachedLayer.animate { layer.attachedLayer.opacity = 1 } } else if mode == .none && cancelled { layer.animate { layer.position = originalPosition } updateAnnotationTextLayer(with: originalTimestampString) } } } var isSnappingBack = false { didSet { if !oldValue && isSnappingBack { // give haptic feedback when snapping the annotation back to its original position NSHapticFeedbackManager.defaultPerformer.perform(.alignment, performanceTime: .default) } } } func makeTimestamp(for point: CGPoint) -> Double { var timestamp = Double(point.x / bounds.width) * mediaDuration if timestamp < 0 { timestamp = 0 } else if timestamp > mediaDuration { timestamp = mediaDuration } return timestamp } func updateAnnotationTextLayer(at point: CGPoint) { let timestamp = makeTimestamp(for: point) layer.attachedLayer.string = attributedString(for: timestamp) } func updateAnnotationTextLayer(with string: Any?) { guard let str = string else { return } layer.attachedLayer.string = str } window?.trackEvents(matching: [NSEvent.EventTypeMask.leftMouseUp, NSEvent.EventTypeMask.leftMouseDragged, NSEvent.EventTypeMask.keyUp], timeout: NSEvent.foreverDuration, mode: .eventTrackingRunLoopMode) { event, stop in let point = self.convert((event?.locationInWindow)!, from: nil) switch event?.type { case .leftMouseUp?: switch mode { case .delete: cancelled = false // poof __NSShowAnimationEffect(.poof, NSEvent.mouseLocation, .zero, nil, nil, nil) CATransaction.begin() CATransaction.setCompletionBlock { layer.removeFromSuperlayer() } layer.animate { layer.transform = CATransform3DMakeScale(0, 0, 0) layer.opacity = 0 } CATransaction.commit() self.delegate?.timelineDidDeleteAnnotation(annotation) case .move: cancelled = false let timestamp = makeTimestamp(for: point) self.delegate?.timelineDidMoveAnnotation(annotation, to: timestamp) case .none: self.selectedAnnotation = (annotation, layer) self.delegate?.timelineDidSelectAnnotation(annotation) } mode = .none self.hoveredAnnotation = nil updateAnnotationTextLayer(at: point) stop.pointee = true case .leftMouseDragged?: self.selectedAnnotation = nil if mode != .delete { guard point.x - layer.bounds.width / 2 > 0 else { return } guard point.x < self.borderLayer.frame.width - layer.bounds.width / 2 else { return } } let verticalDiff = startingPoint.y - point.y let horizontalDiff = startingPoint.x - point.x var newPosition = layer.position if abs(verticalDiff) > Metrics.annotationDragThresholdVertical && canDelete { newPosition = point mode = .delete isSnappingBack = false } else if abs(horizontalDiff) > Metrics.annotationDragThresholdHorizontal && canMove { newPosition.y = originalPosition.y newPosition.x = point.x mode = .move updateAnnotationTextLayer(at: point) isSnappingBack = false } else { layer.position = originalPosition mode = .none isSnappingBack = true } if mode != .none { layer.position = newPosition } case .keyUp?: // cancel with ESC if event?.keyCode == 53 { mode = .none layer.animate { layer.position = originalPosition } stop.pointee = true } default: break } } } // MARK: - Annotation editing management private var annotationCommandsMonitor: Any? private var currentAnnotationEditor: NSViewController? private func showAnnotationWindow() { guard let (annotation, annotationLayer) = selectedAnnotation else { return } guard let controller = delegate?.viewControllerForTimelineAnnotation(annotation) else { return } currentAnnotationEditor = controller if annotationWindowController == nil { annotationWindowController = PUIAnnotationWindowController() } guard let windowController = annotationWindowController else { return } guard let annotationWindow = windowController.window else { return } guard let contentView = annotationWindowController?.window?.contentView else { return } controller.view.frame = contentView.bounds controller.view.autoresizingMask = [NSView.AutoresizingMask.width, NSView.AutoresizingMask.height] contentView.addSubview(controller.view) let layerRect = convertFromLayer(annotationLayer.frame) let windowRect = convert(layerRect, to: nil) guard var screenRect = window?.convertToScreen(windowRect) else { return } screenRect.origin.y += 56 screenRect.origin.x -= round((contentView.bounds.width / 2) - annotationLayer.bounds.width) annotationWindow.alphaValue = 0 window?.addChildWindow(annotationWindow, ordered: .above) annotationWindow.setFrameOrigin(screenRect.origin) if annotation.isEmpty { annotationWindow.makeKeyAndOrderFront(nil) } else { annotationWindow.orderFront(nil) } annotationWindow.animator().alphaValue = 1 enum AnnotationKeyCommand: UInt16 { case escape = 53 case enter = 36 } annotationCommandsMonitor = NSEvent.addLocalMonitorForEvents(matching: [NSEvent.EventTypeMask.keyUp]) { event in guard let command = AnnotationKeyCommand(rawValue: event.keyCode) else { return event } switch command { case .enter: if event.modifierFlags.contains(NSEvent.ModifierFlags.command) { fallthrough } case .escape: self.selectedAnnotation = nil self.unhighlightCurrentHoveredAnnotationIfNeeded() } return event } } private func hideAnnotationWindow() { if let monitor = annotationCommandsMonitor { NSEvent.removeMonitor(monitor) annotationCommandsMonitor = nil } NSAnimationContext.beginGrouping() NSAnimationContext.current.completionHandler = { self.annotationWindowController?.close() self.currentAnnotationEditor?.view.removeFromSuperview() self.currentAnnotationEditor = nil self.annotationWindowController = nil } annotationWindowController?.window?.animator().alphaValue = 0 NSAnimationContext.endGrouping() } var isEditingAnnotation: Bool { return annotationWindowController != nil } }
bsd-2-clause
c70f44cbc923bd07a5fce5f426c646f7
32.134247
261
0.612576
5.429405
false
false
false
false
GreatfeatServices/gf-mobile-app
olivin-esguerra/ios-exam/Pods/RxSwift/RxSwift/Observables/Implementations/Range.swift
57
1679
// // Range.swift // RxSwift // // Created by Krunoslav Zaher on 9/13/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class RangeProducer<E: SignedInteger> : Producer<E> { fileprivate let _start: E fileprivate let _count: E fileprivate let _scheduler: ImmediateSchedulerType init(start: E, count: E, scheduler: ImmediateSchedulerType) { if count < 0 { rxFatalError("count can't be negative") } if start &+ (count - 1) < start { rxFatalError("overflow of count") } _start = start _count = count _scheduler = scheduler } override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E { let sink = RangeSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } } class RangeSink<O: ObserverType> : Sink<O> where O.E: SignedInteger { typealias Parent = RangeProducer<O.E> private let _parent: Parent init(parent: Parent, observer: O, cancel: Cancelable) { _parent = parent super.init(observer: observer, cancel: cancel) } func run() -> Disposable { return _parent._scheduler.scheduleRecursive(0 as O.E) { i, recurse in if i < self._parent._count { self.forwardOn(.next(self._parent._start + i)) recurse(i + 1) } else { self.forwardOn(.completed) self.dispose() } } } }
apache-2.0
e11c0ca33c228f8d714da9d5ea3f8193
27.440678
139
0.580453
4.280612
false
false
false
false
macbaszii/TreasureHunt
TreasureHunt/GeoLocation.swift
1
1009
// // GeoLocation.swift // TreasureHunt // // Created by Kiattisak Anoochitarom on 9/29/2557 BE. // Copyright (c) 2557 Kiattisak Anoochitarom. All rights reserved. // import Foundation import MapKit struct GeoLocation { var latitude: Double var longitude: Double var coordinate: CLLocationCoordinate2D { return CLLocationCoordinate2DMake(self.latitude, self.longitude) } var mapPoint: MKMapPoint { return MKMapPointForCoordinate(self.coordinate) } func distanceBetween(other: GeoLocation) -> CLLocationDistance { let locationA = CLLocation(latitude: self.latitude, longitude: self.longitude) let locationB = CLLocation(latitude: other.latitude, longitude: other.longitude) return locationA.distanceFromLocation(locationB) } } extension GeoLocation: Equatable { } func ==(lhs: GeoLocation, rhs: GeoLocation) -> Bool { return lhs.latitude == rhs.latitude && lhs.longitude == rhs.longitude }
mit
4b4b8b5cbafdd6a628b902c5bc34537f
24.897436
88
0.694747
4.330472
false
false
false
false
ahoppen/swift
test/Constraints/ErrorBridging.swift
5
2605
// RUN: %target-swift-frontend %clang-importer-sdk -typecheck %s -verify // REQUIRES: objc_interop import Foundation enum FooError: HairyError, Runcible { case A var hairiness: Int { return 0 } func runce() {} } protocol HairyError : Error { var hairiness: Int { get } } protocol Runcible { func runce() } let foo = FooError.A let error: Error = foo let subError: HairyError = foo let compo: HairyError & Runcible = foo // Error-conforming concrete or existential types can be coerced explicitly // to NSError. let ns1 = foo as NSError let ns2 = error as NSError let ns3 = subError as NSError var ns4 = compo as NSError // NSError conversion must be explicit. // TODO: fixit to insert 'as NSError' ns4 = compo // expected-error{{cannot assign value of type 'any HairyError & Runcible' to type 'NSError'}} let e1 = ns1 as? FooError let e1fix = ns1 as FooError // expected-error {{'NSError' is not convertible to 'FooError'}} // expected-note@-1{{did you mean to use 'as!' to force downcast?}} {{17-19=as!}} let esub = ns1 as Error let esub2 = ns1 as? Error // expected-warning{{conditional cast from 'NSError' to 'any Error' always succeeds}} // SR-1562 / rdar://problem/26370984 enum MyError : Error { case failed } func concrete1(myError: MyError) -> NSError { return myError as NSError } func concrete2(myError: MyError) -> NSError { return myError // expected-error{{cannot convert return expression of type 'MyError' to return type 'NSError'}} } func generic<T : Error>(error: T) -> NSError { return error as NSError } extension Error { var asNSError: NSError { return self as NSError } var asNSError2: NSError { return self // expected-error{{cannot convert return expression of type 'Self' to return type 'NSError'}} } } // rdar://problem/27543121 func throwErrorCode() throws { throw FictionalServerError.meltedDown // expected-error{{thrown error code type 'FictionalServerError.Code' does not conform to 'Error'; construct an 'FictionalServerError' instance}}{{29-29=(}}{{40-40=)}} } class MyErrorClass { } extension MyErrorClass: Error { } class MyClass { } func testUnknownErrorBridge(cond: Bool, mc: MyClass) -> NSObject? { if cond { return mc as? NSError // okay } return mc as? NSObject // okay } func testAlwaysErrorBridge(cond: Bool, mec: MyErrorClass) -> NSObject? { if cond { return mec as? NSError // expected-warning{{conditional cast from 'MyErrorClass}}' to 'NSError' always succeeds } return mec as? NSObject // expected-warning{{conditional cast from 'MyErrorClass}}' to 'NSObject' always succeeds }
apache-2.0
b188fc09f39b0a155c4809e831b4f839
25.85567
207
0.712092
3.648459
false
false
false
false
bigL055/Routable
Example/Pods/SPKit/Sources/UIView/SP+UIView.swift
1
3363
// // SPKit // // Copyright (c) 2017 linhay - https:// github.com/linhay // // 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 import UIKit public extension UIView{ /// 圆角 public var cornerRadius: CGFloat { get{ return self.layer.cornerRadius } set{ self.layer.cornerRadius = newValue self.layer.masksToBounds = true } } /// 边框宽度 public var borderWidth: CGFloat { get{ return self.layer.borderWidth } set{ self.layer.borderWidth = newValue } } /// 边框颜色 public var borderColor: UIColor { get{ guard let temp: CGColor = self.layer.borderColor else { return UIColor.clear } return UIColor(cgColor: temp) } set { self.layer.borderColor = newValue.cgColor } } /// 背景图片 public var cgImage: UIImage { get{ guard let temp: Any = self.layer.contents else { return UIImage() } return UIImage.init(cgImage: temp as! CGImage) } set { self.layer.contents = newValue.cgImage } } } public extension BLExtension where Base: UIView{ /// 返回目标View所在的控制器UIViewController public var viewController: UIViewController? { get{ var next:UIView? = base repeat{ if let vc = next?.next as? UIViewController{ return vc } next = next?.superview }while next != nil return nil } } /// 对当前View快照 public var snapshoot: UIImage{ get{ UIGraphicsBeginImageContextWithOptions(base.bounds.size, base.isOpaque, 0) base.layer.render(in: UIGraphicsGetCurrentContext()!) guard let snap = UIGraphicsGetImageFromCurrentImageContext() else { UIGraphicsEndImageContext() return UIImage() } UIGraphicsEndImageContext() return snap } } /// 移除View全部子控件 public func removeSubviews() { for _ in 0..<base.subviews.count { base.subviews.last?.removeFromSuperview() } } /// 设置LayerShadow,offset,radius public func setShadow(color: UIColor, offset: CGSize,radius: CGFloat) { base.layer.shadowColor = color.cgColor base.layer.shadowOffset = offset base.layer.shadowRadius = radius base.layer.shadowOpacity = 1 base.layer.shouldRasterize = true base.layer.rasterizationScale = UIScreen.main.scale } }
mit
7e6c3b1d6a2ec3a125d98e65de0a953e
28.348214
82
0.686949
4.34214
false
false
false
false
ShanghaiTimes/Swift-Radio-Pro
SwiftRadio/NowPlayingViewController.swift
1
19559
// // NowPlayingViewController.swift // Swift Radio // // Created by Matthew Fecher on 7/22/15. // Copyright (c) 2015 MatthewFecher.com. All rights reserved. // import UIKit import MediaPlayer //***************************************************************** // Protocol // Updates the StationsViewController when the track changes //***************************************************************** protocol NowPlayingViewControllerDelegate: class { func songMetaDataDidUpdate(track: Track) func artworkDidUpdate(track: Track) func trackPlayingToggled(track: Track) } //***************************************************************** // NowPlayingViewController //***************************************************************** class NowPlayingViewController: UIViewController { @IBOutlet weak var albumHeightConstraint: NSLayoutConstraint! @IBOutlet weak var albumImageView: SpringImageView! @IBOutlet weak var artistLabel: UILabel! @IBOutlet weak var pauseButton: UIButton! @IBOutlet weak var playButton: UIButton! @IBOutlet weak var songLabel: SpringLabel! @IBOutlet weak var stationDescLabel: UILabel! @IBOutlet weak var volumeParentView: UIView! @IBOutlet weak var slider = UISlider() var currentStation: RadioStation! var downloadTask: NSURLSessionDownloadTask? var iPhone4 = false var justBecameActive = false var newStation = true var nowPlayingImageView: UIImageView! let radioPlayer = Player.radio var track: Track! var mpVolumeSlider = UISlider() weak var delegate: NowPlayingViewControllerDelegate? //***************************************************************** // MARK: - ViewDidLoad //***************************************************************** override func viewDidLoad() { super.viewDidLoad() // Set AlbumArtwork Constraints optimizeForDeviceSize() // Set View Title self.title = currentStation.stationName // Create Now Playing BarItem createNowPlayingAnimation() // Setup MPMoviePlayerController // If you're building an app for a client, you may want to // replace the MediaPlayer player with a more robust // streaming library/SDK. Preferably one that supports interruptions, etc. // Most of the good streaming libaries are in Obj-C, however they // will work nicely with this Swift code. setupPlayer() // Notification for when app becomes active NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActiveNotificationReceived", name:"UIApplicationDidBecomeActiveNotification", object: nil) // Notification for MediaPlayer metadata updated NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("metadataUpdated:"), name:MPMoviePlayerTimedMetadataUpdatedNotification, object: nil); // Check for station change if newStation { track = Track() stationDidChange() } else { updateLabels() albumImageView.image = track.artworkImage if !track.isPlaying { pausePressed() } else { nowPlayingImageView.startAnimating() } } // Setup slider setupVolumeSlider() } func didBecomeActiveNotificationReceived() { // View became active updateLabels() justBecameActive = true updateAlbumArtwork() } deinit { // Be a good citizen NSNotificationCenter.defaultCenter().removeObserver(self, name:"UIApplicationDidBecomeActiveNotification", object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: MPMoviePlayerTimedMetadataUpdatedNotification, object: nil) } //***************************************************************** // MARK: - Setup //***************************************************************** func setupPlayer() { radioPlayer.view.frame = CGRect(x: 0, y: 0, width: 0, height: 0) radioPlayer.view.sizeToFit() radioPlayer.movieSourceType = MPMovieSourceType.Streaming radioPlayer.fullscreen = false radioPlayer.shouldAutoplay = true radioPlayer.prepareToPlay() radioPlayer.controlStyle = MPMovieControlStyle.None } func setupVolumeSlider() { // Note: This slider implementation uses a MPVolumeView // The volume slider only works in devices, not the simulator. volumeParentView.backgroundColor = UIColor.clearColor() let volumeView = MPVolumeView(frame: volumeParentView.bounds) for view in volumeView.subviews { let uiview: UIView = view as UIView if (uiview.description as NSString).rangeOfString("MPVolumeSlider").location != NSNotFound { mpVolumeSlider = (uiview as! UISlider) } } let thumbImageNormal = UIImage(named: "slider-ball") slider?.setThumbImage(thumbImageNormal, forState: .Normal) } func stationDidChange() { radioPlayer.stop() radioPlayer.contentURL = NSURL(string: currentStation.stationStreamURL) radioPlayer.prepareToPlay() radioPlayer.play() updateLabels("Loading Station...") // songLabel animate songLabel.animation = "flash" songLabel.repeatCount = 3 songLabel.animate() resetAlbumArtwork() track.isPlaying = true } //***************************************************************** // MARK: - Player Controls (Play/Pause/Volume) //***************************************************************** @IBAction func playPressed() { track.isPlaying = true playButtonEnable(false) radioPlayer.play() updateLabels() // songLabel Animation songLabel.animation = "flash" songLabel.animate() // Start NowPlaying Animation nowPlayingImageView.startAnimating() // Update StationsVC self.delegate?.trackPlayingToggled(self.track) } @IBAction func pausePressed() { track.isPlaying = false playButtonEnable() radioPlayer.pause() updateLabels("Station Paused...") nowPlayingImageView.stopAnimating() // Update StationsVC self.delegate?.trackPlayingToggled(self.track) } @IBAction func volumeChanged(sender:UISlider) { mpVolumeSlider.value = sender.value } //***************************************************************** // MARK: - UI Helper Methods //***************************************************************** func optimizeForDeviceSize() { // Adjust album size to fit iPhone 4s, 6s & 6s+ let deviceHeight = self.view.bounds.height if deviceHeight == 480 { iPhone4 = true albumHeightConstraint.constant = 186 view.updateConstraints() } else if deviceHeight == 667 { albumHeightConstraint.constant = 231 view.updateConstraints() } else if deviceHeight > 667 { albumHeightConstraint.constant = 234 view.updateConstraints() } } func updateLabels(statusMessage: String = "") { if statusMessage != "" { // There's a an interruption or pause in the audio queue songLabel.text = statusMessage artistLabel.text = currentStation.stationName } else { // Radio is (hopefully) streaming properly if track != nil { songLabel.text = track.title artistLabel.text = track.artist } } // Hide station description when album art is displayed or on iPhone 4 if track.artworkLoaded || iPhone4 { stationDescLabel.hidden = true } else { stationDescLabel.hidden = false stationDescLabel.text = currentStation.stationDesc } } func playButtonEnable(enabled: Bool = true) { if enabled { playButton.enabled = true pauseButton.enabled = false track.isPlaying = false } else { playButton.enabled = false pauseButton.enabled = true track.isPlaying = true } } func createNowPlayingAnimation() { // Setup ImageView nowPlayingImageView = UIImageView(image: UIImage(named: "NowPlayingBars-3")) nowPlayingImageView.autoresizingMask = UIViewAutoresizing.None nowPlayingImageView.contentMode = UIViewContentMode.Center // Create Animation nowPlayingImageView.animationImages = AnimationFrames.createFrames() nowPlayingImageView.animationDuration = 0.7 // Create Top BarButton let barButton = UIButton(type: UIButtonType.Custom) barButton.frame = CGRectMake(0, 0, 40, 40); barButton.addSubview(nowPlayingImageView) nowPlayingImageView.center = barButton.center let barItem = UIBarButtonItem(customView: barButton) self.navigationItem.rightBarButtonItem = barItem } func startNowPlayingAnimation() { nowPlayingImageView.startAnimating() } //***************************************************************** // MARK: - Album Art //***************************************************************** func resetAlbumArtwork() { track.artworkLoaded = false track.artworkURL = currentStation.stationImageURL updateAlbumArtwork() stationDescLabel.hidden = false } func updateAlbumArtwork() { track.artworkLoaded = false if track.artworkURL.rangeOfString("http") != nil { // Hide station description dispatch_async(dispatch_get_main_queue()) { //self.albumImageView.image = nil self.stationDescLabel.hidden = false } // Attempt to download album art from an API if let url = NSURL(string: track.artworkURL) { self.downloadTask = self.albumImageView.loadImageWithURL(url) { (image) in // Update track struct self.track.artworkImage = image self.track.artworkLoaded = true // Turn off network activity indicator UIApplication.sharedApplication().networkActivityIndicatorVisible = false // Animate artwork self.albumImageView.animation = "wobble" self.albumImageView.duration = 2 self.albumImageView.animate() self.stationDescLabel.hidden = true // Update lockscreen self.updateLockScreen() // Call delegate function that artwork updated self.delegate?.artworkDidUpdate(self.track) } } // Hide the station description to make room for album art if track.artworkLoaded && !self.justBecameActive { self.stationDescLabel.hidden = true self.justBecameActive = false } } else if track.artworkURL != "" { // Local artwork self.albumImageView.image = UIImage(named: track.artworkURL) track.artworkImage = albumImageView.image track.artworkLoaded = true // Call delegate function that artwork updated self.delegate?.artworkDidUpdate(self.track) } else { // No Station or API art found, use default art self.albumImageView.image = UIImage(named: "albumArt") track.artworkImage = albumImageView.image } // Force app to update display self.view.setNeedsDisplay() } // Call LastFM or iTunes API to get album art url func queryAlbumArt() { UIApplication.sharedApplication().networkActivityIndicatorVisible = true // Construct either LastFM or iTunes API call URL let queryURL: String if useLastFM { queryURL = String(format: "http://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key=%@&artist=%@&track=%@&format=json", apiKey, track.artist, track.title) } else { queryURL = String(format: "https://itunes.apple.com/search?term=%@+%@&entity=song", track.artist, track.title) } let escapedURL = queryURL.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) // Query API DataManager.getTrackDataWithSuccess(escapedURL!) { (data) in if DEBUG_LOG { print("API SUCCESSFUL RETURN") print("url: \(escapedURL!)") } let json = JSON(data: data) if useLastFM { // Get Largest Sized LastFM Image if let imageArray = json["track"]["album"]["image"].array { let arrayCount = imageArray.count let lastImage = imageArray[arrayCount - 1] if let artURL = lastImage["#text"].string { // Check for Default Last FM Image if artURL.rangeOfString("/noimage/") != nil { self.resetAlbumArtwork() } else { // LastFM image found! self.track.artworkURL = artURL self.track.artworkLoaded = true self.updateAlbumArtwork() } } else { self.resetAlbumArtwork() } } else { self.resetAlbumArtwork() } } else { // Use iTunes API. Images are 100px by 100px if let artURL = json["results"][0]["artworkUrl100"].string { if DEBUG_LOG { print("iTunes artURL: \(artURL)") } self.track.artworkURL = artURL self.track.artworkLoaded = true self.updateAlbumArtwork() } else { self.resetAlbumArtwork() } } } } //***************************************************************** // MARK: - Segue //***************************************************************** override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "InfoDetail" { let infoController = segue.destinationViewController as! InfoDetailViewController infoController.currentStation = currentStation } } @IBAction func infoButtonPressed(sender: UIButton) { performSegueWithIdentifier("InfoDetail", sender: self) } //***************************************************************** // MARK: - MPNowPlayingInfoCenter (Lock screen) //***************************************************************** func updateLockScreen() { // Update notification/lock screen let albumArtwork = MPMediaItemArtwork(image: track.artworkImage!) MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = [ MPMediaItemPropertyArtist: track.artist, MPMediaItemPropertyTitle: track.title, MPMediaItemPropertyArtwork: albumArtwork ] } override func remoteControlReceivedWithEvent(receivedEvent: UIEvent?) { super.remoteControlReceivedWithEvent(receivedEvent) if receivedEvent!.type == UIEventType.RemoteControl { switch receivedEvent!.subtype { case .RemoteControlPlay: playPressed() case .RemoteControlPause: pausePressed() default: break } } } //***************************************************************** // MARK: - MetaData Updated Notification //***************************************************************** func metadataUpdated(n: NSNotification) { if(radioPlayer.timedMetadata != nil && radioPlayer.timedMetadata.count > 0) { startNowPlayingAnimation() let firstMeta: MPTimedMetadata = radioPlayer.timedMetadata.first as! MPTimedMetadata let metaData = firstMeta.value as! String var stringParts = [String]() if metaData.rangeOfString(" - ") != nil { stringParts = metaData.componentsSeparatedByString(" - ") } else { stringParts = metaData.componentsSeparatedByString("-") } // Set artist & songvariables let currentSongName = track.title track.artist = stringParts[0] track.title = stringParts[0] if stringParts.count > 1 { track.title = stringParts[1] } if track.artist == "" && track.title == "" { track.artist = currentStation.stationDesc track.title = currentStation.stationName } dispatch_async(dispatch_get_main_queue()) { if currentSongName != self.track.title { if DEBUG_LOG { print("METADATA artist: \(self.track.artist) | title: \(self.track.title)") } // Update Labels self.artistLabel.text = self.track.artist self.songLabel.text = self.track.title // songLabel animation self.songLabel.animation = "zoomIn" self.songLabel.duration = 1.5 self.songLabel.damping = 1 self.songLabel.animate() // Update Stations Screen self.delegate?.songMetaDataDidUpdate(self.track) // Query API for album art self.resetAlbumArtwork() self.queryAlbumArt() self.updateLockScreen() } } } } }
mit
6d8b7a012b3c5d883bbc3f37eeebabf9
34.626594
172
0.515466
6.166141
false
false
false
false
memexapp/memex-swift-sdk
Sources/EncodedJSONTransform.swift
1
822
import Foundation import ObjectMapper class EncodedJSONTransform: TransformType { typealias Object = [String: Any] typealias JSON = String init() {} func transformFromJSON(_ value: Any?) -> [String: Any]? { if let string = value as? String { do { let data = string.data(using: String.Encoding.utf8)! let object = try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any] return object } catch { return nil } } return nil } func transformToJSON(_ value: [String: Any]?) -> String? { if let value = value { let data = try! JSONSerialization.data(withJSONObject: value, options: []) let string = String(data: data, encoding: String.Encoding.utf8) return string } return nil } }
mit
c02c714724573c22947a829507e60e75
22.485714
96
0.613139
4.259067
false
false
false
false
seuzl/iHerald
Herald/EmptyRoomViewController.swift
1
8367
// // EmptyRoomViewController.swift // 先声 // // Created by Wangshuo on 14-8-13. // Copyright (c) 2014年 WangShuo. All rights reserved. // import UIKit class EmptyRoomViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource,UITableViewDelegate,UITableViewDataSource,APIGetter { @IBOutlet var pickerView: UIPickerView! @IBOutlet var tableView: UITableView! let schools = ["九龙湖","四牌楼","丁家桥"] let weeks = ["第一周","第二周","第三周","第四周","第五周","第六周","第七周","第八周","第九周","第十周","第十一周","第十二周","第十三周","第十四周","第十五周","第十六周","第十七周","第十八周","第十九周","第二十周"] let days = ["周一","周二","周三","周四","周五","周六","周日"] let fromLessons = ["1","2","3","4","5","6","7","8","9","10","11","12","13"] let toLessons = ["1","2","3","4","5","6","7","8","9","10","11","12","13"] var selectedSchool:String = "jlh" var selectedWeek:String = "1" var selectedDay:String = "1" var selectedFrom:String = "1" var selectedTo:String = "1" var emptyRooms : NSArray = [] var API = HeraldAPI() override func viewDidLoad() { super.viewDidLoad() self.API.delegate = self // Do any additional setup after loading the view. self.navigationItem.title = "空闲教室查询" Tool.initNavigationAPI(self) let searchButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: Selector("searchRoom")) self.navigationItem.rightBarButtonItem = searchButton self.view.backgroundColor = UIColor(red: 180/255, green: 230/255, blue: 230/255, alpha: 1) self.tableView.backgroundColor = UIColor(red: 180/255, green: 230/255, blue: 230/255, alpha: 1) } override func viewWillDisappear(animated: Bool) { Tool.dismissHUD() API.cancelAllRequest() } func searchRoom() { Config.sharedInstance.isNetworkRunning = CheckNetwork.doesExistenceNetwork() if !Config.sharedInstance.isNetworkRunning { Tool.showErrorHUD("请检查网络连接") } else if Int(self.selectedFrom) >= Int(self.selectedTo) { Tool.showErrorHUD("开始节数必须大于结束节数") } else { Tool.showProgressHUD("正在获取教室数据") API.sendAPI("emptyRoom",APIParameter:self.selectedSchool,self.selectedWeek,self.selectedDay,self.selectedFrom,self.selectedTo) } } func getResult(APIName: String, results: JSON) { Tool.showSuccessHUD("获取数据成功") self.emptyRooms = results.arrayObject ?? [] self.tableView.reloadDataAnimateWithWave(WaveAnimation.RightToLeftWaveAnimation) } func getError(APIName: String, statusCode: Int) { Tool.showErrorHUD("获取数据失败") } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 5 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch component { case 0: return self.schools.count case 1: return self.weeks.count case 2: return self.days.count case 3: return self.fromLessons.count case 4: return self.toLessons.count default: return 0 } } func pickerView(pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { switch component { case 0: return 80 case 1: return 100 case 2: return 50 case 3: return 35 case 4: return 35 default: return 0 } } func pickerView(pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusingView view: UIView?) -> UIView { var myView:UILabel? switch component { case 0: myView = UILabel(frame: CGRectMake(0, 0, 70, 30)) myView?.textAlignment = NSTextAlignment.Center myView?.text = self.schools[row] myView?.font = UIFont.systemFontOfSize(20) myView?.backgroundColor = UIColor.clearColor() return myView! case 1: myView = UILabel(frame: CGRectMake(0, 0, 90, 30)) myView?.textAlignment = NSTextAlignment.Center myView?.text = self.weeks[row] myView?.font = UIFont.systemFontOfSize(20) myView?.backgroundColor = UIColor.clearColor() return myView! case 2: myView = UILabel(frame: CGRectMake(0, 0, 80, 30)) myView?.textAlignment = NSTextAlignment.Center myView?.text = self.days[row] myView?.font = UIFont.systemFontOfSize(20) myView?.backgroundColor = UIColor.clearColor() return myView! case 3: myView = UILabel(frame: CGRectMake(0, 0, 80, 30)) myView?.textAlignment = NSTextAlignment.Center myView?.text = self.fromLessons[row] myView?.font = UIFont.systemFontOfSize(20) myView?.backgroundColor = UIColor.clearColor() return myView! case 4: myView = UILabel(frame: CGRectMake(0, 0, 70, 30)) myView?.textAlignment = NSTextAlignment.Center myView?.text = self.toLessons[row] myView?.font = UIFont.systemFontOfSize(20) myView?.backgroundColor = UIColor.clearColor() return myView! default: return myView! } } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch component { case 0: if 0 == row { self.selectedSchool = "jlh" } if 1 == row { self.selectedSchool = "spl" } if 2 == row { self.selectedSchool = "djq" } case 1: return self.selectedWeek = NSString(format: "%ld", row + 1) as String case 2: return self.selectedDay = NSString(format: "%ld", row + 1) as String case 3: return self.selectedFrom = NSString(format: "%ld", row + 1) as String case 4: return self.selectedTo = NSString(format: "%ld", row + 1) as String default: break } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.emptyRooms.count / 2 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 85 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellIdentifier:String = "EmptyRoomTableViewCell" var cell: EmptyRoomTableViewCell? = self.tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? EmptyRoomTableViewCell if nil == cell { let nibArray:NSArray = NSBundle.mainBundle().loadNibNamed("EmptyRoomTableViewCell", owner: self, options: nil) cell = nibArray.objectAtIndex(0) as? EmptyRoomTableViewCell } cell?.backgroundColor = UIColor(red: 180/255, green: 230/255, blue: 230/255, alpha: 1) let row = indexPath.row if 0 == row { cell!.leftRoom.text = self.emptyRooms[0] as? String cell!.rightRoom.text = self.emptyRooms[1] as? String } else { cell!.leftRoom.text = self.emptyRooms[row * 2] as? String cell!.rightRoom.text = self.emptyRooms[row * 2 + 1] as? String } return cell! } }
mit
695e53ab7822d5922d37001a22a5921a
30.956522
147
0.569326
4.565217
false
false
false
false
daniel-barros/Comedores-UGR
Comedores UGR Watch Extension/MenuManager.swift
1
3678
// // MenuManager.swift // Comedores UGR // // Created by Daniel Barros López on 4/3/16. /* MIT License Copyright (c) 2016 Daniel Barros Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // import Foundation import WatchConnectivity private let DefaultsWeekMenuKey = "DefaultsWeekMenuKey" private let DefaultsLastDataUpdateKey = "DefaultsLastDataUpdateKey" class MenuManager: NSObject, WCSessionDelegate { fileprivate var session = WCSession.default() fileprivate var handler: (([DayMenu]?) -> ())? var savedMenu: [DayMenu]? { return UserDefaults.standard.menu(forKey: DefaultsWeekMenuKey) } func updateMenu(responseHandler handler: @escaping ([DayMenu]?) -> ()) { session.delegate = self session.activate() self.handler = handler } /// `true` if savedMenu is nil or corrupt, or if it's next Sunday or later. var needsToUpdateMenu: Bool { guard let menu = savedMenu, let firstDate = menu.first?.processedDate else { return true } return Calendar.current.differenceInDays(from: firstDate, to: Date()) > 5 } var hasUpdatedDataToday: Bool { if let date = UserDefaults.standard.object(forKey: DefaultsLastDataUpdateKey) as? Date, Calendar.current.isDateInToday(date) { return true } return false } // MARK: WCSessionDelegate func session(_ session: WCSession, didReceiveMessageData messageData: Data) { if let menu = NSKeyedUnarchiver.unarchiveMenu(with: messageData) { let defaults = UserDefaults.standard defaults.setMenu(menu, forKey: DefaultsWeekMenuKey) defaults.set(Date(), forKey: DefaultsLastDataUpdateKey) handler?(menu) } else { handler?(nil) print("Error: Bad data.") } handler = nil } func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { if activationState == .activated { session.sendMessage([:], replyHandler: nil, errorHandler: nil) } else { handler?(nil) handler = nil } } } extension MenuManager { /// Returns a filtered array containing only menus corresponding to today and beyond. var relevantSavedMenu: [DayMenu] { guard let weekMenu = savedMenu else { return [] } return weekMenu.flatMap { menu -> DayMenu? in if let date = menu.processedDate, date.isTodayOrFuture { return menu } return nil } } }
mit
4dc58823d271ab5407eec43cf7a5af06
31.539823
134
0.670383
4.775325
false
false
false
false
devpunk/punknote
punknote/View/Share/VShareCellGif.swift
1
2606
import UIKit class VShareCellGif:VShareCell { private let kShareWidth:CGFloat = 75 private let kShareInsets:CGFloat = 6 private let kTitleWidth:CGFloat = 300 override init(frame:CGRect) { super.init(frame:frame) let buttonShare:UIButton = UIButton() buttonShare.translatesAutoresizingMaskIntoConstraints = false buttonShare.clipsToBounds = true buttonShare.setImage( #imageLiteral(resourceName: "assetGenericShareColor").withRenderingMode(UIImageRenderingMode.alwaysOriginal), for:UIControlState.normal) buttonShare.setImage( #imageLiteral(resourceName: "assetGenericShareColor").withRenderingMode(UIImageRenderingMode.alwaysTemplate), for:UIControlState.highlighted) buttonShare.imageView!.clipsToBounds = true buttonShare.imageView!.contentMode = UIViewContentMode.center buttonShare.imageView!.tintColor = UIColor.punkOrange buttonShare.imageEdgeInsets = UIEdgeInsets( top:0, left:0, bottom:kShareInsets, right:0) buttonShare.addTarget( self, action:#selector(actionShare(sender:)), for:UIControlEvents.touchUpInside) let labelTitle:UILabel = UILabel() labelTitle.isUserInteractionEnabled = false labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.backgroundColor = UIColor.clear labelTitle.text = NSLocalizedString("VShareCellGif_labelTitle", comment:"") labelTitle.textColor = UIColor.black labelTitle.font = UIFont.regular(size:15) labelTitle.textAlignment = NSTextAlignment.right addSubview(labelTitle) addSubview(buttonShare) NSLayoutConstraint.equalsVertical( view:buttonShare, toView:self) NSLayoutConstraint.rightToRight( view:buttonShare, toView:self) NSLayoutConstraint.width( view:buttonShare, constant:kShareWidth) NSLayoutConstraint.equalsVertical( view:labelTitle, toView:self) NSLayoutConstraint.rightToLeft( view:labelTitle, toView:buttonShare) NSLayoutConstraint.width( view:labelTitle, constant:kTitleWidth) } required init?(coder:NSCoder) { return nil } //MARK: actions func actionShare(sender button:UIButton) { controller?.shareGif() } }
mit
a79be37a8d71d2dbc8fc54d954f865fc
31.987342
121
0.640829
5.652928
false
false
false
false
khizkhiz/swift
test/SILGen/toplevel.swift
2
3239
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s | FileCheck %s func markUsed<T>(t: T) {} @noreturn func trap() { fatalError() } // CHECK-LABEL: sil @main // CHECK: bb0({{%.*}} : $Int32, {{%.*}} : $UnsafeMutablePointer<UnsafeMutablePointer<Int8>>): // -- initialize x // CHECK: alloc_global @_Tv8toplevel1xSi // CHECK: [[X:%[0-9]+]] = global_addr @_Tv8toplevel1xSi : $*Int // CHECK: integer_literal $Builtin.Int2048, 999 // CHECK: store {{.*}} to [[X]] var x = 999 func print_x() { markUsed(x) } // -- assign x // CHECK: integer_literal $Builtin.Int2048, 0 // CHECK: assign {{.*}} to [[X]] // CHECK: [[PRINT_X:%[0-9]+]] = function_ref @_TF8toplevel7print_xFT_T_ : // CHECK: apply [[PRINT_X]] x = 0 print_x() // <rdar://problem/19770775> Deferred initialization of let bindings rejected at top level in playground // CHECK: alloc_global @_Tv8toplevel5countSi // CHECK: [[COUNTADDR:%[0-9]+]] = global_addr @_Tv8toplevel5countSi : $*Int // CHECK-NEXT: [[COUNTMUI:%[0-9]+]] = mark_uninitialized [var] [[COUNTADDR]] : $*Int let count: Int // CHECK: cond_br if x == 5 { count = 0 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE:bb[0-9]+]] } else { count = 10 // CHECK: assign {{.*}} to [[COUNTMUI]] // CHECK: br [[MERGE]] } // CHECK: [[MERGE]]: // CHECK: load [[COUNTMUI]] markUsed(count) var y : Int func print_y() { markUsed(y) } // -- assign y // CHECK: alloc_global @_Tv8toplevel1ySi // CHECK: [[Y1:%[0-9]+]] = global_addr @_Tv8toplevel1ySi : $*Int // CHECK: [[Y:%[0-9]+]] = mark_uninitialized [var] [[Y1]] // CHECK: assign {{.*}} to [[Y]] // CHECK: [[PRINT_Y:%[0-9]+]] = function_ref @_TF8toplevel7print_yFT_T_ y = 1 print_y() // -- treat 'guard' vars as locals // CHECK-LABEL: function_ref toplevel.A.__allocating_init // CHECK: switch_enum {{%.+}} : $Optional<A>, case #Optional.some!enumelt.1: [[SOME_CASE:.+]], default // CHECK: [[SOME_CASE]]([[VALUE:%.+]] : $A): // CHECK: store [[VALUE]] to [[BOX:%.+]] : $*A // CHECK-NOT: release // CHECK: [[SINK:%.+]] = function_ref @_TF8toplevel8markUsedurFxT_ // CHECK-NOT: release // CHECK: apply [[SINK]]<A>({{%.+}}) class A {} guard var a = Optional(A()) else { trap() } markUsed(a) // CHECK: alloc_global @_Tv8toplevel21NotInitializedIntegerSi // CHECK-NEXT: [[VARADDR:%[0-9]+]] = global_addr @_Tv8toplevel21NotInitializedIntegerSi // CHECK-NEXT: [[VARMUI:%[0-9]+]] = mark_uninitialized [var] [[VARADDR]] : $*Int // CHECK-NEXT: mark_function_escape [[VARMUI]] : $*Int // <rdar://problem/21753262> Bug in DI when it comes to initialization of global "let" variables let NotInitializedInteger : Int func fooUsesUninitializedValue() { _ = NotInitializedInteger } fooUsesUninitializedValue() NotInitializedInteger = 10 fooUsesUninitializedValue() // CHECK: [[RET:%[0-9]+]] = struct $Int32 // CHECK: return [[RET]] // CHECK-LABEL: sil hidden @_TF8toplevel7print_xFT_T_ // CHECK-LABEL: sil hidden @_TF8toplevel7print_yFT_T_ // CHECK: sil hidden @_TF8toplevel13testGlobalCSEFT_Si // CHECK-NOT: global_addr // CHECK: %0 = global_addr @_Tv8toplevel1xSi : $*Int // CHECK-NOT: global_addr // CHECK: return func testGlobalCSE() -> Int { // We should only emit one global_addr in this function. return x + x }
apache-2.0
6802e6c5ee14668f58cef767c95ff840
25.120968
104
0.635073
3.096558
false
false
false
false
stormpath/stormpath-swift-example
Pods/Stormpath/Stormpath/Networking/RegistrationForm.swift
1
2100
// // RegistrationAPIRequestManager.swift // Stormpath // // Created by Edward Jiang on 2/5/16. // Copyright © 2016 Stormpath. All rights reserved. // import Foundation /** Model for the account registration form. The fields requested in the initializer are required. */ @objc(SPHRegistrationForm) public class RegistrationForm: NSObject { /** Given (first) name of the user. Required by default, but can be turned off in the Framework configuration. */ public var givenName = "" /** Sur (last) name of the user. Required by default, but can be turned off in the Framework configuration. */ public var surname = "" /// Email address of the user. Only validated server-side at the moment. public var email: String /// Password for the user. Only validated server-side at the moment. public var password: String /** Username. Optional, but if not set retains the value of the email address. */ public var username = "" /** Custom fields may be configured in the server-side API. Include them in this */ public var customFields = [String: String]() /** Initializer for Registration Model. After initialization, all fields can be modified. - parameters: - givenName: Given (first) name of the user. - surname: Sur (last) name of the user. - email: Email address of the user. - password: Password for the user. */ public init(email: String, password: String) { self.email = email self.password = password } var asDictionary: [String: Any] { var registrationDictionary: [String: Any] = customFields let accountDictionary = ["username": username, "email": email, "password": password, "givenName": givenName, "surname": surname] for (key, value) in accountDictionary { if value != "" { registrationDictionary[key] = value } } return registrationDictionary } }
mit
2c45820960bb30a361a2afb226a2f64e
27.364865
136
0.620295
4.695749
false
false
false
false
shuuchen/SwiftTips
methods.swift
1
3094
// methods // functions associated with a type // class/structure/enumeration can define instance/type methods // instance methods // exact the same syntax as functions class Counter { var count = 0 func increment() { ++count } func incrementBy(amount: Int) { count += amount } func reset() { count = 0 } } let counter = Counter() counter.increment() counter.incrementBy(5) counter.reset() // modifying value types from within instance methods // by default, value types cannot be modified by instance methods // use "mutating" keyword // not for "let" value types struct Point { var x = 0.0, y = 0.0 mutating func moveByX(deltaX: Double, y deltaY: Double) { x += deltaX y += deltaY } } var somePoint = Point(x: 1.0, y: 1.0) somePoint.moveByX(2.0, y: 3.0) print("The point is now at (\(somePoint.x), \(somePoint.y))") // assigning to self struct Point2 { var x = 0.0, y = 0.0 mutating func moveByX(deltaX: Double, y deltaY: Double) { self = Point2(x: x + deltaX, y: y + deltaY) // assign an entirely new instance to self } } // "mutating" methods in enumeration // modify self to a new case enum TriStateSwitch { case Off, Low, High mutating func next() { switch self { case Off: self = Low case Low: self = High case High: self = Off } } } var ovenLight = TriStateSwitch.Low ovenLight.next() ovenLight.next() // type methods // using "static" keyword // using "class" keyword to allow subclasses to override // in which "self" refers to type, not instance class SomeClass { class func someTypeMethod() { println("class func") } } SomeClass.someTypeMethod() struct LevelTracker { static var highestUnlockedLevel = 1 static func unlockLevel(level: Int) { if level > highestUnlockedLevel { highestUnlockedLevel = level } } static func levelIsUnlocked(level: Int) -> Bool { return level <= highestUnlockedLevel } var currentLevel = 1 mutating func advanceToLevel(level: Int) -> Bool { if LevelTracker.levelIsUnlocked(level) { currentLevel = level return true } else { return false } } } class Player { var tracker = LevelTracker() let playerName: String func completedLevel(level: Int) { LevelTracker.unlockLevel(level + 1) tracker.advanceToLevel(level + 1) } init(name: String) { playerName = name } } var player = Player(name: "Argyrios") player.completedLevel(1) print("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)") player = Player(name: "Beto") if player.tracker.advanceToLevel(6) { print("player is now on level 6") } else { print("level 6 has not yet been unlocked") }
mit
a360998eaaf1fa245a6cff591727abc8
17.526946
94
0.586942
4.141901
false
false
false
false
SteveMarshall/photos-metadata-fixer
Sources/PhotosMetadataFixerFramework/FlickrPhoto.swift
1
2035
import Foundation public struct FlickrPhoto { public let id: String public let title: String public let location: (latitude: Double, longitude: Double)? public let tags: [String]? public let dateTaken: Date? static let dateFormatter: DateFormatter = { $0.locale = Locale(identifier: "en_US_POSIX") $0.dateFormat = "yyyy-MM-dd HH:mm:ss" return $0 }(DateFormatter()) init?(json: [String: Any]) { guard let id = json["id"] as? String, let title = ( (json["title"] as? [String: String])?["_content"] ?? json["title"] as? String ) else { return nil } self.id = id self.title = title let locationElement: [String: Any] if let locationTree = json["location"] as? [String: Any] { locationElement = locationTree } else { locationElement = json } if let latitudeElement = locationElement["latitude"] as? String, let latitude = Double(latitudeElement), let longitudeElement = locationElement["longitude"] as? String, let longitude = Double(longitudeElement) { self.location = (latitude, longitude) } else { self.location = nil } let dateTakenElement: String? if let dateElement = json["dates"] as? [String: Any] { dateTakenElement = dateElement["taken"] as? String } else { dateTakenElement = json["datetaken"] as? String } if let dateTakenElement = dateTakenElement, let dateTaken = FlickrPhoto.dateFormatter.date( from: dateTakenElement ) { self.dateTaken = dateTaken } else { self.dateTaken = nil } if let tags = (json["tags"] as? [String: [[String: Any]]])?["tag"] { self.tags = tags.flatMap { $0["raw"] as? String } } else { self.tags = nil } } }
mit
70944a65a5c3dcf34c0bddba75be53c7
30.307692
76
0.542015
4.404762
false
false
false
false
wanliming11/MurlocAlgorithms
Last/编程之法/1.1 字符串的旋转.playground/Contents.swift
1
3837
//: Playground - noun: a place where people can play import UIKit /* 1. "abcdef" ==> "defabc" Thinking: Move f to head ==> f abcde ... ef abcd ... def abc 时间复杂度: 由于每次都要移动 n-1 次,而总共移动的次数是拿到前面的数目 m, 复杂度 O(nm) 空间复杂度: 需要一个字符数组来做交换,所以空间复杂度 O(n) Thinking: 先翻转部分,再反转整体,或者先反转整体,再反转部分 reverse ==> cba fed ==> def abc 或者先整体翻转,再局部翻转,从思想上感觉先整体后局部更合适,因为我先改变两部分的位置, 然后负负得正,就完成了整体的交换。 时间复杂度: 交换一次是 O(n) 时间复杂度,整体相当于交换了两次,所以整体的时间复杂度是 O(n) 空间复杂度: 需要一个中间的数组,来做整体的交换 O(n) 当然如果变成整体的 C 语言的方式,则不需要中的数组,空间复杂度为O(1) 2. "I am a student." ==> "student. a am I" Thinking: 整体位置逆序,每个单词保持原样。 先整体翻转,然后从非空格位置到有空格的位置,执行一次反转。 空间复杂度: 依然用了一个中间数组,空间复杂度 O(n) 。 时间复杂度:由于整体反转,时间复杂度O(n), 查找出空格,O(n), 由于并不是每次都再去循环, 整体的时间复杂度 O(n)。 */ //1. 暴力解法 func violenceReverseString(_ s: String, n: Int) -> String { var sArray: [Character] = [Character](s.characters) guard sArray.count > 0 else { return "" } //把头一位移动到最后 func moveStr(_ sArray: inout [Character]) { if let c = sArray.first { for i in 1..<sArray.count { sArray[i - 1] = sArray[i] } sArray[sArray.count - 1] = c } } for _ in 0..<n { moveStr(&sArray) print(sArray) } return String(sArray) } //violenceReverseString("abcdef", n: 3) //1. 反转方法 func reverseString(_ s: String, n: Int) -> String { var sArray: [Character] = [Character](s.characters) guard sArray.count > 0 else { return "" } func reverse(_ sArray: inout [Character], from: Int, to: Int) { var left = from var right = to while left < right { let c = sArray[left] sArray[left] = sArray[right] sArray[right] = c left += 1 right -= 1 } } reverse(&sArray, from: 0, to: sArray.count - 1) //下面两个区间合并成为一个整体区间 reverse(&sArray, from: 0, to: n-1) reverse(&sArray, from: n, to: sArray.count - 1) return String(sArray) } //reverseString("abcdef", n: 3) //2. 反转方法 func reverseWords(_ s: String) -> String { var sArray: [Character] = [Character](s.characters) guard sArray.count > 0 else { return s } func reverse(_ a: inout [Character], from: Int, to: Int) { var left = from var right = to while left < right { let c = a[left] a[left] = a[right] a[right] = c left += 1 right -= 1 } } reverse(&sArray, from: 0, to: sArray.count - 1) var from = 0 var to = 0 for i in 0..<sArray.count { if sArray[i] != " ", from == 0 { from = i } else if sArray[i] == " " { to = i - 1 reverse(&sArray, from: from, to: to) from = 0 to = 0 } } if (from > 0) { reverse(&sArray, from: from, to: sArray.count - 1) } return String(sArray) } reverseWords(" I am a student. ")
mit
084a2005e52e2f341a3ce5a35a76dca0
21.40146
67
0.523949
2.934034
false
false
false
false
acort3255/Emby.ApiClient.Swift
Emby.ApiClient/model/dto/BaseItemPerson.swift
1
726
// // BaseItemPersonDto.swift // Emby.ApiClient // import Foundation public class BaseItemPerson: Codable { public let name: String public var id: String? public let role: String? public let type: String public var primaryImageTag: String? public var hasPrimaryImage: Bool { get { return primaryImageTag != nil } } init (name: String, role: String, type: String) { self.name = name self.role = role self.type = type } enum CodingKeys: String, CodingKey { case name = "Name" case id = "Id" case role = "Role" case type = "Type" case primaryImageTag = "PrimaryImageTag" } }
mit
3501c4abade831013d9fcffb62041439
20.352941
53
0.577135
4.033333
false
false
false
false
apple/swift-algorithms
Tests/SwiftAlgorithmsTests/FirstNonNilTests.swift
1
837
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Algorithms 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 // //===----------------------------------------------------------------------===// import XCTest import Algorithms final class FirstNonNilTests: XCTestCase { func testFirstNonNil() { XCTAssertNil([].firstNonNil { $0 }) XCTAssertNil(["A", "B", "C"].firstNonNil { Int($0) }) XCTAssertNil(["A", "B", "C"].firstNonNil { _ in nil }) XCTAssertEqual(["A", "B", "10"].firstNonNil { Int($0) }, 10) XCTAssertEqual(["20", "B", "10"].firstNonNil { Int($0) }, 20) } }
apache-2.0
f2e71371577b8facd7ee8f0830a43697
35.391304
80
0.532855
4.5
false
true
false
false
carlynorama/learningSwift
Playgrounds/blinky_inky_pinky_and_clyde.playground/Contents.swift
1
1630
// Created by carlynorama on 2016-08-22 // License CC0 - No rights reserved. // Modified from https://www.udemy.com/complete-ios-10-developer-course/learn/v4/t/lecture/5449162 import UIKit class Ghost { var isAlive = true var strength:Int = 9 var color = "grey" init() {} init(color: String, strength: Int) { self.color = color self.strength = strength } func kill() { isAlive = false } func isStrong() -> Bool { if strength > 10 { return true } else { return false } } } //This doesn't work... not even a little bit let ghostNames = ["blinky", "inky", "pinky", "clyde"] let ghostColors = ["red", "blue", "pink", "orange"] let ghostStrengths = [7, 8, 9, 10] var ghostCollection = [Ghost]() for (index, ghostname) in ghostNames.enumerated() { var newGhost = Ghost(color: ghostColors[index], strength: ghostStrengths[index]) // <-superbad trying to use a string as a variable name like this // newGhost.color = ghostColors[index] //if don't make custom init // newGhost.strength = ghostStrengths[index] //if don't make custom init ghostCollection.append(newGhost) } var blinky = ghostCollection[0] var inky = ghostCollection[1] var pinky = ghostCollection[2] var clyde = ghostCollection[3] var ghostInTheMachine = Ghost() print(blinky.isAlive) ghostCollection[0].kill() print(blinky.isAlive) print (inky.isStrong()) inky.strength = 20 print(inky.strength) print(inky.isStrong()) clyde.kill() print(clyde.isAlive) print(ghostInTheMachine.color)
unlicense
2fccd09e151b15c069ef3e42cfebcf8a
21.328767
151
0.646012
3.410042
false
false
false
false
louisdh/panelkit
PanelKitTests/MainTests.swift
1
10462
// // MainTests.swift // PanelKitTests // // Created by Louis D'hauwe on 16/11/2017. // Copyright © 2017 Silver Fox. All rights reserved. // import XCTest import UIKit @testable import PanelKit class MainTests: XCTestCase { var viewController: ViewController! var navigationController: UINavigationController! override func setUp() { super.setUp() viewController = ViewController() navigationController = UINavigationController(rootViewController: viewController) navigationController.view.frame = CGRect(origin: .zero, size: CGSize(width: 1024, height: 768)) let window = UIWindow(frame: UIScreen.main.bounds) window.rootViewController = navigationController window.makeKeyAndVisible() XCTAssertNotNil(navigationController.view) XCTAssertNotNil(viewController.view) if UIDevice.current.userInterfaceIdiom == .phone { continueAfterFailure = false XCTFail("Test does not work on an iPhone") } } override func tearDown() { super.tearDown() // Put teardown code here. This method is called after the invocation of each test method in the class. } func testFloating() { let mapPanel = viewController.mapPanelVC! XCTAssert(!mapPanel.isFloating) XCTAssert(!mapPanel.isPinned) XCTAssert(!mapPanel.isPresentedModally) XCTAssert(!mapPanel.isPresentedAsPopover) let exp = self.expectation(description: "floating") viewController.showMapPanelFromBarButton { XCTAssert(mapPanel.isPresentedAsPopover) self.viewController.toggleFloatStatus(for: mapPanel, completion: { XCTAssert(mapPanel.isFloating) self.viewController.toggleFloatStatus(for: mapPanel, completion: { XCTAssert(!mapPanel.isFloating) exp.fulfill() }) }) } waitForExpectations(timeout: 10.0) { (error) in if let error = error { XCTFail(error.localizedDescription) } } } func testExpose() { let mapPanel = viewController.mapPanelVC! let textPanel = viewController.textPanelVC! let exp = self.expectation(description: "expose") viewController.showMapPanelFromBarButton { XCTAssert(mapPanel.isPresentedAsPopover) self.viewController.toggleFloatStatus(for: mapPanel, completion: { self.viewController.showTextPanelFromBarButton { self.viewController.toggleFloatStatus(for: textPanel, completion: { XCTAssert(mapPanel.isFloating) XCTAssert(textPanel.isFloating) self.viewController.enterExpose() XCTAssert(mapPanel.isInExpose) XCTAssert(textPanel.isInExpose) self.viewController.exitExpose() XCTAssert(!mapPanel.isInExpose) XCTAssert(!textPanel.isInExpose) exp.fulfill() }) } }) } waitForExpectations(timeout: 10.0) { (error) in if let error = error { XCTFail(error.localizedDescription) } } } func testPinnedFloating() { let mapPanel = viewController.mapPanelVC! let textPanel = viewController.textPanelVC! let exp = self.expectation(description: "pinnedFloating") viewController.showMapPanelFromBarButton { self.viewController.toggleFloatStatus(for: mapPanel, completion: { self.viewController.showTextPanelFromBarButton { self.viewController.toggleFloatStatus(for: textPanel, completion: { self.viewController.didEndDrag(mapPanel, toEdgeOf: .right) XCTAssert(mapPanel.isPinned) XCTAssert(self.viewController.panelPinnedRight == mapPanel) self.viewController.didDragFree(mapPanel, from: mapPanel.view.frame.origin) XCTAssert(!mapPanel.isPinned) XCTAssert(self.viewController.panelPinnedRight == nil) exp.fulfill() }) } }) } waitForExpectations(timeout: 10.0) { (error) in if let error = error { XCTFail(error.localizedDescription) } } } func testPinned() { let mapPanel = viewController.mapPanelVC! let exp = self.expectation(description: "pinned") viewController.showMapPanelFromBarButton { XCTAssert(mapPanel.isPresentedAsPopover) self.viewController.toggleFloatStatus(for: mapPanel, completion: { self.viewController.didEndDrag(mapPanel, toEdgeOf: .right) XCTAssert(mapPanel.isPinned) XCTAssert(self.viewController.panelPinnedRight == mapPanel) self.viewController.didDragFree(mapPanel, from: mapPanel.view.frame.origin) XCTAssert(!mapPanel.isPinned) XCTAssert(self.viewController.panelPinnedRight == nil) exp.fulfill() }) } waitForExpectations(timeout: 10.0) { (error) in if let error = error { XCTFail(error.localizedDescription) } } } func testKeyboard() { let textPanel = viewController.textPanelVC! let exp = self.expectation(description: "keyboard") viewController.showTextPanelFromBarButton { XCTAssert(textPanel.isPresentedAsPopover) self.viewController.toggleFloatStatus(for: textPanel, completion: { let textView = self.viewController.textPanelContentVC.textView textView!.becomeFirstResponder() XCTAssert(textView!.isFirstResponder) textView!.resignFirstResponder() XCTAssert(!textView!.isFirstResponder) exp.fulfill() }) } waitForExpectations(timeout: 10.0) { (error) in if let error = error { XCTFail(error.localizedDescription) } } } func testOffOnScreen() { let mapPanel = viewController.mapPanelVC! let exp = self.expectation(description: "offOnScreen") viewController.showMapPanelFromBarButton { XCTAssert(mapPanel.isPresentedAsPopover) self.viewController.toggleFloatStatus(for: mapPanel, completion: { // Move off screen self.viewController.panelsPrepareMoveOffScreen() self.viewController.panelsMoveOffScreen() self.viewController.view.layoutIfNeeded() self.viewController.panelsCompleteMoveOffScreen() let vcFrame = self.viewController.view.bounds let mapPanelFrame = mapPanel.view.frame XCTAssert(!vcFrame.intersects(mapPanelFrame)) // Move on screen self.viewController.panelsPrepareMoveOnScreen() self.viewController.panelsMoveOnScreen() self.viewController.view.layoutIfNeeded() self.viewController.panelsCompleteMoveOnScreen() let mapPanelFrameOn = mapPanel.view.frame XCTAssert(vcFrame.intersects(mapPanelFrameOn)) exp.fulfill() }) } waitForExpectations(timeout: 10.0) { (error) in if let error = error { XCTFail(error.localizedDescription) } } } func testClosing() { let mapPanel = viewController.mapPanelVC! let exp = self.expectation(description: "closing") viewController.showMapPanelFromBarButton { XCTAssert(mapPanel.isPresentedAsPopover) self.viewController.toggleFloatStatus(for: mapPanel, completion: { XCTAssert(mapPanel.isFloating) self.viewController.close(mapPanel) XCTAssert(!mapPanel.isFloating) exp.fulfill() }) } waitForExpectations(timeout: 10.0) { (error) in if let error = error { XCTFail(error.localizedDescription) } } } func testClosingAllFloating() { let mapPanel = viewController.mapPanelVC! let exp = self.expectation(description: "closing") viewController.showMapPanelFromBarButton { self.viewController.toggleFloatStatus(for: mapPanel, completion: { XCTAssert(mapPanel.isFloating) self.viewController.closeAllFloatingPanels() XCTAssert(!mapPanel.isFloating) exp.fulfill() }) } waitForExpectations(timeout: 10.0) { (error) in if let error = error { XCTFail(error.localizedDescription) } } } func testClosingAllPinned() { let mapPanel = viewController.mapPanelVC! let textPanel = viewController.textPanelVC! let exp = self.expectation(description: "closing") viewController.showMapPanelFromBarButton { self.viewController.toggleFloatStatus(for: mapPanel, completion: { self.viewController.didEndDrag(mapPanel, toEdgeOf: .right) XCTAssert(mapPanel.isPinned) XCTAssert(self.viewController.panelPinnedRight == mapPanel) self.viewController.showTextPanelFromBarButton { self.viewController.toggleFloatStatus(for: textPanel, completion: { self.viewController.didEndDrag(textPanel, toEdgeOf: .left) XCTAssert(textPanel.isPinned) XCTAssert(self.viewController.panelPinnedLeft == textPanel) self.viewController.closeAllPinnedPanels() XCTAssert(!mapPanel.isPinned) XCTAssert(self.viewController.panelPinnedRight == nil) XCTAssert(!textPanel.isPinned) XCTAssert(self.viewController.panelPinnedLeft == nil) exp.fulfill() }) } }) } waitForExpectations(timeout: 10.0) { (error) in if let error = error { XCTFail(error.localizedDescription) } } } func testDragToPin() { let mapPanel = viewController.mapPanelVC! let exp = self.expectation(description: "dragToPin") viewController.showMapPanelFromBarButton { XCTAssert(mapPanel.isPresentedAsPopover) self.viewController.toggleFloatStatus(for: mapPanel, completion: { let from = CGPoint(x: mapPanel.view.center.x - 1, y: mapPanel.view.center.y + 200) let toX = self.viewController.view.bounds.width - mapPanel.contentViewController!.view.bounds.width/2 let to = CGPoint(x: toX, y: mapPanel.view.center.y + 200) mapPanel.moveWithTouch(from: from, to: to) self.viewController.view.layoutIfNeeded() mapPanel.moveWithTouch(from: to, to: to) mapPanel.didEndDrag() XCTAssert(mapPanel.isPinned) XCTAssert(self.viewController.panelPinnedRight == mapPanel) mapPanel.moveWithTouch(from: to, to: from) self.viewController.view.layoutIfNeeded() mapPanel.moveWithTouch(from: to, to: from) mapPanel.didEndDrag() XCTAssert(!mapPanel.isPinned) XCTAssert(self.viewController.panelPinnedRight == nil) exp.fulfill() }) } waitForExpectations(timeout: 10.0) { (error) in if let error = error { XCTFail(error.localizedDescription) } } } }
mit
60bcf31e61427bc6c75670c824a4d833
22.143805
105
0.687124
4.086328
false
false
false
false
nheagy/WordPress-iOS
WordPress/Classes/ViewRelated/Cells/PickerTableViewCell.swift
1
3786
import Foundation import WordPressShared /// The purpose of this class is to display a UIPickerView instance inside a UITableView, /// and wrap up all of the Picker Delegate / DataSource methods public class PickerTableViewCell : WPTableViewCell, UIPickerViewDelegate, UIPickerViewDataSource { // MARK: - Public Properties /// Closure, to be executed on selection change public var onChange : ((newValue: Int) -> ())? /// String Format, to be applied to the Row Titles public var textFormat : String? { didSet { picker.reloadAllComponents() } } /// Currently Selected Value public var selectedValue : Int? { didSet { refreshSelectedValue() } } /// Specifies the Minimum Possible Value public var minimumValue : Int = 0 { didSet { picker.reloadAllComponents() } } /// Specifies the Maximum Possible Value public var maximumValue : Int = 0 { didSet { picker.reloadAllComponents() } } // MARK: - Initializers public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! setupSubviews() } public required override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupSubviews() } // MARK: - Private Helpers private func setupSubviews() { // Setup Picker picker.dataSource = self picker.delegate = self picker.backgroundColor = UIColor.whiteColor() contentView.addSubview(picker) // ContentView: Pin to Left + Right edges contentView.translatesAutoresizingMaskIntoConstraints = false contentView.leadingAnchor.constraintEqualToAnchor(leadingAnchor).active = true contentView.trailingAnchor.constraintEqualToAnchor(trailingAnchor).active = true // Picker: Pin to Top + Bottom + CenterX edges picker.translatesAutoresizingMaskIntoConstraints = false picker.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true picker.bottomAnchor.constraintEqualToAnchor(contentView.bottomAnchor).active = true picker.leadingAnchor.constraintEqualToAnchor(contentView.leadingAnchor).active = true picker.trailingAnchor.constraintEqualToAnchor(contentView.trailingAnchor).active = true } private func refreshSelectedValue() { guard let unwrappedSelectedValue = selectedValue else { return } let row = unwrappedSelectedValue - minimumValue picker.selectRow(row, inComponent: 0, animated: false) } // MARK: UIPickerView Methods public func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return numberOfComponentsInPicker } public func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { // We *include* the last value, as well return maximumValue - minimumValue + 1 } public func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let unwrappedFormat = textFormat ?? "%d" let value = row + minimumValue return String(format: unwrappedFormat, value) } public func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let value = row + minimumValue onChange?(newValue: value) } // MARK: - Private Properties private let picker = UIPickerView() private let numberOfComponentsInPicker = 1 }
gpl-2.0
5b903e3a944cf7cc5b62e7ecf6225a7b
30.289256
116
0.65346
5.897196
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/WordPressTest/ViewRelated/Stats/Insights/SiteStatsInsightViewModelTests.swift
1
5784
import Foundation import XCTest @testable import WordPress class SiteStatsInsightsViewModelTests: XCTestCase { /// The standard api result for a normal user func testSummarySplitIntervalData14DaysBasecase() throws { // Given statsSummaryTimeIntervalData with 14 days data guard let statsSummaryTimeIntervalData = try! StatsMockDataLoader.createStatsSummaryTimeIntervalData(fileName: "stats-visits-day-14.json") else { XCTFail("Failed to create statsSummaryTimeIntervalData") return } // When splitting into thisWeek and prevWeek validateResults(SiteStatsInsightsViewModel.splitStatsSummaryTimeIntervalData(statsSummaryTimeIntervalData)) } /// The api result for a new user that has full data for this week but a partial dataset for the previous week func testSummarySplitIntervalData11Days() throws { // Given statsSummaryTimeIntervalData with 11 days data guard let statsSummaryTimeIntervalData = try! StatsMockDataLoader.createStatsSummaryTimeIntervalData(fileName: "stats-visits-day-11.json") else { XCTFail(Constants.failCreateStatsSummaryTimeIntervalData) return } // When splitting into thisWeek and prevWeek validateResults(SiteStatsInsightsViewModel.splitStatsSummaryTimeIntervalData(statsSummaryTimeIntervalData)) } /// The api result for a new user that has an incomplete dataset for this week and no data for prev week func testSummarySplitIntervalData4Days() throws { // Given statsSummaryTimeIntervalData with 4 days data guard let statsSummaryTimeIntervalData = try! StatsMockDataLoader.createStatsSummaryTimeIntervalData(fileName: "stats-visits-day-4.json") else { XCTFail(Constants.failCreateStatsSummaryTimeIntervalData) return } // When splitting into thisWeek and prevWeek validateResults(SiteStatsInsightsViewModel.splitStatsSummaryTimeIntervalData(statsSummaryTimeIntervalData)) } func validateResults(_ statsSummaryTimeIntervalDataAsAWeeks: [StatsSummaryTimeIntervalDataAsAWeek]) { XCTAssertTrue(statsSummaryTimeIntervalDataAsAWeeks.count == 2) // Then 14 days should be split into thisWeek and nextWeek evenly statsSummaryTimeIntervalDataAsAWeeks.forEach { week in switch week { case .thisWeek(let thisWeek): XCTAssertTrue(thisWeek.summaryData.count == 7) XCTAssertEqual(thisWeek.summaryData.last?.periodStartDate, Calendar.autoupdatingCurrent.date(from: DateComponents(year: 2019, month: 2, day: 21))) XCTAssertEqual(thisWeek.summaryData.first?.periodStartDate, Calendar.autoupdatingCurrent.date(from: DateComponents(year: 2019, month: 2, day: 15))) case .prevWeek(let prevWeek): XCTAssertTrue(prevWeek.summaryData.count == 7) XCTAssertEqual(prevWeek.summaryData.last?.periodStartDate, Calendar.autoupdatingCurrent.date(from: DateComponents(year: 2019, month: 2, day: 14))) XCTAssertEqual(prevWeek.summaryData.first?.periodStartDate, Calendar.autoupdatingCurrent.date(from: DateComponents(year: 2019, month: 2, day: 8))) } } } /// The api result for a new user that has an incomplete dataset for this week and no data for prev week /// we should pad forward days to represent the equivalent of the web period view func testSummarySplitIntervalData4DaysPeriodWeekView() throws { // Given statsSummaryTimeIntervalData with 4 days data guard let statsSummaryTimeIntervalData = try! StatsMockDataLoader.createStatsSummaryTimeIntervalData(fileName: "stats-visits-day-4.json") else { XCTFail(Constants.failCreateStatsSummaryTimeIntervalData) return } let week = StatsPeriodHelper().weekIncludingDate(statsSummaryTimeIntervalData.periodEndDate) guard let periodEndDateForWeek = week?.weekEnd else { XCTFail("week EndDate not found") return } // When splitting into thisWeek and prevWeek let data = SiteStatsInsightsViewModel.splitStatsSummaryTimeIntervalData(statsSummaryTimeIntervalData, periodEndDate: periodEndDateForWeek) validateResultsPeriodWeekView(data) } func validateResultsPeriodWeekView(_ statsSummaryTimeIntervalDataAsAWeeks: [StatsSummaryTimeIntervalDataAsAWeek]) { XCTAssertTrue(statsSummaryTimeIntervalDataAsAWeeks.count == 2) // Then 14 days should be split into thisWeek and nextWeek evenly statsSummaryTimeIntervalDataAsAWeeks.forEach { week in switch week { case .thisWeek(let thisWeek): XCTAssertTrue(thisWeek.summaryData.count == 7) XCTAssertEqual(thisWeek.summaryData.last?.periodStartDate, Calendar.autoupdatingCurrent.date(from: DateComponents(year: 2019, month: 2, day: 24))) XCTAssertEqual(thisWeek.summaryData.first?.periodStartDate, Calendar.autoupdatingCurrent.date(from: DateComponents(year: 2019, month: 2, day: 18))) case .prevWeek(let prevWeek): XCTAssertTrue(prevWeek.summaryData.count == 7) XCTAssertEqual(prevWeek.summaryData.last?.periodStartDate, Calendar.autoupdatingCurrent.date(from: DateComponents(year: 2019, month: 2, day: 17))) XCTAssertEqual(prevWeek.summaryData.first?.periodStartDate, Calendar.autoupdatingCurrent.date(from: DateComponents(year: 2019, month: 2, day: 11))) } } } } private extension SiteStatsInsightsViewModelTests { enum Constants { static let failCreateStatsSummaryTimeIntervalData = "Failed to create statsSummaryTimeIntervalData" } }
gpl-2.0
3c6ca8c6d18bed56cc3e05a69f80c41e
54.085714
163
0.726141
4.990509
false
true
false
false
shashank3369/GifMaker
GifMaker_Swift_Template/Gif.swift
1
1398
// // Gif.swift // GifMaker_Swift_Template // // Created by Kothapalli on 1/8/17. // Copyright © 2017 Gabrielle Miller-Messner. All rights reserved. // import Foundation import UIKit class Gif: NSObject, NSCoding{ var url: URL? var caption: String? var gifImage: UIImage? var videoURL: URL? var data: Data? init(name: String) { self.gifImage = UIImage.gif(name: name)! } init(url: URL, videoURL: URL, caption: String?) { self.url = url self.videoURL = videoURL self.caption = caption self.gifImage = UIImage.gif(url: url.absoluteString)! self.data = nil } required init?(coder aDecoder: NSCoder) { self.url = aDecoder.decodeObject(forKey: "url") as? URL self.videoURL = aDecoder.decodeObject(forKey: "videoURL") as? URL self.caption = aDecoder.decodeObject(forKey: "caption") as? String self.gifImage = aDecoder.decodeObject(forKey: "gifImage") as? UIImage self.data = aDecoder.decodeObject(forKey: "gifData") as? Data } func encode(with aCoder: NSCoder) { aCoder.encode(self.url, forKey: "url") aCoder.encode(self.videoURL, forKey: "videoURL") aCoder.encode(self.caption, forKey: "caption") aCoder.encode(self.gifImage, forKey: "gifImage") aCoder.encode(self.data, forKey: "gifData") } }
mit
0f1ed851923d1a70845507254f53e1fa
29.369565
77
0.631353
3.891365
false
false
false
false
andresinaka/SnapTimer
SnapTimer/SnapTimerCircleLayer.swift
2
1969
// // SnapTimerCircleLayer.swift // SnapTimer // // Created by Andres on 8/29/16. // Copyright © 2016 Andres. All rights reserved. // import UIKit class SnapTimerCircleLayer: CALayer { @NSManaged var circleColor: CGColor @NSManaged var startAngle: CGFloat @NSManaged var radius: CGFloat override init(layer: Any) { super.init(layer: layer) if let layer = layer as? SnapTimerCircleLayer { startAngle = layer.startAngle circleColor = layer.circleColor radius = layer.radius } else { startAngle = 0 } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init() { super.init() } func animation(_ key: String) -> CAAnimation { let animation = CABasicAnimation(keyPath: key) if let pLayer = self.presentation(), let value = pLayer.value(forKey: key) { animation.fromValue = value } let animationTiming = CATransaction.animationTimingFunction() ?? CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) let duration = CATransaction.animationDuration() animation.timingFunction = animationTiming animation.duration = duration return animation } override func action(forKey key: String) -> CAAction? { if key == "startAngle" { return self.animation(key) } return super.action(forKey: key) } override class func needsDisplay(forKey key: String) -> Bool { if key == "startAngle" || key == "circleColor" || key == "radius" { return true } return super.needsDisplay(forKey: key) } override func draw(in ctx: CGContext) { let center = CGPoint(x:bounds.width/2, y: bounds.height/2) ctx.beginPath() ctx.setLineWidth(0) ctx.move(to: CGPoint(x: center.x, y: center.y)) ctx.addArc( center: center, radius: self.radius, startAngle: self.startAngle, endAngle: SnapTimerView.endAngle, clockwise: false ) ctx.setFillColor(self.circleColor) ctx.drawPath(using: .fillStroke) } }
mit
17f9f7fdde592856aef68286c339177e
24.230769
124
0.688008
3.637708
false
false
false
false
daisysomus/swift-algorithm-club
Union-Find/UnionFind.playground/Contents.swift
1
1624
//: Playground - noun: a place where people can play var dsu = UnionFindQuickUnion<Int>() for i in 1...10 { dsu.addSetWith(i) } // now our dsu contains 10 independent sets // let's divide our numbers into two sets by divisibility by 2 for i in 3...10 { if i % 2 == 0 { dsu.unionSetsContaining(2, and: i) } else { dsu.unionSetsContaining(1, and: i) } } // check our division print(dsu.inSameSet(2, and: 4)) print(dsu.inSameSet(4, and: 6)) print(dsu.inSameSet(6, and: 8)) print(dsu.inSameSet(8, and: 10)) print(dsu.inSameSet(1, and: 3)) print(dsu.inSameSet(3, and: 5)) print(dsu.inSameSet(5, and: 7)) print(dsu.inSameSet(7, and: 9)) print(dsu.inSameSet(7, and: 4)) print(dsu.inSameSet(3, and: 6)) var dsuForStrings = UnionFindQuickUnion<String>() let words = ["all", "border", "boy", "afternoon", "amazing", "awesome", "best"] dsuForStrings.addSetWith("a") dsuForStrings.addSetWith("b") // In that example we divide strings by its first letter for word in words { dsuForStrings.addSetWith(word) if word.hasPrefix("a") { dsuForStrings.unionSetsContaining("a", and: word) } else if word.hasPrefix("b") { dsuForStrings.unionSetsContaining("b", and: word) } } print(dsuForStrings.inSameSet("a", and: "all")) print(dsuForStrings.inSameSet("all", and: "awesome")) print(dsuForStrings.inSameSet("amazing", and: "afternoon")) print(dsuForStrings.inSameSet("b", and: "boy")) print(dsuForStrings.inSameSet("best", and: "boy")) print(dsuForStrings.inSameSet("border", and: "best")) print(dsuForStrings.inSameSet("amazing", and: "boy")) print(dsuForStrings.inSameSet("all", and: "border"))
mit
07c4abb4d4f2fc9f6b82e42bd326b935
25.193548
79
0.693966
2.688742
false
false
false
false
minamakary25/Swift-Extensions
StringExtension.swift
1
1949
// // Created by Mina Makary on 12/23/16. // Copyright © 2016 Particles. All rights reserved. // import Foundation extension String { func hasUniqueCharacters() -> Bool { var hasUniqueCharacters = true autoreleasepool { let charactersCount = NSMutableDictionary() for char in characters { if charactersCount.value(forKey: String(char)) != nil { hasUniqueCharacters = false } else { charactersCount.setValue(1, forKey: String(char)) } } } return hasUniqueCharacters } func reverseString() -> String { var reversedString = Array(characters) var mid = reversedString.count / 2 if reversedString.count % 2 == 0 { mid -= 1 } for i in 0...mid { let temp = reversedString[i] reversedString[i] = reversedString[reversedString.count - i - 1] reversedString[reversedString.count - i - 1] = temp } return String(reversedString) } func isTheReverseOf(string otherString: String) -> Bool { if characters.count != otherString.characters.count { return false } for i in 0..<characters.count { if self[index(startIndex, offsetBy: i)] != otherString[index(startIndex, offsetBy: characters.count - i - 1)] { return false } } return true } func isAPermutationOf(string otherString: String) -> Bool { if characters.count != otherString.characters.count { return false } if self.utf16.sorted() != otherString.utf16.sorted() { return false } return true } }
mit
e41964f4e16c69cdd2bde1a25640468a
24.631579
123
0.510267
5.099476
false
false
false
false
raulriera/Bike-Compass
App/Carthage/Checkouts/Decodable/Tests/Repository.swift
1
1958
// // RepositoryExample.swift // Decodable // // Created by Fran_DEV on 13/07/15. // Copyright © 2015 anviking. All rights reserved. // import Foundation @testable import Decodable struct Owner { let id: Int let login: String } struct Repository { let id: Int let name: String let description: String let htmlUrlString : String let owner: Owner // Struct conforming to Decodable let coverage: Double let files: Array<String> let optional: String? let active: Bool let optionalActive: Bool? } extension Owner : Decodable { static func decode(_ j: AnyObject) throws -> Owner { return try Owner( id: j => "id", login: j => "login" ) } } extension Repository : Decodable { static func decode(_ j: AnyObject) throws -> Repository { return try Repository( id: j => "id", name: j => "name", description: j => "description", htmlUrlString : j => "html_url", owner: j => "owner", coverage: j => "coverage", files: j => "files", optional: j => "optional", active: j => "active", optionalActive: j => "optionalActive" ) } } // MARK: Equatable func == (lhs: Owner, rhs: Owner) -> Bool { return lhs.id == rhs.id && lhs.login == rhs.login } extension Owner: Equatable { var hashValue: Int { return id.hashValue } } func == (lhs: Repository, rhs: Repository) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name && lhs.description == rhs.description && lhs.htmlUrlString == rhs.htmlUrlString && lhs.owner == rhs.owner && lhs.coverage == rhs.coverage && lhs.files == rhs.files && lhs.optional == rhs.optional && lhs.active == rhs.active && lhs.optionalActive == rhs.optionalActive } extension Repository: Equatable { var hashValue: Int { return id.hashValue } }
mit
e9a9817376d72b6b84fd43fb32c2c705
23.160494
61
0.583546
3.953535
false
false
false
false
hughbe/swift
test/IDE/print_synthesized_extensions.swift
4
12429
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module-path %t/print_synthesized_extensions.swiftmodule -emit-module-doc -emit-module-doc-path %t/print_synthesized_extensions.swiftdoc %s // RUN: %target-swift-ide-test -print-module -annotate-print -synthesize-extension -print-interface -no-empty-line-between-members -module-to-print=print_synthesized_extensions -I %t -source-filename=%s > %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK1 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK2 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK3 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK4 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK5 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK6 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK7 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK8 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK9 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK10 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK11 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK12 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK13 < %t.syn.txt // RUN: %FileCheck %s -check-prefix=CHECK14 < %t.syn.txt public protocol P1 { associatedtype T1 associatedtype T2 func f1(t : T1) -> T1 func f2(t : T2) -> T2 } public extension P1 where T1 == Int { func p1IntFunc(i : Int) -> Int {return 0} } public extension P1 where T1 : P3 { func p3Func(i : Int) -> Int {return 0} } public protocol P2 { associatedtype P2T1 } public extension P2 where P2T1 : P2{ public func p2member() {} } public protocol P3 {} public extension P1 where T1 : P2 { public func ef1(t : T1) {} public func ef2(t : T2) {} } public extension P1 where T1 == P2, T2 : P3 { public func ef3(t : T1) {} public func ef4(t : T1) {} } public extension P1 where T2 : P3 { public func ef5(t : T2) {} } public struct S2 {} public struct S1<T> : P1, P2 { public typealias T1 = T public typealias T2 = S2 public typealias P2T1 = T public func f1(t : T1) -> T1 { return t } public func f2(t : T2) -> T2 { return t } } public struct S3<T> : P1 { public typealias T1 = (T, T) public typealias T2 = (T, T) public func f1(t : T1) -> T1 { return t } public func f2(t : T2) -> T2 { return t } } public struct S4<T> : P1 { public typealias T1 = Int public typealias T2 = Int public func f1(t : T1) -> T1 { return t } public func f2(t : T2) -> T2 { return t } } public struct S5 : P3 {} public struct S6<T> : P1 { public typealias T1 = S5 public typealias T2 = S5 public func f1(t : T1) -> T1 { return t } public func f2(t : T2) -> T2 { return t } } public extension S6 { public func f3() {} } public struct S7 { public struct S8 : P1 { public typealias T1 = S5 public typealias T2 = S5 public func f1(t : T1) -> T1 { return t } public func f2(t : T2) -> T2 { return t } } } public extension P1 where T1 == S9<Int> { public func S9IntFunc() {} } public struct S9<T> : P3 {} public struct S10 : P1 { public typealias T1 = S9<Int> public typealias T2 = S9<Int> public func f1(t : T1) -> T1 { return t } public func f2(t : T2) -> T2 { return t } } public protocol P4 {} /// Extension on P4Func1 public extension P4 { func P4Func1() {} } /// Extension on P4Func2 public extension P4 { func P4Func2() {} } public struct S11 : P4 {} public extension S6 { public func fromActualExtension() {} } public protocol P5 { associatedtype T1 /// This is picked func foo1() } public extension P5 { /// This is not picked public func foo1() {} } public extension P5 where T1 == Int { /// This is picked public func foo2() {} } public extension P5 { /// This is not picked public func foo2() {} } public extension P5 { /// This is not picked public func foo3() {} } public extension P5 where T1 : Comparable{ /// This is picked public func foo3() {} } public extension P5 where T1 : Comparable { /// This is picked public func foo4() {} } public extension P5 { /// This is not picked public func foo4() {} } public struct S12 : P5{ public typealias T1 = Int public func foo1() {} } public protocol P6 { func foo1() func foo2() } public extension P6 { public func foo1() {} } public protocol P7 { associatedtype T1 func f1(t: T1) } public extension P7 { public func nomergeFunc(t: T1) -> T1 { return t } public func f1(t: T1) -> T1 { return t } } public struct S13 {} extension S13 : P5 { public typealias T1 = Int public func foo1() {} } // CHECK1: <synthesized>extension <ref:Struct>S1</ref> where T : <ref:Protocol>P2</ref> { // CHECK1-NEXT: <decl:Func>public func <loc>p2member()</loc></decl> // CHECK1-NEXT: <decl:Func>public func <loc>ef1(<decl:Param>t: T</decl>)</loc></decl> // CHECK1-NEXT: <decl:Func>public func <loc>ef2(<decl:Param>t: <ref:Struct>S2</ref></decl>)</loc></decl> // CHECK1-NEXT: }</synthesized> // CHECK2: <synthesized>extension <ref:Struct>S1</ref> where T : <ref:Protocol>P3</ref> { // CHECK2-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl> // CHECK2-NEXT: }</synthesized> // CHECK3: <synthesized>extension <ref:Struct>S1</ref> where T == <ref:Struct>Int</ref> { // CHECK3-NEXT: <decl:Func>public func <loc>p1IntFunc(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl> // CHECK3-NEXT: }</synthesized> // CHECK4: <synthesized>extension <ref:Struct>S1</ref> where T == <ref:Struct>S9</ref><<ref:Struct>Int</ref>> { // CHECK4-NEXT: <decl:Func>public func <loc>S9IntFunc()</loc></decl> // CHECK4-NEXT: }</synthesized> // CHECK5: <decl:Struct>public struct <loc>S10</loc> : <ref:Protocol>P1</ref> { // CHECK5-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl> // CHECK5-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl> // CHECK5-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T1</ref></decl> // CHECK5-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S10</ref>.<ref:TypeAlias>T2</ref></decl></decl> // CHECK5-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl> // CHECK5-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S9</ref><<ref:Struct>Int</ref>></decl>)</loc></decl> // CHECK5-NEXT: <decl:Func>public func <loc>S9IntFunc()</loc></decl> // CHECK5-NEXT: }</synthesized> // CHECK6: <synthesized>/// Extension on P4Func1 // CHECK6-NEXT: extension <ref:Struct>S11</ref> { // CHECK6-NEXT: <decl:Func>public func <loc>P4Func1()</loc></decl> // CHECK6-NEXT: }</synthesized> // CHECK7: <synthesized>/// Extension on P4Func2 // CHECK7-NEXT: extension <ref:Struct>S11</ref> { // CHECK7-NEXT: <decl:Func>public func <loc>P4Func2()</loc></decl> // CHECK7-NEXT: }</synthesized> // CHECK8: <decl:Struct>public struct <loc>S4<<decl:GenericTypeParam>T</decl>></loc> : <ref:Protocol>P1</ref> { // CHECK8-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:Struct>Int</ref></decl> // CHECK8-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:Struct>Int</ref></decl> // CHECK8-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref>.<ref:TypeAlias>T1</ref></decl> // CHECK8-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S4</ref>.<ref:TypeAlias>T2</ref></decl></decl> // CHECK8-NEXT: <decl:Func>public func <loc>p1IntFunc(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl> // CHECK8-NEXT: }</synthesized> // CHECK9: <decl:Struct>public struct <loc>S6<<decl:GenericTypeParam>T</decl>></loc> : <ref:Protocol>P1</ref> { // CHECK9-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S5</ref></decl> // CHECK9-NEXT: <decl:TypeAlias>public typealias <loc>T2</loc> = <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S5</ref></decl> // CHECK9-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref>.<ref:TypeAlias>T1</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref>.<ref:TypeAlias>T1</ref></decl> // CHECK9-NEXT: <decl:Func>public func <loc>f2(<decl:Param>t: <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref>.<ref:TypeAlias>T2</ref></decl>)</loc> -> <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S6</ref>.<ref:TypeAlias>T2</ref></decl></decl> // CHECK9-NEXT: <decl:Extension><decl:Func>public func <loc>f3()</loc></decl></decl> // CHECK9-NEXT: <decl:Extension><decl:Func>public func <loc>fromActualExtension()</loc></decl></decl> // CHECK9-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl> // CHECK9-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S5</ref></decl>)</loc></decl> // CHECK9-NEXT: }</synthesized> // CHECK10: <synthesized>extension <ref:module>print_synthesized_extensions</ref>.<ref:Struct>S7</ref>.<ref:Struct>S8</ref> { // CHECK10-NEXT: <decl:Func>public func <loc>p3Func(<decl:Param>i: <ref:Struct>Int</ref></decl>)</loc> -> <ref:Struct>Int</ref></decl> // CHECK10-NEXT: <decl:Func>public func <loc>ef5(<decl:Param>t: <ref:Struct>S5</ref></decl>)</loc></decl> // CHECK10-NEXT: }</synthesized> // CHECK11: <decl:Struct>public struct <loc>S12</loc> : <ref:Protocol>P5</ref> { // CHECK11-NEXT: <decl:TypeAlias>public typealias <loc>T1</loc> = <ref:Struct>Int</ref></decl> // CHECK11-NEXT: <decl:Func>/// This is picked // CHECK11-NEXT: public func <loc>foo1()</loc></decl></decl> // CHECK11-NEXT: <decl:Func>/// This is picked // CHECK11-NEXT: public func <loc>foo2()</loc></decl> // CHECK11-NEXT: <decl:Func>/// This is picked // CHECK11-NEXT: public func <loc>foo3()</loc></decl> // CHECK11-NEXT: <decl:Func>/// This is picked // CHECK11-NEXT: public func <loc>foo4()</loc></decl> // CHECK11-NEXT: }</synthesized> // CHECK12: <decl:Protocol>public protocol <loc>P6</loc> { // CHECK12-NEXT: <decl:Func(HasDefault)>public func <loc>foo1()</loc></decl> // CHECK12-NEXT: <decl:Func>public func <loc>foo2()</loc></decl> // CHECK12-NEXT: }</decl> // CHECK13: <decl:Protocol>public protocol <loc>P7</loc> { // CHECK13-NEXT: <decl:AssociatedType>associatedtype <loc>T1</loc></decl> // CHECK13-NEXT: <decl:Func(HasDefault)>public func <loc>f1(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc></decl> // CHECK13-NEXT: }</decl> // CHECK13: <decl:Extension>extension <loc><ref:Protocol>P7</ref></loc> { // CHECK13-NEXT: <decl:Func>public func <loc>nomergeFunc(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc> -> <ref:GenericTypeParam>Self</ref>.T1</decl> // CHECK13-NEXT: <decl:Func>public func <loc>f1(<decl:Param>t: <ref:GenericTypeParam>Self</ref>.T1</decl>)</loc> -> <ref:GenericTypeParam>Self</ref>.T1</decl> // CHECK13-NEXT: }</decl> // CHECK14: <decl:Struct>public struct <loc>S13</loc> {</decl> // CHECK14-NEXT: <decl:Func>/// This is picked // CHECK14-NEXT: public func <loc>foo2()</loc></decl> // CHECK14-NEXT: <decl:Func>/// This is picked // CHECK14-NEXT: public func <loc>foo3()</loc></decl> // CHECK14-NEXT: <decl:Func>/// This is picked // CHECK14-NEXT: public func <loc>foo4()</loc></decl> // CHECK14-NEXT: }</synthesized>
apache-2.0
f1376de62026eec96fc06f0fcb444d31
36.663636
279
0.655644
2.803112
false
false
false
false
lkzhao/YetAnotherAnimationLibrary
Sources/YetAnotherAnimationLibrary/AnimationProperty/AnimationProperty.swift
2
1852
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public class AnimationProperty<Value: VectorConvertible> { private var _changes: Announcer<Value>? public var changes: Announcer<Value> { if _changes == nil { _changes = Announcer<Value>() } return _changes! } public var vector: Value.Vector = Value.Vector() { didSet { if let announcer = _changes { announcer.notify(old: oldValue, new: vector) } } } public var value: Value { get { return Value.from(vector: vector) } set { vector = newValue.vector } } public init() {} public init(value: Value) { self.value = value } }
mit
abc0411e5f2f30f504e17f9a88aed214
35.313725
80
0.681965
4.39905
false
false
false
false
felipedemetrius/WatchMe
WatchMe/SeasonsSerieViewController.swift
1
4297
// // SeasonsSerieViewController.swift // WatchMe // // Created by Felipe Silva on 1/21/17. // Copyright © 2017 Felipe Silva . All rights reserved. // import UIKit class SeasonsSerieViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var serie : SerieModel! var seasons : [SeasonModel]? override func viewDidLoad() { super.viewDidLoad() title = serie.title configureTableView() configureDatasource() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } private func configureDatasource(){ SeasonRepository.getSeasons(slug: serie.slug ?? "") { [weak self] seasons in if let seasons = seasons { self?.seasons = seasons self?.tableView.reloadData() } } } private func configureTableView(){ if let topItem = navigationController?.navigationBar.topItem { topItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.plain, target: nil, action: nil) } tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 175 tableView.register(UINib(nibName: "EpisodeTableViewCell", bundle: nil), forCellReuseIdentifier: "EpisodeTableViewCell") } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "goToDetailEpisode" { let vc = segue.destination as? DetailEpisodeViewController if let episode = sender as? EpisodeModel { vc?.serie = serie vc?.episode = episode } } } } extension SeasonsSerieViewController : UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let seasons = self.seasons else {return 0} let season = seasons[section] return season.episodes?.count ?? 0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let seasons = self.seasons else {return } let season = seasons[indexPath.section] guard let episode = season.episodes?[indexPath.row] else {return } performSegue(withIdentifier: "goToDetailEpisode", sender: episode) } func numberOfSections(in tableView: UITableView) -> Int { guard let seasons = self.seasons else {return 0} return seasons.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let seasons = self.seasons else {return UITableViewCell()} let season = seasons[indexPath.section] guard let episode = season.episodes?[indexPath.row] else {return UITableViewCell()} let cell = tableView.dequeueReusableCell(withIdentifier: "EpisodeTableViewCell", for: indexPath) as? EpisodeTableViewCell cell?.configureEpisode(episode: episode, serie: serie) return cell! } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let seasons = self.seasons else {return nil} let headerView = Bundle.main.loadNibNamed("HeaderTableViewCell", owner: nil, options: nil)! [0] as! HeaderTableViewCell let season = seasons[section] headerView.lblNumber.text = "Season " + (season.number?.description ?? "") return headerView } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 175 } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.separatorInset = UIEdgeInsets.zero cell.layoutMargins = UIEdgeInsets.zero } }
mit
86e548d70a651a9dbe9cfaeca9a3d4ce
29.253521
129
0.625233
5.48659
false
false
false
false
AudioY/iOSTutorialOverlay
iOSTutorialOverlay/JNTutorialOverlay.swift
1
16029
/* JNTutorialOverlay.swift iOSTutorialOverlay Created by Jonathan Neumann on 20/02/2015. Copyright (c) 2015 Audio Y. www.audioy.co Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import UIKit struct ScreenConstants { static var size: CGRect = UIScreen.mainScreen().bounds static var width = size.width static var height = size.height static var scale:CGFloat = UIScreen.mainScreen().scale } struct ColourConstants { // If the RGB value is 252831, pass 0x252831 as the HEX value static var mercury = getUIColorObjectFromHex("E6E6E6", 1.0) // Normal text colour, light grey static var shark = getUIColorObjectFromHex("1A1C22", 1.0) // Darker background colour, very dark blue static var brightTurquoise = getUIColorObjectFromHex("31D8F8", 1.0) // Bright turquoise colour } enum Corners{ case Straight case Rounded } enum Theme{ case Dark case Light } // Custom UIView with the name of the overlay (stored in NSUserDefaults) class JNTutorialOverlay:UIView{ var overlayName:String? // The name saved in NSUserDefaults once the overlay has been removed var opacity:CGFloat? let oneTap = UITapGestureRecognizer() var onHide: ((Bool) -> ())? // This is the completion handler to be called when hideOverlay is called var corners:Corners?{ didSet { switch self.corners!{ case .Straight: setStraightCorners() case .Rounded: setRoundedCorners() } } } var theme:Theme?{ didSet { switch self.theme!{ case .Dark: setDarkTheme() case .Light: setLightTheme() } } } private var overlayView:UIView? private var titleLabel:UILabel? private var messageLabel:UILabel? private var imageView:UIImageView? var title:String?{ didSet{ self.titleLabel?.text = self.title! } } var message:String?{ didSet{ if let message = message{ setMessageLabel(message) } } } var image:UIImage?{ didSet{ if let image = self.image{ setImageView(image) } } } /* -------- INIT METHODS -------- */ // Init with a centred frame and no picture init(overlayName:String, width:CGFloat, opacity: CGFloat, title:String?, message:String?){ super.init(frame: CGRectMake(0, 0, ScreenConstants.width, ScreenConstants.height)) // Centre the frame within the screen //super.init(frame:CGRectMake((ScreenConstants.width - width)/2, (ScreenConstants.height - height)/2, width, height)) // Create the overlay and centre it within the screen createOverlay(CGRectMake((ScreenConstants.width - width)/2, 0, width, 0), overlayName: overlayName, opacity: opacity, title: title, message: message, image: nil) } // Init with a centred frame and a picture init(overlayName:String, width:CGFloat, opacity: CGFloat, title:String?, message:String?, image:UIImage?){ super.init(frame: CGRectMake(0, 0, ScreenConstants.width, ScreenConstants.height)) // Centre the frame within the screen //super.init(frame:CGRectMake((ScreenConstants.width - width)/2, (ScreenConstants.height - height)/2, width, height)) // Create the overlay and centre it within the screen createOverlay(CGRectMake((ScreenConstants.width - width)/2, 0, width, 0), overlayName: overlayName, opacity: opacity, title: title, message: message, image: image) } // Init with a set frame and no picture init(overlayName:String, frame:CGRect, opacity:CGFloat, title:String?, message:String?) { super.init(frame: CGRectMake(0, 0, ScreenConstants.width, ScreenConstants.height)) // Init the frame //super.init(frame: frame) // Create the overlay createOverlay(frame, overlayName: overlayName, opacity: opacity, title: title, message: message, image: nil) } // Init with a set frame and a picture init(overlayName:String, frame:CGRect, opacity:CGFloat, title:String?, message:String?, image:UIImage?) { super.init(frame: CGRectMake(0, 0, ScreenConstants.width, ScreenConstants.height)) // Init the frame //super.init(frame: frame) // Create the overlay createOverlay(frame, overlayName: overlayName, opacity: opacity, title: title, message: message, image: image) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /* -------- OVERLAY VIEW METHODS -------- */ func createOverlay(frame: CGRect, overlayName:String, opacity: CGFloat, title:String?, message:String?, image:UIImage?){ // Init the name self.overlayName = overlayName // Init the opacity self.opacity = opacity // Init the tap to get rid of the overlay oneTap.addTarget(self, action: "hideOverlay:") self.addGestureRecognizer(oneTap) // Prepare the overlay view overlayView = UIView(frame: frame) // Set a dark theme by default setDarkTheme() // Set rounded corners by default setRoundedCorners() // Prepare the title label var font = UIFont(name: "Helvetica-Bold", size: 19.0) titleLabel = UILabel(frame: CGRectMake(10, 20, overlayView!.frame.width - 20, 50)) titleLabel?.numberOfLines = 0 titleLabel?.textAlignment = .Center titleLabel?.font = font! titleLabel?.textColor = ColourConstants.mercury // Assign it the text if it has been set if let title = title{ self.title = title titleLabel?.text = title } // Prepare the message label font = UIFont(name: "Helvetica", size: 16.0) messageLabel = UILabel(frame: CGRectMake(20, titleLabel!.frame.origin.y + titleLabel!.frame.height + 15, overlayView!.frame.width - 40, 0)) messageLabel?.numberOfLines = 0 messageLabel?.textAlignment = .Center messageLabel?.font = font! messageLabel?.textColor = ColourConstants.mercury // Assign it the message if it has been set if let message = message{ self.message = message setMessageLabel(message) } // Prepare the image view self.imageView = UIImageView(frame: CGRectMake(0, 0, 0, 0)) if let image = image{ self.image = image setImageView(image) } overlayView?.addSubview(titleLabel!) overlayView?.addSubview(messageLabel!) overlayView?.addSubview(imageView!) self.adaptHeight() self.addSubview(overlayView!) } // Use this function to show the view func show(){ if checkScreenShownBefore(self.overlayName!) == false{ animateWithPopIn() } } // Use this function to show the view and know when it's been hidden thanks to the block func showWithBlock(onHide: (Bool) -> ()){ self.onHide = onHide if checkScreenShownBefore(self.overlayName!) == false{ animateWithPopIn() } } func hideOverlay(sender:UITapGestureRecognizer){ if let name = self.overlayName{ // Save in NSUserDefaults as this overlay is not to be shown again NSUserDefaults.standardUserDefaults().setBool(true, forKey: name) NSUserDefaults.standardUserDefaults().synchronize() } // Animate animateWithPopOut() } /* -------- SETTING METHODS IN ORDER TO AVOIR REPEATING CODE -------- */ func setStraightCorners(){ overlayView?.layer.borderWidth = 3 overlayView?.layer.cornerRadius = 0 } func setRoundedCorners(){ overlayView?.layer.borderWidth = 3 overlayView?.layer.cornerRadius = 10 overlayView?.clipsToBounds = true } func setDarkTheme(){ self.backgroundColor = getUIColorObjectFromHex("000000", 0.5) overlayView?.backgroundColor = getUIColorObjectFromHex("000000", opacity!) overlayView?.layer.borderColor = UIColor.blackColor().CGColor self.titleLabel?.textColor = ColourConstants.mercury self.messageLabel?.textColor = ColourConstants.mercury } func setLightTheme(){ self.backgroundColor = getUIColorObjectFromHex("FFFFFF", 0.5) overlayView?.backgroundColor = getUIColorObjectFromHex("FFFFFF", opacity!) overlayView?.layer.borderColor = UIColor.whiteColor().CGColor self.titleLabel?.textColor = ColourConstants.shark self.messageLabel?.textColor = ColourConstants.shark } func setMessageLabel(message:String){ self.messageLabel?.text = message self.messageLabel?.sizeToFit() self.messageLabel?.frame = CGRectMake(20, titleLabel!.frame.origin.y + titleLabel!.frame.height + 15, overlayView!.frame.width - 40, self.messageLabel!.frame.height) // Move the image if it already exists if let image = self.image{ setImageView(image) } self.adaptHeight() } func setImageView(image:UIImage){ // Reset the imageView frame to the dimensions of the image self.imageView?.frame.size.width = image.size.width self.imageView?.frame.size.height = image.size.height // Set the frame in the middle self.imageView?.frame.origin.y = messageLabel!.frame.origin.y + messageLabel!.frame.height + 20 self.imageView?.frame.origin.x = (overlayView!.frame.width - image.size.width)/2 // Finally, set the image and resize the overlay self.imageView?.image = self.image! self.adaptHeight() } // Find the tallest subview and automatically adapt the height to this height + 20 func adaptHeight(){ var overlayHeight:CGFloat = 0 for subview in self.overlayView!.subviews{ overlayHeight = max(overlayHeight, subview.frame.origin.y + subview.frame.size.height) } self.overlayView?.frame.size.height = overlayHeight + 32 self.overlayView?.frame.origin.y = (ScreenConstants.height - (overlayHeight + 32))/2 } /* -------- ANIMATION METHODS -------- */ func animateWithPopIn(){ let rootViewController: UIViewController = UIApplication.sharedApplication().windows[0].rootViewController!! let originalFrame = overlayView!.frame // Start at the centre overlayView!.frame.origin.x = originalFrame.origin.x + originalFrame.width/2 overlayView!.frame.size.width = 0 overlayView!.frame.origin.y = originalFrame.origin.y + originalFrame.height/2 overlayView!.frame.size.height = 0 // Hide everything hideElements() rootViewController.view.addSubview(self) // Animate UIView.animateWithDuration(0.2, delay: 0.0, options: .CurveEaseOut, animations: { // Expand too much! self.overlayView!.frame.origin.x = originalFrame.origin.x - 10 self.overlayView!.frame.size.width = originalFrame.width + 20 self.overlayView!.frame.origin.y = originalFrame.origin.y - 10 self.overlayView!.frame.size.height = originalFrame.height + 20 }, completion: { finished in // Shrink back to the intended frame UIView.animateWithDuration(0.1, delay: 0.0, options: .CurveEaseOut, animations: { self.overlayView!.frame = originalFrame self.showElements() }, completion: nil) }) } func animateWithPopOut(){ // Hide everything hideElements() // Animate UIView.animateWithDuration(0.1, delay: 0.0, options: .CurveEaseOut, animations: { // Step 1 - Expand a little bit... self.overlayView!.frame.origin.x = self.overlayView!.frame.origin.x - 10 self.overlayView!.frame.size.width = self.overlayView!.frame.width + 20 self.overlayView!.frame.origin.y = self.overlayView!.frame.origin.y - 10 self.overlayView!.frame.size.height = self.overlayView!.frame.height + 20 }, completion: { finished in UIView.animateWithDuration(0.2, delay: 0.0, options: .CurveEaseOut, animations: { // Step 2 - Shrink! self.overlayView!.frame.origin.x = self.overlayView!.frame.origin.x + self.overlayView!.frame.width/2 self.overlayView!.frame.size.width = 0 self.overlayView!.frame.origin.y = self.overlayView!.frame.origin.y + self.overlayView!.frame.height/2 self.overlayView!.frame.size.height = 0 }, completion: { finished in self.removeFromSuperview() self.onHide?(true) // Let the block know the overlay has finished being removed }) }) } func hideElements(){ self.titleLabel?.alpha = 0 self.messageLabel?.alpha = 0 self.imageView?.alpha = 0 } func showElements(){ self.titleLabel?.alpha = 1 self.messageLabel?.alpha = 1 self.imageView?.alpha = 1 } } /* -------- CUSTOM METHODS -------- */ func checkScreenShownBefore(name:String) -> BooleanLiteralType{ if let hasBeenShown:AnyObject = NSUserDefaults.standardUserDefaults().objectForKey(name){ // If an object was returned, it means that something was shown. No need to create the overlay then! return true } else { return false } } func getUIColorObjectFromHex(hex:String, alpha:CGFloat) -> UIColor { var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet() as NSCharacterSet).uppercaseString if (cString.hasPrefix("#")) { cString = cString.substringFromIndex(advance(cString.startIndex, 1)) } if (count(cString) != 6) { return UIColor.grayColor() } var rgbValue:UInt32 = 0 NSScanner(string: cString).scanHexInt(&rgbValue) return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(alpha) ) }
mit
381125da4d3c53b4910004f1f22cffee
36.020785
173
0.620999
4.777645
false
false
false
false
davirdgs/ABC4
MN4/Tutorial2ViewController.swift
1
4609
// // Tutorial2ViewController.swift // MN4 // // Created by Davi Rodrigues on 27/08/15. // Copyright (c) 2015 Pedro Rodrigues Grijó. All rights reserved. // import UIKit class Tutorial2ViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var word1: UILabel! @IBOutlet weak var word2: UILabel! @IBOutlet weak var word3: UILabel! @IBOutlet weak var word4: UILabel! @IBOutlet weak var tutorialLabel: UILabel! @IBOutlet weak var score: UILabel! @IBOutlet weak var countdown: UILabel! @IBOutlet weak var heart1: UIImageView! @IBOutlet weak var heart2: UIImageView! @IBOutlet weak var heart3: UIImageView! @IBOutlet weak var auxiliarView1: UIView! @IBOutlet weak var auxiliarView2: UIView! override func viewDidLoad() { super.viewDidLoad() //Set background image as newspaper self.view.backgroundColor = Styles.backgroundColor word1.font = Styles.getFont() word2.font = Styles.getFont() word3.font = Styles.getFont() word4.font = Styles.getFont() tutorialLabel.font = Styles.getFont() //Set Hearts heart1.image = heart1.image!.withRenderingMode(UIImageRenderingMode.alwaysTemplate) heart1.tintColor = Styles.heartColor heart2.image = heart1.image!.withRenderingMode(UIImageRenderingMode.alwaysTemplate) heart2.tintColor = Styles.heartColor heart3.image = heart1.image!.withRenderingMode(UIImageRenderingMode.alwaysTemplate) heart3.tintColor = Styles.heartColor //Buttons border word1.layer.borderWidth = 0 word2.layer.borderWidth = 0 word3.layer.borderWidth = 0 word4.layer.borderWidth = 0 word1.layer.cornerRadius = word1.frame.height/4 word1.layer.masksToBounds = true word2.layer.cornerRadius = word2.frame.height/4 word2.layer.masksToBounds = true word3.layer.cornerRadius = word3.frame.height/4 word3.layer.masksToBounds = true word4.layer.cornerRadius = word4.frame.height/4 word4.layer.masksToBounds = true score.font = Styles.getFont() let attributedString2 = NSMutableAttributedString(string:"pontos", attributes:Styles.attributesScore) let attributedString3 = NSMutableAttributedString(string:" antes que o ") let attributedString4 = NSMutableAttributedString(string:"tempo", attributes:Styles.attributesTime) let attributedString5 = NSMutableAttributedString(string:" acabe.") let finalString = NSMutableAttributedString(string:"Faça o maior número de ") finalString.append(attributedString2) finalString.append(attributedString3) finalString.append(attributedString4) finalString.append(attributedString5) //tutorialLabel.attributedText = ProjectStrings.instructionString2 tutorialLabel.text = ProjectStrings.instructionString2 tutorialLabel.layer.borderWidth = 0 tutorialLabel.layer.cornerRadius = tutorialLabel.frame.height/4 tutorialLabel.layer.masksToBounds = true auxiliarView1.layer.cornerRadius = auxiliarView1.frame.height/4 auxiliarView1.layer.masksToBounds = true auxiliarView1.alpha = 0.3 auxiliarView2.layer.cornerRadius = auxiliarView2.frame.height/4 auxiliarView2.layer.masksToBounds = true auxiliarView2.alpha = 0.3 } override func viewDidAppear(_ animated: Bool) { UIView.animate(withDuration: 1.3, delay: 0, options: .repeat, animations: { () -> Void in self.auxiliarView1.alpha = 0.5 self.auxiliarView2.alpha = 0.5 }, completion: {(result) -> Void in UIView.animate(withDuration: 1.3, animations: { () -> Void in self.auxiliarView1.alpha = 0 self.countdown.textColor = UIColor.white self.auxiliarView2.alpha = 0 self.countdown.textColor = UIColor.white }) }) //End of completion } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func tapReceived(_ sender: AnyObject) { performSegue(withIdentifier: "toTutorial3ViewController", sender: self) } }
gpl-3.0
3608278ed70601cc8d2f22b71a5f7327
34.160305
109
0.637429
4.85865
false
false
false
false
AboutObjectsTraining/swift-comp-reston-2017-02
ReadingListModel/ReadingListStore.swift
2
1879
// // Copyright (C) 2014 About Objects, Inc. All Rights Reserved. // See LICENSE.txt for this example's licensing information. // import Foundation let documentsURLs = FileManager.default.urls( for: FileManager.SearchPathDirectory.documentDirectory, in: FileManager.SearchPathDomainMask.userDomainMask) // MARK: - File Utilities func fileURLForDocument(_ name: String, type: String) -> URL { precondition(!documentsURLs.isEmpty, "Documents directory must exist.") let fileURL = documentsURLs.first! return fileURL.appendingPathComponent(name).appendingPathExtension(type) } // MARK: - ReadingListStore open class ReadingListStore : NSObject { let storeType = "plist" let storeName: String let documentURL: URL public init(_ storeName: String) { self.storeName = storeName documentURL = fileURLForDocument(storeName, type: storeType) super.init() } open func fetchReadingList() -> ReadingList { if FileManager.default.fileExists(atPath: documentURL.path), let dict = NSDictionary(contentsOf: documentURL) as? [String: AnyObject] { return ReadingList(dictionary: dict) } let bundle = Bundle(for: ReadingListStore.self) guard let URL = bundle.url(forResource: storeName, withExtension: storeType) else { fatalError("Unable to locate \(storeName) in app bundle") } guard let dict = NSDictionary(contentsOf: URL) as? [String: AnyObject] else { fatalError("Unable to load \(storeName) with bundle URL \(URL)") } return ReadingList(dictionary: dict) } open func saveReadingList(_ readingList: ReadingList) { let dict = readingList.dictionaryRepresentation() as NSDictionary dict.write(to: documentURL, atomically: true) } }
mit
94b25a679894eeffeb0aaa2c4af302f3
29.803279
91
0.673763
4.842784
false
false
false
false
MounikaAnkam/DrawingAssignment
Drawing Assignment/hillsView.swift
1
880
// // hillsView.swift // Drawing Assignment // // Created by Mounika Ankamon 4/3/15. // Copyright (c) 2015 Mounika Ankam. All rights reserved. // import UIKit class hillsView: UIView { // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { var bPath = UIBezierPath() bPath.moveToPoint(CGPoint(x: 0, y: 300)) var count = 250 for J in 1...6 { bPath.addLineToPoint(CGPoint(x: J*62, y: count)) if count == 250 { count = count + 50 }else{ count = 250 } } bPath.lineWidth = 6.0 bPath.stroke() } }
mit
493d0886d52fd92a1dcf74f301a7cc45
22.157895
78
0.494318
4.422111
false
false
false
false
RevenueCat/purchases-ios
Sources/Misc/MacDevice.swift
1
3106
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // MacDevice.swift // // Created by Juanpe Catalán on 30/11/21. #if os(macOS) || targetEnvironment(macCatalyst) import Foundation #if canImport(IOKit) import IOKit #endif enum MacDevice { // Based on Apple's documentation, the mac address must // be used to validate receipts. // https://developer.apple.com/documentation/appstorereceipts/validating_receipts_on_the_device static var identifierForVendor: UUID? { networkInterfaceMacAddressData?.uuid } static var networkInterfaceMacAddressData: Data? { #if canImport(IOKit) guard let service = getIOService(named: "en0", wantBuiltIn: true) ?? getIOService(named: "en1", wantBuiltIn: true) ?? getIOService(named: "en0", wantBuiltIn: false) else { return nil } defer { IOObjectRelease(service) } return IORegistryEntrySearchCFProperty( service, kIOServicePlane, "IOMACAddress" as CFString, kCFAllocatorDefault, IOOptionBits(kIORegistryIterateRecursively | kIORegistryIterateParents) ) as? Data #else return nil #endif } #if canImport(IOKit) static private func getIOService(named name: String, wantBuiltIn: Bool) -> io_service_t? { // 0 is `kIOMasterPortDefault` / `kIOMainPortDefault`, but the first is deprecated // And the second isn't available in Catalyst on Xcode 14. let defaultPort: mach_port_t = 0 var iterator = io_iterator_t() defer { if iterator != IO_OBJECT_NULL { IOObjectRelease(iterator) } } guard let matchingDict = IOBSDNameMatching(defaultPort, 0, name), IOServiceGetMatchingServices(defaultPort, matchingDict as CFDictionary, &iterator) == KERN_SUCCESS, iterator != IO_OBJECT_NULL else { return nil } var candidate = IOIteratorNext(iterator) while candidate != IO_OBJECT_NULL { if let cftype = IORegistryEntryCreateCFProperty(candidate, "IOBuiltin" as CFString, kCFAllocatorDefault, 0) { // swiftlint:disable:next force_cast let isBuiltIn = cftype.takeRetainedValue() as! CFBoolean if wantBuiltIn == CFBooleanGetValue(isBuiltIn) { return candidate } } IOObjectRelease(candidate) candidate = IOIteratorNext(iterator) } return nil } #endif } #endif
mit
43833d3ed8d36a9d53b5735741e27788
31.684211
99
0.568116
4.806502
false
false
false
false
visenze/visearch-widget-swift
ViSearchWidgets/ViSearchWidgets/Models/ViImageConfig.swift
2
1318
// // ViImageConfig.swift // ViSearchWidgets // // Created by Hung on 9/11/16. // Copyright © 2016 Visenze. All rights reserved. // import UIKit /// Configuration for product image public struct ViImageConfig { /// image size public var size: CGSize /// image view content mode public var contentMode: UIViewContentMode /// loading image public var loadingImg: UIImage? /// error image if network fails or broken link public var errImg: UIImage? /// init image config /// /// - Parameters: /// - size: image size /// - contentMode: content mode for uiimageview /// - loadingImg: loading image /// - errImg: error image public init( size: CGSize = CGSize(width: 150 , height: 240), contentMode: UIViewContentMode = ViImageConfig.default_content_mode, loadingImg: UIImage? = nil, errImg: UIImage? = nil){ // TODO: add configuration for loading image animation later e.g. fading self.size = size self.contentMode = contentMode self.loadingImg = loadingImg self.errImg = errImg } /// Default image view content mode public static var default_content_mode : UIViewContentMode = .scaleToFill }
mit
6d357f2fead1dafebde6140389c697b9
25.877551
85
0.613516
4.621053
false
true
false
false
Friend-LGA/LGSideMenuController
LGSideMenuController/LGSideMenuController.swift
1
111549
// // LGSideMenuController.swift // LGSideMenuController // // // The MIT License (MIT) // // Copyright © 2015 Grigorii Lutkov <[email protected]> // (https://github.com/Friend-LGA/LGSideMenuController) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation import CoreGraphics import QuartzCore import UIKit open class LGSideMenuController: UIViewController, UIGestureRecognizerDelegate { public typealias Completion = () -> Void public typealias Callback = (LGSideMenuController) -> Void public typealias AnimationsCallback = (LGSideMenuController, TimeInterval, CAMediaTimingFunction) -> Void public typealias TransformCallback = (LGSideMenuController, CGFloat) -> Void /// Notification names and keys to observe behaviour of LGSideMenuController public struct Notification { public static let willShowLeftView = NSNotification.Name("LGSideMenuController.Notification.willShowLeftView") public static let didShowLeftView = NSNotification.Name("LGSideMenuController.Notification.didShowLeftView") public static let willHideLeftView = NSNotification.Name("LGSideMenuController.Notification.willHideLeftView") public static let didHideLeftView = NSNotification.Name("LGSideMenuController.Notification.didHideLeftView") public static let willShowRightView = NSNotification.Name("LGSideMenuController.Notification.willShowRightView") public static let didShowRightView = NSNotification.Name("LGSideMenuController.Notification.didShowRightView") public static let willHideRightView = NSNotification.Name("LGSideMenuController.Notification.willHideRightView") public static let didHideRightView = NSNotification.Name("LGSideMenuController.Notification.didHideRightView") /// This notification is posted inside animation block for showing left view. /// You can retrieve duration and timing function of the animation from userInfo dictionary. /// Use it to add some custom animations. public static let showAnimationsForLeftView = NSNotification.Name("LGSideMenuController.Notification.showAnimationsForLeftView") /// This notification is posted inside animation block for hiding left view. /// You can retrieve duration and timing function of the animation from userInfo dictionary. /// Use it to add some custom animations. public static let hideAnimationsForLeftView = NSNotification.Name("LGSideMenuController.Notification.hideAnimationsForLeftView") /// This notification is posted inside animation block for showing right view. /// You can retrieve duration and timing function of the animation from userInfo dictionary. /// Use it to add some custom animations. public static let showAnimationsForRightView = NSNotification.Name("LGSideMenuController.Notification.showAnimationsForRightView") /// This notification is posted inside animation block for hiding right view. /// You can retrieve duration and timing function of the animation from userInfo dictionary. /// Use it to add some custom animations. public static let hideAnimationsForRightView = NSNotification.Name("LGSideMenuController.Notification.hideAnimationsForRightView") /// This notification is posted on every transformation of root view during showing/hiding of side views. /// You can retrieve percentage between `0.0` and `1.0` from userInfo dictionary, where /// - `0.0` - view is fully shown /// - `1.0` - view is fully hidden public static let didTransformRootView = NSNotification.Name("LGSideMenuController.Notification.didTransformRootView") /// This notification is posted on every transformation of left view during showing/hiding. /// You can retrieve percentage between `0.0` and `1.0` from userInfo dictionary, where /// - `0.0` - view is fully hidden /// - `1.0` - view is fully shown public static let didTransformLeftView = NSNotification.Name("LGSideMenuController.Notification.didTransformLeftView") /// This notification is posted on every transformation of right view during showing/hiding. /// You can retrieve percentage between `0.0` and `1.0` from userInfo dictionary, where /// - `0.0` - view is fully hidden /// - `1.0` - view is fully shown public static let didTransformRightView = NSNotification.Name("LGSideMenuController.Notification.didTransformRightView") /// Key names to retrieve data from userInfo dictionary passed with notification. public struct Key { /// Key for userInfo dictionary which represents duration of the animation. static let duration = "duration" /// Key for userInfo dictionary which represents timing function of the animation. static let timigFunction = "timigFunction" /// Key for userInfo dictionary which represents current transformation percentage. static let percentage = "percentage" } } /// Options which determine when side view should be always visible. /// For example you might want to always show side view on iPad with landscape orientation. public struct AlwaysVisibleOptions: OptionSet { public let rawValue: Int public static let padLandscape = AlwaysVisibleOptions(rawValue: 1 << 0) public static let padPortrait = AlwaysVisibleOptions(rawValue: 1 << 1) public static let phoneLandscape = AlwaysVisibleOptions(rawValue: 1 << 2) public static let phonePortrait = AlwaysVisibleOptions(rawValue: 1 << 3) /// Based on horizontalSizeClass of current traitCollection. public static let padRegular = AlwaysVisibleOptions(rawValue: 1 << 4) /// Based on horizontalSizeClass of current traitCollection. public static let padCompact = AlwaysVisibleOptions(rawValue: 1 << 5) /// Based on horizontalSizeClass of current traitCollection. public static let phoneRegular = AlwaysVisibleOptions(rawValue: 1 << 6) /// Based on horizontalSizeClass of current traitCollection. public static let phoneCompact = AlwaysVisibleOptions(rawValue: 1 << 7) public static let landscape: AlwaysVisibleOptions = [.padLandscape, .phoneLandscape] public static let portrait: AlwaysVisibleOptions = [.padPortrait, .phonePortrait] /// Based on horizontalSizeClass of current traitCollection. public static let regular: AlwaysVisibleOptions = [.padRegular, .phoneRegular] /// Based on horizontalSizeClass of current traitCollection. public static let compact: AlwaysVisibleOptions = [.padCompact, .phoneCompact] public static let pad: AlwaysVisibleOptions = [.padLandscape, .padPortrait, .padRegular, .padCompact] public static let phone: AlwaysVisibleOptions = [.phoneLandscape, .phonePortrait, .phoneRegular, .phoneCompact] public static let all: AlwaysVisibleOptions = [.pad, .phone] public init(rawValue: Int = 0) { self.rawValue = rawValue } public func isVisible(sizeClass: UIUserInterfaceSizeClass) -> Bool { guard let orientation = LGSideMenuHelper.getInterfaceOrientation() else { return false } return isVisible(orientation: orientation, sizeClass: sizeClass) } public func isVisible(orientation: UIInterfaceOrientation, sizeClass: UIUserInterfaceSizeClass) -> Bool { if LGSideMenuHelper.isPad() { if orientation.isLandscape && contains(.padLandscape) { return true } if orientation.isPortrait && contains(.padPortrait) { return true } if sizeClass == .regular && contains(.padRegular) { return true } if sizeClass == .compact && contains(.padCompact) { return true } } if LGSideMenuHelper.isPhone() { if orientation.isLandscape && contains(.phoneLandscape) { return true } if orientation.isPortrait && contains(.phonePortrait) { return true } if sizeClass == .regular && contains(.phoneRegular) { return true } if sizeClass == .compact && contains(.phoneCompact) { return true } } return false } } /// Default styles to present side views public enum PresentationStyle { /// Side view is located below the root view and when appearing is changing its scale from large to normal. /// Root view also is going to be minimized and moved aside. case scaleFromBig /// Side view is located below the root view and when appearing is changing its scale from small to normal. /// Root view also is going to be minimized and moved aside. case scaleFromLittle /// Side view is located above the root view and when appearing is sliding from a side. /// Root view is staying still. case slideAbove /// Side view is located above the root view and when appearing is sliding from a side. /// Root view is staying still. /// Side view has blurred background. case slideAboveBlurred /// Side view is located below the root view. /// Root view is going to be moved aside. case slideBelow /// Side view is located below the root view. /// Root view is going to be moved aside. /// Also content of the side view has extra shifting. case slideBelowShifted /// Side view is located at the same level as root view and when appearing is sliding from a side. /// Root view is going to be moved together with the side view. case slideAside public init() { self = .slideAbove } /// Tells if a side view is located above the root view. public var isAbove: Bool { return self == .slideAbove || self == .slideAboveBlurred } /// Tells if a side view is located below the root view. public var isBelow: Bool { return self == .slideBelow || self == .slideBelowShifted || self == .scaleFromBig || self == .scaleFromLittle } /// Tells if a side view is located on the same level as the root view. public var isAside: Bool { return self == .slideAside } /// Tells if a side view is appearing from a side. public var isHiddenAside: Bool { return self == .slideAbove || self == .slideAboveBlurred || self == .slideAside } /// Tells if a side view width needs to take whole space of the container. public var isWidthFull: Bool { return self == .slideBelow || self == .slideBelowShifted || self == .scaleFromBig || self == .scaleFromLittle } /// Tells if a side view width needs to take only necessary space. public var isWidthCompact: Bool { return self == .slideAbove || self == .slideAboveBlurred || self == .slideAside } /// Tells if the root view is going to move. public var shouldRootViewMove: Bool { return self == .slideBelow || self == .slideBelowShifted || self == .slideAside || self == .scaleFromBig || self == .scaleFromLittle } /// Tells if the root view is going to change its scale. public var shouldRootViewScale: Bool { return self == .scaleFromBig || self == .scaleFromLittle } } /// The area which should be responsive to gestures. public enum SwipeGestureArea { /// When root view is opened then gestures are going to work only at the edges of the root view. /// When root view is hidden by the side view, whole root view is responsive to gestures. case borders /// Whole root view is always responsive to gestures. case full public init() { self = .borders } } /// When `SwipeGestureArea` is `borders` this range is used to determine the area around borders of the root view, /// which should be responsive to gestures. /// When `SwipeGestureArea` is `full` this range is used to determine only the outside area around borders of the root view, /// which should be responsive to gestures. public struct SwipeGestureRange { /// Distance to the left side from an edge of the root view public let left: CGFloat /// Distance to the right side from an edge of the root view public let right: CGFloat public init(left: CGFloat = 44.0, right: CGFloat = 44.0) { self.left = left self.right = right } } /// Needs to keep internal state of LGSideMenuController. /// Describes which view is showing/hidden or is going to be shown/hidden public enum State { case rootViewIsShowing case leftViewWillShow case leftViewIsShowing case leftViewWillHide case rightViewWillShow case rightViewIsShowing case rightViewWillHide public init() { self = .rootViewIsShowing } public var isLeftViewVisible: Bool { return self == .leftViewIsShowing || self == .leftViewWillShow || self == .leftViewWillHide } public var isRightViewVisible: Bool { return self == .rightViewIsShowing || self == .rightViewWillShow || self == .rightViewWillHide } public var isRootViewHidden: Bool { return self == .leftViewIsShowing || self == .rightViewIsShowing } public var isLeftViewHidden: Bool { return !isLeftViewVisible } public var isRightViewHidden: Bool { return !isRightViewVisible } } // MARK: - Base View Controllers - /// Main view controller which view is presented as the root view. /// User needs to provide this view controller. /// - Note: /// - Either one of the properties can be used at a time: `rootViewController` or `rootView`. /// - If `rootViewController` is assigned, then `rootView` will return `rootViewController.view`. open var rootViewController: UIViewController? { set { removeViewController(_rootViewController) _rootViewController = newValue _rootView?.removeFromSuperview() _rootView = nil guard let viewController = _rootViewController else { removeRootViews() return } _rootView = viewController.view LGSideMenuHelper.setSideMenuController(self, to: viewController) setNeedsUpdateRootViewLayoutsAndStyles() } get { if _rootViewController == nil && storyboard != nil { tryPerformRootSegueIfNeeded() } return _rootViewController } } private var _rootViewController: UIViewController? = nil /// View controller which view is presented as the left side view. /// User needs to provide this view controller. /// - Note: /// - Either one of the properties can be used at a time: `leftViewController` or `leftView`. /// - If `leftViewController` is assigned, then `leftView` will return `leftViewController.view`. open var leftViewController: UIViewController? { set { removeViewController(_leftViewController) _leftViewController = newValue _leftView?.removeFromSuperview() _leftView = nil guard let viewController = _leftViewController else { removeLeftViews() return } _leftView = viewController.view LGSideMenuHelper.setSideMenuController(self, to: viewController) setNeedsUpdateLeftViewLayoutsAndStyles() } get { if _leftViewController == nil && storyboard != nil { tryPerformLeftSegueIfNeeded() } return _leftViewController } } private var _leftViewController: UIViewController? = nil /// View controller which view is presented as the right side view. /// User needs to provide this view controller. /// - Note: /// - Either one of the properties can be used at a time: `rightViewController` or `rightView`. /// - If `rightViewController` is assigned, then `rightView` will return `rightViewController.view`. open var rightViewController: UIViewController? { set { removeViewController(_rightViewController) _rightViewController = newValue _rightView?.removeFromSuperview() _rightView = nil guard let viewController = _rightViewController else { removeRightViews() return } _rightView = viewController.view LGSideMenuHelper.setSideMenuController(self, to: viewController) setNeedsUpdateRightViewLayoutsAndStyles() } get { if _rightViewController == nil && storyboard != nil { tryPerformRightSegueIfNeeded() } return _rightViewController } } private var _rightViewController: UIViewController? = nil // MARK: - Base Views - /// View which is presented as the root view. /// User needs to provide this view. /// - Note: /// - Either one of the properties can be used at a time: `rootViewController` or `rootView`. /// - If `rootViewController` is assigned, then `rootView` will return `rootViewController.view`. open var rootView: UIView? { set { _rootView?.removeFromSuperview() _rootView = newValue removeViewController(_rootViewController) _rootViewController = nil guard _rootView != nil else { removeRootViews() return } setNeedsUpdateRootViewLayoutsAndStyles() } get { return _rootView } } private var _rootView: UIView? = nil /// View which is presented as the left side view. /// User needs to provide this view. /// - Note: /// - Either one of the properties can be used at a time: `leftViewController` or `leftView`. /// - If `leftViewController` is assigned, then `leftView` will return `leftViewController.view`. open var leftView: UIView? { set { _leftView?.removeFromSuperview() _leftView = newValue removeViewController(_leftViewController) _leftViewController = nil guard _leftView != nil else { removeLeftViews() return } setNeedsUpdateLeftViewLayoutsAndStyles() } get { return _leftView } } private var _leftView: UIView? = nil /// View which is presented as the right side view. /// User needs to provide this view. /// - Note: /// - Either one of the properties can be used at a time: `rightViewController` or `rightView`. /// - If `rightViewController` is assigned, then `rightView` will return `rightViewController.view`. open var rightView: UIView? { set { _rightView?.removeFromSuperview() _rightView = newValue removeViewController(_rightViewController) _rightViewController = nil guard _rightView != nil else { removeRightViews() return } setNeedsUpdateRightViewLayoutsAndStyles() } get { return _rightView } } private var _rightView: UIView? = nil // MARK: - Gestures - /// Gesture recognizer which is used to handle tap gestures on the rootView when it is hidden to close any opened side view. /// Usually shouldn't be manipulated by user. public let tapGesture: UITapGestureRecognizer /// Gesture recognizer which is used to handle pan gestures on the rootView to show and hide left side views. /// Usually shouldn't be manipulated by user. public let panGestureForLeftView: UIPanGestureRecognizer /// Gesture recognizer which is used to handle pan gestures on the rootView to show and hide right side views. /// Usually shouldn't be manipulated by user. public let panGestureForRightView: UIPanGestureRecognizer // MARK: - Side Views Availability - /// Use this property when you want to temporarily disable left side view. /// When view is disabled, it won't respond to gestures and show/hide requests. @IBInspectable open var isLeftViewEnabled: Bool = true /// Use this property when you want to temporarily disable right side view. /// When view is disabled, it won't respond to gestures and show/hide requests. @IBInspectable open var isRightViewEnabled: Bool = true /// Use this property when you want to temporarily disable left side view. /// When view is disabled, it won't respond to gestures and show/hide requests. open var isLeftViewDisabled: Bool { set { self.isLeftViewEnabled = !newValue } get { return !isLeftViewEnabled } } /// Use this property when you want to temporarily disable right side view. /// When view is disabled, it won't respond to gestures and show/hide requests. open var isRightViewDisabled: Bool { set { self.isRightViewEnabled = !newValue } get { return !isRightViewEnabled } } // MARK: - Width - /// Basic property to determine width of the left side view. /// User assignable. /// - Returns: Default: /// - `min(ScreenSize.minSide - 44.0, 320.0)` @IBInspectable open var leftViewWidth: CGFloat = { let minScreenSide = min(UIScreen.main.bounds.width, UIScreen.main.bounds.height) return min(minScreenSide - 44.0, 320.0) }() { didSet { setNeedsUpdateLayoutsAndStyles() } } /// Basic property to determine width of the right side view. /// User assignable. /// - Returns: Default: /// - `min(ScreenSize.minSide - 44.0, 320.0)` @IBInspectable open var rightViewWidth: CGFloat = { let minScreenSide = min(UIScreen.main.bounds.width, UIScreen.main.bounds.height) return min(minScreenSide - 44.0, 320.0) }() { didSet { setNeedsUpdateLayoutsAndStyles() } } // MARK: - Presentation Style - /// Basic property to determine style of left side view presentation. User assignable. open var leftViewPresentationStyle: PresentationStyle = .slideAbove { didSet { setNeedsUpdateLayoutsAndStyles() } } /// Basic property to determine style of right side view presentation. User assignable. open var rightViewPresentationStyle: PresentationStyle = .slideAbove { didSet { setNeedsUpdateLayoutsAndStyles() } } // MARK: - Always Visible Options - /// Options which determine when the left side view should be always visible. /// For example you might want to always show side view on iPad with landscape orientation. open var leftViewAlwaysVisibleOptions: AlwaysVisibleOptions = [] { didSet { setNeedsUpdateLayoutsAndStyles() } } /// Options which determine when the right side view should be always visible. /// For example you might want to always show side view on iPad with landscape orientation. open var rightViewAlwaysVisibleOptions: AlwaysVisibleOptions = [] { didSet { setNeedsUpdateLayoutsAndStyles() } } // MARK: - Gestures Availability - /// Set it to true to be able to hide left view without animation by touching root view. @IBInspectable open var shouldLeftViewHideOnTouch: Bool = true /// Set it to true to be able to hide right view without animation by touching root view. @IBInspectable open var shouldRightViewHideOnTouch: Bool = true /// Set it to true to be able to hide left view with animation by touching root view. @IBInspectable open var shouldLeftViewHideOnTouchAnimated: Bool = true /// Set it to true to be able to hide right view with animation by touching root view. @IBInspectable open var shouldRightViewHideOnTouchAnimated: Bool = true /// Use this property to disable pan gestures to show/hide left side view. @IBInspectable open var isLeftViewSwipeGestureEnabled: Bool = true /// Use this property to disable pan gestures to show/hide right side view. @IBInspectable open var isRightViewSwipeGestureEnabled: Bool = true /// Use this property to disable pan gestures to show/hide left side view. open var isLeftViewSwipeGestureDisabled: Bool { set { self.isLeftViewSwipeGestureEnabled = !newValue } get { return !isLeftViewSwipeGestureEnabled } } /// Use this property to disable pan gestures to show/hide right side view. open var isRightViewSwipeGestureDisabled: Bool { set { self.isRightViewSwipeGestureEnabled = !newValue } get { return !isRightViewSwipeGestureEnabled } } // MARK: - Swipe Gesture Area - /// The area which should be responsive to pan gestures to show/hide left side view. open var leftViewSwipeGestureArea: SwipeGestureArea = .borders /// The area which should be responsive to pan gestures to show/hide right side view. open var rightViewSwipeGestureArea: SwipeGestureArea = .borders // MARK: - Swipe Gesture Range - /// This range is used to determine the area around left border of the root view, /// which should be responsive to gestures. /// - Description: /// - For `SwipeGestureRange(left: 44.0, right: 44.0)` => leftView 44.0 | 44.0 rootView. /// - For `SwipeGestureRange(left: 0.0, right: 44.0)` => leftView 0.0 | 44.0 rootView. /// - For `SwipeGestureRange(left: 44.0, right: 0.0)` => leftView 44.0 | 0.0 rootView. /// - Note: /// - if `leftSwipeGestureArea == .full` then right part is ignored. open var leftViewSwipeGestureRange = SwipeGestureRange(left: 0.0, right: 44.0) /// This range is used to determine the area around right border of the root view, /// which should be responsive to gestures. /// - Description: /// - For `SwipeGestureRange(left: 44.0, right: 44.0)` => rootView 44.0 | 44.0 rightView. /// - For `SwipeGestureRange(left: 0.0, right: 44.0)` => rootView 0.0 | 44.0 rightView. /// - For `SwipeGestureRange(left: 44.0, right: 0.0)` => rootView 44.0 | 0.0 rightView. /// - Note: /// - if `rightSwipeGestureArea == .full` then left part is ignored. open var rightViewSwipeGestureRange = SwipeGestureRange(left: 44.0, right: 0.0) // MARK: - Animations Properties - /// Duration of the animation to show/hide left side view. @IBInspectable open var leftViewAnimationDuration: TimeInterval = 0.45 /// Duration of the animation to show/hide right side view. @IBInspectable open var rightViewAnimationDuration: TimeInterval = 0.45 /// Timing Function to describe animation to show/hide left side view. @IBInspectable open var leftViewAnimationTimingFunction = CAMediaTimingFunction(controlPoints: 0.33333, 0.66667, 0.33333, 1.0) /// Timing Function to describe animation to show/hide right side view. @IBInspectable open var rightViewAnimationTimingFunction = CAMediaTimingFunction(controlPoints: 0.33333, 0.66667, 0.33333, 1.0) // MARK: - Background Color - /// Color for the background view, located behind the root view. /// - Note: /// - Not equal to `rootView.backgroundColor`. @IBInspectable open var rootViewBackgroundColor: UIColor = .clear { didSet { setNeedsUpdateLayoutsAndStyles() } } /// Color for the background view, located behind the left side view. /// - Note: /// - Not equal to `leftView.backgroundColor`. @IBInspectable open var leftViewBackgroundColor: UIColor = .clear { didSet { setNeedsUpdateLayoutsAndStyles() } } /// Color for the background view, located behind the right side view. /// - Note: /// - Not equal to `rightView.backgroundColor`. @IBInspectable open var rightViewBackgroundColor: UIColor = .clear { didSet { setNeedsUpdateLayoutsAndStyles() } } // MARK: - Background View - /// Use this property to provide custom background view, located behind the left side view. /// - Note: /// - Can't be used together with `leftViewBackgroundImage`. @IBInspectable open var leftViewBackgroundView: UIView? { willSet { if newValue == nil { leftViewBackgroundView?.removeFromSuperview() } } didSet { if leftViewBackgroundView != nil { leftViewBackgroundImage = nil } setNeedsUpdateLayoutsAndStyles() } } /// Use this property to provide custom background view, located behind the right side view. /// - Note: /// - Can't be used together with `rightViewBackgroundImage`. @IBInspectable open var rightViewBackgroundView: UIView? { willSet { if newValue == nil { rightViewBackgroundView?.removeFromSuperview() } } didSet { if rightViewBackgroundView != nil { rightViewBackgroundImage = nil } setNeedsUpdateLayoutsAndStyles() } } // MARK: - Background Image - /// Use this property to provide custom background image, located behind the left side view. /// - Note: /// - Can't be used together with `leftViewBackgroundView`. @IBInspectable open var leftViewBackgroundImage: UIImage? { willSet { if newValue == nil, let leftViewBackgroundImageView = self.leftViewBackgroundImageView { leftViewBackgroundImageView.removeFromSuperview() self.leftViewBackgroundImageView = nil } } didSet { if leftViewBackgroundImage != nil, let leftViewBackgroundView = self.leftViewBackgroundView { leftViewBackgroundView.removeFromSuperview() self.leftViewBackgroundView = nil } setNeedsUpdateLayoutsAndStyles() } } /// Use this property to provide custom background image, located behind the right side view. /// - Note: /// - Can't be used together with `rightViewBackgroundView`. @IBInspectable open var rightViewBackgroundImage: UIImage? { willSet { if newValue == nil, let rightViewBackgroundImageView = self.rightViewBackgroundImageView { rightViewBackgroundImageView.removeFromSuperview() self.rightViewBackgroundImageView = nil } } didSet { if rightViewBackgroundImage != nil, let rightViewBackgroundView = self.rightViewBackgroundView { rightViewBackgroundView.removeFromSuperview() self.rightViewBackgroundView = nil } setNeedsUpdateLayoutsAndStyles() } } // MARK: - Background Blur Effect - /// Use this property to set `UIBlurEffect` for background view, located behind the left side view. /// - Returns: Default: /// - `.regular` if `presentationStyle == .slideAboveBlurred` /// - `nil` otherwise @IBInspectable open var leftViewBackgroundBlurEffect: UIBlurEffect? { set { _leftViewBackgroundBlurEffect = newValue _isLeftViewBackgroundBlurEffectAssigned = true } get { if _isLeftViewBackgroundBlurEffectAssigned { return _leftViewBackgroundBlurEffect } if leftViewPresentationStyle == .slideAboveBlurred { if #available(iOS 10.0, *) { return UIBlurEffect(style: .regular) } else { return UIBlurEffect(style: .light) } } return nil } } private var _leftViewBackgroundBlurEffect: UIBlurEffect? private var _isLeftViewBackgroundBlurEffectAssigned: Bool = false /// Use this property to set `UIBlurEffect` for background view, located behind the right side view. /// - Returns: Default: /// - `.regular` if `presentationStyle == .slideAboveBlurred` /// - `nil` otherwise @IBInspectable open var rightViewBackgroundBlurEffect: UIBlurEffect? { set { _rightViewBackgroundBlurEffect = newValue _isRightViewBackgroundBlurEffectAssigned = true } get { if _isRightViewBackgroundBlurEffectAssigned { return _rightViewBackgroundBlurEffect } if rightViewPresentationStyle == .slideAboveBlurred { if #available(iOS 10.0, *) { return UIBlurEffect(style: .regular) } else { return UIBlurEffect(style: .light) } } return nil } } private var _rightViewBackgroundBlurEffect: UIBlurEffect? private var _isRightViewBackgroundBlurEffectAssigned: Bool = false // MARK: - Background Alpha - /// Use this property to set `alpha` for background view, located behind the left side view. @IBInspectable open var leftViewBackgroundAlpha: CGFloat = 1.0 /// Use this property to set `alpha` for background view, located behind the left side view. @IBInspectable open var rightViewBackgroundAlpha: CGFloat = 1.0 // MARK: - Layer Border Color - /// Use this property to decorate the root view with border. /// - Note: /// - Make sense only together with `rootViewLayerBorderWidth` @IBInspectable open var rootViewLayerBorderColor: UIColor? /// Use this property to decorate the root view with border, /// which is visible only when the left side view is showing. /// - Returns: Default: /// - `rootViewLayerBorderColor` if assigned /// - `.clear` otherwise /// - Note: /// - Make sense only together with `rootViewLayerBorderWidthForLeftView` @IBInspectable open var rootViewLayerBorderColorForLeftView: UIColor { set { _rootViewLayerBorderColorForLeftView = newValue } get { if let rootViewLayerBorderColorForLeftView = _rootViewLayerBorderColorForLeftView { return rootViewLayerBorderColorForLeftView } if let rootViewLayerBorderColorForLeftView = rootViewLayerBorderColor { return rootViewLayerBorderColorForLeftView } return .clear } } private var _rootViewLayerBorderColorForLeftView: UIColor? /// Use this property to decorate the root view with border, /// which is visible only when the right side view is showing. /// - Returns: Default: /// - `rootViewLayerBorderColor` if assigned /// - `.clear` otherwise /// - Note: /// - Make sense only together with `rootViewLayerBorderWidthForRightView` @IBInspectable open var rootViewLayerBorderColorForRightView: UIColor { set { _rootViewLayerBorderColorForRightView = newValue } get { if let rootViewLayerBorderColorForRightView = _rootViewLayerBorderColorForRightView { return rootViewLayerBorderColorForRightView } if let rootViewLayerBorderColorForRightView = rootViewLayerBorderColor { return rootViewLayerBorderColorForRightView } return .clear } } private var _rootViewLayerBorderColorForRightView: UIColor? /// Use this property to decorate the left side view with border. /// - Note: /// - Make sense only together with `leftViewLayerBorderWidth` @IBInspectable open var leftViewLayerBorderColor: UIColor = .clear /// Use this property to decorate the right side view with border. /// - Note: /// - Make sense only together with `rightViewLayerBorderWidth` @IBInspectable open var rightViewLayerBorderColor: UIColor = .clear // MARK: - Layer Border Width - /// Use this property to decorate the root view with border. /// - Note: /// - Make sense only together with `rootViewLayerBorderColor` open var rootViewLayerBorderWidth: CGFloat? /// Use this property to decorate the root view with border, /// which is visible only when the left side view is showing. /// - Returns: Default: /// - `rootViewLayerBorderWidth` if assigned /// - `0.0` otherwise /// - Note: /// - Make sense only together with `rootViewLayerBorderColorForLeftView` @IBInspectable open var rootViewLayerBorderWidthForLeftView: CGFloat { set { _rootViewLayerBorderWidthForLeftView = newValue } get { if let rootViewLayerBorderWidthForLeftView = _rootViewLayerBorderWidthForLeftView { return rootViewLayerBorderWidthForLeftView } if let rootViewLayerBorderWidthForLeftView = rootViewLayerBorderWidth { return rootViewLayerBorderWidthForLeftView } return 0.0 } } private var _rootViewLayerBorderWidthForLeftView: CGFloat? /// Use this property to decorate the root view with border, /// which is visible only when the right side view is showing. /// - Returns: Default: /// - `rootViewLayerBorderWidth` if assigned /// - `0.0` otherwise /// - Note: /// - Make sense only together with `rootViewLayerBorderColorForRightView` @IBInspectable open var rootViewLayerBorderWidthForRightView: CGFloat { set { _rootViewLayerBorderWidthForRightView = newValue } get { if let rootViewLayerBorderWidthForRightView = _rootViewLayerBorderWidthForRightView { return rootViewLayerBorderWidthForRightView } if let rootViewLayerBorderWidthForRightView = rootViewLayerBorderWidth { return rootViewLayerBorderWidthForRightView } return 0.0 } } private var _rootViewLayerBorderWidthForRightView: CGFloat? /// Use this property to decorate the left side view with border. /// - Note: /// - Make sense only together with `leftViewLayerBorderColor` @IBInspectable open var leftViewLayerBorderWidth: CGFloat = 0.0 /// Use this property to decorate the right side view with border. /// - Note: /// - Make sense only together with `rightViewLayerBorderColor` @IBInspectable open var rightViewLayerBorderWidth: CGFloat = 0.0 // MARK: - Layer Shadow Color - /// Use this property to decorate the root view with shadow. /// - Note: /// - Make sense only together with `rootViewLayerShadowRadius` @IBInspectable open var rootViewLayerShadowColor: UIColor? /// Use this property to decorate the root view with shadow /// which is visible only when the left side view is showing. /// - Returns: Default: /// - `rootViewLayerShadowColor` if assigned /// - `UIColor(white: 0.0, alpha: 0.5)` if `presentationStyle.isBelow` /// - `.clear` otherwise /// - Note: /// - Make sense only together with `rootViewLayerShadowRadiusForLeftView` @IBInspectable open var rootViewLayerShadowColorForLeftView: UIColor { set { _rootViewLayerShadowColorForLeftView = newValue } get { if let rootViewLayerShadowColorForLeftView = _rootViewLayerShadowColorForLeftView { return rootViewLayerShadowColorForLeftView } if let rootViewLayerShadowColorForLeftView = rootViewLayerShadowColor { return rootViewLayerShadowColorForLeftView } if leftViewPresentationStyle.isBelow { return UIColor(white: 0.0, alpha: 0.5) } return .clear } } private var _rootViewLayerShadowColorForLeftView: UIColor? /// Use this property to decorate the root view with shadow /// which is visible only when the right side view is showing. /// - Returns: Default: /// - `rootViewLayerShadowColor` if assigned /// - `UIColor(white: 0.0, alpha: 0.5)` if `presentationStyle.isBelow` /// - `.clear` otherwise /// - Note: /// - Make sense only together with `rootViewLayerShadowRadiusForRightView` @IBInspectable open var rootViewLayerShadowColorForRightView: UIColor { set { _rootViewLayerShadowColorForRightView = newValue } get { if let rootViewLayerShadowColorForRightView = _rootViewLayerShadowColorForRightView { return rootViewLayerShadowColorForRightView } if let rootViewLayerShadowColorForRightView = rootViewLayerShadowColor { return rootViewLayerShadowColorForRightView } if rightViewPresentationStyle.isBelow { return UIColor(white: 0.0, alpha: 0.5) } return .clear } } private var _rootViewLayerShadowColorForRightView: UIColor? /// Use this property to decorate the left side view with shadow. /// - Returns: Default: /// - `UIColor(white: 0.0, alpha: 0.5)` if `presentationStyle.isAbove` /// - `.clear` otherwise /// - Note: /// - Make sense only together with `leftViewLayerShadowRadius` @IBInspectable open var leftViewLayerShadowColor: UIColor { set { _leftViewLayerShadowColor = newValue } get { if let leftViewLayerShadowColor = _leftViewLayerShadowColor { return leftViewLayerShadowColor } if leftViewPresentationStyle.isAbove { return UIColor(white: 0.0, alpha: 0.5) } return .clear } } private var _leftViewLayerShadowColor: UIColor? /// Use this property to decorate the right side view with shadow. /// - Returns: Default: /// - `UIColor(white: 0.0, alpha: 0.5)` if `presentationStyle.isAbove` /// - `.clear` otherwise /// - Note: /// - Make sense only together with `rightViewLayerShadowRadius` @IBInspectable open var rightViewLayerShadowColor: UIColor { set { _rightViewLayerShadowColor = newValue } get { if let rightViewLayerShadowColor = _rightViewLayerShadowColor { return rightViewLayerShadowColor } if rightViewPresentationStyle.isAbove { return UIColor(white: 0.0, alpha: 0.5) } return .clear } } private var _rightViewLayerShadowColor: UIColor? // MARK: - Layer Shadow Radius - /// Use this property to decorate the root view with shadow. /// - Note: /// - Make sense only together with `rootViewLayerShadowColor` open var rootViewLayerShadowRadius: CGFloat? /// Use this property to decorate the root view with shadow /// which is visible only when the left side view is showing. /// - Returns: Default: /// - `rootViewLayerShadowRadius` if assigned /// - `8.0` if `presentationStyle.isBelow` /// - `0.0` otherwise /// - Note: /// - Make sense only together with `rootViewLayerShadowColorForLeftView` @IBInspectable open var rootViewLayerShadowRadiusForLeftView: CGFloat { set { _rootViewLayerShadowRadiusForLeftView = newValue } get { if let rootViewLayerShadowRadiusForLeftView = _rootViewLayerShadowRadiusForLeftView { return rootViewLayerShadowRadiusForLeftView } if let rootViewLayerShadowRadiusForLeftView = rootViewLayerShadowRadius { return rootViewLayerShadowRadiusForLeftView } if leftViewPresentationStyle.isBelow { return 8.0 } return 0.0 } } private var _rootViewLayerShadowRadiusForLeftView: CGFloat? /// Use this property to decorate the root view with shadow /// which is visible only when the right side view is showing. /// - Returns: Default: /// - `rootViewLayerShadowRadius` if assigned /// - `8.0` if `presentationStyle.isBelow` /// - `0.0` otherwise /// - Note: /// - Make sense only together with `rootViewLayerShadowColorForRightView` @IBInspectable open var rootViewLayerShadowRadiusForRightView: CGFloat { set { _rootViewLayerShadowRadiusForRightView = newValue } get { if let rootViewLayerShadowRadiusForRightView = _rootViewLayerShadowRadiusForRightView { return rootViewLayerShadowRadiusForRightView } if let rootViewLayerShadowRadiusForRightView = rootViewLayerShadowRadius { return rootViewLayerShadowRadiusForRightView } if rightViewPresentationStyle.isBelow { return 8.0 } return 0.0 } } private var _rootViewLayerShadowRadiusForRightView: CGFloat? /// Use this property to decorate the left side view with shadow. /// - Returns: Default: /// - `8.0` if `presentationStyle.isAbove` /// - `0.0` otherwise /// - Note: /// - Make sense only together with `leftViewLayerShadowColor` @IBInspectable open var leftViewLayerShadowRadius: CGFloat { set { _leftViewLayerShadowRadius = newValue } get { if let leftViewLayerShadowRadius = _leftViewLayerShadowRadius { return leftViewLayerShadowRadius } if leftViewPresentationStyle.isAbove { return 8.0 } return .zero } } private var _leftViewLayerShadowRadius: CGFloat? /// Use this property to decorate the right side view with shadow. /// - Returns: Default: /// - `8.0` if `presentationStyle.isAbove` /// - `0.0` otherwise /// - Note: /// - Make sense only together with `rightViewLayerShadowColor` @IBInspectable open var rightViewLayerShadowRadius: CGFloat { set { _rightViewLayerShadowRadius = newValue } get { if let rightViewLayerShadowRadius = _rightViewLayerShadowRadius { return rightViewLayerShadowRadius } if rightViewPresentationStyle.isAbove { return 8.0 } return .zero } } private var _rightViewLayerShadowRadius: CGFloat? // MARK: - Cover Blur Effect - /// Use this property to set `UIBlurEffect` for cover view, located above the root view. /// - Note: /// - Cover view is visible only when the root view is hidden. Animated between show/hide states. /// - Make sense to use if you want to hide the content of the root view or lower the attention. @IBInspectable open var rootViewCoverBlurEffect: UIBlurEffect? /// Use this property to set `UIBlurEffect` for cover view, located above the root view, /// which is visible only when the left side view is showing. /// - Returns: Default: /// - `rootViewCoverBlurEffect` if assigned /// - Note: /// - Cover view is visible only when the root view is hidden. Animated between show/hide states. /// - Make sense to use if you want to hide the content of the root view or lower the attention. @IBInspectable open var rootViewCoverBlurEffectForLeftView: UIBlurEffect? { set { _rootViewCoverBlurEffectForLeftView = newValue } get { if let rootViewCoverBlurEffectForLeftView = rootViewCoverBlurEffect { return rootViewCoverBlurEffectForLeftView } return _rootViewCoverBlurEffectForLeftView } } private var _rootViewCoverBlurEffectForLeftView: UIBlurEffect? /// Use this property to set `UIBlurEffect` for cover view, located above the root view, /// which is visible only when the right side view is showing. /// - Returns: Default: /// - `rootViewCoverBlurEffect` if assigned /// - Note: /// - Cover view is visible only when the root view is hidden. Animated between show/hide states. /// - Make sense to use if you want to hide the content of the root view or lower the attention. @IBInspectable open var rootViewCoverBlurEffectForRightView: UIBlurEffect? { set { _rootViewCoverBlurEffectForRightView = newValue } get { if let rootViewCoverBlurEffectForRightView = rootViewCoverBlurEffect { return rootViewCoverBlurEffectForRightView } return _rootViewCoverBlurEffectForRightView } } private var _rootViewCoverBlurEffectForRightView: UIBlurEffect? /// Use this property to set `UIBlurEffect` for cover view, located above the left side view. /// - Note: /// - Cover view is visible only when the left side view is hidden. Animated between show/hide states. @IBInspectable open var leftViewCoverBlurEffect: UIBlurEffect? /// Use this property to set `UIBlurEffect` for cover view, located above the left side view, /// which is visible only if the `leftViewAlwaysVisibleOptions` is true for current conditions. /// - Returns: Default: /// - `rootViewCoverBlurEffectForRightView` /// - Note: /// - Cover view is visible only when the left side view is hidden. Animated between show/hide states. @IBInspectable open var leftViewCoverBlurEffectWhenAlwaysVisible: UIBlurEffect? { set { _leftViewCoverBlurEffectWhenAlwaysVisible = newValue _isLeftViewCoverBlurEffectWhenAlwaysVisibleAssigned = true } get { if _isLeftViewCoverBlurEffectWhenAlwaysVisibleAssigned { return _leftViewCoverBlurEffectWhenAlwaysVisible } return rootViewCoverBlurEffectForRightView } } private var _leftViewCoverBlurEffectWhenAlwaysVisible: UIBlurEffect? private var _isLeftViewCoverBlurEffectWhenAlwaysVisibleAssigned: Bool = false /// Use this property to set `UIBlurEffect` for cover view, located above the right side view. /// - Note: /// - Cover view is visible only when the right side view is hidden. Animated between show/hide states. @IBInspectable open var rightViewCoverBlurEffect: UIBlurEffect? /// Use this property to set `UIBlurEffect` for cover view, located above the right side view, /// which is visible only if the `rightViewAlwaysVisibleOptions` is true for current conditions. /// - Returns: Default: /// - `rootViewCoverBlurEffectForLeftView` /// - Note: /// - Cover view is visible only when the right side view is hidden. Animated between show/hide states. @IBInspectable open var rightViewCoverBlurEffectWhenAlwaysVisible: UIBlurEffect? { set { _rightViewCoverBlurEffectWhenAlwaysVisible = newValue _isRightViewCoverBlurEffectWhenAlwaysVisibleAssigned = true } get { if _isRightViewCoverBlurEffectWhenAlwaysVisibleAssigned { return _rightViewCoverBlurEffectWhenAlwaysVisible } return rootViewCoverBlurEffectForLeftView } } private var _rightViewCoverBlurEffectWhenAlwaysVisible: UIBlurEffect? private var _isRightViewCoverBlurEffectWhenAlwaysVisibleAssigned: Bool = false // MARK: - Cover Alpha - /// Use this property to set `alpha` for cover view, located above the root view. /// - Note: /// - Cover view is visible only when the root view is hidden. Animated between show/hide states. open var rootViewCoverAlpha: CGFloat? /// Use this property to set `alpha` for cover view, located above the root view, /// which is visible only when the left side view is showing. /// - Returns: Default: /// - `rootViewCoverAlpha` if assigned /// - `1.0` otherwise /// - Note: /// - Cover view is visible only when the root view is hidden. Animated between show/hide states. @IBInspectable open var rootViewCoverAlphaForLeftView: CGFloat { set { _rootViewCoverAlphaForLeftView = newValue } get { if let rootViewCoverAlphaForLeftView = _rootViewCoverAlphaForLeftView { return rootViewCoverAlphaForLeftView } if let rootViewCoverAlphaForLeftView = rootViewCoverAlpha { return rootViewCoverAlphaForLeftView } return 1.0 } } private var _rootViewCoverAlphaForLeftView: CGFloat? /// Use this property to set `alpha` for cover view, located above the root view, /// which is visible only when the right side view is showing. /// - Returns: Default: /// - `rootViewCoverAlpha` if assigned /// - `1.0` otherwise /// - Note: /// - Cover view is visible only when the root view is hidden. Animated between show/hide states. @IBInspectable open var rootViewCoverAlphaForRightView: CGFloat { set { _rootViewCoverAlphaForRightView = newValue } get { if let rootViewCoverAlphaForRightView = _rootViewCoverAlphaForRightView { return rootViewCoverAlphaForRightView } if let rootViewCoverAlphaForRightView = rootViewCoverAlpha { return rootViewCoverAlphaForRightView } return 1.0 } } private var _rootViewCoverAlphaForRightView: CGFloat? /// Use this property to set `alpha` for cover view, located above the left side view. /// - Note: /// - Cover view is visible only when the left side view is hidden. Animated between show/hide states. @IBInspectable open var leftViewCoverAlpha: CGFloat = 1.0 /// Use this property to set `alpha` for cover view, located above the left side view, /// which is visible only if the `leftViewAlwaysVisibleOptions` is true for current conditions. /// - Returns: Default: /// - `rootViewCoverAlphaForRightView` /// - Note: /// - Cover view is visible only when the left side view is hidden. Animated between show/hide states. @IBInspectable open var leftViewCoverAlphaWhenAlwaysVisible: CGFloat { set { _leftViewCoverAlphaWhenAlwaysVisible = newValue } get { if let leftViewCoverAlphaWhenAlwaysVisible = _leftViewCoverAlphaWhenAlwaysVisible { return leftViewCoverAlphaWhenAlwaysVisible } return rootViewCoverAlphaForRightView } } private var _leftViewCoverAlphaWhenAlwaysVisible: CGFloat? /// Use this property to set `alpha` for cover view, located above the right side view. /// - Note: /// - Cover view is visible only when the right side view is hidden. Animated between show/hide states. @IBInspectable open var rightViewCoverAlpha: CGFloat = 1.0 /// Use this property to set `alpha` for cover view, located above the right side view, /// which is visible only if the `rightViewAlwaysVisibleOptions` is true for current conditions. /// - Returns: Default: /// - `rootViewCoverAlphaForLeftView` /// - Note: /// - Cover view is visible only when the right side view is hidden. Animated between show/hide states. @IBInspectable open var rightViewCoverAlphaWhenAlwaysVisible: CGFloat { set { _rightViewCoverAlphaWhenAlwaysVisible = newValue } get { if let rightViewCoverAlphaWhenAlwaysVisible = _rightViewCoverAlphaWhenAlwaysVisible { return rightViewCoverAlphaWhenAlwaysVisible } return rootViewCoverAlphaForLeftView } } private var _rightViewCoverAlphaWhenAlwaysVisible: CGFloat? // MARK: - Cover Color - /// Use this property to set color for cover view, located above the root view. /// - Note: /// - Cover view is visible only when the root view is hidden. Animated between show/hide states. /// - Make sense to use if you want to hide the content of the root view or lower the attention. @IBInspectable open var rootViewCoverColor: UIColor? /// Use this property to set color for cover view, located above the root view, /// which is visible only when the left side view is showing. /// - Returns: Default: /// - `rootViewCoverColor` if assigned /// - `.clear` otherwise /// - Note: /// - Cover view is visible only when the root view is hidden. Animated between show/hide states. /// - Make sense to use if you want to hide the content of the root view or lower the attention. @IBInspectable open var rootViewCoverColorForLeftView: UIColor { set { _rootViewCoverColorForLeftView = newValue } get { if let rootViewCoverColorForLeftView = _rootViewCoverColorForLeftView { return rootViewCoverColorForLeftView } if let rootViewCoverColorForLeftView = rootViewCoverColor { return rootViewCoverColorForLeftView } return .clear } } private var _rootViewCoverColorForLeftView: UIColor? /// Use this property to set color for cover view, located above the root view, /// which is visible only when the right side view is showing. /// - Returns: Default: /// - `rootViewCoverColor` if assigned /// - `.clear` otherwise /// - Note: /// - Cover view is visible only when the root view is hidden. Animated between show/hide states. /// - Make sense to use if you want to hide the content of the root view or lower the attention. @IBInspectable open var rootViewCoverColorForRightView: UIColor { set { _rootViewCoverColorForRightView = newValue } get { if let rootViewCoverColorForRightView = _rootViewCoverColorForRightView { return rootViewCoverColorForRightView } if let rootViewCoverColorForRightView = rootViewCoverColor { return rootViewCoverColorForRightView } return .clear } } private var _rootViewCoverColorForRightView: UIColor? /// Use this property to set color for cover view, located above the left side view. /// - Returns: Default: /// - `UIColor(white: 0.0, alpha: 0.5)` if `presentationStyle.isBelow` /// - `.clear` otherwise /// - Note: /// - Cover view is visible only when the left side view is hidden. Animated between show/hide states. @IBInspectable open var leftViewCoverColor: UIColor { set { _leftViewCoverColor = newValue } get { if let leftViewCoverColor = _leftViewCoverColor { return leftViewCoverColor } if leftViewPresentationStyle.isBelow { return UIColor(white: 0.0, alpha: 0.5) } return .clear } } private var _leftViewCoverColor: UIColor? /// Use this property to set color for cover view, located above the left side view, /// which is visible only if the `leftViewAlwaysVisibleOptions` is true for current conditions. /// - Returns: Default: /// - `rootViewCoverColorForRightView` /// - Note: /// - Cover view is visible only when the left side view is hidden. Animated between show/hide states. @IBInspectable open var leftViewCoverColorWhenAlwaysVisible: UIColor { set { _leftViewCoverColorWhenAlwaysVisible = newValue } get { if let leftViewCoverColorWhenAlwaysVisible = _leftViewCoverColorWhenAlwaysVisible { return leftViewCoverColorWhenAlwaysVisible } return rootViewCoverColorForRightView } } private var _leftViewCoverColorWhenAlwaysVisible: UIColor? /// Use this property to set color for cover view, located above the right side view. /// - Returns: Default: /// - `UIColor(white: 0.0, alpha: 0.5)` if `presentationStyle.isBelow` /// - `.clear` otherwise /// - Note: /// - Cover view is visible only when the right side view is hidden. Animated between show/hide states. @IBInspectable open var rightViewCoverColor: UIColor { set { _rightViewCoverColor = newValue } get { if let rightViewCoverColor = _rightViewCoverColor { return rightViewCoverColor } if rightViewPresentationStyle.isBelow { return UIColor(white: 0.0, alpha: 0.5) } return .clear } } private var _rightViewCoverColor: UIColor? /// Use this property to set color for cover view, located above the right side view, /// which is visible only if the `rightViewAlwaysVisibleOptions` is true for current conditions. /// - Returns: Default: /// - `rootViewCoverColorForLeftView` /// - Note: /// - Cover view is visible only when the right side view is hidden. Animated between show/hide states. @IBInspectable open var rightViewCoverColorWhenAlwaysVisible: UIColor { set { _rightViewCoverColorWhenAlwaysVisible = newValue } get { if let rightViewCoverColorWhenAlwaysVisible = _rightViewCoverColorWhenAlwaysVisible { return rightViewCoverColorWhenAlwaysVisible } return rootViewCoverColorForLeftView } } private var _rightViewCoverColorWhenAlwaysVisible: UIColor? // MARK: - Status Bar - /// Duration of the animation with which status bar update its style while swipe gesture to show/hide side view. @IBInspectable open var statusBarAnimationDuration: TimeInterval = 0.2 // MARK: - Status Bar Hidden - /// Determines if the status bar should be hidden when the root view is showing. /// - Returns: Default: /// - `rootViewController.prefersStatusBarHidden ?? prefersStatusBarHidden` /// - Note: /// - The recommended way is to override `prefersStatusBarHidden` method inside `rootViewController`. @IBInspectable open var isRootViewStatusBarHidden: Bool { set { _isRootViewStatusBarHidden = newValue } get { return _isRootViewStatusBarHidden ?? rootViewController?.prefersStatusBarHidden ?? prefersStatusBarHidden } } private var _isRootViewStatusBarHidden: Bool? /// Determines if the status bar should be hidden when the left side view is showing. /// - Returns: Default: /// - `leftViewController.prefersStatusBarHidden ?? rootViewStatusBarHidden` /// - Note: /// - The recommended way is to override `prefersStatusBarHidden` method inside `leftViewController`. @IBInspectable open var isLeftViewStatusBarHidden: Bool { set { _isLeftViewStatusBarHidden = newValue } get { return _isLeftViewStatusBarHidden ?? leftViewController?.prefersStatusBarHidden ?? isRootViewStatusBarHidden } } private var _isLeftViewStatusBarHidden: Bool? /// Determines if the status bar should be hidden when the right side view is showing. /// - Returns: Default: /// - `rightViewController.prefersStatusBarHidden ?? rootViewStatusBarHidden` /// - Note: /// - The recommended way is to override `prefersStatusBarHidden` method inside `rightViewController`. @IBInspectable open var isRightViewStatusBarHidden: Bool { set { _isRightViewStatusBarHidden = newValue } get { return _isRightViewStatusBarHidden ?? rightViewController?.prefersStatusBarHidden ?? isRootViewStatusBarHidden } } private var _isRightViewStatusBarHidden: Bool? // MARK: - Status Bar Style - /// Determines the status bar style when the root view is showing. /// - Returns: Default: /// - `rootViewController.preferredStatusBarStyle ?? preferredStatusBarStyle` /// - Note: /// - The recommended way is to override `preferredStatusBarStyle` method inside `rootViewController`. @IBInspectable open var rootViewStatusBarStyle: UIStatusBarStyle { set { _rootViewStatusBarStyle = newValue } get { return _rootViewStatusBarStyle ?? rootViewController?.preferredStatusBarStyle ?? preferredStatusBarStyle } } private var _rootViewStatusBarStyle: UIStatusBarStyle? /// Determines the status bar style when the left side view is showing. /// - Returns: Default: /// - `leftViewController.preferredStatusBarStyle ?? rootViewStatusBarStyle` /// - Note: /// - The recommended way is to override `preferredStatusBarStyle` method inside `leftViewController`. @IBInspectable open var leftViewStatusBarStyle: UIStatusBarStyle { set { _leftViewStatusBarStyle = newValue } get { return _leftViewStatusBarStyle ?? leftViewController?.preferredStatusBarStyle ?? rootViewStatusBarStyle } } private var _leftViewStatusBarStyle: UIStatusBarStyle? /// Determines the status bar style when the right side view is showing. /// - Returns: Default: /// - `rightViewController.preferredStatusBarStyle ?? rootViewStatusBarStyle` /// - Note: /// - The recommended way is to override `preferredStatusBarStyle` method inside `rightViewController`. @IBInspectable open var rightViewStatusBarStyle: UIStatusBarStyle { set { _rightViewStatusBarStyle = newValue } get { return _rightViewStatusBarStyle ?? rightViewController?.preferredStatusBarStyle ?? rootViewStatusBarStyle } } private var _rightViewStatusBarStyle: UIStatusBarStyle? // MARK: - Status Bar Update Animation - /// Determines the status bar update animation when the root view is showing. /// - Returns: Default: /// - `rootViewController.preferredStatusBarUpdateAnimation ?? preferredStatusBarUpdateAnimation` /// - Note: /// - The recommended way is to override `preferredStatusBarUpdateAnimation` method inside `rootViewController`. @IBInspectable open var rootViewStatusBarUpdateAnimation: UIStatusBarAnimation { set { _rootViewStatusBarUpdateAnimation = newValue } get { return _rootViewStatusBarUpdateAnimation ?? rootViewController?.preferredStatusBarUpdateAnimation ?? preferredStatusBarUpdateAnimation } } private var _rootViewStatusBarUpdateAnimation: UIStatusBarAnimation? /// Determines the status bar update animation when the left side view is showing. /// - Returns: Default: /// - `leftViewController.preferredStatusBarUpdateAnimation ?? rootViewStatusBarUpdateAnimation` /// - Note: /// - The recommended way is to override `preferredStatusBarUpdateAnimation` method inside `leftViewController`. @IBInspectable open var leftViewStatusBarUpdateAnimation: UIStatusBarAnimation { set { _leftViewStatusBarUpdateAnimation = newValue } get { return _leftViewStatusBarUpdateAnimation ?? leftViewController?.preferredStatusBarUpdateAnimation ?? rootViewStatusBarUpdateAnimation } } private var _leftViewStatusBarUpdateAnimation: UIStatusBarAnimation? /// Determines the status bar update animation when the right side view is showing. /// - Returns: Default: /// - `rightViewController.preferredStatusBarUpdateAnimation ?? rootViewStatusBarUpdateAnimation` /// - Note: /// - The recommended way is to override `preferredStatusBarUpdateAnimation` method inside `rightViewController`. @IBInspectable open var rightViewStatusBarUpdateAnimation: UIStatusBarAnimation { set { _rightViewStatusBarUpdateAnimation = newValue } get { return _rightViewStatusBarUpdateAnimation ?? rightViewController?.preferredStatusBarUpdateAnimation ?? rootViewStatusBarUpdateAnimation } } private var _rightViewStatusBarUpdateAnimation: UIStatusBarAnimation? // MARK: - Status Bar Background Visibility - /// Most of the time side view contains table view but not navigation bar. /// In this case we provide default background view for status bar, /// to not interfere with the content of the side view. /// If this status bar background is unwanted, you can hide it using this property. @IBInspectable open var isLeftViewStatusBarBackgroundVisible: Bool = true /// Most of the time side view contains table view but not navigation bar. /// In this case we provide default background view for status bar, /// to not interfere with the content of the side view. /// If this status bar background is unwanted, you can hide it using this property. open var isLeftViewStatusBarBackgroundHidden: Bool { set { isLeftViewStatusBarBackgroundVisible = !newValue } get { return !isLeftViewStatusBarBackgroundVisible } } /// Most of the time side view contains table view but not navigation bar. /// In this case we provide default background view for status bar, /// to not interfere with the content of the side view. /// If this status bar background is unwanted, you can hide it using this property. @IBInspectable open var isRightViewStatusBarBackgroundVisible: Bool = true /// Most of the time side view contains table view but not navigation bar. /// In this case we provide default background view for status bar, /// to not interfere with the content of the side view. /// If this status bar background is unwanted, you can hide it using this property. open var isRightViewStatusBarBackgroundHidden: Bool { set { isRightViewStatusBarBackgroundVisible = !newValue } get { return !isRightViewStatusBarBackgroundVisible } } // MARK: - Status Bar Background Color - /// Color for the background view of the status bar, which is visible when the left side view is showing. /// - Note: /// - `isLeftViewStatusBarBackgroundVisible` should be enabled to use this property. @IBInspectable open var leftViewStatusBarBackgroundColor: UIColor = .clear /// Color for the background view of the status bar, which is visible when the right side view is showing. /// - Note: /// - `isRightViewStatusBarBackgroundVisible` should be enabled to use this property. @IBInspectable open var rightViewStatusBarBackgroundColor: UIColor = .clear // MARK: - Status Bar Background Blur Effect - /// `UIBlurEffect` for the background view of the status bar, which is visible when the left side view is showing. /// - Note: /// - `isLeftViewStatusBarBackgroundVisible` should be enabled to use this property. @IBInspectable open var leftViewStatusBarBackgroundBlurEffect: UIBlurEffect? { set { _leftViewStatusBarBackgroundBlurEffect = newValue _isLeftViewStatusBarBackgroundBlurEffectAssigned = true } get { if _isLeftViewStatusBarBackgroundBlurEffectAssigned { return _leftViewStatusBarBackgroundBlurEffect } if leftViewStatusBarStyle == .lightContent { return UIBlurEffect(style: .dark) } if #available(iOS 13.0, *) { if leftViewStatusBarStyle == .darkContent { return UIBlurEffect(style: .light) } } if #available(iOS 10.0, *) { return UIBlurEffect(style: .regular) } return UIBlurEffect(style: .dark) } } private var _leftViewStatusBarBackgroundBlurEffect: UIBlurEffect? private var _isLeftViewStatusBarBackgroundBlurEffectAssigned: Bool = false /// `UIBlurEffect` for the background view of the status bar, which is visible when the right side view is showing. /// - Note: /// - `isRightViewStatusBarBackgroundVisible` should be enabled to use this property. @IBInspectable open var rightViewStatusBarBackgroundBlurEffect: UIBlurEffect? { set { _rightViewStatusBarBackgroundBlurEffect = newValue _isRightViewStatusBarBackgroundBlurEffectAssigned = true } get { if _isRightViewStatusBarBackgroundBlurEffectAssigned { return _rightViewStatusBarBackgroundBlurEffect } if rightViewStatusBarStyle == .lightContent { return UIBlurEffect(style: .dark) } if #available(iOS 13.0, *) { if rightViewStatusBarStyle == .darkContent { return UIBlurEffect(style: .light) } } if #available(iOS 10.0, *) { return UIBlurEffect(style: .regular) } return UIBlurEffect(style: .dark) } } private var _rightViewStatusBarBackgroundBlurEffect: UIBlurEffect? private var _isRightViewStatusBarBackgroundBlurEffectAssigned: Bool = false // MARK: - Status Bar Background Alpha - /// `alpha` for the background view of the status bar, which is visible when the left side view is showing. /// - Note: /// - `isLeftViewStatusBarBackgroundVisible` should be enabled to use this property. @IBInspectable open var leftViewStatusBarBackgroundAlpha: CGFloat = 1.0 /// `alpha` for the background view of the status bar, which is visible when the right side view is showing. /// - Note: /// - `isRightViewStatusBarBackgroundVisible` should be enabled to use this property. @IBInspectable open var rightViewStatusBarBackgroundAlpha: CGFloat = 1.0 // MARK: - Status Bar Background Shadow Color - /// Shadow color for the background view of the status bar, which is visible when the left side view is showing. /// - Note: /// - `isLeftViewStatusBarBackgroundVisible` should be enabled to use this property. /// - Make sense only together with `leftViewStatusBarBackgroundShadowRadius` @IBInspectable open var leftViewStatusBarBackgroundShadowColor: UIColor = .clear /// Shadow color for the background view of the status bar, which is visible when the right side view is showing. /// - Note: /// - `isRightViewStatusBarBackgroundVisible` should be enabled to use this property. /// - Make sense only together with `rightViewStatusBarBackgroundShadowRadius` @IBInspectable open var rightViewStatusBarBackgroundShadowColor: UIColor = .clear // MARK: - Status Bar Background Shadow Radius - /// Shadow radius for the background view of the status bar, which is visible when the left side view is showing. /// - Note: /// - `isLeftViewStatusBarBackgroundVisible` should be enabled to use this property. /// - Make sense only together with `leftViewStatusBarBackgroundShadowColor` @IBInspectable open var leftViewStatusBarBackgroundShadowRadius: CGFloat = 0.0 /// Shadow radius for the background view of the status bar, which is visible when the right side view is showing. /// - Note: /// - `isRightViewStatusBarBackgroundVisible` should be enabled to use this property. /// - Make sense only together with `rightViewStatusBarBackgroundShadowColor` @IBInspectable open var rightViewStatusBarBackgroundShadowRadius: CGFloat = 0.0 // MARK: - Alpha - /// Use this property to set `alpha` for the root view when it is hidden. /// - Note: /// - Animated between show/hide states. /// - Make sense to use if you want to hide the content of the root view or lower the attention. open var rootViewAlphaWhenHidden: CGFloat? /// Use this property to set `alpha` for the root view when it is hidden, /// which is applied only when the left side view is showing. /// - Returns: Default: /// - `rootViewAlphaWhenHidden` if assigned /// - `1.0` otherwise /// - Note: /// - Animated between show/hide states. /// - Make sense to use if you want to hide the content of the root view or lower the attention. @IBInspectable open var rootViewAlphaWhenHiddenForLeftView: CGFloat { set { _rootViewAlphaWhenHiddenForLeftView = newValue } get { if let rootViewAlphaWhenHiddenForLeftView = _rootViewAlphaWhenHiddenForLeftView { return rootViewAlphaWhenHiddenForLeftView } if let rootViewAlphaWhenHiddenForLeftView = rootViewAlphaWhenHidden { return rootViewAlphaWhenHiddenForLeftView } return 1.0 } } private var _rootViewAlphaWhenHiddenForLeftView: CGFloat? /// Use this property to set `alpha` for the root view when it is hidden, /// which is applied only when the right side view is showing. /// - Returns: Default: /// - `rootViewAlphaWhenHidden` if assigned /// - `1.0` otherwise /// - Note: /// - Animated between show/hide states. /// - Make sense to use if you want to hide the content of the root view or lower the attention. @IBInspectable open var rootViewAlphaWhenHiddenForRightView: CGFloat { set { _rootViewAlphaWhenHiddenForRightView = newValue } get { if let rootViewAlphaWhenHiddenForRightView = _rootViewAlphaWhenHiddenForRightView { return rootViewAlphaWhenHiddenForRightView } if let rootViewAlphaWhenHiddenForRightView = rootViewAlphaWhenHidden { return rootViewAlphaWhenHiddenForRightView } return 1.0 } } private var _rootViewAlphaWhenHiddenForRightView: CGFloat? /// Use this property to set `alpha` for the left side view when it is hidden. /// - Returns: Default: /// - `0.0` if `presentationStyle == .scaleFromBig` /// - `0.0` if `presentationStyle == .scaleFromLittle` /// - `1.0` otherwise /// - Note: /// - Animated between show/hide states. @IBInspectable open var leftViewAlphaWhenHidden: CGFloat { set { _leftViewAlphaWhenHidden = newValue } get { if let leftViewAlphaWhenHidden = _leftViewAlphaWhenHidden { return leftViewAlphaWhenHidden } if leftViewPresentationStyle == .scaleFromBig || leftViewPresentationStyle == .scaleFromLittle { return 0.0 } return 1.0 } } private var _leftViewAlphaWhenHidden: CGFloat? /// Use this property to set `alpha` for the right side view when it is hidden. /// - Returns: Default: /// - `0.0` if `presentationStyle == .scaleFromBig` /// - `0.0` if `presentationStyle == .scaleFromLittle` /// - `1.0` otherwise /// - Note: /// - Animated between show/hide states. @IBInspectable open var rightViewAlphaWhenHidden: CGFloat { set { _rightViewAlphaWhenHidden = newValue } get { if let rightViewAlphaWhenHidden = _rightViewAlphaWhenHidden { return rightViewAlphaWhenHidden } if rightViewPresentationStyle == .scaleFromBig || rightViewPresentationStyle == .scaleFromLittle { return 0.0 } return 1.0 } } private var _rightViewAlphaWhenHidden: CGFloat? // MARK: - Offset - /// Use this property to set extra offset for the root view when it is hidden. open var rootViewOffsetWhenHidden: CGPoint? /// Use this property to set extra offset for the root view when it is hidden, /// which is applied only when the left side view is showing. /// - Returns: Default: /// - `rootViewOffsetWhenHidden` if assigned /// - `.zero` otherwise @IBInspectable open var rootViewOffsetWhenHiddenForLeftView: CGPoint { set { _rootViewOffsetWhenHiddenForLeftView = newValue } get { if let rootViewOffsetWhenHiddenForLeftView = _rootViewOffsetWhenHiddenForLeftView { return rootViewOffsetWhenHiddenForLeftView } if let rootViewOffsetWhenHiddenForLeftView = rootViewOffsetWhenHidden { return rootViewOffsetWhenHiddenForLeftView } return .zero } } private var _rootViewOffsetWhenHiddenForLeftView: CGPoint? /// Use this property to set extra offset for the root view when it is hidden, /// which is applied only when the right side view is showing. /// - Returns: Default: /// - `rootViewOffsetWhenHidden` if assigned /// - `.zero` otherwise @IBInspectable open var rootViewOffsetWhenHiddenForRightView: CGPoint { set { _rootViewOffsetWhenHiddenForRightView = newValue } get { if let rootViewOffsetWhenHiddenForRightView = _rootViewOffsetWhenHiddenForRightView { return rootViewOffsetWhenHiddenForRightView } if let rootViewOffsetWhenHiddenForRightView = rootViewOffsetWhenHidden { return rootViewOffsetWhenHiddenForRightView } return .zero } } private var _rootViewOffsetWhenHiddenForRightView: CGPoint? /// Use this property to set extra offset for the left side view when it is hidden. /// - Returns: Default: /// - `CGPoint(x: -(leftViewWidth / 2.0), y: 0.0)` if `presentationStyle == .slideBelowShifted` /// - `.zero` otherwise @IBInspectable open var leftViewOffsetWhenHidden: CGPoint { set { _leftViewOffsetWhenHidden = newValue } get { if let leftViewOffsetWhenHidden = _leftViewOffsetWhenHidden { return leftViewOffsetWhenHidden } if leftViewPresentationStyle == .slideBelowShifted { return CGPoint(x: -(leftViewWidth / 2.0), y: 0.0) } return .zero } } private var _leftViewOffsetWhenHidden: CGPoint? /// Use this property to set extra offset for the right side view when it is hidden. /// - Returns: Default: /// - `CGPoint(x: rightViewWidth / 2.0, y: 0.0)` if `presentationStyle == .slideBelowShifted` /// - `.zero` otherwise @IBInspectable open var rightViewOffsetWhenHidden: CGPoint { set { _rightViewOffsetWhenHidden = newValue } get { if let rightViewOffsetWhenHidden = _rightViewOffsetWhenHidden { return rightViewOffsetWhenHidden } if rightViewPresentationStyle == .slideBelowShifted { return CGPoint(x: rightViewWidth / 2.0, y: 0.0) } return .zero } } private var _rightViewOffsetWhenHidden: CGPoint? /// Use this property to set extra offset for the left side view when it is showing. @IBInspectable open var leftViewOffsetWhenShowing: CGPoint = .zero /// Use this property to set extra offset for the right side view when it is showing. @IBInspectable open var rightViewOffsetWhenShowing: CGPoint = .zero // MARK: - Scale - /// Use this property to set scale for the root view when it is hidden. open var rootViewScaleWhenHidden: CGFloat? /// Use this property to set scale for the root view when it is hidden, /// which is applied only when the left side view is showing. /// - Returns: Default: /// - `rootViewScaleWhenHidden` if assigned /// - `0.8` if `presentationStyle.shouldRootViewScale` /// - `1.0` otherwise @IBInspectable open var rootViewScaleWhenHiddenForLeftView: CGFloat { set { _rootViewScaleWhenHiddenForLeftView = newValue } get { if let rootViewScaleWhenHiddenForLeftView = _rootViewScaleWhenHiddenForLeftView { return rootViewScaleWhenHiddenForLeftView } if let rootViewScaleWhenHiddenForLeftView = rootViewScaleWhenHidden { return rootViewScaleWhenHiddenForLeftView } if leftViewPresentationStyle.shouldRootViewScale { return 0.8 } return 1.0 } } private var _rootViewScaleWhenHiddenForLeftView: CGFloat? /// Use this property to set scale for the root view when it is hidden, /// which is applied only when the right side view is showing. /// - Returns: Default: /// - `rootViewScaleWhenHidden` if assigned /// - `0.8` if `presentationStyle.shouldRootViewScale` /// - `1.0` otherwise @IBInspectable open var rootViewScaleWhenHiddenForRightView: CGFloat { set { _rootViewScaleWhenHiddenForRightView = newValue } get { if let rootViewScaleWhenHiddenForRightView = _rootViewScaleWhenHiddenForRightView { return rootViewScaleWhenHiddenForRightView } if let rootViewScaleWhenHiddenForRightView = rootViewScaleWhenHidden { return rootViewScaleWhenHiddenForRightView } if rightViewPresentationStyle.shouldRootViewScale { return 0.8 } return 1.0 } } private var _rootViewScaleWhenHiddenForRightView: CGFloat? /// Use this property to set scale for the left side view when it is hidden. /// - Returns: Default: /// - `1.2` if `presentationStyle == .scaleFromBig` /// - `0.8` if `presentationStyle == .scaleFromLittle` /// - `1.0` otherwise @IBInspectable open var leftViewScaleWhenHidden: CGFloat { set { _leftViewScaleWhenHidden = newValue } get { if let leftViewScaleWhenHidden = _leftViewScaleWhenHidden { return leftViewScaleWhenHidden } if leftViewPresentationStyle == .scaleFromBig { return 1.2 } if leftViewPresentationStyle == .scaleFromLittle { return 0.8 } return 1.0 } } private var _leftViewScaleWhenHidden: CGFloat? /// Use this property to set scale for the right side view when it is hidden. /// - Returns: Default: /// - `1.2` if `presentationStyle == .scaleFromBig` /// - `0.8` if `presentationStyle == .scaleFromLittle` /// - `1.0` otherwise @IBInspectable open var rightViewScaleWhenHidden: CGFloat { set { _rightViewScaleWhenHidden = newValue } get { if let rightViewScaleWhenHidden = _rightViewScaleWhenHidden { return rightViewScaleWhenHidden } if rightViewPresentationStyle == .scaleFromBig { return 1.2 } if rightViewPresentationStyle == .scaleFromLittle { return 0.8 } return 1.0 } } private var _rightViewScaleWhenHidden: CGFloat? // MARK: - Background Image Scale - /// Use this property to set scale for background view, located behind the left side view, when it is hidden. /// - Returns: Default: /// - `1.4` if `presentationStyle == .scaleFromBig` /// - `1.0` otherwise @IBInspectable open var leftViewBackgroundScaleWhenHidden: CGFloat { set { _leftViewBackgroundScaleWhenHidden = newValue } get { if let leftViewBackgroundScaleWhenHidden = _leftViewBackgroundScaleWhenHidden { return leftViewBackgroundScaleWhenHidden } if leftViewPresentationStyle == .scaleFromBig { return 1.4 } return 1.0 } } private var _leftViewBackgroundScaleWhenHidden: CGFloat? /// Use this property to set scale for background view, located behind the right side view, when it is hidden. /// - Returns: Default: /// - `1.4` if `presentationStyle == .scaleFromBig` /// - `1.0` otherwise @IBInspectable open var rightViewBackgroundScaleWhenHidden: CGFloat { set { _rightViewBackgroundScaleWhenHidden = newValue } get { if let rightViewBackgroundScaleWhenHidden = _rightViewBackgroundScaleWhenHidden { return rightViewBackgroundScaleWhenHidden } if rightViewPresentationStyle == .scaleFromBig { return 1.4 } return 1.0 } } private var _rightViewBackgroundScaleWhenHidden: CGFloat? /// Use this property to set scale for background view, located behind the left side view, when it is showing. /// - Returns: Default: /// - `1.4` if `presentationStyle == .scaleFromLittle` /// - `1.0` otherwise @IBInspectable open var leftViewBackgroundScaleWhenShowing: CGFloat { set { _leftViewBackgroundScaleWhenShowing = newValue } get { if let leftViewBackgroundScaleWhenShowing = _leftViewBackgroundScaleWhenShowing { return leftViewBackgroundScaleWhenShowing } if leftViewPresentationStyle == .scaleFromLittle { return 1.4 } return 1.0 } } private var _leftViewBackgroundScaleWhenShowing: CGFloat? /// Use this property to set scale for background view, located behind the right side view, when it is showing. /// - Returns: Default: /// - `1.4` if `presentationStyle == .scaleFromLittle` /// - `1.0` otherwise @IBInspectable open var rightViewBackgroundScaleWhenShowing: CGFloat { set { _rightViewBackgroundScaleWhenShowing = newValue } get { if let rightViewBackgroundScaleWhenShowing = _rightViewBackgroundScaleWhenShowing { return rightViewBackgroundScaleWhenShowing } if rightViewPresentationStyle == .scaleFromLittle { return 1.4 } return 1.0 } } private var _rightViewBackgroundScaleWhenShowing: CGFloat? // MARK: - Background Image Offset - /// Use this property to set offset for background view, located behind the left side view, when it is hidden. /// - Returns: Default: /// - `CGPoint(x: -(leftViewWidth / 2.0), y: 0.0)` if `presentationStyle == .slideBelowShifted` /// - `.zero` otherwise @IBInspectable open var leftViewBackgroundOffsetWhenHidden: CGPoint { set { _leftViewBackgroundOffsetWhenHidden = newValue } get { if let leftViewBackgroundOffsetWhenHidden = _leftViewBackgroundOffsetWhenHidden { return leftViewBackgroundOffsetWhenHidden } if leftViewPresentationStyle == .slideBelowShifted { return CGPoint(x: -(leftViewWidth / 2.0), y: 0.0) } return .zero } } private var _leftViewBackgroundOffsetWhenHidden: CGPoint? /// Use this property to set offset for background view, located behind the right side view, when it is hidden. /// - Returns: Default: /// - `CGPoint(x: rightViewWidth / 2.0, y: 0.0)` if `presentationStyle == .slideBelowShifted` /// - `.zero` otherwise @IBInspectable open var rightViewBackgroundOffsetWhenHidden: CGPoint { set { _rightViewBackgroundOffsetWhenHidden = newValue } get { if let rightViewBackgroundOffsetWhenHidden = _rightViewBackgroundOffsetWhenHidden { return rightViewBackgroundOffsetWhenHidden } if rightViewPresentationStyle == .slideBelowShifted { return CGPoint(x: rightViewWidth / 2.0, y: 0.0) } return .zero } } private var _rightViewBackgroundOffsetWhenHidden: CGPoint? /// Use this property to set offset for background view, located behind the left side view, when it is showing. @IBInspectable open var leftViewBackgroundOffsetWhenShowing: CGPoint = .zero /// Use this property to set offset for background view, located behind the right side view, when it is showing. @IBInspectable open var rightViewBackgroundOffsetWhenShowing: CGPoint = .zero // MARK: - Callbacks - open var willShowLeftView: Callback? open var didShowLeftView: Callback? open var willHideLeftView: Callback? open var didHideLeftView: Callback? open var willShowRightView: Callback? open var didShowRightView: Callback? open var willHideRightView: Callback? open var didHideRightView: Callback? /// This callback is executed inside animation block for showing left view. /// You can use it to add some custom animations. open var showAnimationsForLeftView: AnimationsCallback? /// This callback is executed inside animation block for hiding left view. /// You can use it to add some custom animations open var hideAnimationsForLeftView: AnimationsCallback? /// This callback is executed inside animation block for showing right view. /// You can use this notification to add some custom animations open var showAnimationsForRightView: AnimationsCallback? /// This callback is executed inside animation block for hiding right view. /// You can use this notification to add some custom animations open var hideAnimationsForRightView: AnimationsCallback? /// This callback is executed on every transformation of root view during showing/hiding of side views /// You can retrieve percentage between `0.0` and `1.0` from userInfo dictionary, where /// - `0.0` - view is fully shown /// - `1.0` - view is fully hidden open var didTransformRootView: TransformCallback? /// This callback is executed on every transformation of left view during showing/hiding /// You can retrieve percentage between `0.0` and `1.0` from userInfo dictionary, where /// - `0.0` - view is fully hidden /// - `1.0` - view is fully shown open var didTransformLeftView: TransformCallback? /// This callback is executed on every transformation of right view during showing/hiding /// You can retrieve percentage between `0.0` and `1.0` from userInfo dictionary, where /// - `0.0` - view is fully hidden /// - `1.0` - view is fully shown open var didTransformRightView: TransformCallback? // MARK: - Delegate - /// Delegate object to observe behaviour of LGSideMenuController open var delegate: LGSideMenuDelegate? // MARK: - Internal Properties - /// Keeps current state. Describes which view is showing/hidden or is going to be shown/hidden. /// For internal purposes. Usually shouldn't be accessed by user. open internal(set) var state: State = .rootViewIsShowing /// Tells if any animations are currently in process. /// For internal purposes. Usually shouldn't be accessed by user. open internal(set) var isAnimating = false /// Tells if layouts and styles should be updated. /// For internal purposes. Usually shouldn't be accessed by user. open internal(set) var isNeedsUpdateLayoutsAndStyles: Bool = false /// Tells if root view layouts and styles should be updated. /// For internal purposes. Usually shouldn't be accessed by user. open internal(set) var isNeedsUpdateRootViewLayoutsAndStyles: Bool = false /// Tells if left view layouts and styles should be updated. /// For internal purposes. Usually shouldn't be accessed by user. open internal(set) var isNeedsUpdateLeftViewLayoutsAndStyles: Bool = false /// Tells if right view layouts and styles should be updated. /// For internal purposes. Usually shouldn't be accessed by user. open internal(set) var isNeedsUpdateRightViewLayoutsAndStyles: Bool = false internal var savedSize: CGSize = .zero internal var leftViewGestureStartX: CGFloat? internal var rightViewGestureStartX: CGFloat? internal var isLeftViewShowingBeforeGesture: Bool = false internal var isRightViewShowingBeforeGesture: Bool = false internal var shouldUpdateVisibility: Bool = true internal var isRotationInvalidatedLayout: Bool = false internal var isRootViewLayoutingEnabled: Bool = true internal var isRootViewControllerLayoutingEnabled: Bool = true // MARK: - Internal Root Views - /// View that contains all root-related views. /// This view does not clip to bounds. /// Usually shouldn't be accessed by user. open internal(set) var rootContainerView: UIView? /// View that contains all root-related views except background views. /// This view located right inside border and clips to bounds. /// Usually shouldn't be accessed by user. open internal(set) var rootContainerClipToBorderView: UIView? /// View that responcible for shadow, border and background of the root view. /// Usually shouldn't be accessed by user. open internal(set) var rootViewBackgroundDecorationView: LGSideMenuBackgroundDecorationView? /// View that responcible for shadow of the root view. Located inside `rootViewBackgroundDecorationView`. /// Usually shouldn't be accessed by user. open internal(set) var rootViewBackgroundShadowView: LGSideMenuBackgroundShadowView? /// View that wraps user-provided root view. /// Usually shouldn't be accessed by user. /// Might be useful to make animated transition to a new root view. open internal(set) var rootViewWrapperView: LGSideMenuWrapperView? /// View that located on top of all root-related views to hide their content if necessary. /// Usually shouldn't be accessed by user. open internal(set) var rootViewCoverView: UIVisualEffectView? // MARK: - Internal Left Views - /// View that contains all left-related views. /// This view clips to bounds. /// Usually shouldn't be accessed by user. open internal(set) var leftContainerView: UIView? /// View that contains all left-related views except background views. /// This view located right inside border and clips to bounds. /// Usually shouldn't be accessed by user. open internal(set) var leftContainerClipToBorderView: UIView? /// View that responcible for shadow, border and background of the left view. /// Usually shouldn't be accessed by user. open internal(set) var leftViewBackgroundDecorationView: LGSideMenuBackgroundDecorationView? /// View that responcible for shadow of the left view. Located inside `leftViewBackgroundDecorationView`. /// Usually shouldn't be accessed by user. open internal(set) var leftViewBackgroundShadowView: LGSideMenuBackgroundShadowView? /// View that wraps user-provided background view for left view. /// Usually shouldn't be accessed by user. open internal(set) var leftViewBackgroundWrapperView: UIView? /// View that shows user-provided background image for left view. /// Usually shouldn't be accessed by user. open internal(set) var leftViewBackgroundImageView: UIImageView? /// View that shows background visual effect for left view. /// Usually shouldn't be accessed by user. open internal(set) var leftViewBackgroundEffectView: UIVisualEffectView? /// View that wraps user-provided left view. /// Usually shouldn't be accessed by user. open internal(set) var leftViewWrapperView: LGSideMenuWrapperView? /// View that located on top of all left-related views to hide their content if necessary. /// Usually shouldn't be accessed by user. open internal(set) var leftViewCoverView: UIVisualEffectView? /// View that located right below status bar to avoid interference of user's content with status bar. /// Responcible for shadow, border and background of the status bar. /// Usually shouldn't be accessed by user. open internal(set) var leftViewStatusBarBackgroundView: LGSideMenuStatusBarBackgroundView? /// View that adds visual effect to status bar background. /// Usually shouldn't be accessed by user. open internal(set) var leftViewStatusBarBackgroundEffectView: UIVisualEffectView? // MARK: - Internal Right Views - /// View that contains all right-related views. /// This view clips to bounds. /// Usually shouldn't be accessed by user. open internal(set) var rightContainerView: UIView? /// View that contains all right-related views except background views. /// This view located right inside border and clips to bounds. /// Usually shouldn't be accessed by user. open internal(set) var rightContainerClipToBorderView: UIView? /// View that responcible for shadow, border and background of the right view. /// Usually shouldn't be accessed by user. open internal(set) var rightViewBackgroundDecorationView: LGSideMenuBackgroundDecorationView? /// View that responcible for shadow of the right view. Located inside `rightViewBackgroundDecorationView`. /// Usually shouldn't be accessed by user. open internal(set) var rightViewBackgroundShadowView: LGSideMenuBackgroundShadowView? /// View that wraps user-provided background view for right view. /// Usually shouldn't be accessed by user. open internal(set) var rightViewBackgroundWrapperView: UIView? /// View that shows user-provided background image for right view. /// Usually shouldn't be accessed by user. open internal(set) var rightViewBackgroundImageView: UIImageView? /// View that shows background visual effect for right view. /// Usually shouldn't be accessed by user. open internal(set) var rightViewBackgroundEffectView: UIVisualEffectView? /// View that wraps user-provided right view. /// Usually shouldn't be accessed by user. open internal(set) var rightViewWrapperView: LGSideMenuWrapperView? /// View that located on top of all right-related views to hide their content if necessary. /// Usually shouldn't be accessed by user. open internal(set) var rightViewCoverView: UIVisualEffectView? /// View that located right below status bar to avoid interference of user's content with status bar. /// Responcible for shadow, border and background of the status bar. /// Usually shouldn't be accessed by user. open internal(set) var rightViewStatusBarBackgroundView: LGSideMenuStatusBarBackgroundView? /// View that adds visual effect to status bar background. /// Usually shouldn't be accessed by user. open internal(set) var rightViewStatusBarBackgroundEffectView: UIVisualEffectView? // MARK: - Initialization - public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { self.tapGesture = UITapGestureRecognizer() self.panGestureForLeftView = UIPanGestureRecognizer() self.panGestureForRightView = UIPanGestureRecognizer() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required public init?(coder: NSCoder) { self.tapGesture = UITapGestureRecognizer() self.panGestureForLeftView = UIPanGestureRecognizer() self.panGestureForRightView = UIPanGestureRecognizer() super.init(coder: coder) } convenience public init() { self.init(nibName: nil, bundle: nil) } convenience public init(rootViewController: UIViewController? = nil, leftViewController: UIViewController? = nil, rightViewController: UIViewController? = nil) { self.init() // We need to use `defer` here to trigger `willSet` and `didSet` callbacks defer { self.rootViewController = rootViewController self.leftViewController = leftViewController self.rightViewController = rightViewController } } convenience public init(rootView: UIView? = nil, leftView: UIView? = nil, rightView: UIView? = nil) { self.init() // We need to use `defer` here to trigger `willSet` and `didSet` callbacks defer { self.rootView = rootView self.leftView = leftView self.rightView = rightView } } open override func viewDidLoad() { super.viewDidLoad() self.tapGesture.addTarget(self, action: #selector(handleTapGesture)) self.tapGesture.delegate = self self.tapGesture.numberOfTapsRequired = 1 self.tapGesture.numberOfTouchesRequired = 1 self.view.addGestureRecognizer(self.tapGesture) self.panGestureForLeftView.addTarget(self, action: #selector(handlePanGestureForLeftView)) self.panGestureForLeftView.delegate = self self.panGestureForLeftView.minimumNumberOfTouches = 1 self.panGestureForLeftView.maximumNumberOfTouches = 1 self.view.addGestureRecognizer(self.panGestureForLeftView) self.panGestureForRightView.addTarget(self, action: #selector(handlePanGestureForRightView)) self.panGestureForRightView.delegate = self self.panGestureForRightView.minimumNumberOfTouches = 1 self.panGestureForRightView.maximumNumberOfTouches = 1 self.view.addGestureRecognizer(self.panGestureForRightView) // Try to initialize root, left and right view controllers from storyboard by segues if self.storyboard != nil { self.tryPerformRootSegueIfNeeded() self.tryPerformLeftSegueIfNeeded() self.tryPerformRightSegueIfNeeded() } } // MARK: - Segues - /// Is trying to initialize root view controller by performing segue if possible. /// Normally shouldn't be executed by user. open func tryPerformRootSegueIfNeeded() { guard self.storyboard != nil, _rootViewController == nil, LGSideMenuHelper.canPerformSegue(self, withIdentifier: LGSideMenuSegue.Identifier.root) else { return } self.performSegue(withIdentifier: LGSideMenuSegue.Identifier.root, sender: self) } /// Is trying to initialize left view controller by performing segue if possible. /// Normally shouldn't be executed by user. open func tryPerformLeftSegueIfNeeded() { guard self.storyboard != nil, _leftViewController == nil, LGSideMenuHelper.canPerformSegue(self, withIdentifier: LGSideMenuSegue.Identifier.left) else { return } self.performSegue(withIdentifier: LGSideMenuSegue.Identifier.left, sender: self) } /// Is trying to initialize right view controller by performing segue if possible. /// Normally shouldn't be executed by user. open func tryPerformRightSegueIfNeeded() { guard self.storyboard != nil, _rightViewController == nil, LGSideMenuHelper.canPerformSegue(self, withIdentifier: LGSideMenuSegue.Identifier.right) else { return } self.performSegue(withIdentifier: LGSideMenuSegue.Identifier.right, sender: self) } // MARK: - Layouting - /// Called when root view is layouting subviews. /// Use this to update root view related layout if necessary. open func rootViewLayoutSubviews() { // only for overriding } /// Called when left view is layouting subviews. /// Use this to update left view related layout if necessary. open func leftViewLayoutSubviews() { // only for overriding } /// Called when right view is layouting subviews. /// Use this to update right view related layout if necessary. open func rightViewLayoutSubviews() { // only for overriding } // MARK: - deinit - deinit { if let rootViewController = rootViewController { LGSideMenuHelper.setSideMenuController(nil, to: rootViewController) } if let leftViewController = leftViewController { LGSideMenuHelper.setSideMenuController(nil, to: leftViewController) } if let rightViewController = rightViewController { LGSideMenuHelper.setSideMenuController(nil, to: rightViewController) } } }
mit
35d35dd20d2609906f55a16108168cdc
39.607208
165
0.652894
5.157335
false
false
false
false
carabina/XMLParser
XMLParser Demo/Pods/XMLParser/XMLParser/XMLParser.swift
4
2783
// // XMLParser.swift // XMLParser // // Created by Eugene Mozharovsky on 8/29/15. // Copyright © 2015 DotMyWay LCC. All rights reserved. // import Foundation /// A parser class supposed to provide features for (de)coding /// data into XML and vice versa. /// The class provides a singleton. public class XMLParser: XMLCoder, XMLDecoder { /// A singleton accessor. public static let sharedParser = XMLParser() // MARK: - XMLCoder & XMLDecoder public func encode<Key : Hashable, Value>(data: Dictionary<Key, Value>, header: String = "") -> String { guard let tries = data.generateTries() else { return "" } return header + tries.map { $0.parsedRequestBody() }.reduce("", combine: +) } public func decode(data: String) -> Dictionary<String, [String]> { return findTags(data) } // MARK: - Initialization /// A private initializer for singleton implementation. private init() { } // MARK: - Utils /// Finds XML tags in a given string (supposed to be previously parsed into XML format). /// - parameter body: A given XML parsed string. /// - returns: A dictionary with arrays of values. private func findTags(body: String) -> [String : [String]] { var keys: [String] = [] var write = false var char = "" var value = "" var values: [String : [String]] = [:] for ch in body.characters { if ch == "<" { write = true } else if ch == ">" { write = false } if ch == "\n" { continue } if write { if let last = keys.last where value != "" { if let _ = values[last.original()] { values[last.original()]! += [value] } else { values[last.original()] = [] values[last.original()]! += [value] } value = "" } char += String(ch) } else { if char != "" { char += String(ch) keys += [char] char = "" } else if let last = keys.last where last == last.original().startHeader() { if ch == " " && (value.characters.last == " " || value.characters.last == "\n" || value.characters.count == 0) { continue } value += String(ch) } } } return values } }
mit
d38a496bedc220bf6f464115b6b19625
29.571429
133
0.455428
4.872154
false
false
false
false
na4lapy/na4lapy-ios
Na4Łapy/FavouriteViewController.swift
1
4235
// // FavouriteViewController.swift // Na4Łapy // // Created by Andrzej Butkiewicz on 04.11.2016. // Copyright © 2016 Stowarzyszenie Na4Łapy. All rights reserved. // import UIKit class FavouriteViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var favouriteAnimals: [Animal] = [] var searchController: UISearchController? var favAnimalType: FavAnimalType = .All var header: FavouriteTableHeader? override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self tableView.separatorStyle = .none let nib = UINib(nibName: "FavoubriteTableHeaderView", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "TableHeader") } override func viewDidAppear(_ animated: Bool) { self.prepareFavouriteTable() } func prepareFavouriteTable() { self.favouriteAnimals.removeAll() guard let favouriteIds = Favourite.get() else { log.debug("Brak ulubionych zwierzaków") return } // Sposób użycia: {{url}}/v1/animals?filter=0,1,2,3,4 for id in favouriteIds { Animal.getById(id, success: { [weak self] animals in DispatchQueue.main.async { //if species of animal is the same as the one set from header or any type of species is set if animals.first?.species?.rawValue == self?.favAnimalType.toString() || self?.favAnimalType.rawValue == 0 { self?.favouriteAnimals.append(animals.first!) log.debug("Zwierzak nr \(animals.first?.id) pobrany z ulubionych") self?.tableView.reloadData() } } }, failure: { _ in log.error("Błąd podczas pobierania ulubionych zwierzaków") } ) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return favouriteAnimals.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(withIdentifier: "favouriteCell", for: indexPath) as? FavouriteTableViewCell else { assert(false, "Cell should be favouriteCell") } cell.configureCell(withAnimal: favouriteAnimals[indexPath.row]) cell.delegate = self return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let bundle = Bundle.main header = bundle.loadNibNamed("FavouriteTableHeader", owner: self, options: nil)?.first as? FavouriteTableHeader header?.delegate = self header?.animalTypeSelector.selectedSegmentIndex = favAnimalType.rawValue return header } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard segue.identifier == "FavouriteAnimalSegue", let animalId = (sender as? FavouriteTableViewCell)?.favouriteAnimalId, let vc = segue.destination as? AnimalDetailViewController else { return } vc.animal = favouriteAnimals.filter( { $0.id == animalId } ).first } } extension FavouriteViewController: FavouriteTableHeaderDelegate { func didSelect(favAnimalType: FavAnimalType) { self.favAnimalType = favAnimalType prepareFavouriteTable() } } extension FavouriteViewController: FavouriteTableCellDelegate { func removeFromFavouritesAnimal(withId id: Int) { Favourite.delete(id) } }
apache-2.0
fd0b8abf3ea66904cb835e86dad80c27
29.846715
137
0.63204
4.954279
false
false
false
false
djwbrown/swift
stdlib/public/core/StringUTF16.swift
1
17555
//===--- StringUTF16.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // FIXME(ABI)#71 : The UTF-16 string view should have a custom iterator type to // allow performance optimizations of linear traversals. extension String { /// A view of a string's contents as a collection of UTF-16 code units. /// /// You can access a string's view of UTF-16 code units by using its `utf16` /// property. A string's UTF-16 view encodes the string's Unicode scalar /// values as 16-bit integers. /// /// let flowers = "Flowers 💐" /// for v in flowers.utf16 { /// print(v) /// } /// // 70 /// // 108 /// // 111 /// // 119 /// // 101 /// // 114 /// // 115 /// // 32 /// // 55357 /// // 56464 /// /// Unicode scalar values that make up a string's contents can be up to 21 /// bits long. The longer scalar values may need two `UInt16` values for /// storage. Those "pairs" of code units are called *surrogate pairs*. /// /// let flowermoji = "💐" /// for v in flowermoji.unicodeScalars { /// print(v, v.value) /// } /// // 💐 128144 /// /// for v in flowermoji.utf16 { /// print(v) /// } /// // 55357 /// // 56464 /// /// To convert a `String.UTF16View` instance back into a string, use the /// `String` type's `init(_:)` initializer. /// /// let favemoji = "My favorite emoji is 🎉" /// if let i = favemoji.utf16.index(where: { $0 >= 128 }) { /// let asciiPrefix = String(favemoji.utf16[..<i]) /// print(asciiPrefix) /// } /// // Prints "My favorite emoji is " /// /// UTF16View Elements Match NSString Characters /// ============================================ /// /// The UTF-16 code units of a string's `utf16` view match the elements /// accessed through indexed `NSString` APIs. /// /// print(flowers.utf16.count) /// // Prints "10" /// /// let nsflowers = flowers as NSString /// print(nsflowers.length) /// // Prints "10" /// /// Unlike `NSString`, however, `String.UTF16View` does not use integer /// indices. If you need to access a specific position in a UTF-16 view, use /// Swift's index manipulation methods. The following example accesses the /// fourth code unit in both the `flowers` and `nsflowers` strings: /// /// print(nsflowers.character(at: 3)) /// // Prints "119" /// /// let i = flowers.utf16.index(flowers.utf16.startIndex, offsetBy: 3) /// print(flowers.utf16[i]) /// // Prints "119" /// /// Although the Swift overlay updates many Objective-C methods to return /// native Swift indices and index ranges, some still return instances of /// `NSRange`. To convert an `NSRange` instance to a range of /// `String.UTF16View.Index`, follow these steps: /// /// 1. Use the `NSRange` type's `toRange` method to convert the instance to /// an optional range of `Int` values. /// 2. Use your string's `utf16` view's index manipulation methods to convert /// the integer bounds to `String.UTF16View.Index` values. /// 3. Create a new `Range` instance from the new index values. /// /// Here's an implementation of those steps, showing how to retrieve a /// substring described by an `NSRange` instance from the middle of a /// string. /// /// let snowy = "❄️ Let it snow! ☃️" /// let nsrange = NSRange(location: 3, length: 12) /// if let r = nsrange.toRange() { /// let start = snowy.utf16.index(snowy.utf16.startIndex, offsetBy: r.lowerBound) /// let end = snowy.utf16.index(snowy.utf16.startIndex, offsetBy: r.upperBound) /// let substringRange = start..<end /// print(snowy.utf16[substringRange]) /// } /// // Prints "Let it snow!" public struct UTF16View : BidirectionalCollection, CustomStringConvertible, CustomDebugStringConvertible { public typealias Index = String.Index public typealias IndexDistance = Int /// The position of the first code unit if the `String` is /// nonempty; identical to `endIndex` otherwise. public var startIndex: Index { return Index(encodedOffset: _offset) } /// The "past the end" position---that is, the position one greater than /// the last valid subscript argument. /// /// In an empty UTF-16 view, `endIndex` is equal to `startIndex`. public var endIndex: Index { return Index(encodedOffset: _offset + _length) } public struct Indices { internal var _elements: String.UTF16View internal var _startIndex: Index internal var _endIndex: Index } public var indices: Indices { return Indices( _elements: self, startIndex: startIndex, endIndex: endIndex) } // TODO: swift-3-indexing-model - add docs public func index(after i: Index) -> Index { // FIXME: swift-3-indexing-model: range check i? return Index(encodedOffset: _unsafePlus(i.encodedOffset, 1)) } // TODO: swift-3-indexing-model - add docs public func index(before i: Index) -> Index { // FIXME: swift-3-indexing-model: range check i? return Index(encodedOffset: _unsafeMinus(i.encodedOffset, 1)) } // TODO: swift-3-indexing-model - add docs public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { // FIXME: swift-3-indexing-model: range check i? return Index(encodedOffset: i.encodedOffset.advanced(by: n)) } // TODO: swift-3-indexing-model - add docs public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: range check i? let d = i.encodedOffset.distance(to: limit.encodedOffset) if (d > 0) ? (d < n) : (d > n) { return nil } return Index(encodedOffset: i.encodedOffset.advanced(by: n)) } // TODO: swift-3-indexing-model - add docs public func distance(from start: Index, to end: Index) -> IndexDistance { // FIXME: swift-3-indexing-model: range check start and end? return start.encodedOffset.distance(to: end.encodedOffset) } func _internalIndex(at i: Int) -> Int { return _core.startIndex + i } /// Accesses the code unit at the given position. /// /// The following example uses the subscript to print the value of a /// string's first UTF-16 code unit. /// /// let greeting = "Hello, friend!" /// let i = greeting.utf16.startIndex /// print("First character's UTF-16 code unit: \(greeting.utf16[i])") /// // Prints "First character's UTF-16 code unit: 72" /// /// - Parameter position: A valid index of the view. `position` must be /// less than the view's end index. public subscript(i: Index) -> UTF16.CodeUnit { _precondition(i >= startIndex && i < endIndex, "out-of-range access on a UTF16View") let index = _internalIndex(at: i.encodedOffset) let u = _core[index] if _fastPath((u &>> 11) != 0b1101_1) { // Neither high-surrogate, nor low-surrogate -- well-formed sequence // of 1 code unit. return u } if (u &>> 10) == 0b1101_10 { // `u` is a high-surrogate. Sequence is well-formed if it // is followed by a low-surrogate. if _fastPath( index + 1 < _core.count && (_core[index + 1] &>> 10) == 0b1101_11) { return u } return 0xfffd } // `u` is a low-surrogate. Sequence is well-formed if // previous code unit is a high-surrogate. if _fastPath(index != 0 && (_core[index - 1] &>> 10) == 0b1101_10) { return u } return 0xfffd } #if _runtime(_ObjC) // These may become less important once <rdar://problem/19255291> is addressed. @available( *, unavailable, message: "Indexing a String's UTF16View requires a String.UTF16View.Index, which can be constructed from Int when Foundation is imported") public subscript(i: Int) -> UTF16.CodeUnit { Builtin.unreachable() } @available( *, unavailable, message: "Slicing a String's UTF16View requires a Range<String.UTF16View.Index>, String.UTF16View.Index can be constructed from Int when Foundation is imported") public subscript(bounds: Range<Int>) -> UTF16View { Builtin.unreachable() } #endif /// Accesses the contiguous subrange of elements enclosed by the specified /// range. /// /// - Complexity: O(*n*) if the underlying string is bridged from /// Objective-C, where *n* is the length of the string; otherwise, O(1). public subscript(bounds: Range<Index>) -> UTF16View { return UTF16View( _core, offset: _internalIndex(at: bounds.lowerBound.encodedOffset), length: bounds.upperBound.encodedOffset - bounds.lowerBound.encodedOffset) } internal init(_ _core: _StringCore) { self.init(_core, offset: 0, length: _core.count) } internal init(_ _core: _StringCore, offset: Int, length: Int) { self._offset = offset self._length = length self._core = _core } public var description: String { let start = _internalIndex(at: _offset) let end = _internalIndex(at: _offset + _length) return String(_core[start..<end]) } public var debugDescription: String { return "StringUTF16(\(self.description.debugDescription))" } internal var _offset: Int internal var _length: Int internal let _core: _StringCore } /// A UTF-16 encoding of `self`. public var utf16: UTF16View { get { return UTF16View(_core) } set { self = String(describing: newValue) } } /// Creates a string corresponding to the given sequence of UTF-16 code units. /// /// If `utf16` contains unpaired UTF-16 surrogates, the result is `nil`. /// /// You can use this initializer to create a new string from a slice of /// another string's `utf16` view. /// /// let picnicGuest = "Deserving porcupine" /// if let i = picnicGuest.utf16.index(of: 32) { /// let adjective = String(picnicGuest.utf16[..<i]) /// print(adjective) /// } /// // Prints "Optional(Deserving)" /// /// The `adjective` constant is created by calling this initializer with a /// slice of the `picnicGuest.utf16` view. /// /// - Parameter utf16: A UTF-16 code sequence. public init?(_ utf16: UTF16View) { let wholeString = String(utf16._core) guard let start = UTF16Index(encodedOffset: utf16._offset) .samePosition(in: wholeString), let end = UTF16Index(encodedOffset: utf16._offset + utf16._length) .samePosition(in: wholeString) else { return nil } self = wholeString[start..<end] } /// The index type for subscripting a string's `utf16` view. public typealias UTF16Index = UTF16View.Index } extension String.UTF16View : _SwiftStringView { var _ephemeralContent : String { return _persistentContent } var _persistentContent : String { return String(self._core) } } // Index conversions extension String.UTF16View.Index { /// Creates an index in the given UTF-16 view that corresponds exactly to the /// specified string position. /// /// The following example finds the position of a space in a string and then /// converts that position to an index in the string's `utf16` view. /// /// let cafe = "Café 🍵" /// /// let stringIndex = cafe.index(of: "é")! /// let utf16Index = String.UTF16View.Index(stringIndex, within: cafe.utf16) /// /// print(cafe.utf16[...utf16Index]) /// // Prints "Café" /// /// - Parameters: /// - sourcePosition: A position in a string or one of its views /// - target: The `UTF16View` in which to find the new position. public init?( _ sourcePosition: String.Index, within target: String.UTF16View ) { guard sourcePosition._transcodedOffset == 0 else { return nil } self.init(encodedOffset: sourcePosition.encodedOffset) } /// Returns the position in the given view of Unicode scalars that /// corresponds exactly to this index. /// /// This index must be a valid index of `String(unicodeScalars).utf16`. /// /// This example first finds the position of a space (UTF-16 code point `32`) /// in a string's `utf16` view and then uses this method to find the same /// position in the string's `unicodeScalars` view. /// /// let cafe = "Café 🍵" /// let i = cafe.utf16.index(of: 32)! /// let j = i.samePosition(in: cafe.unicodeScalars)! /// print(cafe.unicodeScalars[..<j]) /// // Prints "Café" /// /// - Parameter unicodeScalars: The view to use for the index conversion. /// - Returns: The position in `unicodeScalars` that corresponds exactly to /// this index. If this index does not have an exact corresponding /// position in `unicodeScalars`, this method returns `nil`. For example, /// an attempt to convert the position of a UTF-16 trailing surrogate /// returns `nil`. public func samePosition( in unicodeScalars: String.UnicodeScalarView ) -> String.UnicodeScalarIndex? { return String.UnicodeScalarIndex(self, within: unicodeScalars) } } // Reflection extension String.UTF16View : CustomReflectable { /// Returns a mirror that reflects the UTF-16 view of a string. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } extension String.UTF16View : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(description) } } extension String.UTF16View.Indices : BidirectionalCollection { public typealias Index = String.UTF16View.Index public typealias IndexDistance = String.UTF16View.IndexDistance public typealias Indices = String.UTF16View.Indices public typealias SubSequence = String.UTF16View.Indices internal init( _elements: String.UTF16View, startIndex: Index, endIndex: Index ) { self._elements = _elements self._startIndex = startIndex self._endIndex = endIndex } public var startIndex: Index { return _startIndex } public var endIndex: Index { return _endIndex } public var indices: Indices { return self } public subscript(i: Index) -> Index { // FIXME: swift-3-indexing-model: range check. return i } public subscript(bounds: Range<Index>) -> String.UTF16View.Indices { // FIXME: swift-3-indexing-model: range check. return String.UTF16View.Indices( _elements: _elements, startIndex: bounds.lowerBound, endIndex: bounds.upperBound) } public func index(after i: Index) -> Index { // FIXME: swift-3-indexing-model: range check. return _elements.index(after: i) } public func formIndex(after i: inout Index) { // FIXME: swift-3-indexing-model: range check. _elements.formIndex(after: &i) } public func index(before i: Index) -> Index { // FIXME: swift-3-indexing-model: range check. return _elements.index(before: i) } public func formIndex(before i: inout Index) { // FIXME: swift-3-indexing-model: range check. _elements.formIndex(before: &i) } public func index(_ i: Index, offsetBy n: IndexDistance) -> Index { // FIXME: swift-3-indexing-model: range check i? return _elements.index(i, offsetBy: n) } public func index( _ i: Index, offsetBy n: IndexDistance, limitedBy limit: Index ) -> Index? { // FIXME: swift-3-indexing-model: range check i? return _elements.index(i, offsetBy: n, limitedBy: limit) } // TODO: swift-3-indexing-model - add docs public func distance(from start: Index, to end: Index) -> IndexDistance { // FIXME: swift-3-indexing-model: range check start and end? return _elements.distance(from: start, to: end) } } // backward compatibility for index interchange. extension String.UTF16View { @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index") public func index(after i: Index?) -> Index { return index(after: i) } @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index") public func index( _ i: Index?, offsetBy n: IndexDistance) -> Index { return index(i!, offsetBy: n) } @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional indices") public func distance(from i: Index?, to j: Index?) -> IndexDistance { return distance(from: i!, to: j!) } @available( swift, obsoleted: 4.0, message: "Any String view index conversion can fail in Swift 4; please unwrap the optional index") public subscript(i: Index?) -> Unicode.UTF16.CodeUnit { return self[i!] } }
apache-2.0
f2cffbd84d377207b79d22691608c9ee
33.293542
167
0.630336
3.984538
false
false
false
false
juliangrosshauser/HomeControl
HomeControl/Source/Store.swift
1
1350
// // Store.swift // HomeControl // // Created by Julian Grosshauser on 29/12/15. // Copyright © 2015 Julian Grosshauser. All rights reserved. // import CoreData /// Sets up Core Data stack and gives access to managed object context. public final class Store { //MARK: Properties /// Managed object context. public let context: NSManagedObjectContext //MARK: Initialization /// Construct `Store` by setting up Core Data stack. public init() { // Use `NSBundle(forClass:)` so that the code still works if it's moved to a different module. let bundle = NSBundle(forClass: Store.self) guard let model = NSManagedObjectModel.mergedModelFromBundles([bundle]) else { fatalError("Model not found") } let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model) let storeURL = NSURL.documentDirectory.URLByAppendingPathComponent("HomeControl.sqlite") do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil) } catch { fatalError("Couldn't add persistent store to coordinator: \(error)") } context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) context.persistentStoreCoordinator = coordinator } }
mit
4a066bf0b465c6eae02b1d437548bb01
31.119048
122
0.6894
5.249027
false
false
false
false
pennlabs/penn-mobile-ios
PennMobile/GSR-Booking/Views/GSRRangeSlider.swift
1
2853
// // GSRRangeSlider.swift // PennMobile // // Created by Josh Doman on 2/3/18. // Copyright © 2018 PennLabs. All rights reserved. // import Foundation protocol GSRRangeSliderDelegate { func parseData(startDate: Date, endDate: Date) func existsNonEmptyRoom() -> Bool func getMinDate() -> Date? func getMaxDate() -> Date? } class GSRRangeSlider: RangeSlider { fileprivate var startDate = Date.midnightYesterday fileprivate var endDate = Date.midnightToday fileprivate var minDate = Date.midnightYesterday fileprivate var maxDate = Date.midnightToday var delegate: GSRRangeSliderDelegate? override init(frame: CGRect) { super.init(frame: frame) setupUI() setupCallbacks() } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Reload override func reload() { guard let start = delegate?.getMinDate(), let end = delegate?.getMaxDate() else { return } startDate = start endDate = end super.reload() } } // MARK: - Setup extension GSRRangeSlider { fileprivate func setupUI() { self.setMinAndMaxValue(0, maxValue: 100) self.thumbSize = 24.0 self.displayTextFontSize = 14.0 } fileprivate func setupCallbacks() { self.setMinValueDisplayTextGetter { (minValue) -> String? in return self.delegate!.existsNonEmptyRoom() ? self.getStringTimeFromValue(minValue) : "" } self.setMaxValueDisplayTextGetter { (maxValue) -> String? in return self.delegate!.existsNonEmptyRoom() ? self.getStringTimeFromValue(maxValue) : "" } self.setValueFinishedChangingCallback { (min, max) in let totalMinutes = CGFloat(self.startDate.minutesFrom(date: self.endDate)) let minMinutes = (Int((CGFloat(min) / 100.0) * totalMinutes) / 60) * 60 let maxMinutes = (Int((CGFloat(max) / 100.0) * totalMinutes) / 60) * 60 self.minDate = self.startDate.add(minutes: minMinutes).roundedDownToHour self.maxDate = self.startDate.add(minutes: maxMinutes).roundedDownToHour self.delegate!.parseData(startDate: self.minDate, endDate: self.maxDate) } } private func getStringTimeFromValue(_ val: Int) -> String? { let formatter = DateFormatter() formatter.dateFormat = "hh:mma" formatter.locale = Locale(identifier: "en_US_POSIX") let totalMinutes = CGFloat(startDate.minutesFrom(date: endDate)) let minutes = Int((CGFloat(val) / 100.0) * totalMinutes) let chosenDate = startDate.add(minutes: minutes) formatter.amSymbol = "a" formatter.pmSymbol = "p" formatter.dateFormat = "ha" return formatter.string(from: chosenDate) } }
mit
0e718b39a2294e98b16ad0b4c1cacce1
33.361446
99
0.651823
4.20649
false
false
false
false
practicalswift/swift
test/decl/func/default-values-swift4.swift
6
4347
// RUN: %target-typecheck-verify-swift -swift-version 4 // RUN: %target-typecheck-verify-swift -swift-version 4 -enable-testing private func privateFunction() {} // expected-note@-1 2{{global function 'privateFunction()' is not public}} fileprivate func fileprivateFunction() {} // expected-note@-1 2{{global function 'fileprivateFunction()' is not public}} func internalFunction() {} // expected-note@-1 2{{global function 'internalFunction()' is not public}} @usableFromInline func versionedFunction() {} // expected-note@-1 5{{global function 'versionedFunction()' is not public}} public func publicFunction() {} func internalIntFunction() -> Int {} // expected-note@-1 {{global function 'internalIntFunction()' is not public}} private func privateFunction2() {} // expected-note@-1 2{{global function 'privateFunction2()' is not '@usableFromInline' or public}} fileprivate func fileprivateFunction2() {} // expected-note@-1 2{{global function 'fileprivateFunction2()' is not '@usableFromInline' or public}} func internalFunction2() {} // expected-note@-1 2{{global function 'internalFunction2()' is not '@usableFromInline' or public}} func internalIntFunction2() -> Int {} // expected-note@-1 {{global function 'internalIntFunction2()' is not '@usableFromInline' or public}} func internalFunctionWithDefaultValue( x: Int = { struct Nested {} // OK publicFunction() // OK versionedFunction() // OK internalFunction() // OK fileprivateFunction() // OK privateFunction() // OK return 0 }(), y: Int = internalIntFunction()) {} @usableFromInline func versionedFunctionWithDefaultValue( x: Int = { struct Nested {} // expected-error@-1 {{type 'Nested' cannot be nested inside a default argument value}} // FIXME: Some errors below are diagnosed twice publicFunction() // OK versionedFunction() // OK internalFunction2() // expected-error@-1 2{{global function 'internalFunction2()' is internal and cannot be referenced from a default argument value}} fileprivateFunction2() // expected-error@-1 2{{global function 'fileprivateFunction2()' is fileprivate and cannot be referenced from a default argument value}} privateFunction2() // expected-error@-1 2{{global function 'privateFunction2()' is private and cannot be referenced from a default argument value}} return 0 }(), y: Int = internalIntFunction2()) {} // expected-error@-1 {{global function 'internalIntFunction2()' is internal and cannot be referenced from a default argument value}} public func publicFunctionWithDefaultValue( x: Int = { struct Nested {} // expected-error@-1 {{type 'Nested' cannot be nested inside a default argument value}} // FIXME: Some errors below are diagnosed twice publicFunction() versionedFunction() // expected-error@-1 2{{global function 'versionedFunction()' is internal and cannot be referenced from a default argument value}} internalFunction() // expected-error@-1 2{{global function 'internalFunction()' is internal and cannot be referenced from a default argument value}} fileprivateFunction() // expected-error@-1 2{{global function 'fileprivateFunction()' is fileprivate and cannot be referenced from a default argument value}} privateFunction() // expected-error@-1 2{{global function 'privateFunction()' is private and cannot be referenced from a default argument value}} return 0 }(), y: Int = internalIntFunction()) {} // expected-error@-1 {{global function 'internalIntFunction()' is internal and cannot be referenced from a default argument value}} // https://bugs.swift.org/browse/SR-5559 public class MyClass { public func method<T>(_: T.Type = T.self) -> T { } } public func evilCode( x: Int = { let _ = publicFunction() let _ = versionedFunction() // expected-error@-1 2{{global function 'versionedFunction()' is internal and cannot be referenced from a default argument value}} func localFunction() { publicFunction() versionedFunction() // expected-error@-1 {{global function 'versionedFunction()' is internal and cannot be referenced from a default argument value}} } return 0 }()) {}
apache-2.0
defe6966c6eac28517e9f59bf7308860
37.469027
142
0.691511
4.803315
false
false
false
false
ajohnson388/rss-reader
RSS Reader/RSS Reader/CustomListViewController.swift
1
6135
// // CustomListViewController.swift // RSS Reader // // Created by Andrew Johnson on 9/16/16. // Copyright © 2016 Andrew Johnson. All rights reserved. // import Foundation /** A delegate protocol that interfaces a selection chosen inside the SelectionListViewController. */ protocol CustomListDelegate { func didSelectItem(_ item: String?, forListID id: String) } /** A view controller that allows a user to create a new item or create an item based on previously used items. */ class CustomListViewController: UITableViewController { // MARK: Fields let listID: String let list: [String] var filteredList: [String] var listDelegate: CustomListDelegate? var selection: String? var textFieldButtonCell = TextFieldButtonTableViewCell() // MARK: Initializers init(items: [String], selection: String?, listID: String, title: String?, listDelegate: CustomListDelegate?) { list = items filteredList = list self.selection = selection self.listID = listID self.listDelegate = listDelegate super.init(style: .grouped) navigationItem.title = title } required init?(coder aDecoder: NSCoder) { fatalError("\(#function) should not be used") } // MARK: Helper Methods // Loads the filteredList parameter based of the textFieldButtonCell text string. Calling this method does not reaload the table view. fileprivate func loadFilteredList() { //If the searchbar is empty display all items guard let searchText = textFieldButtonCell.textField.text , searchText != "" else { filteredList = list return } //Filter the list since there is search text filteredList = list.filter({ return $0.lowercased().contains(searchText.lowercased()) }) } fileprivate func refreshAddButton() { let text = textFieldButtonCell.textField.text?.trimmingCharacters(in: CharacterSet.whitespaces) ?? "" textFieldButtonCell.addButton.isEnabled = text != "" } func setupTextFieldButtonCell() { textFieldButtonCell.addButton.addTarget(self, action: #selector(addButtonTapped(_:)), for: .touchUpInside) textFieldButtonCell.textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) textFieldButtonCell.textField.placeholder = "Tap to add a new field" textFieldButtonCell.textField.delegate = self // Preset the text field if the selection is not in the list if let selection = selection , !list.contains(selection) { textFieldButtonCell.textField.text = selection } refreshAddButton() } // MARK: UIViewController LifeCycle Methods override func viewDidLoad() { super.viewDidLoad() setupTextFieldButtonCell() } override func viewWillDisappear(_ animated: Bool) { textFieldButtonCell.textField.resignFirstResponder() super.viewWillDisappear(animated) } // MARK: Selectors func textFieldDidChange(_ sender: UITextField!) { loadFilteredList() UIView.setAnimationsEnabled(false) tableView.beginUpdates() tableView.reloadSections(IndexSet(integer: 1), with: .none) tableView.endUpdates() UIView.setAnimationsEnabled(true) refreshAddButton() } func addButtonTapped(_ sender: UIButton?) { selection = textFieldButtonCell.textField.text listDelegate?.didSelectItem(selection, forListID: listID) _ = navigationController?.popViewController(animated: true) // TODO - Prompt error } // MARK: UITableView DataSource override func numberOfSections(in tableView: UITableView) -> Int { return 2 // TextFieldButtonCell and list } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if (indexPath as NSIndexPath).section == 0 { return textFieldButtonCell } else { let reuseID = "list_cell" let cell = tableView.dequeueReusableCell(withIdentifier: reuseID) ?? UITableViewCell(style: .value1, reuseIdentifier: reuseID) let item = filteredList[(indexPath as NSIndexPath).row] cell.textLabel?.attributedText = TextUtils.boldSearchResult(textFieldButtonCell.textField.text, resultString: item, size: cell.textLabel?.font.pointSize) cell.selectionStyle = .gray cell.accessoryView = nil cell.accessoryType = selection == item ? .checkmark : .none return cell } } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? 1 : filteredList.count } // MARK: UITableView Delegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) // Assert a list cell was touched guard (indexPath as NSIndexPath).section == 1 else { return } let item = filteredList[(indexPath as NSIndexPath).row] // Set the selection or deselect selection = selection == item ? nil : item // Update the cell tableView.beginUpdates() tableView.reloadRows(at: [indexPath], with: .automatic) tableView.endUpdates() // Call the delegate method and pop the controller listDelegate?.didSelectItem(selection, forListID: listID) _ = navigationController?.popViewController(animated: true) } override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { textFieldButtonCell.textField.resignFirstResponder() } } // MARK: TextField Delegate extension CustomListViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { addButtonTapped(nil) return true } }
apache-2.0
f8d89d79efca9459acd8fe7201f2a3fa
33.268156
165
0.66058
5.357205
false
false
false
false
ProVir/WebServiceSwift
Source/WebServiceRequestProvider.swift
1
12451
// // WebServiceRequestProvider.swift // WebServiceSwift 3.0.0 // // Created by Короткий Виталий (ViR) on 24.04.2018. // Updated to 3.0.0 by Короткий Виталий (ViR) on 04.09.2018. // Copyright © 2018 ProVir. All rights reserved. // import Foundation /// Provider for single request type. public class WebServiceRequestProvider<RequestType: WebServiceRequesting>: WebServiceProvider { fileprivate let service: WebService public required init(webService: WebService) { self.service = webService } /// Response delegate for responses. Apply before call new request. public weak var delegate: WebServiceDelegate? /// Default excludeDuplicate for hashable requests. public var excludeDuplicateDefault: Bool = false /// When `true` - response result from storage send to delegate only if have data. public var responseStorageOnlyDataForDelegate: Bool = false // MARK: Perform requests and read from storage /** Request to server (endpoint). Response result in closure. - Parameters: - request: The request with data and result type. - completionHandler: Closure for response result from server. */ public func performRequest(_ request: RequestType, completionHandler: @escaping (_ response: WebServiceResponse<RequestType.ResultType>) -> Void) { service.performBaseRequest(request, key: nil, excludeDuplicate: excludeDuplicateDefault, completionHandler: { completionHandler( $0.convert() ) }) } /** Request to server (endpoint). Response result in closure. - Parameters: - request: The request with data and result type. - key: Unique key for controling requests - contains and canceled. Also use for excludeDuplicate. - excludeDuplicate: Exclude duplicate requests. Requests are equal if their keys match. - completionHandler: Closure for response result from server. */ public func performRequest(_ request: RequestType, key: AnyHashable, excludeDuplicate: Bool, completionHandler: @escaping (_ response: WebServiceResponse<RequestType.ResultType>) -> Void) { service.performBaseRequest(request, key: key, excludeDuplicate: excludeDuplicate, completionHandler: { completionHandler( $0.convert() ) }) } /** Read last success data from storage. Response result in closure. - Parameters: - request: The request with data. - dependencyNextRequest: Type dependency from next performRequest. - completionHandler: Closure for read data from storage. - timeStamp: TimeStamp when saved from server (endpoint). - response: Result read from storage. */ public func readStorage(_ request: RequestType, dependencyNextRequest: WebService.ReadStorageDependencyType = .notDepend, completionHandler: @escaping (_ timeStamp: Date?, _ response: WebServiceResponse<RequestType.ResultType>) -> Void) { service.readStorage(request, dependencyNextRequest: dependencyNextRequest, completionHandler: completionHandler) } // MARK: Perform requests use delegate for response /** Request to server (endpoint). Response result send to `WebServiceRequestProvider.delegate`. - Parameters: - request: The request with data. */ public func performRequest(_ request: RequestType) { internalPerformRequest(request, key: nil, excludeDuplicate: excludeDuplicateDefault, responseDelegate: delegate) } /** Request to server (endpoint). Response result send to `WebServiceRequestProvider.delegate`. - Parameters: - request: The request with data. - key: unique key for controling requests - contains and canceled. Also use for excludeDuplicate. - excludeDuplicate: Exclude duplicate requests. Requests are equal if their keys match. */ public func performRequest(_ request: RequestType, key: AnyHashable, excludeDuplicate: Bool) { service.performRequest(request, key: key, excludeDuplicate: excludeDuplicate, responseDelegate: delegate) } /** Read last success data from storage. Response result send to `WebServiceRequestProvider.delegate`. - Parameters: - request: The request with data. - key: unique key for controling requests, use only for response delegate. - dependencyNextRequest: Type dependency from next performRequest. - responseOnlyData: When `true` - response result send to delegate only if have data. Default use `responseStorageOnlyDataForDelegate`. */ public func readStorage(_ request: RequestType, key: AnyHashable? = nil, dependencyNextRequest: WebService.ReadStorageDependencyType = .notDepend, responseOnlyData: Bool? = nil) { if let delegate = delegate { service.readStorage(request, key: key, dependencyNextRequest: dependencyNextRequest, responseOnlyData: responseOnlyData ?? responseStorageOnlyDataForDelegate, responseDelegate: delegate) } } // MARK: Contains requests /** Returns a Boolean value indicating whether the current queue contains requests the given type. - Returns: `true` if one request with RequestType.Type was found in the current queue; otherwise, `false`. */ public func containsRequests() -> Bool { return service.containsRequest(type: RequestType.self) } /** Returns a Boolean value indicating whether the current queue contains the given request with key. - Parameter key: The key to find requests in the current queue. - Returns: `true` if the request with key was found in the current queue; otherwise, `false`. */ public func containsRequest(key: AnyHashable) -> Bool { return service.containsRequest(key: key) } /** Returns a Boolean value indicating whether the current queue contains requests the given type key. - Parameter keyType: The type requestKey to find in the all current queue. - Returns: `true` if one request with key.Type was found in the current queue; otherwise, `false`. */ public func containsRequest<K: Hashable>(keyType: K.Type) -> Bool { return service.containsRequest(keyType: keyType) } //MARK: Cancel requests /// Cancel all requests for request type. The RequestType.Type to find in the current queue. public func cancelRequests() { service.cancelRequests(type: RequestType.self) } /** Cancel all requests with key. - Parameter key: The key to find in the current queue. */ public func cancelRequests(key: AnyHashable) { service.cancelRequests(key: key) } /** Cancel all requests with key.Type. - Parameter keyType: The key.Type to find in the current queue. */ public func cancelRequests<K: Hashable>(keyType: K.Type) { service.cancelRequests(keyType: keyType) } //MARK: Delete data in Storages /** Delete data in storage for concrete request. - Parameter request: Original request. */ public func deleteInStorage(request: RequestType) { service.deleteInStorage(request: request) } //MARK: Internal private func internalPerformRequest(_ request: WebServiceBaseRequesting, key: AnyHashable?, excludeDuplicate: Bool, responseDelegate delegate: WebServiceDelegate?) { service.performBaseRequest(request, key: key, excludeDuplicate: excludeDuplicate) { [weak delegate] response in if let delegate = delegate { delegate.webServiceResponse(request: request, key: key, isStorageRequest: false, response: response) } } } } //MARK: Support Hashable requests extension WebServiceRequestProvider where RequestType: Hashable { /** Request to server (endpoint). Response result in closure. - Parameters: - request: The hashable (also equatable) request with data and result type. - excludeDuplicate: Exclude duplicate equatable requests. - completionHandler: Closure for response result from server. */ public func performRequest(_ request: RequestType, excludeDuplicate: Bool, completionHandler: @escaping (_ response: WebServiceResponse<RequestType.ResultType>) -> Void) { service.performBaseRequest(request, key: nil, excludeDuplicate: excludeDuplicate, completionHandler: { completionHandler( $0.convert() ) }) } /** Request to server (endpoint). Response result send to `WebServiceRequestProvider.delegate`. - Parameters: - request: The hashable (also equatable) request with data. - excludeDuplicate: Exclude duplicate equatable requests. */ public func performRequest(_ request: RequestType, excludeDuplicate: Bool) { internalPerformRequest(request, key: nil, excludeDuplicate: excludeDuplicate, responseDelegate: delegate) } /** Returns a Boolean value indicating whether the current queue contains the given request. - Parameter request: The request to find in the current queue. - Returns: `true` if the request was found in the current queue; otherwise, `false`. */ public func containsRequest(_ request: RequestType) -> Bool { return service.containsRequest(request) } /** Cancel all requests with equal this request. - Parameter request: The request to find in the current queue. */ public func cancelRequests(_ request: RequestType) { service.cancelRequests(request) } } //MARK: Support Empty requests extension WebServiceRequestProvider where RequestType: WebServiceEmptyRequesting { /** Request to server (endpoint). Response result in closure. - Parameters: - completionHandler: Closure for response result from server. */ public func performRequest(completionHandler: @escaping (_ response: WebServiceResponse<RequestType.ResultType>) -> Void) { service.performBaseRequest(RequestType.init(), key: nil, excludeDuplicate: excludeDuplicateDefault, completionHandler: { completionHandler( $0.convert() ) }) } /** Request to server (endpoint). Response result send to `WebServiceRequestProvider.delegate`. */ public func performRequest() { internalPerformRequest(RequestType.init(), key: nil, excludeDuplicate: excludeDuplicateDefault, responseDelegate: delegate) } /** Read last success data from storage. Response result in closure. - Parameters: - dependencyNextRequest: Type dependency from next performRequest. - completionHandler: Closure for read data from storage. - timeStamp: TimeStamp when saved from server (endpoint). - response: Result read from storage. */ public func readStorage(dependencyNextRequest: WebService.ReadStorageDependencyType = .notDepend, completionHandler: @escaping (_ timeStamp: Date?, _ response: WebServiceResponse<RequestType.ResultType>) -> Void) { service.readStorage(RequestType.init(), dependencyNextRequest: dependencyNextRequest, completionHandler: completionHandler) } /** Read last success data from storage. Response result send to `WebServiceRequestProvider.delegate`. - Parameters: - key: unique key for controling requests, use only for response delegate. - dependencyNextRequest: Type dependency from next performRequest. - responseOnlyData: When `true` - response result send to delegate only if have data. Default use `responseStorageOnlyDataForDelegate`. */ public func readStorage(key: AnyHashable? = nil, dependencyNextRequest: WebService.ReadStorageDependencyType = .notDepend, responseOnlyData: Bool? = nil) { if let delegate = delegate { service.readStorage(RequestType.init(), key: key, dependencyNextRequest: dependencyNextRequest, responseOnlyData: responseOnlyData ?? responseStorageOnlyDataForDelegate, responseDelegate: delegate) } } }
mit
af3e75d36e62bc84c724e6d3466626ce
42.125
242
0.685024
5.157807
false
false
false
false
kysonyangs/ysbilibili
ysbilibili/Classes/Home/Live/View/YSLiveHeadMenu.swift
1
2375
// // HomeLiveHeadMenu.swift // zhnbilibili // // Created by zhn on 16/11/30. // Copyright © 2016年 zhn. All rights reserved. // import UIKit class YSLiveHeadMenu: UIView { struct HeadItem { var title: String var imageName: String } fileprivate let items = [ HeadItem(title: "关注", imageName: "live_home_follow_ico"), HeadItem(title: "中心", imageName: "live_home_center_ico"), HeadItem(title: "小视频", imageName: "live_home_video_ico"), HeadItem(title: "搜索", imageName: "live_home_search_ico"), HeadItem(title: "分类", imageName: "live_home_category_ico") ] override init(frame: CGRect) { super.init(frame: frame) let bWidth = kScreenWidth / CGFloat(items.count) for (index, headItem) in items.enumerated() { let button = UIButton(type: .custom) button.tag = index button.addTarget(self, action: #selector(menuChoseAction(_:)), for: .touchUpInside) self.addSubview(button) button.snp.makeConstraints({ (make) in make.top.bottom.equalTo(self) make.width.equalTo(bWidth) make.left.equalTo(self).offset(bWidth * CGFloat(index)) }) let imgv = UIImageView(image: UIImage(named: headItem.imageName)) button.addSubview(imgv) let textLabel = UILabel() textLabel.text = headItem.title textLabel.font = UIFont.systemFont(ofSize: 12) textLabel.textAlignment = .center button.addSubview(textLabel) imgv.snp.makeConstraints({ (make) in make.centerX.equalTo(button) make.size.equalTo(CGSize(width: 50, height: 50)) make.centerY.equalTo(button).offset(-10) }) textLabel.snp.makeConstraints({ (make) in make.centerX.equalTo(button) make.left.right.equalTo(button) make.top.equalTo(imgv.snp.bottom) make.height.equalTo(20) }) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc fileprivate func menuChoseAction(_ sender: UIButton) { print(sender.tag) } }
mit
7deffe3ee4451a8c9122421d99d4926c
33.057971
95
0.570638
4.234234
false
false
false
false
biohazardlover/ROer
Roer/StatusCalculator.swift
1
40728
import Foundation import UIKit import JavaScriptCore let StatusCalculatorValueDidChangeNotification = "StatusCalculatorValueDidChangeNotification" var context: JSContext! var www: UIWebView! @objc protocol StatusCalculatorDelegate: NSObjectProtocol { @objc optional func statusCalculatorDidFinishLoad(_ statusCalculator: StatusCalculator) @objc optional func statusCalculator(_ statusCalculator: StatusCalculator, didFailLoadWithError error: NSError?) } class StatusCalculator: NSObject { weak var delegate: StatusCalculatorDelegate? class ElementSection { var title: String var elements: [AnyObject] init(title: String, elements: [AnyObject]) { self.title = title self.elements = elements } } class Element { fileprivate(set) var id: String! fileprivate(set) var name: String! fileprivate(set) var description: String? fileprivate var observer: NSObjectProtocol! fileprivate var idOrName: String { return id ?? name } init(id: String, description: String?) { self.id = id self.description = description addObserver() } init(name: String, description: String?) { self.name = name self.description = description addObserver() } deinit { removeObserver() } func addObserver() { observer = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: StatusCalculatorValueDidChangeNotification), object: nil, queue: OperationQueue.main) { [weak self] (note) -> Void in self?.clearCachedValues() } } func removeObserver() { NotificationCenter.default.removeObserver(observer) } func clearCachedValues() { } } class StaticTextElement: Element { fileprivate var _textContent: String? var textContent: String { get { if _textContent == nil { _textContent = context.evaluateScript("document.getElementById('" + id + "').textContent").toString() } return _textContent! } } override func clearCachedValues() { super.clearCachedValues() _textContent = nil } } class InputElement: Element { } class CheckboxInputElement: InputElement { fileprivate var _checked: Bool? var checked: Bool { set { context.evaluateScript("document.calcForm." + idOrName + ".checked = \(newValue)") context.evaluateScript("document.calcForm." + idOrName + ".onclick()") NotificationCenter.default.post(name: Notification.Name(rawValue: StatusCalculatorValueDidChangeNotification), object: nil) } get { if _checked == nil { _checked = context.evaluateScript("document.calcForm." + idOrName + ".checked").toBool() } return _checked! } } override func clearCachedValues() { super.clearCachedValues() _checked = nil } } class NumberInputElement: InputElement { fileprivate var _min: Int? = nil var min: Int { get { if _min == nil { _min = Int(context.evaluateScript("document.calcForm.\(idOrName).min").toInt32()) } return _min! } } fileprivate var _max: Int? = nil var max: Int { get { if _max == nil { _max = Int(context.evaluateScript("document.calcForm.\(idOrName).max").toInt32()) } return _max! } } fileprivate var _value: Int? = nil var value: Int { set { // context.evaluateScript("document.calcForm.\(idOrName).value = \(newValue)") // context.evaluateScript("document.calcForm.\(idOrName).onchange()") www.stringByEvaluatingJavaScript(from: "document.calcForm.\(idOrName).value = \(newValue)") www.stringByEvaluatingJavaScript(from: "document.calcForm.\(idOrName).onchange()") NotificationCenter.default.post(name: Notification.Name(rawValue: StatusCalculatorValueDidChangeNotification), object: nil) } get { if _value == nil { _value = Int(context.evaluateScript("document.calcForm.\(idOrName).value").toInt32()) } return _value! } } override func clearCachedValues() { super.clearCachedValues() _min = nil _max = nil _value = nil } } class TextInputElement: InputElement { var value: String? override func clearCachedValues() { super.clearCachedValues() } } class SelectElement: Element { fileprivate var _options: [Option]? var options: [Option] { get { if _options == nil { _options = [Option]() let length = context.evaluateScript("document.calcForm." + idOrName + ".options.length").toInt32() for i in 0..<length { let text = context.evaluateScript("document.calcForm." + idOrName + ".options[\(i)].text").toString() let value = context.evaluateScript("document.calcForm." + idOrName + ".options[\(i)].value").toString() let option = Option(text: text!, value: value!) _options!.append(option) } } return _options! } } fileprivate var _length: Int? var length: Int { get { if _length == nil { _length = Int(context.evaluateScript("document.calcForm." + idOrName + ".length").toInt32()) } return _length! } } fileprivate var _selectedIndex: Int? var selectedIndex: Int { set { let aaa = "document.calcForm.\(idOrName).selectedIndex = \(newValue);" + "document.calcForm.\(idOrName).onchange();" // context.performSelectorOnMainThread("evaluateScript:", withObject: aaa, waitUntilDone: true) www.stringByEvaluatingJavaScript(from: aaa) NotificationCenter.default.post(name: Notification.Name(rawValue: StatusCalculatorValueDidChangeNotification), object: nil) } get { if _selectedIndex == nil { _selectedIndex = Int(context.evaluateScript("document.calcForm." + idOrName + ".selectedIndex").toInt32()) } return _selectedIndex! } } fileprivate var _currentText: String? var currentText: String { get { if _currentText == nil { if selectedIndex >= 0 && selectedIndex < length { _currentText = context.evaluateScript("document.calcForm.\(idOrName).options[\(selectedIndex)].text").toString() } else { _currentText = "" } } return _currentText! } } override func clearCachedValues() { super.clearCachedValues() _options = nil _length = nil _selectedIndex = nil _currentText = nil } } class Option { var text: String var value: String init(text: String, value: String) { self.text = text self.value = value } } fileprivate var automaticallyAdjustsBaseLevel = CheckboxInputElement(name: "BLVauto", description: "") fileprivate var job = SelectElement(name: "A_JOB", description: "Class") fileprivate var baseLevel = SelectElement(name: "A_BaseLV", description: "Base Lv.") fileprivate var jobLevel = SelectElement(name: "A_JobLV", description: "Job Lv.") fileprivate var str = SelectElement(name: "A_STR", description: "STR") fileprivate var strPlus = StaticTextElement(id: "A_STRp", description: "STR Plus") fileprivate var agi = SelectElement(name: "A_AGI", description: "AGI") fileprivate var agiPlus = StaticTextElement(id: "A_AGIp", description: "AGI Plus") fileprivate var vit = SelectElement(name: "A_VIT", description: "VIT") fileprivate var vitPlus = StaticTextElement(id: "A_VITp", description: "VIT Plus") fileprivate var int = SelectElement(name: "A_INT", description: "INT") fileprivate var intPlus = StaticTextElement(id: "A_INTp", description: "INT Plus") fileprivate var dex = SelectElement(name: "A_DEX", description: "DEX") fileprivate var dexPlus = StaticTextElement(id: "A_DEXp", description: "DEX Plus") fileprivate var luk = SelectElement(name: "A_LUK", description: "LUK") fileprivate var lukPlus = StaticTextElement(id: "A_LUKp", description: "LUK Plus") fileprivate var maxHp = StaticTextElement(id: "A_MaxHP", description: "Max HP") fileprivate var maxSp = StaticTextElement(id: "A_MaxSP", description: "Max SP") fileprivate var atk = StaticTextElement(id: "A_ATK", description: "ATK") fileprivate var def = StaticTextElement(id: "A_totalDEF", description: "DEF") fileprivate var matk = StaticTextElement(id: "A_MATK", description: "MATK") fileprivate var mdef = StaticTextElement(id: "A_MDEF", description: "MDEF") fileprivate var hit = StaticTextElement(id: "A_HIT", description: "HIT") fileprivate var flee = StaticTextElement(id: "A_FLEE", description: "FLEE") fileprivate var perfectDodge = StaticTextElement(id: "A_LUCKY", description: "P. Dodge") fileprivate var critical = StaticTextElement(id: "A_CRI", description: "Critical") fileprivate var aspd = StaticTextElement(id: "A_ASPD", description: "ASPD") fileprivate var hpRegen = StaticTextElement(id: "A_HPR", description: "HP Regen") fileprivate var spRegen = StaticTextElement(id: "A_SPR", description: "SP Regen") fileprivate var statusPoint = StaticTextElement(id: "A_STPOINT", description: "Status Point") fileprivate var mainWeaponType = SelectElement(name: "A_WeaponType", description: "Weapon Type") fileprivate var mainWeaponName = SelectElement(name: "A_weapon1", description: "Name") fileprivate var mainWeaponRefining = SelectElement(name: "A_Weapon_ATKplus", description: nil) fileprivate var mainWeaponCardShortcuts = SelectElement(name: "A_SHORTCUT_R", description: "Card Shortcuts") fileprivate var mainWeaponCard1 = SelectElement(name: "A_weapon1_card1", description: "Card 1") fileprivate var mainWeaponCard2 = SelectElement(name: "A_weapon1_card2", description: "Card 2") fileprivate var mainWeaponCard3 = SelectElement(name: "A_weapon1_card3", description: "Card 3") fileprivate var mainWeaponCard4 = SelectElement(name: "A_weapon1_card4", description: "Card 4") fileprivate var mainWeaponElement = SelectElement(name: "A_Weapon_element", description: "Element") fileprivate var mainWeaponProjectile = SelectElement(name: "A_Arrow", description: "Projectile") fileprivate var armorCardShortcuts = SelectElement(name: "A_cardshort", description: nil) fileprivate var upperHeadgear = SelectElement(name: "A_head1", description: "Upper Headgear") fileprivate var upperHeadgearRefining = SelectElement(name: "A_HEAD_DEF_PLUS", description: nil) fileprivate var upperHeadgearCard = SelectElement(name: "A_head1_card", description: "") fileprivate var upperHeadgearEnchant = SelectElement(name: "A_HSE_HEAD1", description: nil) fileprivate var middleHeadgear = SelectElement(name: "A_head2", description: "Middle Headgear") fileprivate var middleHeadgearCard = SelectElement(name: "A_head2_card", description: "") fileprivate var lowerHeadgear = SelectElement(name: "A_head3", description: "Lower Headgear") fileprivate var armor = SelectElement(name: "A_body", description: "Armor") fileprivate var armorRefining = SelectElement(name: "A_BODY_DEF_PLUS", description: nil) fileprivate var armorCard = SelectElement(name: "A_body_card", description: "") fileprivate var armorEnchant = SelectElement(name: "A_HSE", description: nil) fileprivate var shield = SelectElement(name: "A_left", description: "Shield") fileprivate var shieldRefining = SelectElement(name: "A_LEFT_DEF_PLUS", description: nil) fileprivate var shieldCard = SelectElement(name: "A_left_card", description: "") fileprivate var garment = SelectElement(name: "A_shoulder", description: "Garment") fileprivate var garmentRefining = SelectElement(name: "A_SHOULDER_DEF_PLUS", description: nil) fileprivate var garmentCard = SelectElement(name: "A_shoulder_card", description: "") fileprivate var footgear = SelectElement(name: "A_shoes", description: "Footgear") fileprivate var footgearRefining = SelectElement(name: "A_SHOES_DEF_PLUS", description: nil) fileprivate var footgearCard = SelectElement(name: "A_shoes_card", description: "") fileprivate var accessory1 = SelectElement(name: "A_acces1", description: "Accessory") fileprivate var accessory1Card = SelectElement(name: "A_acces1_card", description: "") fileprivate var accessory2 = SelectElement(name: "A_acces2", description: "Accessory") fileprivate var accessory2Card = SelectElement(name: "A_acces2_card", description: "") fileprivate var strEnchant = NumberInputElement(id: "E_BOOST_STR", description: "STR") fileprivate var agiEnchant = NumberInputElement(id: "E_BOOST_AGI", description: "AGI") fileprivate var vitEnchant = NumberInputElement(id: "E_BOOST_VIT", description: "VIT") fileprivate var intEnchant = NumberInputElement(id: "E_BOOST_INT", description: "INT") fileprivate var dexEnchant = NumberInputElement(id: "E_BOOST_DEX", description: "DEX") fileprivate var lukEnchant = NumberInputElement(id: "E_BOOST_LUK", description: "LUK") fileprivate var atkEnchant = NumberInputElement(id: "E_BOOST_ATK", description: "ATK") fileprivate var atkPercentEnchant = NumberInputElement(id: "E_BOOST_ATK_PERC", description: "ATK %") fileprivate var matkEnchant = NumberInputElement(id: "E_BOOST_MATK", description: "MATK") fileprivate var matkPercentEnchant = NumberInputElement(id: "E_BOOST_MATK_PERC", description: "MATK %") fileprivate var hitEnchant = NumberInputElement(id: "E_BOOST_HIT", description: "HIT") fileprivate var fleeEnchant = NumberInputElement(id: "E_BOOST_FLEE", description: "FLEE") fileprivate var perfectDodgeEnchant = NumberInputElement(id: "E_BOOST_DODGE", description: "P. Dodge") fileprivate var criticalEnchant = NumberInputElement(id: "E_BOOST_CRIT", description: "CRIT") fileprivate var maxHpEnchant = NumberInputElement(id: "E_BOOST_HP", description: "MAX HP") fileprivate var maxSpEnchant = NumberInputElement(id: "E_BOOST_SP", description: "MAX SP") fileprivate var maxHpPercentEnchant = NumberInputElement(id: "E_BOOST_HP_PERC", description: "MAX HP %") fileprivate var maxSpPercentEnchant = NumberInputElement(id: "E_BOOST_SP_PERC", description: "MAX SP %") fileprivate var defEnchant = NumberInputElement(id: "E_BOOST_DEF", description: "DEF") fileprivate var mdefEnchant = NumberInputElement(id: "E_BOOST_MDEF", description: "MDEF") fileprivate var aspdEnchant = NumberInputElement(id: "E_BOOST_ASPD", description: "ASPD") fileprivate var aspdPercentEnchant = NumberInputElement(id: "E_BOOST_ASPD_PERC", description: "ASPD %") fileprivate var rangedDamagePercentEnchant = NumberInputElement(id: "E_BOOST_RANGED", description: "Ranged Damage %") fileprivate var damageReductionPercentEnchant = NumberInputElement(id: "E_BOOST_RED_PERC", description: "Damage Reduction %") fileprivate var castTimePercentEnchant = NumberInputElement(id: "E_BOOST_CASTING", description: "Cast Time %") fileprivate var blessing = SelectElement(id: "blessing", description: "Blessing") fileprivate var increaseAgi = SelectElement(id: "increaseAgi", description: "Increase AGI") fileprivate var angelus = SelectElement(id: "angelus", description: "Angelus") fileprivate var impositioManus = SelectElement(id: "imposito", description: "Impositio Manus") fileprivate var suffragium = SelectElement(id: "suffragium", description: "Suffragium") fileprivate var gloria = CheckboxInputElement(id: "gloria", description: "Gloria") fileprivate var assumptio = SelectElement(id: "assumptio", description: "Assumptio") fileprivate var spiritSpheres = SelectElement(id: "spheres", description: "Spirit Spheres") fileprivate var clementia = SelectElement(id: "clementia", description: "Clementia (bonus)") fileprivate var cantoCandidus = SelectElement(id: "candidus", description: "Canto Candidus (bonus)") fileprivate var expiatio = SelectElement(id: "expiatio", description: "Expiatio") fileprivate var sacrament = SelectElement(id: "sacrament", description: "Sacrament") fileprivate var laudaAgnus = SelectElement(id: "agnus", description: "Lauda Agnus") fileprivate var laudaRamus = SelectElement(id: "ramus", description: "Lauda Ramus") fileprivate var gentleTouchConvert = SelectElement(id: "ppChange", description: "Gentle Touch Convert") fileprivate var gentleTouchRevitalize = SelectElement(id: "ppRevitalize", description: "Gentle Touch Revitalize") fileprivate var suraStr = SelectElement(id: "suraStr", description: "Sura stats") fileprivate var suraAgi = SelectElement(id: "suraAgi", description: nil) fileprivate var suraVit = SelectElement(id: "suraVit", description: nil) fileprivate var suraInt = SelectElement(id: "suraInt", description: nil) fileprivate var suraDex = SelectElement(id: "suraDex", description: nil) fileprivate var bardSkills = SelectElement(id: "bardSkills", description: "Bard") fileprivate var bardSkillLevel = SelectElement(id: "bardSkillLevel", description: nil) fileprivate var musicLessons = SelectElement(id: "musicLessons", description: "") fileprivate var maestroSkills = SelectElement(id: "maestroSkills", description: "") fileprivate var maestroSkillLevel = SelectElement(id: "maestroSkillLevel", description: nil) fileprivate var voiceLessonsMaestro = SelectElement(id: "voiceLessonsM", description: "") fileprivate var bardAgi = SelectElement(id: "bardAgi", description: nil) fileprivate var bardInt = SelectElement(id: "bardInt", description: nil) fileprivate var bardDex = SelectElement(id: "bardDex", description: nil) fileprivate var bardVit = SelectElement(id: "bardVit", description: nil) fileprivate var bardJobLevel = SelectElement(id: "bardJob", description: "") fileprivate var dancerSkills = SelectElement(id: "dancerSkills", description: "Dancer") fileprivate var dancerSkillLevel = SelectElement(id: "dancerSkillLevel", description: nil) fileprivate var danceLessons = SelectElement(id: "danceLessons", description: "") fileprivate var wandererSkills = SelectElement(id: "wandererSkills", description: "") fileprivate var wandererSkillLevel = SelectElement(id: "wandererSkillLevel", description: nil) fileprivate var voiceLessonsWanderer = SelectElement(id: "voiceLessonsW", description: "") fileprivate var dancerAgi = SelectElement(id: "dancerAgi", description: nil) fileprivate var dancerInt = SelectElement(id: "dancerInt", description: nil) fileprivate var dancerDex = SelectElement(id: "dancerDex", description: nil) fileprivate var dancerLuk = SelectElement(id: "dancerLuk", description: nil) fileprivate var dancerJobLevel = SelectElement(id: "dancerJob", description: "") fileprivate var ensembleSkills = SelectElement(id: "ensembleSkills", description: "Group") fileprivate var bardLevel = SelectElement(id: "bardLevel", description: "") fileprivate var dancerLevel = SelectElement(id: "dancerLevel", description: nil) fileprivate var chorusSkill = SelectElement(id: "chorusSkill", description: "") fileprivate var chorusLevel = SelectElement(id: "chorusLevel", description: nil) fileprivate var performerCount = SelectElement(id: "performerCount", description: "") fileprivate var marionette = CheckboxInputElement(id: "marionetteControl", description: "Marionette") fileprivate var marionetteStr = SelectElement(id: "marionetteStr", description: nil) fileprivate var marionetteAgi = SelectElement(id: "marionetteAgi", description: nil) fileprivate var marionetteVit = SelectElement(id: "marionetteVit", description: nil) fileprivate var marionetteInt = SelectElement(id: "marionetteInt", description: nil) fileprivate var marionetteDex = SelectElement(id: "marionetteDex", description: nil) fileprivate var marionetteLuk = SelectElement(id: "marionetteLuk", description: nil) fileprivate var battleCommand = CheckboxInputElement(id: "guildSkill0", description: "Battle Command") fileprivate var greatLeadership = SelectElement(id: "guildSkill1", description: "Great Leadership") fileprivate var gloriousWounds = SelectElement(id: "guildSkill2", description: "Glorious Wounds") fileprivate var coldHeart = SelectElement(id: "guildSkill3", description: "Cold Heart") fileprivate var sharpGaze = SelectElement(id: "guildSkill4", description: "Sharp Gaze") fileprivate var regeneration = SelectElement(id: "guildSkill5", description: "Regeneration") fileprivate var allStatsPlus20 = CheckboxInputElement(id: "battleChant0", description: "All Stats +20") fileprivate var hpPlus100Percent = CheckboxInputElement(id: "battleChant1", description: "HP +100%") fileprivate var spPlus100Percent = CheckboxInputElement(id: "battleChant2", description: "SP +100%") fileprivate var atkPlus100Percent = CheckboxInputElement(id: "battleChant3", description: "ATK +100%") fileprivate var hitAndFleePlus100Percent = CheckboxInputElement(id: "battleChant4", description: "HIT & FLEE +50") fileprivate var damageReduced50Percent = CheckboxInputElement(id: "battleChant5", description: "Damage Reduced 50%") fileprivate var elementField = SelectElement(name: "eleField", description: nil) fileprivate var elementFieldLevel = SelectElement(name: "eleFieldLvl", description: nil) fileprivate var murdererBonus = SelectElement(name: "murderBonus", description: "Murderer Bonus") fileprivate var improveConcentrationLevel = SelectElement(name: "improveCon", description: "Improve Concentration Lv") fileprivate var selfMindBreaker = SelectElement(name: "mindBreaker", description: "Self Mind Breaker") fileprivate var selfProvoke = SelectElement(name: "provoke", description: "Self Provoke") fileprivate var bsSacrimenti = CheckboxInputElement(name: "bss", description: "BS Sacrimenti") fileprivate var andrenalineRush = SelectElement(name: "adrenalineRush", description: "Andrenaline Rush") fileprivate var weaponPerfection = CheckboxInputElement(name: "weaponPerfection", description: "Weapon Perfection") fileprivate var powerThrust = SelectElement(name: "powerThrust", description: "Power-Thrust") fileprivate var windWalk = SelectElement(name: "windWalker", description: "Wind Walk") fileprivate var magnumBreakBonus = CheckboxInputElement(name: "magnumBreak", description: "Magnum Break Bonus") fileprivate var aloevera = CheckboxInputElement(name: "aloe", description: "Aloevera") fileprivate var resistantSouls = SelectElement(name: "resistantSouls", description: "Resistant Souls") fileprivate var striking = SelectElement(name: "striking", description: "Striking") fileprivate var strikingEndowBonus = SelectElement(name: "strikingEndow", description: "Striking Endow Bonus") fileprivate var odinsPower = SelectElement(name: "odinsPower", description: "Odin's Power") fileprivate var petBonuses = SelectElement(id: "petBonus", description: "Pet Bonuses") fileprivate var tempEffect1 = SelectElement(id: "tempOne", description: "Temp Effect") fileprivate var tempEffect2 = SelectElement(id: "tempTwo", description: "Temp Effect") fileprivate var tempEffect3 = SelectElement(id: "tempThree", description: "Temp Effect") fileprivate var tempEffect4 = SelectElement(id: "tempFour", description: "Temp Effect") fileprivate var advanceFirstSpirit = CheckboxInputElement(id: "firstSpirit", description: "Advance 1st Spirit (Max Stats)") fileprivate var superNoviceMarriageBonus = CheckboxInputElement(id: "noviceMarried", description: "SN Marriage Bonus (Stats + 1)") fileprivate var numberOfEnemies = SelectElement(id: "numEnemies", description: "# of Enemies") fileprivate var quagmire = SelectElement(id: "playerQuaged", description: "Quagmire") fileprivate var agiDown = SelectElement(id: "playerAgiDowned", description: "AGI Down") fileprivate var setCriticalToZero = CheckboxInputElement(id: "playerNoCrit", description: "Set CRIT% to 0") fileprivate var poisoned = CheckboxInputElement(id: "playerPoisoned", description: "Poisoned") fileprivate var cursed = CheckboxInputElement(id: "playerCursed", description: "Cursed") fileprivate var aspdPotions = SelectElement(id: "speedPot", description: "ASPD Potions") fileprivate var strFood = SelectElement(id: "strFood", description: "STR Food") fileprivate var agiFood = SelectElement(id: "agiFood", description: "AGI Food") fileprivate var vitFood = SelectElement(id: "vitFood", description: "VIT Food") fileprivate var intFood = SelectElement(id: "intFood", description: "INT Food") fileprivate var dexFood = SelectElement(id: "dexFood", description: "DEX Food") fileprivate var lukFood = SelectElement(id: "lukFood", description: "LUK Food") fileprivate var vipBuffs = CheckboxInputElement(id: "vipBuff", description: "VIP Buffs (STATS +7)") fileprivate var luckyRiceCake = CheckboxInputElement(id: "luckyRiceCake", description: "Lucky Rice Cake (LUK +21)") fileprivate var sesamePastry = CheckboxInputElement(id: "sesamePastry", description: "Sesame Pastry (HIT +30)") fileprivate var honeyPastry = CheckboxInputElement(id: "honeyPastry", description: "Honey Pastry (FLEE +30)") fileprivate var rainbowCake = CheckboxInputElement(id: "rainbowCake", description: "Rainbow Cake (ATK/MATK +10)") fileprivate var militaryRationB = CheckboxInputElement(id: "militaryRationB", description: "Military Ration B (HIT +33)") fileprivate var militaryRationC = CheckboxInputElement(id: "militaryRationC", description: "Military Ration C (FLEE +33)") fileprivate var tastyPinkRation = CheckboxInputElement(id: "pinkRation", description: "Tasty Pink Ration (ATK +15)") fileprivate var tastyWhiteRation = CheckboxInputElement(id: "whiteRation", description: "Tasty White Ration (MATK +15)") fileprivate var boxOfResentment = CheckboxInputElement(id: "resentment", description: "Box of Resentment (ATK +20)") fileprivate var boxOfDrowsiness = CheckboxInputElement(id: "drowsiness", description: "Box of Drowsiness (MATK +20)") fileprivate var fireproofPotion = CheckboxInputElement(id: "fireproof", description: "Fireproof Potion") fileprivate var coldproofPotion = CheckboxInputElement(id: "coldproof", description: "Coldproof Potion") fileprivate var thunderproofPotion = CheckboxInputElement(id: "thunderproof", description: "Thunderproof Potion") fileprivate var earthproofPotion = CheckboxInputElement(id: "earthproof", description: "Earthproof Potion") fileprivate var celermineJuice = CheckboxInputElement(id: "celermineJuice", description: "Celermine Juice (ASPD +10%)") fileprivate var vitata500 = CheckboxInputElement(id: "vitataFiveHundred", description: "Vitata500 (SP +5%)") fileprivate var increaseHpPotion = SelectElement(id: "increaseHpPotion", description: "Increase HP Potion") fileprivate var increaseSpPotion = SelectElement(id: "increaseSpPotion", description: "Increase SP Potion") fileprivate var abrasive = CheckboxInputElement(id: "abrasive", description: "Abrasive (Crit +30)") fileprivate var runeStrawberryCake = CheckboxInputElement(id: "runeStrawberry", description: "Rune Strawberry Cake (ATK/MATK +5)") fileprivate var schwartzwaldPineJubilee = CheckboxInputElement(id: "pineJubilee", description: "Schwartzwald Pine Jubilee (HIT +10/FLEE +20)") fileprivate var arunafeltzDesertSandwich = CheckboxInputElement(id: "desertSandwich", description: "Arunafeltz Desert Sandwich (CRIT +7)") fileprivate var bucheDeNoel = CheckboxInputElement(id: "boucheDeNoel", description: "Buche de Noel (HIT +3/CRIT +7)") fileprivate var distilledFightingSpirit = CheckboxInputElement(id: "fightingSpirit", description: "Distilled Fighting Spirit (ATK +30)") fileprivate var durian = CheckboxInputElement(id: "durian", description: "Durian (ATK/MATK +10)") fileprivate var guaranaCandy = CheckboxInputElement(id: "guaranaCandy", description: "Guarana Candy (AGI LVL 5/ASPD +10%)") fileprivate var magicScrollOrYggdrasilLeafOrEtc = CheckboxInputElement(id: "castScrolls", description: "Magic Scroll/Yggdrasil Leaf/Etc") fileprivate var holyElementalScroll = CheckboxInputElement(id: "holyEl", description: "Holy Elemental Scroll") fileprivate var undeadElementalScroll = CheckboxInputElement(id: "undeadEl", description: "Undead Elemental Scroll") fileprivate(set) var statuses: ElementSection fileprivate(set) var properties: ElementSection fileprivate(set) var mainWeapon: ElementSection fileprivate(set) var armorSection: ElementSection fileprivate(set) var additionalEnchantsSection: ElementSection fileprivate(set) var acolyteSkillsSection: ElementSection fileprivate(set) var performerSkillsSection: ElementSection fileprivate(set) var guildSkillsSection: ElementSection fileprivate(set) var battleChantEffectsSection: ElementSection fileprivate(set) var otherBuffsSection: ElementSection fileprivate(set) var miscellaneousEffectsSection: ElementSection fileprivate(set) var items: ElementSection fileprivate var passiveSkillCount: Int { let script = "var job = n_A_JOB; var skillCount = 0; for ( skillCount; JobSkillPassOBJ[job][skillCount] !== 999; skillCount++ ); skillCount;" return Int(context.evaluateScript(script).toInt32()) } fileprivate var _passiveSkillSection: ElementSection? = nil var passiveSkillSection: ElementSection { var passiveSkills = [AnyObject]() if _passiveSkillSection == nil { for i in 0..<passiveSkillCount { let skillName = context.evaluateScript("document.getElementById('P_Skill\(i)').textContent").toString() let passiveSkill = SelectElement(name: "A_Skill\(i)", description: skillName) passiveSkills.append(passiveSkill) } } return ElementSection(title: "Self Passive/Duration Skills", elements: passiveSkills) } var webView = UIWebView() fileprivate(set) var loading = true fileprivate var observer: NSObjectProtocol! override init() { statuses = ElementSection(title: "Stats", elements: [ job, [baseLevel, jobLevel] as AnyObject, [str, strPlus, agi, agiPlus] as AnyObject, [vit, vitPlus, int, intPlus] as AnyObject, [dex, dexPlus, luk, lukPlus] as AnyObject ]) properties = ElementSection(title: "Properties", elements: [ [maxHp, maxSp] as AnyObject, [hit, flee] as AnyObject, [perfectDodge, critical] as AnyObject, [hpRegen, spRegen] as AnyObject, atk, matk, def, mdef, aspd, statusPoint ]) mainWeapon = ElementSection(title: "Main Weapon", elements: [ mainWeaponType, [mainWeaponRefining, mainWeaponName] as AnyObject, mainWeaponCardShortcuts, mainWeaponCard1, mainWeaponCard2, mainWeaponCard3, mainWeaponCard4, mainWeaponElement, mainWeaponProjectile ]) armorSection = ElementSection(title: "Armor", elements: [ armorCardShortcuts, [upperHeadgearRefining, upperHeadgear] as AnyObject, [upperHeadgearEnchant, upperHeadgearCard] as AnyObject, middleHeadgear, middleHeadgearCard, lowerHeadgear, [armorRefining, armor] as AnyObject, [armorEnchant, armorCard] as AnyObject, [shieldRefining, shield] as AnyObject, shieldCard, [garmentRefining, garment] as AnyObject, garmentCard, [footgearRefining, footgear] as AnyObject, footgearCard, accessory1, accessory1Card, accessory2, accessory2Card ]) additionalEnchantsSection = ElementSection(title: "Additional Enchants", elements: [ [strEnchant, agiEnchant] as AnyObject, [vitEnchant, intEnchant] as AnyObject, [dexEnchant, lukEnchant] as AnyObject, [atkEnchant, atkPercentEnchant] as AnyObject, [matkEnchant, matkPercentEnchant] as AnyObject, [hitEnchant, fleeEnchant] as AnyObject, [perfectDodgeEnchant, criticalEnchant] as AnyObject, [maxHpEnchant, maxSpEnchant] as AnyObject, [maxHpPercentEnchant, maxSpPercentEnchant] as AnyObject, [defEnchant, mdefEnchant] as AnyObject, [aspdEnchant, aspdPercentEnchant] as AnyObject, rangedDamagePercentEnchant, damageReductionPercentEnchant, castTimePercentEnchant ]) acolyteSkillsSection = ElementSection(title: "Acolyte Skills", elements: [ blessing, increaseAgi, angelus, impositioManus, suffragium, gloria, assumptio, spiritSpheres, clementia, cantoCandidus, expiatio, sacrament, laudaAgnus, laudaRamus, gentleTouchConvert, gentleTouchRevitalize, [suraStr, suraAgi] as AnyObject, [suraVit, suraInt, suraDex] as AnyObject ]) performerSkillsSection = ElementSection(title: "Performer Skills", elements: [ [bardSkills, bardSkillLevel] as AnyObject, musicLessons, [maestroSkills, maestroSkillLevel] as AnyObject, voiceLessonsMaestro, [bardAgi, bardInt, bardDex, bardVit] as AnyObject, bardJobLevel, [dancerSkills, dancerSkillLevel] as AnyObject, danceLessons, [wandererSkills, wandererSkillLevel] as AnyObject, voiceLessonsWanderer, [dancerAgi, dancerInt, dancerDex, dancerLuk] as AnyObject, dancerJobLevel, ensembleSkills, [bardLevel, dancerLevel] as AnyObject, [chorusSkill, chorusLevel] as AnyObject, performerCount, marionette, [marionetteStr, marionetteAgi, marionetteVit] as AnyObject, [marionetteInt, marionetteDex, marionetteLuk] as AnyObject ]) guildSkillsSection = ElementSection(title: "Guild Skills", elements: [ battleCommand, greatLeadership, gloriousWounds, coldHeart, sharpGaze, regeneration ]) battleChantEffectsSection = ElementSection(title: "Battle Chant Effects", elements: [ allStatsPlus20, hpPlus100Percent, spPlus100Percent, atkPlus100Percent, hitAndFleePlus100Percent, damageReduced50Percent ]) otherBuffsSection = ElementSection(title: "Other Buffs", elements: [ [elementField, elementFieldLevel] as AnyObject, murdererBonus, improveConcentrationLevel, selfMindBreaker, selfProvoke, bsSacrimenti, andrenalineRush, weaponPerfection, powerThrust, windWalk, magnumBreakBonus, aloevera, resistantSouls, striking, strikingEndowBonus, odinsPower, ]) miscellaneousEffectsSection = ElementSection(title: "Miscellaneous Effects", elements: [ petBonuses, tempEffect1, tempEffect2, tempEffect3, tempEffect4, advanceFirstSpirit, superNoviceMarriageBonus, numberOfEnemies, quagmire, agiDown, setCriticalToZero, poisoned, cursed, ]) let itemElements1 = [ aspdPotions, strFood, agiFood, vitFood, intFood, dexFood, lukFood, vipBuffs, luckyRiceCake, sesamePastry, honeyPastry, rainbowCake, militaryRationB, militaryRationC, tastyPinkRation, tastyWhiteRation, boxOfResentment, boxOfDrowsiness ] as [AnyObject] let itemElements2 = [ fireproofPotion, coldproofPotion, thunderproofPotion, earthproofPotion, celermineJuice, vitata500, increaseHpPotion, increaseSpPotion, abrasive, runeStrawberryCake, schwartzwaldPineJubilee, arunafeltzDesertSandwich, bucheDeNoel, distilledFightingSpirit, durian, guaranaCandy, magicScrollOrYggdrasilLeafOrEtc, holyElementalScroll, undeadElementalScroll ] as [AnyObject] items = ElementSection(title: "Items", elements: itemElements1 + itemElements2) super.init() addObserver() } deinit { removeObserver() } func addObserver() { observer = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: StatusCalculatorValueDidChangeNotification), object: nil, queue: OperationQueue.main) { [weak self] (note) -> Void in self?.clearCachedValues() } } func removeObserver() { NotificationCenter.default.removeObserver(observer) } func clearCachedValues() { _passiveSkillSection = nil } } extension StatusCalculator { func load() { let path = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "iW Stat Simulator/calc.irowiki.org")! let url = URL(fileURLWithPath: path) webView.delegate = self webView.loadRequest(URLRequest(url: url)) } func cancelLoad() { webView.stopLoading() } } extension StatusCalculator: UIWebViewDelegate { func webViewDidFinishLoad(_ webView: UIWebView) { loading = false www = webView context = webView.value(forKeyPath: "documentView.webView.mainFrame.javaScriptContext") as! JSContext context.exceptionHandler = { context, exception in print("JS Error: \(String(describing: exception))") } automaticallyAdjustsBaseLevel.checked = false delegate?.statusCalculatorDidFinishLoad?(self) } func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { loading = false delegate?.statusCalculator?(self, didFailLoadWithError: error as NSError?) } }
mit
8b33a8e6f7c653957815350dcfe3133c
50.230189
218
0.661412
4.343393
false
false
false
false
fewspider/FFNavigationBar
Pod/FFSetChildViewSegue.swift
1
927
// // FFSetChildViewSegue.swift // Pods // // Created by fewspider on 16/1/23. // // import UIKit public class FFSetChildViewSegue: UIStoryboardSegue { private let screenWidth = UIScreen.mainScreen().bounds.size.width // MARK: - Segue Identifier static let segueIdentifier = "setChild" override public func perform() { let navigationBarHeight:CGFloat = 66 let firstVC = self.sourceViewController as! FFNavigationBarController let secondVC = self.destinationViewController firstVC.addChildViewController(secondVC) let childCount = firstVC.childViewControllers.count - 1 secondVC.view.frame = CGRect(x: CGFloat(childCount) * screenWidth,y: -navigationBarHeight,width: screenWidth,height: firstVC.contentScrollView.frame.height) firstVC.contentScrollView.addSubview(secondVC.view) secondVC.didMoveToParentViewController(firstVC) } }
mit
0354476eed88f1bc292fa148b18ac7ca
27.090909
164
0.728155
4.778351
false
false
false
false
nicky1525/Gomoku
Gomoku/GameManager.swift
1
5636
import Foundation protocol GameManagerDelegate { func render(coordinates: Coordinates, player: Player) func endGame(player: Player) } struct GameManager { var delegate: GameManagerDelegate! func addMove(_ move: Move, _ model: GameModel) -> GameModel { return GameModel(moves:model.moves + [move], currentTurn: model.currentTurn) } func checkForWinner(_ move: Move, _ moves: [Move]) -> Player? { let coords = move.coordinates let player = move.player if moves.contains(where: { $0.coordinates == (coords.x-1, coords.y) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x-2, coords.y) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x+1, coords.y) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x+2, coords.y) && $0.player == player }) { return player } if moves.contains(where: { $0.coordinates == (coords.x, coords.y-1) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x, coords.y-2) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x, coords.y+1) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x, coords.y+2) && $0.player == player }) { return player } if moves.contains(where: { $0.coordinates == (coords.x-4, coords.y) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x-3, coords.y) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x-2, coords.y) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x-1, coords.y) && $0.player == player }) { return player } if moves.contains(where: { $0.coordinates == (coords.x+4, coords.y) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x+3, coords.y) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x+2, coords.y) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x+1, coords.y) && $0.player == player }) { return player } if moves.contains(where: { $0.coordinates == (coords.x, coords.y-4) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x, coords.y-3) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x, coords.y-2) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x, coords.y-1) && $0.player == player }) { return player } if moves.contains(where: { $0.coordinates == (coords.x, coords.y+4) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x, coords.y+3) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x, coords.y+2) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x, coords.y+1) && $0.player == player }) { return player } if moves.contains(where: { $0.coordinates == (coords.x+1, coords.y+1) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x+2, coords.y+2) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x+3, coords.y+3) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x+4, coords.y+4) && $0.player == player }) { return player } if moves.contains(where: { $0.coordinates == (coords.x-1, coords.y-1) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x-2, coords.y-2) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x-3, coords.y-3) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x-4, coords.y-4) && $0.player == player }) { return player } if moves.contains(where: { $0.coordinates == (coords.x+1, coords.y+1) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x+2, coords.y+2) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x-1, coords.y-1) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x-2, coords.y-2) && $0.player == player }) { return player } if moves.contains(where: { $0.coordinates == (coords.x+1, coords.y-1) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x+2, coords.y-2) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x+3, coords.y-3) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x+4, coords.y-4) && $0.player == player }) { return player } if moves.contains(where: { $0.coordinates == (coords.x-1, coords.y+1) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x-2, coords.y+2) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x-3, coords.y+3) && $0.player == player }) && moves.contains(where: { $0.coordinates == (coords.x-4, coords.y+4) && $0.player == player }) { return player } return nil } }
mit
a461f7ad66501527178a1cb726455c7b
63.045455
107
0.546309
3.329002
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/Argo/Sources/Argo/Extensions/RawRepresentable.swift
9
1047
/** Default implementation of `Decodable` for `RawRepresentable` types using `String` as the raw value. */ public extension Decodable where Self.DecodedType == Self, Self: RawRepresentable, Self.RawValue == String { static func decode(_ json: JSON) -> Decoded<Self> { switch json { case let .string(s): return self.init(rawValue: s) .map(pure) ?? .typeMismatch(expected: "rawValue for \(self)", actual: json) default: return .typeMismatch(expected: "String", actual: json) } } } /** Default implementation of `Decodable` for `RawRepresentable` types using `Int` as the raw value. */ public extension Decodable where Self.DecodedType == Self, Self: RawRepresentable, Self.RawValue == Int { static func decode(_ json: JSON) -> Decoded<Self> { switch json { case let .number(n): return self.init(rawValue: n.intValue) .map(pure) ?? .typeMismatch(expected: "rawValue for \(self)", actual: json) default: return .typeMismatch(expected: "Int", actual: json) } } }
mit
8ab876ccaf6da1e3105187c949383bf2
32.774194
108
0.665712
4.011494
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Base/Vender/TransitionAnimation/CategoryNextTransitionAnimation.swift
1
3236
// // CategoryNextTransitionAnimation.swift // selluv-ios // // Created by 조백근 on 2016. 12. 16.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // import UIKit public class CategoryNextTransitionAnimation: NSObject, TRViewControllerAnimatedTransitioning, TransitionInteractiveable { public var transitionStatus: TransitionStatus public var transitionContext: UIViewControllerContextTransitioning? public let maskView: UIView public var fromPosition: CGPoint public var toPosition: CGPoint public var percentTransition: UIPercentDrivenInteractiveTransition? public var completion: (() -> Void)? public var cancelPop: Bool = false public var interacting: Bool = false public private(set) lazy var maskViewCopy: UIView = self.maskView.tr_copyWithSnapshot() fileprivate var animationCount: Int = 0 public init(maskView view: UIView, from: CGPoint, to: CGPoint, status: TransitionStatus = .push) { maskView = view fromPosition = from toPosition = to transitionStatus = status super.init() } public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { self.transitionContext = transitionContext var fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) var toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) let containView = transitionContext.containerView var y = (fromVC?.view.frame.origin.y)! + toPosition.y if transitionStatus == .pop { swap(&fromVC, &toVC) swap(&fromPosition, &toPosition) y = 0 } let rect = CGRect(x: toPosition.x, y: toPosition.y, width: maskViewCopy.frame.size.width, height: maskViewCopy.frame.size.height) let viewFrame = CGRect(x: (fromVC?.view.frame.origin.x)!, y: y, width: (fromVC?.view.frame.size.width)!, height: (fromVC?.view.frame.size.height)! ) maskViewCopy.frame = CGRect(x: fromPosition.x, y: fromPosition.y, width: maskViewCopy.frame.size.width, height: maskViewCopy.frame.size.height) containView.addSubview(fromVC!.view) containView.addSubview(toVC!.view) containView.addSubview(maskViewCopy) toVC!.view.layer.opacity = 0 UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveEaseInOut, animations: { fromVC!.view.frame = viewFrame toVC!.view.layer.opacity = 1 self.maskViewCopy.frame = rect }) { finished in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) if !self.cancelPop { if finished { self.maskViewCopy.removeFromSuperview() self.completion?() self.completion = nil } } self.cancelPop = false } } }
mit
a13fb4ac4680b964ec739bb63e84947b
38.839506
156
0.662845
5.1632
false
false
false
false
buyiyang/iosstar
iOSStar/Other/NewVC.swift
3
1509
// // NewVC.swift // wp // // Created by mu on 2017/5/11. // Copyright © 2017年 com.yundian. All rights reserved. // import UIKit class NewVC: UIViewController { @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var versionLabel: UILabel! @IBOutlet weak var mLabel: UILabel! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var sureBtn: UIButton! @IBOutlet weak var contentView: UIView! override func viewDidLoad() { super.viewDidLoad() contentView.layer.masksToBounds = true guard AppConfigHelper.shared().updateModel != nil else { return } sureBtn.backgroundColor = UIColor(hexString: AppConst.Color.main) timeLabel.text = "发布时间:\(AppConfigHelper.shared().updateModel!.newAppReleaseTime)" versionLabel.text = "版本:\(AppConfigHelper.shared().updateModel!.newAppVersionName)" mLabel.text = "大小:\(AppConfigHelper.shared().updateModel!.newAppSize)M" contentLabel.text = AppConfigHelper.shared().updateModel!.newAppUpdateDesc } //确认 @IBAction func sureBtnTapped(_ sender: Any) { guard AppConfigHelper.shared().updateModel != nil else { return } if AppConfigHelper.shared().updateModel!.isForceUpdate == 0 { UIApplication.shared.openURL(URL(string:ShareDataModel.share().qiniuHeader + "https://fir.im/starShareUser")!) return } dismissController() } }
gpl-3.0
02f35e9532691bb2c66f8d8723ac1923
32.022222
124
0.654778
4.409496
false
true
false
false
wikimedia/wikipedia-ios
WMF Framework/AsyncOperation.swift
4
3150
import Foundation enum AsyncOperationError: Error { case cancelled } // Adapted from https://gist.github.com/calebd/93fa347397cec5f88233 @objc(WMFAsyncOperation) open class AsyncOperation: Operation { // MARK: - Operation State fileprivate let semaphore = DispatchSemaphore(value: 1) // Ensures `state` is thread-safe @objc public enum State: Int { case ready case executing case finished var affectedKeyPath: KeyPath<AsyncOperation, Bool> { switch self { case .ready: return \.isReady case .executing: return \.isExecuting case .finished: return \.isFinished } } } public var error: Error? fileprivate var _state = AsyncOperation.State.ready @objc public var state: AsyncOperation.State { get { semaphore.wait() let state = _state defer { semaphore.signal() } return state } set { willChangeValue(for: \.state) let affectedKeyPaths = [_state.affectedKeyPath, newValue.affectedKeyPath] for keyPath in affectedKeyPaths { willChangeValue(for: keyPath) } semaphore.wait() _state = newValue semaphore.signal() didChangeValue(for: \.state) for keyPath in affectedKeyPaths { didChangeValue(for: keyPath) } } } // MARK: - Operation subclass requirements public final override var isReady: Bool { return state == .ready && super.isReady } public final override var isExecuting: Bool { return state == .executing } public final override var isFinished: Bool { return state == .finished } public final override var isAsynchronous: Bool { return true } open override func start() { // From the docs for `start`: // "Your custom implementation must not call super at any time." if isCancelled { finish(with: AsyncOperationError.cancelled) return } state = .executing execute() } // MARK: - Custom behavior @objc open func finish() { state = .finished } @objc open func finish(with error: Error) { self.error = error state = .finished } /// Subclasses must implement this to perform their work and they must not /// call `super`. The default implementation of this function throws an /// exception. open func execute() { fatalError("Subclasses must implement `execute`.") } } @objc(WMFAsyncBlockOperation) open class AsyncBlockOperation: AsyncOperation { let asyncBlock: (AsyncBlockOperation) -> Void @objc init(asyncBlock block: @escaping (AsyncBlockOperation) -> Void) { asyncBlock = block } final override public func execute() { asyncBlock(self) } }
mit
c4754570b72804d5a7e0bf2129c31cba
24.819672
93
0.566032
5.267559
false
false
false
false
hacktoolkit/GitHubBrowser-iOS
GitHubBrowser/viewControllers/RepositoryDetailsViewController.swift
1
2950
// // RepositoryDetailsViewController.swift // GitHubBrowser // // Created by Jonathan Tsai on 9/27/14. // Copyright (c) 2014 Hacktoolkit. All rights reserved. // import UIKit class RepositoryDetailsViewController: GitHubBrowserTableViewController, UITabBarDelegate { var descriptionLabel: UILabel? var detailsView: UIView? var repository: GitHubRepository var webView: UIWebView? var tabBar: UITabBar? init(repository repo: GitHubRepository) { repository = repo super.init(nibName: nil, bundle: nil) title = repository.name println(repository.name) } override func viewDidLoad() { super.viewDidLoad() let screen = screenRect() descriptionLabel = UILabel() descriptionLabel!.backgroundColor = UIColor.blackColor() detailsView = UIView(frame: screen) detailsView!.backgroundColor = UIColor.whiteColor() // detailsView!.addSubview(descriptionLabel!) webView = UIWebView(frame: CGRect( x: 0, y: 20 + 44, width: CGRectGetWidth(screen), height: CGRectGetHeight(screen) - (20 + 44 + 48) ) ) self.detailsView!.addSubview(webView!) let paper = UIImage(named: "papers") let tab1 = UITabBarItem(title: "Readme", image: paper, tag: 0) let folder = UIImage(named: "folder") let tab2 = UITabBarItem(title: "Files", image: folder, tag: 1) tabBar = UITabBar(frame: CGRect( x: 0, y: CGRectGetHeight(screen) - 48, width: CGRectGetWidth(screen), height: 48 ) ) tabBar!.items = [tab1, tab2] tabBar!.selectedItem = tab1 tabBar!.delegate = self self.view.addSubview(detailsView!) self.mainTableView.hidden = true self.view.addSubview(tabBar!) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.descriptionLabel!.text = repository.description; let rect = self.descriptionLabel!.textRectForBounds( screenRect(), limitedToNumberOfLines: 0 ) self.descriptionLabel!.frame = rect } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let string = repository.getReadmeUrl() println(repository.getReadmeUrl()) let url = NSURL(string: string) let request = NSURLRequest(URL: url) webView!.loadRequest(request) } func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem!) { if item.tag == 0 { self.detailsView!.hidden = false self.mainTableView.hidden = true } else if item.tag == 1 { self.detailsView!.hidden = true self.mainTableView.hidden = false } } }
mit
8f3a612f49dfbbb7b54df8acc69e2810
29.729167
72
0.597966
4.796748
false
false
false
false
emdantrim/WillowTreeReachability
ReachabilityTests/ReachabilityTests.swift
1
1584
// // ReachabilityTests.swift // ReachabilityTests // // Created by Erik LaManna on 8/28/15. // Copyright © 2015 WillowTree, Inc. All rights reserved. // import XCTest import SystemConfiguration @testable import Reachability class TestNetworkSubscriber: NetworkStatusSubscriber { var status: ReachabilityStatus = .Unknown func networkStatusChanged(status: ReachabilityStatus) { self.status = status } } class ReachabilityTests: 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 testSubscriptionLifecycle() { if let monitor = Monitor() { monitor.startMonitoring() let subscriber = TestNetworkSubscriber() var subscription: NetworkStatusSubscription? = monitor.addReachabilitySubscriber(subscriber) let scNetworkCallback = Monitor.systemReachabilityCallback() scNetworkCallback(monitor.reachabilityReference, SCNetworkReachabilityFlags.Reachable, monitor.unsafeSelfPointer) XCTAssert(monitor.reachabilitySubscriptions.count == 1, "Subscription count is not 1") subscription = nil XCTAssert(monitor.reachabilitySubscriptions.count == 0, "Subscription count is not 0") } } }
mit
588b7948b75f5595850dbc5f700b7822
31.306122
125
0.6753
5.207237
false
true
false
false
BBRick/wp
wp/Scenes/User/FeedbackController.swift
1
2256
// // FeedbackViewController.swift // wp // // Created by macbook air on 16/12/23. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit import SnapKit class FeedbackController: UIViewController { let textView: UITextView = UITextView() let placeholderLabel: UILabel = UILabel() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white self.title = "意见反馈" self.automaticallyAdjustsScrollViewInsets = false setupUI() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() placeholderLabel.frame = CGRect(x: 5, y: 5, width: view.bounds.size.width, height: 20) } func setupUI() { textView.autocorrectionType = .no textView.delegate = self self.view.addSubview(textView) //设置约束 textView.snp.makeConstraints { (make) in make.top.equalTo(self.view).offset(80) make.left.equalTo(self.view).offset(10) make.right.equalTo(self.view).offset(-10) make.height.equalTo(200) } setConfig() } func setConfig() { textView.backgroundColor = UIColor(colorLiteralRed: 235/255.0, green: 235/255.0, blue: 235/255.0, alpha: 1) textView.isEditable = true textView.font = UIFont.boldSystemFont(ofSize: 18) placeholderLabel.textColor = UIColor.gray placeholderLabel.text = "请输入反馈信息" textView.addSubview(placeholderLabel) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //MARK: --UITextViewDelegate extension FeedbackController: UITextViewDelegate { func textViewDidBeginEditing(_ textView: UITextView) { placeholderLabel.text = "" } func textViewDidEndEditing(_ textView: UITextView) { if placeholderLabel.text?.length() == 0 { placeholderLabel.text = "请输入内容" } else{ placeholderLabel.text = "" } } }
apache-2.0
b5ccd96d8c821f104fb4f0fc03f04ff6
25.035294
115
0.601898
4.874449
false
false
false
false
anilkumarbp/ringcentral-swiftv2.0
src/src/Http/Client.swift
1
5976
// // CLient.swift // src // // Created by Anil Kumar BP on 1/21/16. // Copyright © 2016 Anil Kumar BP. All rights reserved. // import Foundation import SwiftyJSON public class Client { // Client Variables internal var useMock: Bool = false internal var appName: String internal var appVersion: String internal var mockRegistry: AnyObject? // Client Constants var contentType = "Content-Type" var jsonContentType = "application/json" var multipartContentType = "multipart/mixed" var urlencodedContentType = "application/x-www-form-urlencoded" var utf8ContentType = "charset=UTF-8" var accept = "Accept" /// Constructor for the Client /// /// - parameter appName: The appKey of your app /// - parameter appVersion: The appSecret of your app init(appName: String = "", appVersion: String = "") { self.appName = appName self.appVersion = appVersion } /// Generic HTTP request with completion handler /// /// @param: options List of options for HTTP request /// @param: completion: Completion handler for HTTP request /// @resposne: ApiResponse Callback public func send(request: NSMutableURLRequest, completionHandler: (response: ApiResponse?, exception: NSException?) -> Void) { let semaphore = dispatch_semaphore_create(0) let task: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in let apiresponse = ApiResponse(request: request, data: data, response: response, error: error) // @success Handler if apiresponse.isOK() { completionHandler(response:apiresponse, exception: nil) dispatch_semaphore_signal(semaphore) } // @failure Handler else { completionHandler(response: apiresponse, exception: NSException(name: "HTTP Error", reason: "error", userInfo: nil)) dispatch_semaphore_signal(semaphore) } } task.resume() dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) } /// func createRequest() /// /// @param: method NSMutableURLRequest /// @param: url list of options /// @param: query query ( optional ) /// @param: body body ( optional ) /// @param: headers headers /// @response: NSMutableURLRequest public func createRequest(method: String, url: String, query: [String: String]?=nil, body: [String: AnyObject]?, headers: [String: String]!) -> NSMutableURLRequest { var parse = parseProperties(method, url: url, query: query, body: body, headers: headers) // Create a NSMutableURLRequest var request = NSMutableURLRequest() if let nsurl = NSURL(string: url + (parse["query"] as! String)) { request = NSMutableURLRequest(URL: nsurl) request.HTTPMethod = method request.HTTPBody = parse["body"]!.dataUsingEncoding(NSUTF8StringEncoding) for (key,value) in parse["headers"] as! Dictionary<String, String> { request.setValue(value, forHTTPHeaderField: key) } } return request } // func parseProperties /// @param: method NSMutableURLRequest /// @param: url list of options /// @param: query query ( optional ) /// @param: body body ( optional ) /// @param: headers headers /// @response: Dictionary internal func parseProperties(method: String, url: String, query: [String: String]?=nil, body: [String: AnyObject]?, headers: [String: String]!) -> [String: AnyObject] { var parse = [String: AnyObject]() var truncatedBodyFinal: String = "" var truncatedQueryFinal: String = "" var queryFinal: String = "" // Check for query if let q = query { queryFinal = "?" for key in q.keys { if(q[key] == "") { queryFinal = "&" } else { queryFinal = queryFinal + key + "=" + q[key]! + "&" } } truncatedQueryFinal = queryFinal.substringToIndex(queryFinal.endIndex.predecessor()) } // Check for Body var bodyFinal: String = "" // Check if the body is empty if (body == nil || body?.count == 0) { truncatedBodyFinal = "" } else { if (headers["Content-type"] == "application/x-www-form-urlencoded;charset=UTF-8") { if let q = body { bodyFinal = "" for key in q.keys { bodyFinal = bodyFinal + key + "=" + (q[key]! as! String) + "&" } truncatedBodyFinal = bodyFinal.substringToIndex(bodyFinal.endIndex.predecessor()) } } else { if let json: AnyObject = body as AnyObject? { let resultJSON = JSON(json) let result = resultJSON.rawString()! truncatedBodyFinal = result } } } parse["query"] = truncatedQueryFinal parse["body"] = truncatedBodyFinal parse["headers"] = [String: [String: String]]() // check for Headers if headers.count == 1 { var headersFinal = [String: String]() headersFinal["Content-Type"] = "application/json" headersFinal["Accept"] = "application/json" parse["headers"] = headersFinal } else { parse["headers"] = headers } return parse } }
mit
b19c3f33a8d51f3479bc611cdf052078
34.565476
173
0.54795
4.958506
false
false
false
false
daltonclaybrook/MCPixelArt-Mac
MCPixelArt/UIColor+Additions.swift
1
1213
// // UIColor+Additions.swift // MCPixelArt // // Created by Dalton Claybrook on 10/28/16. // Copyright © 2016 Claybrook Software, LLC. All rights reserved. // import UIKit extension UIColor: Color { var redValue: CGFloat { var r: CGFloat = 0 self.getRed(&r, green: nil, blue: nil, alpha: nil) return r } var greenValue: CGFloat { var g: CGFloat = 0 self.getRed(nil, green: &g, blue: nil, alpha: nil) return g } var blueValue: CGFloat { var b: CGFloat = 0 self.getRed(nil, green: nil, blue: &b, alpha: nil) return b } static func create(r: CGFloat, g: CGFloat, b: CGFloat) -> Self { return self.init(red: r, green: g, blue: b, alpha: 1.0) } func differenceByComparring(to color: UIColor) -> CGFloat { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 self.getRed(&r, green: &g, blue: &b, alpha: nil) var cr: CGFloat = 0 var cg: CGFloat = 0 var cb: CGFloat = 0 color.getRed(&cr, green: &cg, blue: &cb, alpha: nil) return sqrt(pow(cr-r, 2.0) + pow(cg-g, 2.0) + pow(cb-b, 2.0)) } }
mit
399c20ad1df5bbb0ea2caadd17d15b15
25.933333
69
0.54538
3.338843
false
false
false
false
scotlandyard/expocity
expocity/View/Main/VMainLoader.swift
1
823
import UIKit class VMainLoader:UIImageView { private let kAnimationDuration:TimeInterval = 1 init() { super.init(frame:CGRect.zero) let images:[UIImage] = [ #imageLiteral(resourceName: "genericLoader0"), #imageLiteral(resourceName: "genericLoader1"), #imageLiteral(resourceName: "genericLoader2"), #imageLiteral(resourceName: "genericLoader3") ] isUserInteractionEnabled = false translatesAutoresizingMaskIntoConstraints = false clipsToBounds = true animationDuration = kAnimationDuration animationImages = images contentMode = UIViewContentMode.center startAnimating() } required init?(coder:NSCoder) { fatalError() } }
mit
1f2ae4a8318becee58a7764f035873fa
24.71875
58
0.613609
5.920863
false
false
false
false
justinmakaila/RemoteMapping
RemoteMapping/CoreData+RemoteMapping/NSEntityDescription+RemoteEntityType.swift
1
5920
import CoreData extension NSEntityDescription: RemoteEntityType { /// The remote primary key name. /// /// Defaults to `localPrimaryKeyName` if none provided. public var remotePrimaryKeyName: String { if let remotePrimaryKey = userInfo?[RemoteMapping.Key.RemotePrimaryKey.rawValue] as? String { return remotePrimaryKey } else if let superentityRemotePrimaryKey = superentity?.remotePrimaryKeyName { return superentityRemotePrimaryKey } return localPrimaryKeyName } /// The local primary key name. /// /// Defaults to "remoteID" if none is provided public var localPrimaryKeyName: String { if let localPrimaryKey = userInfo?[RemoteMapping.Key.LocalPrimaryKey.rawValue] as? String { return localPrimaryKey } if let superentityLocalPrimaryKey = superentity?.localPrimaryKeyName { return superentityLocalPrimaryKey } return RemoteMapping.Key.DefaultLocalPrimaryKey.rawValue } } /// MARK: - Propery Helpers /// MARK: Remote Properties extension NSEntityDescription { /// The properties represented on the remote. public var remoteProperties: [NSPropertyDescription] { return properties.filter { !$0.remoteShouldIgnore } } /// An index of remote property names and the corresponding /// property description. public func remotePropertiesByName(_ useLocalNames: Bool = false) -> [String: NSPropertyDescription] { return remoteProperties .reduce([String: NSPropertyDescription]()) { remotePropertiesByName, propertyDescription in let key = (useLocalNames) ? propertyDescription.name : propertyDescription.remotePropertyName var properties = remotePropertiesByName properties[key] = propertyDescription return properties } } } /// MARK: Relationships extension NSEntityDescription { public var relationships: [NSRelationshipDescription] { return properties.flatMap { $0 as? NSRelationshipDescription } } /// The relationships represented on the remote. public var remoteRelationships: [NSRelationshipDescription] { return remoteProperties.flatMap { $0 as? NSRelationshipDescription } } /// An index of remote property names and the corresponding relationship /// description. public func remoteRelationshipsByName(_ useLocalNames: Bool = false) -> [String: NSRelationshipDescription] { return remoteRelationships .reduce([String: NSRelationshipDescription]()) { remoteRelationshipsByName, relationshipDescription in let key = (useLocalNames) ? relationshipDescription.name : relationshipDescription.remotePropertyName var relationships = remoteRelationshipsByName relationships[key] = relationshipDescription return relationships } } } /// MARK: Attributes extension NSEntityDescription { public var attributes: [NSAttributeDescription] { return properties.flatMap { $0 as? NSAttributeDescription } } public var remoteAttributes: [NSAttributeDescription] { return remoteProperties.flatMap { $0 as? NSAttributeDescription } } /// An index of remote attribute names and the corresponding attribute /// description. public func remoteAttributesByName(_ useLocalNames: Bool = false) -> [String: NSAttributeDescription] { return remoteAttributes .reduce([String: NSAttributeDescription]()) { remoteAttributesByName, attributeDescription in let key = (useLocalNames) ? attributeDescription.name : attributeDescription.remotePropertyName var attributes = remoteAttributesByName attributes[key] = attributeDescription return attributes } } } /// MARK: - Query Helpers /// MARK: Local Predicates extension NSEntityDescription { /// Returns a predicate matching the value of key `localPrimaryKeyName` /// against `keyValue`. public func matchingLocalPrimaryKey<Value: CVarArg>(keyValue: Value) -> NSPredicate { return NSPredicate(format: "%K == %@", localPrimaryKeyName, keyValue) } /// Returns a predicate matching the value of key `localPrimaryKeyName` /// in `keyValues`. public func matchingLocalPrimaryKeys<Value: CVarArg>(keyValues: [Value]) -> NSPredicate { return NSPredicate(format: "%K in %@", localPrimaryKeyName, keyValues) } /// Returns a predicate matching the value of key `localPrimaryKeyName` /// in the set `keyValues`. public func matchingLocalPrimaryKeys<Value: CVarArg & Hashable>(keyValues: Set<Value>) -> NSPredicate { return NSPredicate(format: "%K in %@", localPrimaryKeyName, keyValues) } } /// MARK: Remote Predicates extension NSEntityDescription { /// Returns a predicate matching the value of key `remotePrimaryKeyName` /// against `keyValue`. public func matchingRemotePrimaryKey<Value: CVarArg>(keyValue: Value) -> NSPredicate { return NSPredicate(format: "%K == %@", remotePrimaryKeyName, keyValue) } /// Returns a predicate matching the value of key `remotePrimaryKeyName` /// in `keyValues`. public func matchingRemotePrimaryKeys<Value: CVarArg>(keyValues: [Value]) -> NSPredicate { return NSPredicate(format: "%K in %@", remotePrimaryKeyName, keyValues) } /// Returns a predicate matching the value of key `remotePrimaryKeyName` /// in the set `keyValues`. public func matchingRemotePrimaryKeys<Value: CVarArg & Hashable>(keyValues: Set<Value>) -> NSPredicate { return NSPredicate(format: "%K in %@", remotePrimaryKeyName, keyValues) } }
mit
79f1af643af6ceb94579f60059e089e8
39.547945
117
0.677872
5.595463
false
false
false
false
ThilinaHewagama/Pancha
Pancha/Source Files/Extensions/UIImage+Extension.swift
1
1184
// // UIImage+Extension.swift // Pancha // // Created by Thilina Chamin Hewagama on 3/29/17. // Copyright © 2017 Pancha iOS. All rights reserved. // import Foundation import UIKit public extension UIImage { public func resizeToFit(frame: CGRect) -> UIImage { var length:CGFloat = 0 if (frame.size.width < frame.size.height){ length = frame.size.width }else{ length = frame.size.height } var newSize = CGSize.zero if (self.size.width < self.size.height) { newSize.width = length * UIScreen.main.scale newSize.height = newSize.width * (self.size.height / self.size.width) }else{ newSize.height = length * UIScreen.main.scale newSize.width = newSize.height * (self.size.width / self.size.height) } UIGraphicsBeginImageContext(newSize) self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } }
mit
fa4d1bf03a0bfb5417ddaddb7ddcc277
26.511628
87
0.585799
4.333333
false
false
false
false
nfls/nflsers
app/v2/Model/User/Device.swift
1
707
// // Device.swift // NFLSers-iOS // // Created by Qingyang Hu on 2018/7/22. // Copyright © 2018 胡清阳. All rights reserved. // import Foundation import ObjectMapper struct PushDevice: Model { init(map: Map) throws { self.id = try map.value("id") self.token = try map.value("token") self.model = try map.value("model") self.callbackToken = try map.value("callbackToken") self.type = DeviceType(rawValue: try map.value("type"))! } let id: String let token: String let model: String let callbackToken: String let type: DeviceType enum DeviceType: Int, Codable { case ios = 1 case we_chat = 2 } }
apache-2.0
5dd5b6da05b1db707023d6fe288e7b09
21.580645
64
0.607143
3.763441
false
false
false
false
codestergit/swift
stdlib/public/core/MutableCollection.swift
4
17002
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type that provides subscript access to its elements. /// /// In most cases, it's best to ignore this protocol and use the /// `MutableCollection` protocol instead, because it has a more complete /// interface. @available(*, deprecated, message: "it will be removed in Swift 4.0. Please use 'MutableCollection' instead") public typealias MutableIndexable = _MutableIndexable public protocol _MutableIndexable : _Indexable { // FIXME(ABI)#52 (Recursive Protocol Constraints): there is no reason for this protocol // to exist apart from missing compiler features that we emulate with it. // rdar://problem/20531108 // // This protocol is almost an implementation detail of the standard // library; it is used to deduce things like the `SubSequence` and // `Iterator` type from a minimal collection, but it is also used in // exposed places like as a constraint on `IndexingIterator`. /// A type that represents a valid position in the collection. /// /// Valid indices consist of the position of every element and a /// "past the end" position that's not valid for use as a subscript. // TODO: swift-3-indexing-model - Index only needs to be comparable or must be comparable..? associatedtype Index /// The position of the first element in a nonempty collection. /// /// If the collection is empty, `startIndex` is equal to `endIndex`. var startIndex: Index { get } /// The collection's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// When you need a range that includes the last element of a collection, use /// the half-open range operator (`..<`) with `endIndex`. The `..<` operator /// creates a range that doesn't include the upper bound, so it's always /// safe to use with `endIndex`. For example: /// /// let numbers = [10, 20, 30, 40, 50] /// if let index = numbers.index(of: 30) { /// print(numbers[index ..< numbers.endIndex]) /// } /// // Prints "[30, 40, 50]" /// /// If the collection is empty, `endIndex` is equal to `startIndex`. var endIndex: Index { get } // The declaration of _Element and subscript here is a trick used to // break a cyclic conformance/deduction that Swift can't handle. We // need something other than a Collection.Iterator.Element that can // be used as IndexingIterator<T>'s Element. Here we arrange for // the Collection itself to have an Element type that's deducible from // its subscript. Ideally we'd like to constrain this Element to be the same // as Collection.Iterator.Element (see below), but we have no way of // expressing it today. associatedtype _Element /// Accesses the element at the specified position. /// /// For example, you can replace an element of an array by using its /// subscript. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// streets[1] = "Butler" /// print(streets[1]) /// // Prints "Butler" /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one /// past the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. subscript(position: Index) -> _Element { get set } /// A collection that represents a contiguous subrange of the collection's /// elements. associatedtype SubSequence /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// streets[index!] = "Eustace" /// print(streets[index!]) /// // Prints "Eustace" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. subscript(bounds: Range<Index>) -> SubSequence { get set } /// Performs a range check in O(1), or a no-op when a range check is not /// implementable in O(1). /// /// The range check, if performed, is equivalent to: /// /// precondition(bounds.contains(index)) /// /// Use this function to perform a cheap range check for QoI purposes when /// memory safety is not a concern. Do not rely on this range check for /// memory safety. /// /// The default implementation for forward and bidirectional indices is a /// no-op. The default implementation for random access indices performs a /// range check. /// /// - Complexity: O(1). func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) /// Performs a range check in O(1), or a no-op when a range check is not /// implementable in O(1). /// /// The range check, if performed, is equivalent to: /// /// precondition( /// bounds.contains(range.lowerBound) || /// range.lowerBound == bounds.upperBound) /// precondition( /// bounds.contains(range.upperBound) || /// range.upperBound == bounds.upperBound) /// /// Use this function to perform a cheap range check for QoI purposes when /// memory safety is not a concern. Do not rely on this range check for /// memory safety. /// /// The default implementation for forward and bidirectional indices is a /// no-op. The default implementation for random access indices performs a /// range check. /// /// - Complexity: O(1). func _failEarlyRangeCheck(_ range: Range<Index>, bounds: Range<Index>) /// Returns the position immediately after the given index. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. func index(after i: Index) -> Index /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. func formIndex(after i: inout Index) } // TODO: swift-3-indexing-model - review the following /// A collection that supports subscript assignment. /// /// Collections that conform to `MutableCollection` gain the ability to /// change the value of their elements. This example shows how you can /// modify one of the names in an array of students. /// /// var students = ["Ben", "Ivy", "Jordell", "Maxime"] /// if let i = students.index(of: "Maxime") { /// students[i] = "Max" /// } /// print(students) /// // Prints "["Ben", "Ivy", "Jordell", "Max"]" /// /// In addition to changing the value of an individual element, you can also /// change the values of a slice of elements in a mutable collection. For /// example, you can sort *part* of a mutable collection by calling the /// mutable `sort()` method on a subscripted subsequence. Here's an /// example that sorts the first half of an array of integers: /// /// var numbers = [15, 40, 10, 30, 60, 25, 5, 100] /// numbers[0..<4].sort() /// print(numbers) /// // Prints "[10, 15, 30, 40, 60, 25, 5, 100]" /// /// The `MutableCollection` protocol allows changing the values of a /// collection's elements but not the length of the collection itself. For /// operations that require adding or removing elements, see the /// `RangeReplaceableCollection` protocol instead. /// /// Conforming to the MutableCollection Protocol /// ============================================ /// /// To add conformance to the `MutableCollection` protocol to your own /// custom collection, upgrade your type's subscript to support both read /// and write access. /// /// A value stored into a subscript of a `MutableCollection` instance must /// subsequently be accessible at that same position. That is, for a mutable /// collection instance `a`, index `i`, and value `x`, the two sets of /// assignments in the following code sample must be equivalent: /// /// a[i] = x /// let y = a[i] /// /// // Must be equivalent to: /// a[i] = x /// let y = x public protocol MutableCollection : _MutableIndexable, Collection { // FIXME(ABI)#181: should be constrained to MutableCollection // (<rdar://problem/20715009> Implement recursive protocol // constraints) /// A collection that represents a contiguous subrange of the collection's /// elements. associatedtype SubSequence : Collection /*: MutableCollection*/ = MutableSlice<Self> /// Accesses the element at the specified position. /// /// For example, you can replace an element of an array by using its /// subscript. /// /// var streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// streets[1] = "Butler" /// print(streets[1]) /// // Prints "Butler" /// /// You can subscript a collection with any valid index other than the /// collection's end index. The end index refers to the position one /// past the last element of a collection, so it doesn't correspond with an /// element. /// /// - Parameter position: The position of the element to access. `position` /// must be a valid index of the collection that is not equal to the /// `endIndex` property. subscript(position: Index) -> Iterator.Element {get set} /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// streets[index!] = "Eustace" /// print(streets[index!]) /// // Prints "Eustace" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. subscript(bounds: Range<Index>) -> SubSequence {get set} /// Reorders the elements of the collection such that all the elements /// that match the given predicate are after all the elements that do /// not match the predicate. /// /// After partitioning a collection, there is a pivot index `p` where /// no element before `p` satisfies the `belongsInSecondPartition` /// predicate and every element at or after `p` satisfies /// `belongsInSecondPartition`. /// /// In the following example, an array of numbers is partitioned by a /// predicate that matches elements greater than 30. /// /// var numbers = [30, 40, 20, 30, 30, 60, 10] /// let p = numbers.partition(by: { $0 > 30 }) /// // p == 5 /// // numbers == [30, 10, 20, 30, 30, 60, 40] /// /// The `numbers` array is now arranged in two partitions. The first /// partition, `numbers.prefix(upTo: p)`, is made up of the elements that /// are not greater than 30. The second partition, `numbers.suffix(from: p)`, /// is made up of the elements that *are* greater than 30. /// /// let first = numbers.prefix(upTo: p) /// // first == [30, 10, 20, 30, 30] /// let second = numbers.suffix(from: p) /// // second == [60, 40] /// /// - Parameter belongsInSecondPartition: A predicate used to partition /// the collection. All elements satisfying this predicate are ordered /// after all elements not satisfying it. /// - Returns: The index of the first element in the reordered collection /// that matches `belongsInSecondPartition`. If no elements in the /// collection match `belongsInSecondPartition`, the returned index is /// equal to the collection's `endIndex`. /// /// - Complexity: O(*n*) mutating func partition( by belongsInSecondPartition: (Iterator.Element) throws -> Bool ) rethrows -> Index /// Call `body(p)`, where `p` is a pointer to the collection's /// mutable contiguous storage. If no such storage exists, it is /// first created. If the collection does not support an internal /// representation in a form of mutable contiguous storage, `body` is not /// called and `nil` is returned. /// /// Often, the optimizer can eliminate bounds- and uniqueness-checks /// within an algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (UnsafeMutablePointer<Iterator.Element>, Int) throws -> R ) rethrows -> R? // FIXME(ABI)#53 (Type Checker): the signature should use // UnsafeMutableBufferPointer, but the compiler can't handle that. // // <rdar://problem/21933004> Restore the signature of // _withUnsafeMutableBufferPointerIfSupported() that mentions // UnsafeMutableBufferPointer } // TODO: swift-3-indexing-model - review the following extension MutableCollection { @_inlineable public mutating func _withUnsafeMutableBufferPointerIfSupported<R>( _ body: (UnsafeMutablePointer<Iterator.Element>, Int) throws -> R ) rethrows -> R? { return nil } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.index(of: "Evarts") // 4 /// streets[index!] = "Eustace" /// print(streets[index!]) /// // Prints "Eustace" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. @_inlineable public subscript(bounds: Range<Index>) -> MutableSlice<Self> { get { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return MutableSlice(base: self, bounds: bounds) } set { _writeBackMutableSlice(&self, bounds: bounds, slice: newValue) } } } extension MutableCollection where Self: BidirectionalCollection { public subscript(bounds: Range<Index>) -> MutableBidirectionalSlice<Self> { get { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return MutableBidirectionalSlice(base: self, bounds: bounds) } set { _writeBackMutableSlice(&self, bounds: bounds, slice: newValue) } } } extension MutableCollection where Self: RandomAccessCollection { public subscript(bounds: Range<Index>) -> MutableRandomAccessSlice<Self> { get { _failEarlyRangeCheck(bounds, bounds: startIndex..<endIndex) return MutableRandomAccessSlice(base: self, bounds: bounds) } set { _writeBackMutableSlice(&self, bounds: bounds, slice: newValue) } } } @available(*, unavailable, renamed: "MutableCollection") public typealias MutableCollectionType = MutableCollection @available(*, unavailable, message: "Please use 'Collection where SubSequence : MutableCollection'") public typealias MutableSliceable = Collection
apache-2.0
1720f4633fda3e451ec768fdadf5efc9
40.980247
110
0.662451
4.361724
false
false
false
false
ZwxWhite/V2EX
V2EX/Pods/RealmSwift/RealmSwift/List.swift
8
15526
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private /// :nodoc: /// Internal class. Do not use directly. public class ListBase: RLMListBase { // Printable requires a description property defined in Swift (and not obj-c), // and it has to be defined as @objc override, which can't be done in a // generic class. /// Returns a human-readable description of the objects contained in the List. @objc public override var description: String { return descriptionWithMaxDepth(RLMDescriptionMaxDepth) } @objc private func descriptionWithMaxDepth(depth: UInt) -> String { let type = "List<\(_rlmArray.objectClassName)>" return gsub("RLMArray <0x[a-z0-9]+>", template: type, string: _rlmArray.descriptionWithMaxDepth(depth)) ?? type } /// Returns the number of objects in this List. public var count: Int { return Int(_rlmArray.count) } } /** `List<T>` is the container type in Realm used to define to-many relationships. Lists hold a single `Object` subclass (`T`) which defines the "type" of the List. Lists can be filtered and sorted with the same predicates as `Results<T>`. When added as a property on `Object` models, the property must be declared as `let` and cannot be `dynamic`. */ public final class List<T: Object>: ListBase { /// Element type contained in this collection. public typealias Element = T // MARK: Properties /// The Realm the objects in this List belong to, or `nil` if the List's /// owning object does not belong to a Realm (the List is standalone). public var realm: Realm? { return _rlmArray.realm.map { Realm($0) } } /// Indicates if the List can no longer be accessed. public var invalidated: Bool { return _rlmArray.invalidated } // MARK: Initializers /// Creates a `List` that holds objects of type `T`. public override init() { // FIXME: use T.className() super.init(array: RLMArray(objectClassName: (T.self as Object.Type).className())) } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the List. - parameter object: The object whose index is being queried. - returns: The index of the given object, or `nil` if the object is not in the List. */ public func indexOf(object: T) -> Int? { return notFoundToNil(_rlmArray.indexOfObject(unsafeBitCast(object, RLMObject.self))) } /** Returns the index of the first object matching the given predicate, or `nil` no objects match. - parameter predicate: The `NSPredicate` used to filter the objects. - returns: The index of the first matching object, or `nil` if no objects match. */ public func indexOf(predicate: NSPredicate) -> Int? { return notFoundToNil(_rlmArray.indexOfObjectWithPredicate(predicate)) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: The predicate format string, optionally followed by a variable number of arguments. - returns: The index of the first matching object, or `nil` if no objects match. */ public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return indexOf(NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Object Retrieval /** Returns the object at the given `index` on get. Replaces the object at the given `index` on set. - warning: You can only set an object during a write transaction. - parameter index: The index. - returns: The object at the given `index`. */ public subscript(index: Int) -> T { get { throwForNegativeIndex(index) return _rlmArray[UInt(index)] as! T } set { throwForNegativeIndex(index) return _rlmArray[UInt(index)] = unsafeBitCast(newValue, RLMObject.self) } } /// Returns the first object in the List, or `nil` if empty. public var first: T? { return _rlmArray.firstObject() as! T? } /// Returns the last object in the List, or `nil` if empty. public var last: T? { return _rlmArray.lastObject() as! T? } // MARK: KVC /** Returns an Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. - parameter key: The name of the property. - returns: Array containing the results of invoking `valueForKey(_:)` using key on each of the collection's objects. */ public override func valueForKey(key: String) -> AnyObject? { return _rlmArray.valueForKey(key) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified value and key. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property. */ public override func setValue(value: AnyObject?, forKey key: String) { return _rlmArray.setValue(value, forKey: key) } // MARK: Filtering /** Returns `Results` containing elements that match the given predicate. - parameter predicateFormat: The predicate format string which can accept variable arguments. - returns: `Results` containing elements that match the given predicate. */ public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<T> { return Results<T>(_rlmArray.objectsWithPredicate(NSPredicate(format: predicateFormat, argumentArray: args))) } /** Returns `Results` containing elements that match the given predicate. - parameter predicate: The predicate to filter the objects. - returns: `Results` containing elements that match the given predicate. */ public func filter(predicate: NSPredicate) -> Results<T> { return Results<T>(_rlmArray.objectsWithPredicate(predicate)) } // MARK: Sorting /** Returns `Results` containing elements sorted by the given property. - parameter property: The property name to sort by. - parameter ascending: The direction to sort by. - returns: `Results` containing elements sorted by the given property. */ public func sorted(property: String, ascending: Bool = true) -> Results<T> { return sorted([SortDescriptor(property: property, ascending: ascending)]) } /** Returns `Results` with elements sorted by the given sort descriptors. - parameter sortDescriptors: `SortDescriptor`s to sort by. - returns: `Results` with elements sorted by the given sort descriptors. */ public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<T> { return Results<T>(_rlmArray.sortedResultsUsingDescriptors(sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a minimum on. - returns: The minimum value for the property amongst objects in the List, or `nil` if the List is empty. */ public func min<U: MinMaxType>(property: String) -> U? { return filter(NSPredicate(value: true)).min(property) } /** Returns the maximum value of the given property. - warning: Only names of properties of a type conforming to the `MinMaxType` protocol can be used. - parameter property: The name of a property conforming to `MinMaxType` to look for a maximum on. - returns: The maximum value for the property amongst objects in the List, or `nil` if the List is empty. */ public func max<U: MinMaxType>(property: String) -> U? { return filter(NSPredicate(value: true)).max(property) } /** Returns the sum of the given property for objects in the List. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate sum on. - returns: The sum of the given property over all objects in the List. */ public func sum<U: AddableType>(property: String) -> U { return filter(NSPredicate(value: true)).sum(property) } /** Returns the average of the given property for objects in the List. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate average on. - returns: The average of the given property over all objects in the List, or `nil` if the List is empty. */ public func average<U: AddableType>(property: String) -> U? { return filter(NSPredicate(value: true)).average(property) } // MARK: Mutation /** Appends the given object to the end of the List. If the object is from a different Realm it is copied to the List's Realm. - warning: This method can only be called during a write transaction. - parameter object: An object. */ public func append(object: T) { _rlmArray.addObject(unsafeBitCast(object, RLMObject.self)) } /** Appends the objects in the given sequence to the end of the List. - warning: This method can only be called during a write transaction. - parameter objects: A sequence of objects. */ public func appendContentsOf<S: SequenceType where S.Generator.Element == T>(objects: S) { for obj in objects { _rlmArray.addObject(unsafeBitCast(obj, RLMObject.self)) } } /** Inserts the given object at the given index. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the List. - parameter object: An object. - parameter index: The index at which to insert the object. */ public func insert(object: T, atIndex index: Int) { throwForNegativeIndex(index) _rlmArray.insertObject(unsafeBitCast(object, RLMObject.self), atIndex: UInt(index)) } /** Removes the object at the given index from the List. Does not remove the object from the Realm. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the List. - parameter index: The index at which to remove the object. */ public func removeAtIndex(index: Int) { throwForNegativeIndex(index) _rlmArray.removeObjectAtIndex(UInt(index)) } /** Removes the last object in the List. Does not remove the object from the Realm. - warning: This method can only be called during a write transaction. */ public func removeLast() { _rlmArray.removeLastObject() } /** Removes all objects from the List. Does not remove the objects from the Realm. - warning: This method can only be called during a write transaction. */ public func removeAll() { _rlmArray.removeAllObjects() } /** Replaces an object at the given index with a new object. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the List. - parameter index: The index of the object to be replaced. - parameter object: An object to replace at the specified index. */ public func replace(index: Int, object: T) { throwForNegativeIndex(index) _rlmArray.replaceObjectAtIndex(UInt(index), withObject: unsafeBitCast(object, RLMObject.self)) } /** Moves the object at the given source index to the given destination index. - warning: This method can only be called during a write transaction. - warning: Throws an exception when called with an index smaller than zero or greater than or equal to the number of objects in the List. - parameter from: The index of the object to be moved. - parameter to: index to which the object at `from` should be moved. */ public func move(from from: Int, to: Int) { throwForNegativeIndex(from) throwForNegativeIndex(to) _rlmArray.moveObjectAtIndex(UInt(from), toIndex: UInt(to)) } /** Exchanges the objects in the List at given indexes. - warning: Throws an exception when either index exceeds the bounds of the List. - warning: This method can only be called during a write transaction. - parameter index1: The index of the object with which to replace the object at index `index2`. - parameter index2: The index of the object with which to replace the object at index `index1`. */ public func swap(index1: Int, _ index2: Int) { throwForNegativeIndex(index1, parameterName: "index1") throwForNegativeIndex(index2, parameterName: "index2") _rlmArray.exchangeObjectAtIndex(UInt(index1), withObjectAtIndex: UInt(index2)) } } extension List: RealmCollectionType, RangeReplaceableCollectionType { // MARK: Sequence Support /// Returns a `GeneratorOf<T>` that yields successive elements in the List. public func generate() -> RLMGenerator<T> { return RLMGenerator(collection: _rlmArray) } // MARK: RangeReplaceableCollection Support /** Replace the given `subRange` of elements with `newElements`. - parameter subRange: The range of elements to be replaced. - parameter newElements: The new elements to be inserted into the List. */ public func replaceRange<C: CollectionType where C.Generator.Element == T>(subRange: Range<Int>, with newElements: C) { for _ in subRange { removeAtIndex(subRange.startIndex) } for x in newElements.reverse() { insert(x, atIndex: subRange.startIndex) } } /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by zero or more applications of successor(). public var endIndex: Int { return count } }
mit
1f7d954a1485c05a5f57a28421e8e524
35.617925
139
0.674031
4.661063
false
false
false
false
iHunterX/SocketIODemo
DemoSocketIO/Utils/PAPermissions/Classes/Checks/PABluetoothPermissionsCheck.swift
1
1387
// // PAPermissionsChecker.swift // PAPermissionsApp // // Created by Pasquale Ambrosini on 06/09/16. // Copyright © 2016 Pasquale Ambrosini. All rights reserved. // import UIKit import CoreBluetooth public class PABluetoothPermissionsCheck: PAPermissionsCheck, CBCentralManagerDelegate { var managerBLE: CBCentralManager? public override func checkStatus() { self.managerBLE = CBCentralManager(delegate: self, queue: nil, options: nil) } public override func defaultAction() { if #available(iOS 10, *) { self.managerBLE = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey: true]) }else if #available(iOS 9, *) { let url = URL(string: "prefs:root=Bluetooth")! UIApplication.shared.openURL(url) } else { let url = URL(string: "prefs:root=General&path=Bluetooth")! UIApplication.shared.openURL(url) } } public func centralManagerDidUpdateState(_ central: CBCentralManager) { let currentStatus = self.status switch managerBLE!.state { case .poweredOff: self.status = .disabled case .poweredOn: self.status = .enabled case .unsupported: self.status = .unavailable case .resetting: self.status = .checking case .unauthorized: self.status = .disabled case .unknown: self.status = .unavailable } if self.status != currentStatus { self.updateStatus() } } }
gpl-3.0
dcd3e547bd3834493c4a98ead2c2b26a
25.150943
123
0.720779
3.647368
false
false
false
false
rc2server/appserverSwift
Tests/Rc2AppServerTests/MockHTTPRequest.swift
1
1981
// // MockHTTPRequest.swift // // Copyright ©2017 Mark Lilback. This file is licensed under the ISC license. // import Foundation import PerfectHTTP import PerfectNet import PerfectLib class MockHTTPRequest: HTTPRequest { var remoteAddress: (host: String, port: UInt16) = ("", 0) var serverAddress: (host: String, port: UInt16) = ("", 0) var postBodyBytes: [UInt8]? = nil var postBodyString: String? = nil init() { let fd = open("/dev/random", O_RDONLY) connection = NetTCP(fd: fd) } var method = HTTPMethod.get var path = "" var pathComponents = [String]() var queryParams = [(String, String)]() var protocolVersion = (1, 0) var serverName = "localhost" var documentRoot = ".webroot" var connection: NetTCP var urlVariables = [String : String]() var scratchPad = [String : Any]() func header(_ named: HTTPRequestHeader.Name) -> String? { guard let v = headerStore[named] else { return nil } return UTF8Encoding.encode(bytes: v) } func addHeader(_ named: HTTPRequestHeader.Name, value: String) { guard let existing = headerStore[named] else { self.headerStore[named] = [UInt8](value.utf8) return } let valueBytes = [UInt8](value.utf8) let newValue: [UInt8] if named == .cookie { newValue = existing + "; ".utf8 + valueBytes } else { newValue = existing + ", ".utf8 + valueBytes } self.headerStore[named] = newValue } func setHeader(_ named: HTTPRequestHeader.Name, value: String) { headerStore[named] = [UInt8](value.utf8) } var postParams = [(String, String)]() var postFileUploads: [MimeReader.BodySpec]? = nil private var headerStore = Dictionary<HTTPRequestHeader.Name, [UInt8]>() var headers: AnyIterator<(HTTPRequestHeader.Name, String)> { var g = self.headerStore.makeIterator() return AnyIterator<(HTTPRequestHeader.Name, String)> { guard let n = g.next() else { return nil } return (n.key, UTF8Encoding.encode(bytes: n.value)) } } }
isc
c2bbce8a56b5f4ab8cd216ec6a117217
21.247191
78
0.673232
3.344595
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/ugly-number-ii.swift
2
9248
/** * https://leetcode.com/problems/ugly-number-ii/ * * */ // // Heap.swift // // import Foundation public struct Heap<T> { /** The array that stores the heap's nodes. */ private(set) var nodes: [T] /** * Determines how to compare two nodes in the heap. * Use '>' for a max-heap or '<' for a min-heap, * or provide a comparing method if the heap is made * of custom elements, for example tuples. */ fileprivate let sortingComparator: (T, T) -> Bool /** * Creates an empty heap. * The sort function determines whether this is a min-heap or max-heap. * For comparable data types, > makes a max-heap, < makes a min-heap. */ public init(sortingComparator: @escaping (T, T) -> Bool) { self.nodes = [] self.sortingComparator = sortingComparator } /** * Creates a heap from an array. The order of the array does not matter; * the elements are inserted into the heap in the order determined by the * sort function. For comparable data types, '>' makes a max-heap, * '<' makes a min-heap. */ public init(array: [T], sortingComparator: @escaping (T, T) -> Bool) { self.nodes = [] self.sortingComparator = sortingComparator self.buildHeap(from: array) } /** * Configures the max-heap or min-heap from an array, in a bottom-up manner. * Performance: This runs pretty much in O(n). */ private mutating func buildHeap(from array: [T]) { // self.insert(array) self.nodes = array for index in stride(from: array.count / 2 - 1, through: 0, by: -1) { self.shiftDown(from: index) } } } // MARK: - Peek, Insert, Remove, Replace extension Heap { public var isEmpty: Bool { return self.nodes.isEmpty } public var count: Int { return self.nodes.count } /** * Returns the maximum value in the heap (for a max-heap) or the minimum * value (for a min-heap). * Performance: O(1) */ public func peek() -> T? { return self.nodes.first } /** * Adds a new value to the heap. This reorders the heap so that the max-heap * or min-heap property still holds. * Performance: O(log n). */ public mutating func insert(element: T) { self.nodes.append(element) self.shiftUp(from: self.nodes.count - 1) } /** * Adds a sequence of values to the heap. This reorders the heap so that * the max-heap or min-heap property still holds. * Performance: O(log n). */ public mutating func insert<S: Sequence>(_ sequence: S) where S.Iterator.Element == T { for value in sequence { insert(element: value) } } /** * Allows you to change an element. This reorders the heap so that * the max-heap or min-heap property still holds. * Performance: O(log n) */ public mutating func replace(at index: Int, value: T) { guard index < nodes.count else { return } remove(at: index) insert(element: value) } /** * Removes the root node from the heap. For a max-heap, this is the maximum * value; for a min-heap it is the minimum value. * Performance: O(log n). */ @discardableResult public mutating func remove() -> T? { guard self.nodes.count > 0 else { return nil } if self.nodes.count == 1 { return self.nodes.removeLast() } else { let value = self.nodes.first self.nodes[0] = self.nodes.removeLast() self.shiftDown(from: 0) return value } } /** * Removes an arbitrary node from the heap. * Note that you need to know the node's index. * Performance: O(log n) */ @discardableResult public mutating func remove(at index: Int) -> T? { guard index < self.count else { return nil } self.nodes.swapAt(index, self.nodes.count - 1) let value = self.nodes.removeLast() self.shiftDown(from: index) self.shiftUp(from: index) return value } } // MARK: - Index extension Heap { /** * Returns the index of the parent of the element at index i. * The element at index 0 is the root of the tree and has no parent. * Performance: O(1) */ func parentIndex(ofIndex i: Int) -> Int { return (i - 1) / 2 } /** * Returns the index of the left child of the element at index i. * Note that this index can be greater than the heap size, in which case * there is no left child. * Performance: O(1) */ func leftChildIndex(ofIndex index: Int) -> Int { return index * 2 + 1 } /** * Returns the index of the right child of the element at index i. * Note that this index can be greater than the heap size, in which case * there is no right child. * Performance: O(1) */ func rightChildIndex(ofIndex index: Int) -> Int { return index * 2 + 2 } } // MARK: - Shift Up / Down extension Heap { /** * Takes a child node and looks at its parents; if a parent is not larger * (max-heap) or not smaller (min-heap) than the child, we exchange them. * Performance: O(log n) */ mutating func shiftUp(from index: Int) { var childIndex = index var parentIndex = self.parentIndex(ofIndex: childIndex) while parentIndex < childIndex, !self.sortingComparator(self.nodes[parentIndex], self.nodes[childIndex]) { self.nodes.swapAt(childIndex, parentIndex) childIndex = parentIndex parentIndex = self.parentIndex(ofIndex: childIndex) } } /** * Looks at a parent node and makes sure it is still larger (max-heap) or * smaller (min-heap) than its childeren. * Performance: O(log n) */ mutating func shiftDown(from index: Int) { let parentIndex = index let leftChildIndex = self.leftChildIndex(ofIndex: parentIndex) let rightChildIndex = self.rightChildIndex(ofIndex: parentIndex) var subIndex = parentIndex if leftChildIndex < self.nodes.count, self.sortingComparator(self.nodes[subIndex], self.nodes[leftChildIndex]) == false { subIndex = leftChildIndex } if rightChildIndex < self.nodes.count, self.sortingComparator(self.nodes[subIndex], self.nodes[rightChildIndex]) == false { subIndex = rightChildIndex } if parentIndex == subIndex { return } self.nodes.swapAt(subIndex, index) self.shiftDown(from: subIndex) } } extension Heap where T: Equatable { /** * Get the index of a node in the heap. * Performance: O(n). */ public func index(of node: T) -> Int? { return self.nodes.firstIndex(of: node) } /** * Removes the first occurrence of a node from the heap. * Performance: O(n + log n) => O(n). */ @discardableResult public mutating func remove(node: T) -> T? { if let index = self.index(of: node) { return self.remove(at: index) } return nil } } public struct PriorityQueue<T> { fileprivate var heap: Heap<T> /* To create a max-priority queue, supply a > sort function. For a min-priority queue, use <. */ public init(sortingComparator: @escaping (T, T) -> Bool) { self.heap = Heap(sortingComparator: sortingComparator) } public var isEmpty: Bool { return self.heap.isEmpty } public var count: Int { return self.heap.count } public func peek() -> T? { return self.heap.peek() } public mutating func enqueue(element: T) { self.heap.insert(element: element) } public mutating func dequeue() -> T? { return self.heap.remove() } /* Allows you to change the priority of an element. In a max-priority queue, the new priority should be larger than the old one; in a min-priority queue it should be smaller. */ public mutating func changePriority(at index: Int, value: T) { return self.heap.replace(at: index, value: value) } } extension PriorityQueue where T: Equatable { public func index(of element: T) -> Int? { return self.heap.index(of: element) } } class Solution { func nthUglyNumber(_ n: Int) -> Int { var priorityQueue = PriorityQueue<Int>(sortingComparator: <) var count = 0 priorityQueue.enqueue(element: 1) var seens: Set<Int> = [1] while priorityQueue.isEmpty == false { let top = priorityQueue.dequeue()! count += 1 if count == n { return top } for cand in [2, 3, 5] { if seens.contains(cand * top) == false { seens.insert(cand * top) priorityQueue.enqueue(element: cand * top) } } } return 0 } }
mit
d18a6c026a674c29a0781346dba4bf3f
28.265823
131
0.579477
4.072215
false
false
false
false
Pretz/SwiftGraphics
Playgrounds/BezierPath.playground/Contents.swift
2
1160
// Playground - noun: a place where people can play import SwiftGraphics import SwiftGraphicsPlayground let size = CGSize(w: 240, h: 240) let context = CGContextRef.bitmapContext(size) CGContextTranslateCTM(context, 20, 20) let curves = [ BezierCurve( start: CGPoint(x: 10,y: 0), control1: CGPoint(x: -10,y: 180), control2: CGPoint(x: 150,y: 200), end: CGPoint(x: 200,y: 0)), ] let styles = [ "control":Style(elements: [ .strokeColor(CGColor.redColor()), ]), "start":Style(elements: [ .strokeColor(CGColor.redColor()), ]), "end":Style(elements: [ .strokeColor(CGColor.redColor()), ]), "controlLine":Style(elements: [ .strokeColor(CGColor.blueColor()), .lineDash([5,5]), ]), "boundingBox":Style(elements: [ .strokeColor(CGColor.blueColor()), .lineDash([5,5]), ]), "simpleBounds":Style(elements: [ .strokeColor(CGColor.blueColor()), .lineDash([5,5]), ]), ] for curve in curves { let markup = curve.markup context.draw(markup, styles: styles) context.stroke(curve) } context.nsimage
bsd-2-clause
c495369a0ac6a5b381c09b030e217e27
22.2
51
0.601724
3.729904
false
false
false
false
orta/SignalKit
SignalKitTests/Extensions/UIKit/UIControl+SignalTests.swift
1
1619
// // UIControl+SignalTests.swift // SignalKit // // Created by Yanko Dimitrov on 8/15/15. // Copyright © 2015 Yanko Dimitrov. All rights reserved. // import XCTest class UIControl_SignalTests: XCTestCase { var control: MockControl! var signalsBag: SignalBag! override func setUp() { super.setUp() control = MockControl() signalsBag = SignalBag() } func testObserveControlEvent() { var called = false control.observe() .events(.ValueChanged) .next { _ in called = true } .addTo(signalsBag) control.sendActionsForControlEvents(.ValueChanged) XCTAssertEqual(called, true, "Should observe the control for UIControlEvents") } func testObserveMultipleControlEvents() { var called = false control.observe() .events([.ValueChanged, .TouchUpInside]) .next { _ in called = true } .addTo(signalsBag) control.sendActionsForControlEvents(.TouchUpInside) XCTAssertEqual(called, true, "Should observe the control for multiple UIControlEvents") } func testBindToEnabled() { let signal = MockSignal<Bool>() control.enabled = true signal .bindTo(enabled: control) .addTo(signalsBag) signal.dispatch(false) XCTAssertEqual(control.enabled, false, "Should bind a boolean signal to the enabled property of UIControl") } }
mit
601f498d4fa052d96ec8580dd61456d6
23.892308
115
0.575402
5.339934
false
true
false
false
haaakon/Presentation
Source/Content.swift
5
2573
import UIKit import Cartography public class Content: NSObject { public var view: UIView public var centered: Bool public var position: Position { didSet { layout() } } public private(set) var initialPosition: Position private let group = ConstraintGroup() public init(view: UIView, position: Position, centered: Bool = true) { self.view = view self.position = position self.centered = centered initialPosition = position.positionCopy super.init() constrain(view) { [unowned self] view in view.width == CGRectGetWidth(self.view.frame) view.height == CGRectGetHeight(self.view.frame) } } public func layout() { if let superview = view.superview { constrain(view, replace: group) { [unowned self] view in let x = self.position.left == 0.0 ? view.superview!.left * 1.0 : view.superview!.right * self.position.left let y = self.position.top == 0.0 ? view.superview!.top * 1.0 : view.superview!.bottom * self.position.top if self.centered { view.centerX == x view.centerY == y } else { view.left == x view.top == y } } view.layoutIfNeeded() } } } extension Content { public class func titleContent(text: String, attributes: [NSObject: AnyObject]? = nil) -> Content { let label = UILabel(frame: CGRectZero) label.numberOfLines = 1 label.attributedText = NSAttributedString(string: text, attributes: attributes) label.sizeToFit() let position = Position(left: 0.9, bottom: 0.2) return Content(view: label, position: position) } public class func textContent(text: String, attributes: [NSObject: AnyObject]? = nil) -> Content { let textView = UITextView(frame: CGRectZero) textView.backgroundColor = .clearColor() textView.attributedText = NSAttributedString(string: text, attributes: attributes) textView.sizeToFit() return Content(view: textView, position: Position(left: 0.9, bottom: 0.1)) } public class func imageContent(image: UIImage) -> Content { let imageView = UIImageView(image: image) return Content(view: imageView, position: Position(left: 0.5, bottom: 0.5)) } public class func centerTransitionForSlideContent(content: Content) -> Animatable { return TransitionAnimation( content: content, destination: Position(left: 0.5, bottom: content.initialPosition.bottom), duration: 2.0, dumping: 0.8, reflective: true) } }
mit
492a8722454760b60b88172197e1afbc
27.588889
88
0.65138
4.190554
false
false
false
false
xuech/OMS-WH
OMS-WH/Utilities/Libs/Reflect/Coding/Reflect+ArcFile.swift
1
2821
// // String+ArcFile.swift // Reflect // // Created by 成林 on 15/8/23. // Copyright (c) 2015年 冯成林. All rights reserved. // import Foundation extension Reflect{ static var DurationKey: String {return "Duration"} class func save(obj: AnyObject! , name: String, duration: TimeInterval) -> String{ if duration > 0 { UserDefaults.standard.set(NSDate().timeIntervalSince1970, forKey: name) UserDefaults.standard.set(duration, forKey: name + DurationKey) } let path = pathWithName(name: name) if obj != nil { NSKeyedArchiver.archiveRootObject(obj, toFile: path) }else{ let fm = FileManager.default if fm.fileExists(atPath: path) { if fm.isDeletableFile(atPath: path){ do { try fm.removeItem(atPath: path) }catch { } } } } return path } class func read(name: String) -> (Bool, AnyObject?){ let time = UserDefaults.standard.double(forKey: name) let duration = UserDefaults.standard.double(forKey: name + DurationKey) let now = NSDate().timeIntervalSince1970 let path = pathWithName(name: name) let obj = NSKeyedUnarchiver.unarchiveObject(withFile: path) if time > 0 && duration > 0 && time + duration < now {return (false,obj as AnyObject?)} if obj == nil {return (false,obj as AnyObject?)} return (true,obj as AnyObject?) } class func deleteReflectModel(name: String){_ = save(obj: nil, name: name, duration: 0)} static func pathWithName(name: String) -> String{ let path = Reflect.cachesFolder! + "/" + name + ".arc" return path } static var cachesFolder: String? { let cacheRootPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last let cache_reflect_path = cacheRootPath! + "/" + "Reflect" let fm = FileManager.default let existed = fm.fileExists(atPath: cache_reflect_path) if !existed { do { try fm.createDirectory(atPath: cache_reflect_path, withIntermediateDirectories: true, attributes: nil) }catch {} }else{ } return cache_reflect_path } func ignoreCodingPropertiesForCoding() -> [String]? {return nil} }
mit
a82b2ada838c29dbfe792c55de3f8878
26.811881
172
0.534354
5.135283
false
false
false
false
midoks/Swift-Learning
EampleApp/EampleApp/Controllers/RootViewController.swift
1
1817
import UIKit class RootViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setTabBars() } //设置底部显示 func setTabBars(){ //电影 let Movie = MainViewController() let MovieNav = UINavigationController(rootViewController: Movie) let MovieTabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.featured, tag: 1) MovieNav.tabBarItem = MovieTabBarItem //改变 let Change = ChangesViewController() let ChangeNav = UINavigationController(rootViewController: Change) let ChangeTabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.mostViewed, tag: 2) ChangeNav.tabBarItem = ChangeTabBarItem let Rank = RankViewController() let RankNav = UINavigationController(rootViewController: Rank) let RankTabBarItem = UITabBarItem(tabBarSystemItem: UITabBarSystemItem.more, tag: 4) RankNav.tabBarItem = RankTabBarItem //用户界面 let User = UserViewController() let UserTabBarItem = UITabBarItem(title: "我", image: UIImage(named: "tabbar_me"), tag: 0) User.tabBarItem = UserTabBarItem let UserNav = UINavigationController(rootViewController: User) let vc = [ MovieNav, ChangeNav, RankNav, UserNav ] self.setViewControllers(vc, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
beede86c60e21092457b57ece4139843
28.783333
100
0.608282
5.584375
false
false
false
false
Piwigo/Piwigo-Mobile
piwigo/Upload/Upload Options/UploadParametersViewController.swift
1
15768
// // UploadParametersViewController.swift // piwigo // // Created by Eddy Lelièvre-Berna on 15/07/2020. // Copyright © 2020 Piwigo.org. All rights reserved. // import piwigoKit enum EditImageDetailsOrder : Int { case imageName case author case privacy case tags case comment case count } class UploadParametersViewController: UITableViewController, UITextFieldDelegate, UITextViewDelegate { @IBOutlet var paramsTableView: UITableView! var commonTitle = "" private var shouldUpdateTitle = false var commonAuthor = UploadVars.defaultAuthor private var shouldUpdateAuthor = false var commonPrivacyLevel = kPiwigoPrivacy(rawValue: UploadVars.defaultPrivacyLevel) ?? .everybody private var shouldUpdatePrivacyLevel = false var commonTags = [Tag]() private var shouldUpdateTags = false var commonComment = "" private var shouldUpdateComment = false // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() // Collection view identifier paramsTableView.accessibilityIdentifier = "Parameters" } @objc func applyColorPalette() { // Background color of the views view.backgroundColor = .piwigoColorBackground() // Table view paramsTableView.separatorColor = .piwigoColorSeparator() paramsTableView.indicatorStyle = AppVars.shared.isDarkPaletteActive ? .white : .black paramsTableView.reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Set colors, fonts, etc. applyColorPalette() // Register palette changes NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette), name: .pwgPaletteChanged, object: nil) } deinit { // Unregister palette changes NotificationCenter.default.removeObserver(self, name: .pwgPaletteChanged, object: nil) } // MARK: - UITableView - Header private func getContentOfHeader() -> (String, String) { let title = String(format: "%@\n", NSLocalizedString("imageDetailsView_title", comment: "Properties")) let text = NSLocalizedString("imageUploadHeaderText_images", comment: "Please set the parameters to apply to the selection of photos/videos") return (title, text) } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { let (title, text) = getContentOfHeader() return TableViewUtilities.shared.heightOfHeader(withTitle: title, text: text, width: tableView.frame.size.width) } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let (title, text) = getContentOfHeader() return TableViewUtilities.shared.viewOfHeader(withTitle: title, text: text) } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.0 // To hide the section footer } // MARK: - UITableView - Rows override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Don't present privacy level choice to non-admin users var nberOfRows = EditImageDetailsOrder.count.rawValue nberOfRows -= (!NetworkVars.hasAdminRights ? 1 : 0) return nberOfRows } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // Don't present privacy level choice to non-admin users var row = indexPath.row row += (!NetworkVars.hasAdminRights && (row > 1)) ? 1 : 0 var height: CGFloat = 44.0 switch EditImageDetailsOrder(rawValue: row) { case .privacy, .tags: height = 78.0 case .comment: height = 428.0 height += !NetworkVars.hasAdminRights ? 78.0 : 0.0 default: break } return height } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Don't present privacy level choice to non-admin users var row = indexPath.row row += (!NetworkVars.hasAdminRights && (row > 1)) ? 1 : 0 var tableViewCell = UITableViewCell() switch EditImageDetailsOrder(rawValue: row) { case .imageName: guard let cell = tableView.dequeueReusableCell(withIdentifier: "title", for: indexPath) as? EditImageTextFieldTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a EditImageTextFieldTableViewCell!") return EditImageTextFieldTableViewCell() } cell.config(withLabel: NSLocalizedString("editImageDetails_title", comment: "Title:"), placeHolder: NSLocalizedString("editImageDetails_titlePlaceholder", comment: "Title"), andImageDetail: commonTitle) cell.cellTextField.textColor = shouldUpdateTitle ? .piwigoColorOrange() : .piwigoColorRightLabel() cell.cellTextField.tag = EditImageDetailsOrder.imageName.rawValue cell.cellTextField.delegate = self tableViewCell = cell case .author: guard let cell = tableView.dequeueReusableCell(withIdentifier: "author", for: indexPath) as? EditImageTextFieldTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a EditImageTextFieldTableViewCell!") return EditImageTextFieldTableViewCell() } cell.config(withLabel: NSLocalizedString("editImageDetails_author", comment: "Author:"), placeHolder: NSLocalizedString("settings_defaultAuthorPlaceholder", comment: "Author Name"), andImageDetail: (commonAuthor == "NSNotFound") ? "" : commonAuthor) cell.cellTextField.textColor = shouldUpdateAuthor ? .piwigoColorOrange() : .piwigoColorRightLabel() cell.cellTextField.tag = EditImageDetailsOrder.author.rawValue cell.cellTextField.delegate = self tableViewCell = cell case .privacy: guard let cell = tableView.dequeueReusableCell(withIdentifier: "privacy", for: indexPath) as? EditImagePrivacyTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a EditImagePrivacyTableViewCell!") return EditImagePrivacyTableViewCell() } cell.setLeftLabel(withText: NSLocalizedString("editImageDetails_privacyLevel", comment: "Who can see this photo?")) cell.setPrivacyLevel(with: commonPrivacyLevel, inColor: shouldUpdatePrivacyLevel ? .piwigoColorOrange() : .piwigoColorRightLabel()) tableViewCell = cell case .tags: guard let cell = tableView.dequeueReusableCell(withIdentifier: "tags", for: indexPath) as? EditImageTagsTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a EditImageTagsTableViewCell!") return EditImageTagsTableViewCell() } // Switch to old cache data format var tagList = [PiwigoTagData]() commonTags.forEach { (tag) in let newTag = PiwigoTagData() newTag.tagId = Int(tag.tagId) newTag.tagName = tag.tagName newTag.lastModified = tag.lastModified newTag.numberOfImagesUnderTag = tag.numberOfImagesUnderTag tagList.append(newTag) } cell.config(withList: tagList, inColor: shouldUpdateTags ? .piwigoColorOrange() : .piwigoColorRightLabel()) cell.accessibilityIdentifier = "setTags" tableViewCell = cell case .comment: guard let cell = tableView.dequeueReusableCell(withIdentifier: "comment", for: indexPath) as? EditImageTextViewTableViewCell else { print("Error: tableView.dequeueReusableCell does not return a EditImageTextViewTableViewCell!") return EditImageTextViewTableViewCell() } cell.config(withText: commonComment, inColor: shouldUpdateComment ? .piwigoColorOrange() : .piwigoColorRightLabel()) cell.textView.delegate = self tableViewCell = cell default: break } tableViewCell.backgroundColor = .piwigoColorCellBackground() tableViewCell.tintColor = .piwigoColorOrange() return tableViewCell } // MARK: - UITableViewDelegate Methods override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) // Don't present privacy level choice to non-admin users var row = indexPath.row row += (!NetworkVars.hasAdminRights && (row > 1)) ? 1 : 0 switch EditImageDetailsOrder(rawValue: row) { case .author: if (commonAuthor == "NSNotFound") { // only update if not yet set, dont overwrite if 0 < UploadVars.defaultAuthor.count { // must know the default author commonAuthor = UploadVars.defaultAuthor tableView.reloadRows(at: [indexPath], with: .automatic) } } case .privacy: // Dismiss the keyboard view.endEditing(true) // Create view controller let privacySB = UIStoryboard(name: "SelectPrivacyViewController", bundle: nil) guard let privacyVC = privacySB.instantiateViewController(withIdentifier: "SelectPrivacyViewController") as? SelectPrivacyViewController else { return } privacyVC.delegate = self privacyVC.privacy = commonPrivacyLevel navigationController?.pushViewController(privacyVC, animated: true) case .tags: // Dismiss the keyboard view.endEditing(true) // Create view controller let tagsSB = UIStoryboard(name: "TagsViewController", bundle: nil) guard let tagsVC = tagsSB.instantiateViewController(withIdentifier: "TagsViewController") as? TagsViewController else { return } tagsVC.delegate = self tagsVC.setPreselectedTagIds(commonTags.map({$0.tagId})) // Can we propose to create tags? if let switchVC = parent as? UploadSwitchViewController { tagsVC.setTagCreationRights(switchVC.hasTagCreationRights) } navigationController?.pushViewController(tagsVC, animated: true) default: return } } override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool { // Don't present privacy level choice to non-admin users var row = indexPath.row row += (!NetworkVars.hasAdminRights && (row > 1)) ? 1 : 0 var result: Bool switch EditImageDetailsOrder(rawValue: row) { case .imageName, .author, .comment: result = false default: result = true } return result } // MARK: - UITextFieldDelegate Methods func textFieldDidBeginEditing(_ textField: UITextField) { switch EditImageDetailsOrder(rawValue: textField.tag) { case .imageName: // Title shouldUpdateTitle = true case .author: // Author shouldUpdateAuthor = true default: break } } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let finalString = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) else { return true } switch EditImageDetailsOrder(rawValue: textField.tag) { case .imageName: commonTitle = finalString case .author: if finalString.count > 0 { commonAuthor = finalString } else { commonAuthor = "NSNotFound" } default: break } return true } func textFieldShouldClear(_ textField: UITextField) -> Bool { switch EditImageDetailsOrder(rawValue: textField.tag) { case .imageName: commonTitle = "" case .author: commonAuthor = "NSNotFound" default: break } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { paramsTableView.endEditing(true) return true } func textFieldDidEndEditing(_ textField: UITextField) { switch EditImageDetailsOrder(rawValue: textField.tag) { case .imageName: if let typedText = textField.text { commonTitle = typedText } // Update cell let indexPath = IndexPath(row: EditImageDetailsOrder.imageName.rawValue, section: 0) paramsTableView.reloadRows(at: [indexPath], with: .automatic) case .author: if let typedText = textField.text, typedText.count > 0 { commonAuthor = typedText } else { commonAuthor = "NSNotFound" } // Update cell let indexPath = IndexPath(row: EditImageDetailsOrder.author.rawValue, section: 0) paramsTableView.reloadRows(at: [indexPath], with: .automatic) default: break } } // MARK: - UITextViewDelegate Methods func textViewDidBeginEditing(_ textView: UITextView) { shouldUpdateComment = true textView.textColor = .piwigoColorOrange() } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { let finalString = (textView.text as NSString).replacingCharacters(in: range, with: text) commonComment = finalString return true } func textViewShouldEndEditing(_ textView: UITextView) -> Bool { paramsTableView.endEditing(true) return true } func textViewDidEndEditing(_ textView: UITextView) { commonComment = textView.text } } // MARK: - SelectPrivacyDelegate Methods extension UploadParametersViewController: SelectPrivacyDelegate { func didSelectPrivacyLevel(_ privacyLevel: kPiwigoPrivacy) { // Update image parameter commonPrivacyLevel = privacyLevel // Remember to update image info shouldUpdatePrivacyLevel = true // Update cell let indexPath = IndexPath(row: EditImageDetailsOrder.privacy.rawValue, section: 0) paramsTableView.reloadRows(at: [indexPath], with: .automatic) } } // MARK: - TagsViewControllerDelegate Methods extension UploadParametersViewController: TagsViewControllerDelegate { func didSelectTags(_ selectedTags: [Tag]) { // Update image parameter commonTags = selectedTags // Remember to update image info shouldUpdateTags = true // Update cell let indexPath = IndexPath(row: EditImageDetailsOrder.tags.rawValue, section: 0) paramsTableView.reloadRows(at: [indexPath], with: .automatic) } }
mit
942fc3485ec6e26c791ce8f487d693c3
38.613065
168
0.633959
5.461032
false
false
false
false
jingyichushi/SwiftyOpenOauth
HeimdallTests/NSURLRequestExtensionsSpec.swift
1
6664
import Heimdall import Nimble import Quick class HTTPAuthenticationSpec: QuickSpec { override func spec() { describe("<Equatable> ==") { context("BasicAuthentication") { it("returns true if usernames and passwords match") { let lhs: HTTPAuthentication = .BasicAuthentication(username: "username", password: "password") let rhs: HTTPAuthentication = .BasicAuthentication(username: "username", password: "password") expect(lhs == rhs).to(beTrue()) } it("returns false if usernames do not match") { let lhs: HTTPAuthentication = .BasicAuthentication(username: "usernamea", password: "password") let rhs: HTTPAuthentication = .BasicAuthentication(username: "usernameb", password: "password") expect(lhs == rhs).to(beFalse()) } it("returns false if password do not match") { let lhs: HTTPAuthentication = .BasicAuthentication(username: "username", password: "passworda") let rhs: HTTPAuthentication = .BasicAuthentication(username: "username", password: "passwordb") expect(lhs == rhs).to(beFalse()) } } context("Unknown") { it("returns true if accessTokens and tokenTypes match") { let lhs: HTTPAuthentication = .AccessTokenAuthentication(OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType")) let rhs: HTTPAuthentication = .AccessTokenAuthentication(OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType")) expect(lhs == rhs).to(beTrue()) } it("returns false if accessTokens do not match") { let lhs: HTTPAuthentication = .AccessTokenAuthentication(OAuthAccessToken(accessToken: "accessTokena", tokenType: "tokenType")) let rhs: HTTPAuthentication = .AccessTokenAuthentication(OAuthAccessToken(accessToken: "accessTokenb", tokenType: "tokenType")) expect(lhs == rhs).to(beFalse()) } it("returns false if tokenTypes do not match") { let lhs: HTTPAuthentication = .AccessTokenAuthentication(OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenTypeb")) let rhs: HTTPAuthentication = .AccessTokenAuthentication(OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenTypea")) expect(lhs == rhs).to(beFalse()) } } context("Mixed") { it("returns false if authentication methods do not match") { let lhs: HTTPAuthentication = .BasicAuthentication(username: "username", password: "password") let rhs: HTTPAuthentication = .AccessTokenAuthentication(OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType")) expect(lhs == rhs).to(beFalse()) } } } } } class NSURLRequestExtensionsSpec: QuickSpec { override func spec() { var request: NSMutableURLRequest! beforeEach { request = NSMutableURLRequest() } describe(".HTTPAuthorization") { it("returns nil if the Authorization header is not set") { expect(request.HTTPAuthorization).to(beNil()) } it("returns the Authorization header as String if set") { request.setValue("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", forHTTPHeaderField: "Authorization") expect(request.HTTPAuthorization).to(equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=")) } } } } class NSMutableURLRequestExtensionsSpec: QuickSpec { override func spec() { var request: NSMutableURLRequest! beforeEach { request = NSMutableURLRequest() } describe("-setHTTPAuthorization") { context("when given nil") { it("resets the Authorization header") { request.setValue("Basic dXNlcm5hbWU6cGFzc3dvcmQ=", forHTTPHeaderField: "Authorization") request.setHTTPAuthorization(nil) expect(request.HTTPAuthorization).to(beNil()) } } context("when given a String") { it("sets the Authorization header to the given value") { request.setHTTPAuthorization("Basic dXNlcm5hbWU6cGFzc3dvcmQ=") expect(request.HTTPAuthorization).to(equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=")) } } context("when given .BasicAuthentication") { it("sets the Authorization header with encoded username and password") { let authentication: HTTPAuthentication = .BasicAuthentication(username: "username", password: "password") request.setHTTPAuthorization(authentication) expect(request.HTTPAuthorization).to(equal("Basic dXNlcm5hbWU6cGFzc3dvcmQ=")) } } context("when given .AccessTokenAuthentication") { it("sets the Authorization header with access token and token type") { let authentication: HTTPAuthentication = .AccessTokenAuthentication(OAuthAccessToken(accessToken: "accessToken", tokenType: "tokenType")) request.setHTTPAuthorization(authentication) expect(request.HTTPAuthorization).to(equal("tokenType accessToken")) } } } describe("-setHTTPBody") { context("when given nil") { it("resets the body") { request.setHTTPBody(parameters: nil) expect(request.HTTPBody).to(beNil()) } } context("when given parameters") { it("sets the body with encoded parameyers") { request.setHTTPBody(parameters: [ "#key1": "%value1", "#key2": "%value2" ]) var components = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding)?.componentsSeparatedByString("&") as? [String] components = components?.sorted { $0 < $1 } expect(components?[0]).to(equal("%23key1=%25value1")) expect(components?[1]).to(equal("%23key2=%25value2")) } } } } }
mit
a5fbce28280bdb2f94b9a29e1ba315b7
41.993548
157
0.571879
5.382876
false
false
false
false